diff --git a/.coveragerc b/.coveragerc index 65e13c2234b..409fde55643 100644 --- a/.coveragerc +++ b/.coveragerc @@ -9,6 +9,7 @@ omit = ${INITIAL_PWD-.}/.github/* ${INITIAL_PWD-.}/bin.*/* ${INITIAL_PWD-.}/dist.*/* + **/gui/wxpython/*/** **/OBJ.*/* source = . diff --git a/.flake8 b/.flake8 index 18cea9165ce..6bfcc1e5527 100644 --- a/.flake8 +++ b/.flake8 @@ -20,61 +20,10 @@ per-file-ignores = # F841 local variable assigned to but never used # E741 ambiguous variable name 'l' __init__.py: F401, F403 - lib/init/grass.py: E722, F821, F841 - utils/gitlog2changelog.py: E722, E712 - man/build_check_rest.py: F403, F405 - man/build_full_index_rest.py: F403, F405 - man/parser_standard_options.py: F403, F405 - man/build_class.py: F403, F405 - man/build_class_rest.py: F403, F405 - man/build_check.py: F403, F405 - man/build_full_index.py: F403, F405 - man/build_index.py: F403, F405 - man/build_index_rest.py: F403, F405 - man/build_keywords.py: F403, F405, E722 - man/build_topics.py: F403, F405, E722 man/build_html.py: E501 - imagery/i.atcorr/create_iwave.py: F632, F821, W293 - doc/python/raster_example_ctypes.py: F403, F405 - doc/python/vector_example_ctypes.py: F403, F405 - doc/python/m.distance.py: F403, F405, E501 - doc/gui/wxpython/example/dialogs.py: F401 - locale/grass_po_stats.py: E122, E128, E231, E401, E722 + doc/python/m.distance.py: E501 gui/scripts/d.wms.py: E501 - gui/wxpython/core/gcmd.py: E402 - gui/wxpython/core/gthread.py: F841 - gui/wxpython/core/gconsole.py: E722 - gui/wxpython/core/toolboxes.py: E722 - gui/wxpython/core/utils.py: E722, F841 - gui/wxpython/core/workspace.py: E722 - gui/wxpython/core/render.py: E722, F841 - gui/wxpython/core/ws.py: F841 - gui/wxpython/core/settings.py: E722 - gui/wxpython/core/watchdog.py: E402 - gui/wxpython/datacatalog/tree.py: E731, E402 - gui/wxpython/dbmgr/base.py: E722 - gui/wxpython/dbmgr/dialogs.py: E722 - gui/wxpython/dbmgr/sqlbuilder.py: E722 - gui/wxpython/dbmgr/manager.py: E722 - gui/wxpython/docs/wxgui_sphinx/conf.py: E402, W291 - gui/wxpython/gcp/g.gui.gcp.py: F841 - gui/wxpython/gcp/manager.py: F841, E722 - gui/wxpython/gcp/mapdisplay.py: F841 - gui/wxpython/gui_core/*: F841, E266, E722 - gui/wxpython/gui_core/dialogs.py: E722, F841 - gui/wxpython/gui_core/forms.py: E722, F841 - gui/wxpython/gui_core/ghelp.py: E722 - gui/wxpython/gui_core/gselect.py: F841, E266, E722 - gui/wxpython/gui_core/preferences.py: E266, F841 - gui/wxpython/gui_core/treeview.py: F841 - gui/wxpython/gui_core/widgets.py: F841, E722, E266 - gui/wxpython/image2target/*: F841, E722, E265 - gui/wxpython/image2target/g.gui.image2target.py: E501, E265, F841 - gui/wxpython/iscatt/*: F841, E722, F405, F403 - gui/wxpython/lmgr/frame.py: F841, E722 - # layertree still includes some formatting issues (it is ignored by Black) - gui/wxpython/lmgr/layertree.py: E722, E266, W504, E225 - gui/wxpython/lmgr/workspace.py: F841 + gui/wxpython/image2target/g.gui.image2target.py: E501 gui/wxpython/modules/*: F841, E722 gui/wxpython/nviz/*: F841, E266, E722, F403, F405 gui/wxpython/photo2image/*: F841, E722, E265 @@ -84,8 +33,6 @@ per-file-ignores = gui/wxpython/vnet/*: F841 gui/wxpython/wxgui.py: F841 gui/wxpython/animation/g.gui.animation.py: E501 - gui/wxpython/animation/mapwindow.py: F841 - gui/wxpython/animation/provider.py: F841 gui/wxpython/tplot/frame.py: F841, E722 gui/wxpython/tplot/g.gui.tplot.py: E501 gui/wxpython/rdigit/g.gui.rdigit.py: F841 @@ -153,33 +100,28 @@ per-file-ignores = python/grass/*/*/__init__.py: F401, F403 python/grass/*/*/*/__init__.py: F401, F403 # E402 module level import not at top of file - scripts/d.polar/d.polar.py: F841 - scripts/r.in.wms/wms_gdal_drv.py: F841, E722 - scripts/r.in.wms/wms_cap_parsers.py: F841 + scripts/r.in.wms/wms_gdal_drv.py: E722 scripts/r.in.wms/wms_drv.py: E402, E722 scripts/r.in.wms/srs.py: E722 - scripts/r.semantic.label/r.semantic.label.py: F841, E501 - scripts/v.report/v.report.py: F841, E721 + scripts/r.semantic.label/r.semantic.label.py: E501 + scripts/v.report/v.report.py: E721 scripts/db.out.ogr/db.out.ogr.py: F841 scripts/g.extension/g.extension.py: F841, E722, E501 - scripts/v.unpack/v.unpack.py: F841, E722, E501 - scripts/v.import/v.import.py: F841, E722, E501 + scripts/v.unpack/v.unpack.py: E722, E501 + scripts/v.import/v.import.py: E722, E501 scripts/db.univar/db.univar.py: E501 scripts/d.frame/d.frame.py: E722 scripts/i.pansharpen/i.pansharpen.py: E722, E501 scripts/r.in.srtm/r.in.srtm.py: E722 scripts/r.fillnulls/r.fillnulls.py: E722 scripts/d.rast.edit/d.rast.edit.py: E722 - scripts/v.what.strds/v.what.strds.py: E722, E501 + scripts/v.what.strds/v.what.strds.py: E501 # Line too long (esp. module interface definitions) scripts/*/*.py: E501 - # local variable 'column' is assigned to but never used temporal/t.rast.to.vect/t.rast.to.vect.py: E501 - # local variable 'stdstype' is assigned to but never used - temporal/t.vect.algebra/t.vect.algebra.py: F841, E501 + temporal/t.vect.algebra/t.vect.algebra.py: E501 # ## used (##% key: r etc) - # local variable 'map_list' is assigned to but never used - temporal/t.rast.what/t.rast.what.py: E265, E266, F841, E501 + temporal/t.rast.what/t.rast.what.py: E265, E266, E501 # Line too long (esp. module interface definitions) temporal/*/*.py: E501 diff --git a/.github/actions/create-upload-suggestions/action.yml b/.github/actions/create-upload-suggestions/action.yml index 2493fba2573..b80c08c1b46 100644 --- a/.github/actions/create-upload-suggestions/action.yml +++ b/.github/actions/create-upload-suggestions/action.yml @@ -177,7 +177,7 @@ runs: echo "diff-file-name=${INPUT_DIFF_FILE_NAME}" >> "${GITHUB_OUTPUT}" env: INPUT_DIFF_FILE_NAME: ${{ steps.tool-name-safe.outputs.diff-file-name }} - - uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0 + - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 id: upload-diff if: >- ${{ (steps.files_changed.outputs.files_changed == 'true') && @@ -200,7 +200,7 @@ runs: echo 'Suggestions can only be added near to lines changed in this PR.' echo 'If any fixes can be added as code suggestions, they will be added shortly from another workflow.' } >> "${GITHUB_STEP_SUMMARY}" - - uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0 + - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 id: upload-changes if: >- ${{ always() && diff --git a/.github/labeler.yml b/.github/labeler.yml index d6caa447e2e..464ccdce2b8 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -123,9 +123,7 @@ docs: - '**/*.png' - '**.cff' - CITING - - CHANGES - AUTHORS - - NEWS - TODO - all-globs-to-all-files: - '!doc/development/rfc/**' diff --git a/.github/workflows/additional_checks.yml b/.github/workflows/additional_checks.yml index d25cbb49194..a91d221f1e4 100644 --- a/.github/workflows/additional_checks.yml +++ b/.github/workflows/additional_checks.yml @@ -24,7 +24,7 @@ jobs: steps: - name: Checkout repository contents - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 with: fetch-depth: 31 diff --git a/.github/workflows/apt.txt b/.github/workflows/apt.txt index a5a221c939c..4c14cb7b067 100644 --- a/.github/workflows/apt.txt +++ b/.github/workflows/apt.txt @@ -7,8 +7,8 @@ libfftw3-dev libgdal-dev libgl1-mesa-dev libglu1-mesa-dev +liblapacke-dev libnetcdf-dev -libopenblas-dev libpdal-dev libpng-dev libproj-dev diff --git a/.github/workflows/clang-format-check.yml b/.github/workflows/clang-format-check.yml index 12b0b070ec9..13ba5bb3cd9 100644 --- a/.github/workflows/clang-format-check.yml +++ b/.github/workflows/clang-format-check.yml @@ -16,7 +16,7 @@ jobs: name: Formatting Check runs-on: ubuntu-latest steps: - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 with: persist-credentials: false - uses: DoozyX/clang-format-lint-action@c71d0bf4e21876ebec3e5647491186f8797fde31 # v0.18.2 diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 05d4581b689..6672287794c 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -40,7 +40,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - name: Set up Python uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0 with: @@ -52,11 +52,11 @@ jobs: sudo apt-get install -y wget git gawk findutils xargs -a <(awk '! /^ *(#|$)/' ".github/workflows/apt.txt") -r -- \ sudo apt-get install -y --no-install-recommends --no-install-suggests - - uses: rui314/setup-mold@0bf4f07ef9048ec62a45f9dbf2f098afa49695f0 # v1 + - uses: rui314/setup-mold@b015f7e3f2938ad3a5ed6e5111a8c6c7c1d6db6e # v1 if: ${{ matrix.language == 'c-cpp' }} - name: Initialize CodeQL - uses: github/codeql-action/init@4dd16135b69a43b6c8efb853346f8437d92d3c93 # v3.26.6 + uses: github/codeql-action/init@f779452ac5af1c261dce0346a8f964149f49322b # v3.26.13 with: languages: ${{ matrix.language }} config-file: ./.github/codeql/codeql-config.yml @@ -81,6 +81,6 @@ jobs: run: .github/workflows/build_ubuntu-22.04.sh "${HOME}/install" - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@4dd16135b69a43b6c8efb853346f8437d92d3c93 # v3.26.6 + uses: github/codeql-action/analyze@f779452ac5af1c261dce0346a8f964149f49322b # v3.26.13 with: category: "/language:${{matrix.language}}" diff --git a/.github/workflows/coverity.yml b/.github/workflows/coverity.yml index 9f1fc5d843c..22a6b7a42a8 100644 --- a/.github/workflows/coverity.yml +++ b/.github/workflows/coverity.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-22.04 if: github.repository == 'OSGeo/grass' steps: - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - name: Get dependencies run: | diff --git a/.github/workflows/create_release_draft.yml b/.github/workflows/create_release_draft.yml index 09da8ad1317..3112fb8b33f 100644 --- a/.github/workflows/create_release_draft.yml +++ b/.github/workflows/create_release_draft.yml @@ -30,7 +30,7 @@ jobs: contents: write steps: - name: Checks-out repository - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 with: ref: ${{ github.ref }} fetch-depth: 0 diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 1f60ed4c6d7..4de674ee9a2 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -49,7 +49,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 with: fetch-depth: 0 - name: Docker meta @@ -68,7 +68,7 @@ jobs: - name: Set up QEMU uses: docker/setup-qemu-action@49b3bc8e6bdd4a60e6116a5414239cba5943d3cf # v3.2.0 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@988b5a0280414f521da01fcc63a27aeeb4b104db # v3.6.1 + uses: docker/setup-buildx-action@c47758b77c9736f4b2ef4073d4d51994fabfe349 # v3.7.1 - name: Login to DockerHub uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3.3.0 with: @@ -76,7 +76,7 @@ jobs: password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Build and push id: docker_build - uses: docker/build-push-action@5cd11c3a4ced054e52742c5fd54dca954e0edd85 # v6.7.0 + uses: docker/build-push-action@4f58ea79222b3b9dc2c8bbdd6debcef730109a75 # v6.9.0 with: push: true pull: true diff --git a/.github/workflows/gcc.yml b/.github/workflows/gcc.yml index e3e23f43c04..651cb272fba 100644 --- a/.github/workflows/gcc.yml +++ b/.github/workflows/gcc.yml @@ -26,7 +26,7 @@ jobs: fail-fast: false steps: - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - name: Get dependencies run: | sudo apt-get update -y diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index eb99b6ff7a7..41ac51df8ff 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -44,13 +44,20 @@ jobs: -mindepth 1 -maxdepth 1 -type f -print -delete # Rehash to forget about the deleted files hash -r - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 + - name: Get current date cache key segment + id: date + # Year and week of year so cache key changes weekly + run: echo "date=$(date +%Y-%U)" >> "${GITHUB_OUTPUT}" - name: Setup Mamba - uses: mamba-org/setup-micromamba@f8b8a1e23a26f60a44c853292711bacfd3eac822 # v1.9.0 + uses: mamba-org/setup-micromamba@617811f69075e3fd3ae68ca64220ad065877f246 # v2.0.0 with: init-shell: bash environment-file: .github/workflows/macos_dependencies.txt environment-name: grass-env + # Persist on the same period (date). + cache-environment-key: environment-${{ steps.date.outputs.date }} + - name: Environment info shell: bash -el {0} run: | @@ -59,17 +66,17 @@ jobs: - name: Create installation directory run: mkdir $HOME/install - name: Build and install - shell: bash -l {0} + shell: micromamba-shell {0} run: source ./.github/workflows/macos_install.sh $HOME/install - name: Add the bin directory to PATH run: echo "$HOME/install/bin" >> $GITHUB_PATH - name: Check installed version if: ${{ !cancelled() }} - shell: bash -l {0} + shell: micromamba-shell {0} run: source ./.github/workflows/print_versions.sh - name: Run pytest with multiple workers in parallel - shell: bash -el {0} + shell: micromamba-shell {0} run: | export PYTHONPATH=$(grass --config python_path):$PYTHONPATH export LD_LIBRARY_PATH=$(grass --config path)/lib:$LD_LIBRARY_PATH @@ -78,7 +85,7 @@ jobs: -ra . \ -m 'not needs_solo_run' - name: Run pytest with a single worker (for tests marked with needs_solo_run) - shell: bash -el {0} + shell: micromamba-shell {0} run: | export PYTHONPATH=$(grass --config python_path):$PYTHONPATH export LD_LIBRARY_PATH=$(grass --config path)/lib:$LD_LIBRARY_PATH @@ -87,7 +94,7 @@ jobs: -m 'needs_solo_run' - name: Run gunittest tests - shell: bash -el {0} + shell: micromamba-shell {0} run: | grass --tmp-project XY --exec \ g.download.project url=${{ env.SampleData }} path=$HOME @@ -100,7 +107,7 @@ jobs: nc_spm_full_v2alpha2.tar.gz" - name: Make HTML test report available if: ${{ !cancelled() }} - uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 with: name: testreport-macOS path: testreport diff --git a/.github/workflows/macos_dependencies.txt b/.github/workflows/macos_dependencies.txt index bc60609f7b5..8ef1d3460f6 100644 --- a/.github/workflows/macos_dependencies.txt +++ b/.github/workflows/macos_dependencies.txt @@ -1,4 +1,3 @@ -blas cairo clangxx_osx-arm64 clang_osx-arm64 @@ -13,7 +12,6 @@ giflib git ipython krb5 -lapack lastools libgdal-arrow-parquet libgdal-core @@ -32,6 +30,7 @@ libtiff llvm-openmp matplotlib numpy<2 +openblas pandoc pdal pillow diff --git a/.github/workflows/macos_gunittest.cfg b/.github/workflows/macos_gunittest.cfg index b6806ff5823..923ae2cbe5d 100644 --- a/.github/workflows/macos_gunittest.cfg +++ b/.github/workflows/macos_gunittest.cfg @@ -6,25 +6,18 @@ exclude = gui/wxpython/core/testsuite/test_gcmd.py gui/wxpython/core/testsuite/toolboxes.sh - lib/init/testsuite/test_grass_tmp_mapset.py - python/grass/gunittest/testsuite/test_assertions_rast3d.py python/grass/gunittest/testsuite/test_assertions_vect.py - python/grass/gunittest/testsuite/test_gmodules.py - python/grass/gunittest/testsuite/test_gunitest_doctests.py python/grass/pygrass/raster/testsuite/test_pygrass_raster_doctests.py python/grass/pygrass/rpc/testsuite/test_pygrass_rpc_doctests.py - python/grass/script/testsuite/test_script_doctests.py python/grass/temporal/testsuite/unittests_temporal_raster_algebra_equal_ts.py python/grass/temporal/testsuite/unittests_temporal_raster_conditionals_complement_else.py raster/r.in.lidar/testsuite/test_base_resolution.sh raster/r.in.pdal/testsuite/test_r_in_pdal_binning.py raster/r.in.pdal/testsuite/test_r_in_pdal_selection.py - raster/r.terraflow/testsuite/test_r_terraflow.py raster/r.sun/testsuite/test_rsun.py raster3d/r3.flow/testsuite/r3flow_test.py - scripts/g.search.modules/testsuite/test_g_search_modules.py - temporal/t.connect/testsuite/test_distr_tgis_db_raster3d.py temporal/t.connect/testsuite/test_distr_tgis_db_raster.py + temporal/t.connect/testsuite/test_distr_tgis_db_raster3d.py temporal/t.connect/testsuite/test_distr_tgis_db_vector.py temporal/t.info/testsuite/test.t.info.sh temporal/t.rast.aggregate/testsuite/test_aggregation_relative.py diff --git a/.github/workflows/macos_install.sh b/.github/workflows/macos_install.sh index 79446f51867..8a94bc15c6a 100755 --- a/.github/workflows/macos_install.sh +++ b/.github/workflows/macos_install.sh @@ -47,12 +47,8 @@ CONFIGURE_FLAGS="\ --with-bzlib-libs=${CONDA_PREFIX}/lib \ --with-bzlib-includes=${CONDA_PREFIX}/include \ --with-netcdf=${CONDA_PREFIX}/bin/nc-config \ - --with-blas \ - --with-blas-libs=${CONDA_PREFIX}/lib \ - --with-blas-includes=${CONDA_PREFIX}/include \ - --with-lapack - --with-lapack-includes=${CONDA_PREFIX}/include \ - --with-lapack-libs=${CONDA_PREFIX}/lib \ + --with-blas=openblas \ + --with-lapack=openblas \ --with-netcdf=${CONDA_PREFIX}/bin/nc-config \ --with-nls \ --with-libs=${CONDA_PREFIX}/lib \ diff --git a/.github/workflows/milestones.yml b/.github/workflows/milestones.yml new file mode 100644 index 00000000000..e2ade4eb091 --- /dev/null +++ b/.github/workflows/milestones.yml @@ -0,0 +1,70 @@ +--- +name: Assign Milestone + +on: + pull_request_target: + types: [closed] + +jobs: + assign-milestone: + runs-on: ubuntu-latest + if: github.event.pull_request.merged + steps: + # Retreiving the current milestoone from API instead of github context, + # so up-to-date information is used when running after being queued or for reruns + # Otherwise, the information should be available using + # ${{ github.event.pull_request.milestone.title }} + - name: Get current milestone title + id: current-milestone + run: | + echo "milestone<> "${GITHUB_OUTPUT}" + gh pr view ${{ github.event.pull_request.html_url }} --json milestone \ + --jq .milestone.title >> "${GITHUB_OUTPUT}" + echo 'EOF' >> "${GITHUB_OUTPUT}" + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + - name: PR already has a milestone + run: echo "PR already has a milestone" + if: ${{ steps.current-milestone.outputs.milestone }} + - name: PR does not have a milestone + run: echo "PR does not have a milestone" + if: ${{ !steps.current-milestone.outputs.milestone }} + - name: Get VERSION file + if: ${{ !steps.current-milestone.outputs.milestone }} + id: version-file + run: | + echo "version<> "${GITHUB_OUTPUT}" + gh api \ + -H "Accept: application/vnd.github.raw" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + "/repos/{owner}/{repo}/contents/include/VERSION?ref=${{ github.sha }}" >> "${GITHUB_OUTPUT}" + echo "EOF" >> "${GITHUB_OUTPUT}" + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + - name: Show version file + if: ${{ !steps.current-milestone.outputs.milestone }} + run: echo "${VERSIONFILE}" + env: + VERSIONFILE: ${{ steps.version-file.outputs.version }} + - name: Get milestone title from VERSION file + if: ${{ !steps.current-milestone.outputs.milestone }} + id: milestone + run: | + version=$(echo "$VERSIONFILE" | head -n 3 | xargs | sed 's/ /./g; s/\(RC[0-9]*\|dev\)//g') + echo "title=$version" >> "${GITHUB_OUTPUT}" + env: + VERSIONFILE: ${{ steps.version-file.outputs.version }} + - name: Show milestone title + if: ${{ !steps.current-milestone.outputs.milestone }} + run: echo "${MILESTONE}" + env: + MILESTONE: ${{ steps.milestone.outputs.title }} + - name: Set PR milestone + if: ${{ !steps.current-milestone.outputs.milestone }} + run: gh pr edit ${{ github.event.pull_request.html_url }} --milestone "${MILESTONE}" + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + MILESTONE: ${{ steps.milestone.outputs.title }} diff --git a/.github/workflows/osgeo4w.yml b/.github/workflows/osgeo4w.yml index 2f17427b05d..a7694fa9b30 100644 --- a/.github/workflows/osgeo4w.yml +++ b/.github/workflows/osgeo4w.yml @@ -31,7 +31,7 @@ jobs: run: | git config --global core.autocrlf false git config --global core.eol lf - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - uses: msys2/setup-msys2@ddf331adaebd714795f1042345e6ca57bd66cea8 # v2.24.1 with: path-type: inherit @@ -39,25 +39,44 @@ jobs: update: true msystem: MINGW64 install: tar libintl make bison flex diffutils git dos2unix zip mingw-w64-x86_64-toolchain - mingw-w64-x86_64-fftw mingw-w64-x86_64-lapack mingw-w64-x86_64-pkgconf + mingw-w64-x86_64-fftw mingw-w64-x86_64-openblas mingw-w64-x86_64-pkgconf mingw-w64-x86_64-gcc mingw-w64-x86_64-ccache mingw-w64-x86_64-zlib mingw-w64-x86_64-libiconv mingw-w64-x86_64-bzip2 mingw-w64-x86_64-gettext mingw-w64-x86_64-libsystre mingw-w64-x86_64-libtre-git mingw-w64-x86_64-libwinpthread-git mingw-w64-x86_64-libpng mingw-w64-x86_64-pcre - - name: Install OSGeo4W - run: | - $exe = 'osgeo4w-setup.exe' - $url = 'http://download.osgeo.org/osgeo4w/v2/' + $exe - (New-Object System.Net.WebClient).DownloadFile($url, $exe) - Start-Process ('.\'+$exe) -ArgumentList '-A -g -k -q \ - -s http://download.osgeo.org/osgeo4w/v2/ -P ${{ env.Deps }}' -Wait - env: - Deps: "proj-devel,gdal-devel,geos-devel,libtiff-devel,libpng-devel,\ - pdal-devel,netcdf-devel,cairo-devel,fftw,freetype-devel,gdal-ecw,\ - gdal-mrsid,liblas-devel,libxdr,libpq-devel,pdcurses,\ - python3-matplotlib,python3-numpy,python3-ply,python3-pywin32,\ - python3-wxpython,regex-devel,zstd-devel" + - name: Setup OSGeo4W environment + uses: echoix/setup-OSGeo4W@17deecd39e077a80bf1081443998ea8edd6f15bf # v0.1.0 + with: + package-dir: "D:/OSGeo4W_pkg" + packages: | + cairo-devel + fftw + freetype-devel + gdal-devel + gdal-ecw + gdal-mrsid + geos-devel + liblas-devel + libpng-devel + libpq-devel + libtiff-devel + libxdr + netcdf-devel + pdal-devel + pdcurses + proj-devel + python3-core + python3-jupyter + python3-matplotlib + python3-numpy + python3-pip + python3-ply + python3-pytest + python3-pywin32 + python3-wxpython + regex-devel + zstd-devel - name: Set number of cores for compilation run: | @@ -66,7 +85,10 @@ jobs: - name: Compile GRASS GIS shell: msys2 {0} - run: .github/workflows/build_osgeo4w.sh + run: | + export CFLAGS="${CFLAGS} -pipe" + export CXXFLAGS="${CXXFLAGS} -pipe" + .github/workflows/build_osgeo4w.sh - name: Print installed versions if: always() @@ -80,12 +102,25 @@ jobs: shell: msys2 {0} run: .github/workflows/test_simple.sh + - name: Install pytest plugins + run: python -m pip install pytest-timeout + shell: cmd /D /E:ON /V:OFF /S /C "CALL C:/OSGeo4W/OSGeo4W.bat "{0}"" + - name: Run pytest with a single worker + run: | + call %OSGEO4W_ROOT%\opt\grass\etc\env.bat + set PYTHONPATH=%GISBASE%\etc\python;%PYTHONPATH% + path %GISBASE%\lib;%GISBASE%\bin;%PATH% + pytest --verbose --color=yes ^ + --durations=0 --durations-min=0.5 ^ + -ra . + shell: cmd /D /E:ON /V:OFF /S /C "CALL C:/OSGeo4W/OSGeo4W.bat "{0}"" + - name: Run tests run: .github/workflows/test_thorough.bat 'C:\OSGeo4W\opt\grass\grass85.bat' 'C:\OSGeo4W\bin\python3' - name: Make HTML test report available if: ${{ always() }} - uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 with: name: testreport-${{ matrix.os }} path: testreport diff --git a/.github/workflows/osgeo4w_gunittest.cfg b/.github/workflows/osgeo4w_gunittest.cfg new file mode 100644 index 00000000000..b9252cf49ef --- /dev/null +++ b/.github/workflows/osgeo4w_gunittest.cfg @@ -0,0 +1,32 @@ +[gunittest] + +# Files (or wildcard patterns) to exclude from testing separated by newline or +# space. This would be ideally empty or it would include just special cases, +# but it includes mainly tests which can (and should) be fixed. +exclude = + gui/wxpython/core/testsuite/toolboxes.sh + lib/init/testsuite/test_grass_tmp_mapset.py + python/grass/gunittest/testsuite/test_gunitest_doctests.py + python/grass/pygrass/raster/testsuite/test_pygrass_raster_doctests.py + python/grass/pygrass/rpc/testsuite/test_pygrass_rpc_doctests.py + python/grass/script/testsuite/test_script_doctests.py + python/grass/temporal/testsuite/unittests_temporal_raster_conditionals_complement_else.py + temporal/t.info/testsuite/test.t.info.sh + temporal/t.rast.accdetect/testsuite/test.t.rast.accdetect.reverse.sh + temporal/t.rast.accdetect/testsuite/test.t.rast.accdetect.sh + temporal/t.rast.aggregate/testsuite/test_aggregation_relative.py + vector/v.edit/testsuite/select_all_flag.sh + vector/v.in.lidar/testsuite/decimation_test.py + vector/v.in.lidar/testsuite/mask_test.py + vector/v.in.lidar/testsuite/test_v_in_lidar_basic.py + vector/v.in.lidar/testsuite/test_v_in_lidar_filter.py + vector/v.what.rast3/testsuite/test.v.what.rast3.sh + vector/v.what/testsuite/test_vwhat_layers.py + vector/v.what/testsuite/test_vwhat_ncspm.py + +# Maximum time for execution of one test file (not a test function) +# after which test is terminated (which may not terminate child processes +# from that test). +# Using 5 minutes as maximum (average test time should be much shorter, +# couple seconds per file, median should be around one second). +timeout = 300 diff --git a/.github/workflows/periodic_update.yml b/.github/workflows/periodic_update.yml index 346fd12e2d2..17855d6149e 100644 --- a/.github/workflows/periodic_update.yml +++ b/.github/workflows/periodic_update.yml @@ -21,7 +21,7 @@ jobs: - name: Create URL to the run output id: vars run: echo "run-url=https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" >> $GITHUB_OUTPUT - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - name: "Check that autoconf scripts are up-to-date:" run: | rm -f config.guess config.sub @@ -33,7 +33,7 @@ jobs: run: git status --ignored - name: Create Pull Request id: cpr - uses: peter-evans/create-pull-request@8867c4aba1b742c39f8d0ba35429c2dfa4b6cb20 # v7.0.1 + uses: peter-evans/create-pull-request@5e914681df9dc83aa4e4905692ca88beb2f9e91f # v7.0.5 with: commit-message: "config.guess + config.sub: updated from http://git.savannah.gnu.org/cgit/config.git/plain/" branch: periodic/update-configure diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index 8e3b2286b1c..e1b3b84b54e 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -32,7 +32,7 @@ jobs: PYTHONWARNINGS: always steps: - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - name: Set up Python uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0 @@ -48,7 +48,7 @@ jobs: xargs -a <(awk '! /^ *(#|$)/' ".github/workflows/apt.txt") -r -- \ sudo apt-get install -y --no-install-recommends --no-install-suggests - - uses: rui314/setup-mold@0bf4f07ef9048ec62a45f9dbf2f098afa49695f0 # v1 + - uses: rui314/setup-mold@b015f7e3f2938ad3a5ed6e5111a8c6c7c1d6db6e # v1 - name: Install Python dependencies run: | @@ -83,8 +83,13 @@ jobs: run: | export PYTHONPATH=`grass --config python_path`:$PYTHONPATH export LD_LIBRARY_PATH=$(grass --config path)/lib:$LD_LIBRARY_PATH + export INITIAL_GISBASE="$(grass --config path)" + export INITIAL_PWD="${PWD}" pytest --verbose --color=yes --durations=0 --durations-min=0.5 \ - --numprocesses auto -ra . \ + --numprocesses auto \ + --cov \ + --cov-context=test \ + -ra . \ -m 'not needs_solo_run' - name: Run pytest with a single worker (for tests marked with needs_solo_run) @@ -92,9 +97,11 @@ jobs: export PYTHONPATH=`grass --config python_path`:$PYTHONPATH export LD_LIBRARY_PATH=$(grass --config path)/lib:$LD_LIBRARY_PATH export INITIAL_GISBASE="$(grass --config path)" - INITIAL_PWD="${PWD}" pytest --verbose --color=yes --durations=0 --durations-min=0.5 \ + export INITIAL_PWD="${PWD}" + pytest --verbose --color=yes --durations=0 --durations-min=0.5 \ --cov \ --cov-context=test \ + --cov-append \ -ra . \ -m 'needs_solo_run' - name: Fix non-standard installed script paths in coverage data @@ -108,7 +115,7 @@ jobs: coverage html - name: Upload coverage reports to Codecov - uses: codecov/codecov-action@e28ff129e5465c2c0dcc6f003fc735cb6ae0c673 # v4.5.0 + uses: codecov/codecov-action@b9fd7d16f6d7d1b5d2bec1a2887e65ceed900238 # v4.6.0 with: verbose: true flags: pytest-python-${{ matrix.python-version }} @@ -116,7 +123,7 @@ jobs: token: ${{ secrets.CODECOV_TOKEN }} - name: Make python-only code coverage test report available if: ${{ !cancelled() }} - uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 with: name: python-codecoverage-report-${{ matrix.os }}-${{ matrix.python-version }} path: coverage_html_report diff --git a/.github/workflows/python-code-quality.yml b/.github/workflows/python-code-quality.yml index caa530e3b39..886cbe56b47 100644 --- a/.github/workflows/python-code-quality.yml +++ b/.github/workflows/python-code-quality.yml @@ -28,15 +28,15 @@ jobs: PYTHON_VERSION: "3.10" MIN_PYTHON_VERSION: "3.8" # renovate: datasource=pypi depName=black - BLACK_VERSION: "24.8.0" + BLACK_VERSION: "24.10.0" # renovate: datasource=pypi depName=flake8 FLAKE8_VERSION: "7.1.1" # renovate: datasource=pypi depName=pylint PYLINT_VERSION: "2.12.2" # renovate: datasource=pypi depName=bandit - BANDIT_VERSION: "1.7.9" + BANDIT_VERSION: "1.7.10" # renovate: datasource=pypi depName=ruff - RUFF_VERSION: "0.6.3" + RUFF_VERSION: "0.6.9" runs-on: ${{ matrix.os }} permissions: @@ -54,7 +54,7 @@ jobs: echo Bandit: ${{ env.BANDIT_VERSION }} echo Ruff: ${{ env.RUFF_VERSION }} - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - name: Set up Python uses: actions/setup-python@f677139bbe7f9c59b41e40162b753c062f5d49a3 # v5.2.0 @@ -129,13 +129,13 @@ jobs: bandit -c pyproject.toml -iii -r . -f sarif -o bandit.sarif --exit-zero - name: Upload Bandit Scan Results - uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 with: name: bandit.sarif path: bandit.sarif - name: Upload SARIF File into Security Tab - uses: github/codeql-action/upload-sarif@4dd16135b69a43b6c8efb853346f8437d92d3c93 # v3.26.6 + uses: github/codeql-action/upload-sarif@f779452ac5af1c261dce0346a8f964149f49322b # v3.26.13 with: sarif_file: bandit.sarif @@ -147,7 +147,7 @@ jobs: run: | echo "MAKEFLAGS=-j$(nproc)" >> $GITHUB_ENV - - uses: rui314/setup-mold@0bf4f07ef9048ec62a45f9dbf2f098afa49695f0 # v1 + - uses: rui314/setup-mold@b015f7e3f2938ad3a5ed6e5111a8c6c7c1d6db6e # v1 - name: Build run: .github/workflows/build_${{ matrix.os }}.sh $HOME/install @@ -201,7 +201,7 @@ jobs: cp -rp dist.$ARCH/docs/html/libpython sphinx-grass - name: Make Sphinx documentation available - uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 with: name: sphinx-grass path: sphinx-grass diff --git a/.github/workflows/super-linter.yml b/.github/workflows/super-linter.yml index 44da8d9acb7..62328723f77 100644 --- a/.github/workflows/super-linter.yml +++ b/.github/workflows/super-linter.yml @@ -25,7 +25,7 @@ jobs: statuses: write steps: - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 with: # super-linter needs the full git history to get the # list of files that changed across commits diff --git a/.github/workflows/test-nix.yml b/.github/workflows/test-nix.yml index a73ac835414..ba14e0747ab 100644 --- a/.github/workflows/test-nix.yml +++ b/.github/workflows/test-nix.yml @@ -28,10 +28,10 @@ jobs: contents: read steps: - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - name: Install nix - uses: DeterminateSystems/nix-installer-action@ab6bcb2d5af0e904d04aea750e2089e9dc4cbfdd # v13 + uses: DeterminateSystems/nix-installer-action@da36cb69b1c3247ad7a1f931ebfd954a1105ef14 # v14 - name: Setup cachix uses: cachix/cachix-action@ad2ddac53f961de1989924296a1f236fcfbaa4fc # v15 diff --git a/.github/workflows/test_thorough.bat b/.github/workflows/test_thorough.bat index 963f24b9b43..843adb4c4f0 100644 --- a/.github/workflows/test_thorough.bat +++ b/.github/workflows/test_thorough.bat @@ -2,4 +2,4 @@ set grass=%1 set python=%2 call %grass% --tmp-project XY --exec g.download.project url=https://grass.osgeo.org/sampledata/north_carolina/nc_spm_full_v2alpha2.tar.gz path=%USERPROFILE% -call %grass% --tmp-project XY --exec %python% -m grass.gunittest.main --grassdata %USERPROFILE% --location nc_spm_full_v2alpha2 --location-type nc --min-success 80 +call %grass% --tmp-project XY --exec %python% -m grass.gunittest.main --grassdata %USERPROFILE% --location nc_spm_full_v2alpha2 --location-type nc --min-success 96 --config .github\workflows\osgeo4w_gunittest.cfg diff --git a/.github/workflows/titles.yml b/.github/workflows/titles.yml index b8e33c2fb37..f202fdafe02 100644 --- a/.github/workflows/titles.yml +++ b/.github/workflows/titles.yml @@ -21,7 +21,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout base repository (doesn't include the PR changes) - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - name: Call PR title validation function run: python utils/generate_release_notes.py check "${PR_TITLE}" "" "" env: diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index 57b0821eec4..966dbfe21ab 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -59,7 +59,7 @@ jobs: fail-fast: false steps: - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 + - uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4.2.1 - name: Invert inclusion list to an exclusion list id: get-exclude @@ -149,7 +149,7 @@ jobs: - name: Make HTML test report available if: ${{ always() }} - uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 # v4.4.0 + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 with: name: testreport-${{ matrix.os }}-${{ matrix.config }}-${{ matrix.extra-include }} path: testreport diff --git a/.gunittest.cfg b/.gunittest.cfg index 01b06c78913..2117fde9d7a 100644 --- a/.gunittest.cfg +++ b/.gunittest.cfg @@ -4,21 +4,14 @@ # space. This would be ideally empty or it would include just special cases, # but it includes mainly tests which can (and should) be fixed. exclude = - gui/wxpython/core/testsuite/test_gcmd.py gui/wxpython/core/testsuite/toolboxes.sh - lib/init/testsuite/test_grass_tmp_mapset.py - python/grass/gunittest/testsuite/test_assertions_rast3d.py python/grass/gunittest/testsuite/test_assertions_vect.py - python/grass/gunittest/testsuite/test_gmodules.py python/grass/gunittest/testsuite/test_gunitest_doctests.py python/grass/pygrass/raster/testsuite/test_pygrass_raster_doctests.py python/grass/pygrass/rpc/testsuite/test_pygrass_rpc_doctests.py - python/grass/script/testsuite/test_script_doctests.py python/grass/temporal/testsuite/unittests_temporal_raster_algebra_equal_ts.py python/grass/temporal/testsuite/unittests_temporal_raster_conditionals_complement_else.py raster/r.in.lidar/testsuite/test_base_resolution.sh - raster/r.in.lidar/testsuite/test_base_resolution.sh - scripts/g.search.modules/testsuite/test_g_search_modules.py temporal/t.connect/testsuite/test_distr_tgis_db_raster3d.py temporal/t.connect/testsuite/test_distr_tgis_db_raster.py temporal/t.connect/testsuite/test_distr_tgis_db_vector.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f12fde12473..2c136da40ff 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,7 +3,7 @@ ci: skip: [flake8] repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.6.0 + rev: v5.0.0 hooks: - id: trailing-whitespace exclude: | @@ -37,18 +37,18 @@ repos: ) - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.6.3 + rev: v0.6.9 hooks: # Run the linter. - id: ruff args: [--fix, --preview] - repo: https://github.com/igorshubovych/markdownlint-cli - rev: v0.41.0 + rev: v0.42.0 hooks: - id: markdownlint-fix # Using this mirror lets us use mypyc-compiled black, which is about 2x faster - repo: https://github.com/psf/black-pre-commit-mirror - rev: 24.8.0 + rev: 24.10.0 hooks: - id: black-jupyter exclude: | diff --git a/CHANGES b/CHANGES deleted file mode 100644 index d4c8280bc7b..00000000000 --- a/CHANGES +++ /dev/null @@ -1,10 +0,0 @@ -CHANGES in GRASS GIS 8.x - -https://trac.osgeo.org/grass/wiki/Grass8/NewFeatures80 -https://trac.osgeo.org/grass/wiki/Grass8/NewFeatures82 - -List of releases: - -- GitHub list: https://github.com/OSGeo/grass/releases -- Overview list: https://trac.osgeo.org/grass/wiki/Release -- History: https://grass.osgeo.org/home/history/releases/ (starting 1984!) diff --git a/Dockerfile b/Dockerfile index 23bf11ddf27..41fb3264c07 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,11 @@ -# syntax=docker/dockerfile:1.9@sha256:fe40cf4e92cd0c467be2cfc30657a680ae2398318afd50b0c80585784c604f28 +# syntax=docker/dockerfile:1.10@sha256:865e5dd094beca432e8c0a1d5e1c465db5f998dca4e439981029b3b81fb39ed5 # Note: This file must be kept in sync in ./Dockerfile and ./docker/ubuntu/Dockerfile. # Changes to this file must be copied over to the other file. ARG GUI=without -FROM ubuntu:22.04@sha256:adbb90115a21969d2fe6fa7f9af4253e16d45f8d4c1e930182610c4731962658 as common_start +FROM ubuntu:22.04@sha256:58b87898e82351c6cf9cf5b9f3c20257bb9e2dcf33af051e12ce532d7f94e3fe as common_start LABEL authors="Carmen Tawalika,Markus Neteler,Anika Weinmann,Stefan Blumentrath" LABEL maintainer="tawalika@mundialis.de,neteler@mundialis.de,weinmann@mundialis.de" @@ -19,8 +19,9 @@ WORKDIR /tmp ARG GUI # Todo: re-consider required dev packages for addons (~400MB in dev packages) -ARG GRASS_RUN_PACKAGES="build-essential \ +ARG GRASS_RUN_PACKAGES="\ bison \ + build-essential \ bzip2 \ curl \ flex \ @@ -28,8 +29,6 @@ ARG GRASS_RUN_PACKAGES="build-essential \ gcc \ gdal-bin \ geos-bin \ - proj-bin \ - netcdf-bin \ git \ language-pack-en-base \ libcairo2 \ @@ -38,28 +37,29 @@ ARG GRASS_RUN_PACKAGES="build-essential \ libfftw3-dev \ libfreetype6 \ libgdal-dev \ + libgeos-dev \ + libgsl-dev \ libgsl27 \ libjpeg-turbo8 \ libjsoncpp-dev \ - libmagic1 \ + liblapacke-dev \ libmagic-mgc \ + libmagic1 \ libncurses5 \ - libopenblas-dev \ + libomp-dev \ + libomp5 \ libopenblas-base \ + libopenblas-dev \ libopenjp2-7 \ - libomp5 \ - libomp-dev \ - libgeos-dev \ - libpdal-dev \ - libproj-dev \ - libpq-dev \ - libgsl-dev \ libpdal-base13 \ + libpdal-dev \ libpdal-plugin-hdf \ libpdal-plugins \ libpdal-util13 \ libpnglite0 \ + libpq-dev \ libpq5 \ + libproj-dev \ libpython3-all-dev \ libreadline8 \ libsqlite3-0 \ @@ -70,7 +70,9 @@ ARG GRASS_RUN_PACKAGES="build-essential \ mesa-utils \ moreutils \ ncurses-bin \ + netcdf-bin \ pdal \ + proj-bin \ proj-data \ python-is-python3 \ python3 \ @@ -86,56 +88,58 @@ ARG GRASS_RUN_PACKAGES="build-essential \ ENV GRASS_RUN_PACKAGES=${GRASS_RUN_PACKAGES} # Define build packages -ARG GRASS_BUILD_PACKAGES="cmake \ +ARG GRASS_BUILD_PACKAGES="\ + cmake \ libbz2-dev \ libcairo2-dev \ libfreetype6-dev \ - zlib1g-dev \ + libjpeg-dev \ + libncurses5-dev \ libnetcdf-dev \ libopenjp2-7-dev \ - libreadline-dev \ - libjpeg-dev \ libpnglite-dev \ + libreadline-dev \ libsqlite3-dev \ libtiff-dev \ libzstd-dev \ - libncurses5-dev \ mesa-common-dev \ zlib1g-dev \ " ENV GRASS_BUILD_PACKAGES=${GRASS_BUILD_PACKAGES} -ARG GRASS_CONFIG="--with-cxx \ +ARG GRASS_CONFIG="\ --enable-largefile \ - --with-proj-share=/usr/share/proj \ - --with-gdal=/usr/bin/gdal-config \ - --with-geos \ - --with-sqlite \ + --with-blas \ + --with-bzlib \ --with-cairo --with-cairo-ldflags=-lfontconfig \ - --with-freetype --with-freetype-includes=/usr/include/freetype2/ \ + --with-cxx \ --with-fftw \ - --with-postgres --with-postgres-includes=/usr/include/postgresql \ - --with-netcdf \ - --with-zstd \ - --with-bzlib \ - --with-pdal \ - --without-mysql \ - --with-blas \ + --with-freetype --with-freetype-includes=/usr/include/freetype2/ \ + --with-gdal=/usr/bin/gdal-config \ + --with-geos \ --with-lapack \ - --with-readline \ + --with-netcdf \ --with-odbc \ --with-openmp \ + --with-pdal \ + --with-postgres --with-postgres-includes=/usr/include/postgresql \ + --with-proj-share=/usr/share/proj \ + --with-readline \ + --with-sqlite \ + --with-zstd \ + --without-mysql \ " -ARG GRASS_PYTHON_PACKAGES="pip \ - setuptools \ - python-dateutil \ - python-magic \ - numpy \ +ARG GRASS_PYTHON_PACKAGES="\ Pillow \ - ply \ matplotlib \ + numpy \ + pip \ + ply \ psycopg2 \ + python-dateutil \ + python-magic \ + setuptools \ " ENV GRASS_PYTHON_PACKAGES=${GRASS_PYTHON_PACKAGES} @@ -147,31 +151,33 @@ ENV GRASS_CONFIG=${GRASS_CONFIG} FROM common_start as grass_with_gui -ARG GRASS_RUN_PACKAGES="${GRASS_RUN_PACKAGES} adwaita-icon-theme-full \ - libglu1-mesa \ - libgtk-3-0 \ - libnotify4 \ - libsdl2-2.0-0 \ - libxtst6 \ - librsvg2-common \ - gettext \ +ARG GRASS_RUN_PACKAGES="${GRASS_RUN_PACKAGES} \ + adwaita-icon-theme-full \ freeglut3 \ + gettext \ + libglu1-mesa \ libgstreamer-plugins-base1.0 \ + libgtk-3-0 \ libjpeg8 \ + libnotify4 \ libpng16-16 \ + librsvg2-common \ + libsdl2-2.0-0 \ libsm6 \ libtiff5 \ libwebkit2gtk-4.0 \ + libxtst6 \ " # librsvg2-common \ # (fix error (wxgui.py:7782): Gtk-WARNING **: 19:53:09.774: # Could not load a pixbuf from /org/gtk/libgtk/theme/Adwaita/assets/check-symbolic.svg. # This may indicate that pixbuf loaders or the mime database could not be found.) -ARG GRASS_BUILD_PACKAGES="${GRASS_BUILD_PACKAGES} adwaita-icon-theme-full \ +ARG GRASS_BUILD_PACKAGES="${GRASS_BUILD_PACKAGES} \ + adwaita-icon-theme-full \ + freeglut3-dev \ libgl1-mesa-dev \ libglu1-mesa-dev \ - freeglut3-dev \ libgstreamer-plugins-base1.0-dev \ libgtk-3-dev \ libjpeg-dev \ @@ -184,10 +190,11 @@ ARG GRASS_BUILD_PACKAGES="${GRASS_BUILD_PACKAGES} adwaita-icon-theme-full \ libxtst-dev \ " -ARG GRASS_CONFIG="${GRASS_CONFIG} --with-opengl \ - --with-x \ +ARG GRASS_CONFIG="${GRASS_CONFIG} \ --with-nls \ + --with-opengl \ --with-readline \ + --with-x \ " ARG GRASS_PYTHON_PACKAGES="${GRASS_PYTHON_PACKAGES} wxPython" # If you do not use any Gnome Accessibility features, to suppress warning diff --git a/INSTALL.md b/INSTALL.md index e6bd041fcf9..7687266d7c8 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -29,8 +29,8 @@ directory. Installation order: 1. PROJ -2. GDAL-OGR (compiled without GRASS support) -3. optionally: databases such as PostgreSQL, MySQL, sqlite +2. GDAL/OGR (compiled without GRASS support) +3. optionally: databases such as PostgreSQL, MySQL, SQLite 4. GRASS GIS 5. optionally: GDAL-OGR-GRASS plugin @@ -41,7 +41,7 @@ GRASS source code is currently distributed in 2 forms: ### Officially released source code The full source code version contains all the GRASS source code -required for compilation. It is distributed as one file (*.tar.gz +required for compilation. It is distributed as one file (`*.tar.gz` package) and the version is composed of 3 numbers, e.g. 3.7.0, 3.7.1 etc. See . @@ -52,7 +52,7 @@ This version of the source code can be acquired either from the GitHub repository () or as a auto-generated snapshot (`*.tar.gz` package) of the GitHub repository. The snapshot name contains the date when the snapshot was created (checked out from -the GitHub repository), e.g. grass-3.7.git_src_snapshot_2022_04_27.tar.gz +the GitHub repository), e.g. `grass-3.7.git_src_snapshot_2022_04_27.tar.gz` from ## (B) COMPILATION @@ -72,7 +72,7 @@ Detailed Wiki notes for various operating systems (MS-Windows, GNU/Linux distributions, FreeBSD, AIX, etc) are available at: -First step of the compilation (-g for debugging, or -O2 for optimization): +First step of the compilation (`-g` for debugging, or `-O2` for optimization): ```bash CFLAGS="-g -Wall" ./configure @@ -108,7 +108,7 @@ make Note for Solaris users (see also Wiki page above): To configure GRASS correctly on a system which doesn't have a suitable -install program (AC_PROG_INSTALL ignores versions which are known to +install program (`AC_PROG_INSTALL` ignores versions which are known to have problems), you need to ensure that $srcdir is an absolute path, by using e.g.: @@ -136,7 +136,7 @@ CC=cc CPP=cpp ./configure ... ## (C) COMPILATION NOTES for 64bit platforms To successfully compile GRASS on 64bit platforms, the required -FFTW2 library has to be compiled with -fPIC flag: +FFTW library has to be compiled with `-fPIC` flag: ```bash #this applies to FFTW3, not to GRASS GIS: @@ -151,13 +151,13 @@ make install After compilation, the resulting code is stored in the directory ```bash -./dist.$ARCH +./dist.$ARCH/ ``` -and the scripts (grass, ...) in +and the script (`grass`) in ```bash -./bin.$ARCH +./bin.$ARCH/ ``` To run GRASS, simply start @@ -175,7 +175,7 @@ grass ## (E) INSTALLATION ON MACOSX -See the ReadMe.rtf in the ./macosx/ folder and the Wiki page above. +See the `ReadMe.rtf` in the `./macosx/` folder and the Wiki page above. ## (F) RUNNING GRASS GIS @@ -206,7 +206,7 @@ make make install ``` -For details, see +For details, see [Guide to contributing on GitHub](./doc/development/github_guide.md). ## (H) COMPILING INDIVIDUAL MODULES - OWN MODULES @@ -240,7 +240,7 @@ gmake Note: If you keep your module source code outside the standard GRASS source code directory structure, you will have to change the relative -path(s) in the Makefile to absolute path(s). +path(s) in the `Makefile` to absolute path(s). ## (I) CODE OPTIMIZATION @@ -258,8 +258,8 @@ setenv CFLAGS -O ./configure ``` -whichever works on your shell. Use -O2 instead of -O if your compiler -supports this (note: O is the letter, not zero). Using the "gcc" compiler, +whichever works on your shell. Use `-O2` instead of `-O` if your compiler +supports this (note: `O` is the letter, not zero). Using the "gcc" compiler, you can also specify processor specific flags (examples, please suggest better settings to us): @@ -272,11 +272,11 @@ CFLAGS="-O2 -msse -msse2 -mfpmath=sse \ CFLAGS="-mtune=nocona -m64 -minline-all-stringops" # Intel Pentium 64bit processor ``` -Note: As of version 4.3.0, GCC offers the -march=native switch that +Note: As of version 4.3.0, GCC offers the `-march=native` switch that enables CPU auto-detection and automatically selects optimizations supported -by the local machine at GCC runtime including -mtune. +by the local machine at GCC runtime including `-mtune`. -To find out optional CFLAGS for your platform, enter: +To find out optional `CFLAGS` for your platform, enter: ```bash gcc -dumpspecs @@ -285,7 +285,7 @@ gcc -dumpspecs See also: A real fast GRASS version (and small binaries) will be created with -LDFLAGS set to "stripping" (but this disables debugging): +`LDFLAGS` set to "stripping" (but this disables debugging): ```bash CFLAGS="-O2 -mcpu= -Wall" LDFLAGS="-s" ./configure @@ -296,7 +296,7 @@ CFLAGS="-O2 -mcpu= -Wall" LDFLAGS="-s" ./configure The `LDFLAGS=""` part must be undefined as `-s` will strip the debugging information. -Don't use `-O` for CFLAGS if you want to be able to step through function +Don't use `-O` for `CFLAGS` if you want to be able to step through function bodies. When optimisation is enabled, the compiler will re-order statements and re-arrange expressions, resulting in object code which barely resembles the source code. @@ -307,7 +307,7 @@ The `-g` and `-Wall` compiler flags are often useful for assisting debugging: CFLAGS="-g -Wall" ./configure ``` -See also the file ./doc/debugging.txt and the Wiki page +See also the file `./doc/debugging.txt` and the Wiki page ## (K) SUPPORT @@ -321,14 +321,42 @@ developers mailing list. See ## (L) GRASS PROGRAMMER'S MANUAL -The Programmer's manual is generated with doxygen from the source code. -Please see the README file and the files at: - +The Programmer's manual is +generated from the source code. This requires the installation of +`doxygen` () and optionally Graphviz `dot` +(). + +The main file is: `./grasslib.dox` where all sub-documents have +to be linked to. + +To locally generate the 'Programmer's Manual', run + +```sh +make htmldocs +``` + +To generate documentation as a single html file +(recommended for simple reading) + +```sh +make htmldocs-single +``` + +This process takes some time. The result will be found in +the file `lib/html/index.html`. + +To generate the 'Programmer's Manual' in PDF format, run + +```sh +make pdfdocs +``` ## (M) CONTRIBUTING CODE AND PATCHES -Please see ./SUBMITTING in this directory, or better, - +Please see + +- [GRASS Programming Style Guide](./doc/development/style_guide.md) +- [Guide to contributing on GitHub](./doc/development/github_guide.md) ## Authors diff --git a/Makefile b/Makefile index be8834ecf42..8b32a149a5a 100644 --- a/Makefile +++ b/Makefile @@ -51,7 +51,7 @@ DIRS = \ SUBDIRS = $(DIRS) -FILES = AUTHORS CHANGES CITING COPYING GPL.TXT INSTALL.md REQUIREMENTS.md contributors.csv contributors_extra.csv translators.csv +FILES = AUTHORS CITING COPYING GPL.TXT INSTALL.md REQUIREMENTS.md contributors.csv contributors_extra.csv translators.csv FILES_DST = $(patsubst %,$(ARCH_DISTDIR)/%,$(FILES)) default: diff --git a/NEWS b/NEWS deleted file mode 100644 index 32b4cd52110..00000000000 --- a/NEWS +++ /dev/null @@ -1,18 +0,0 @@ -NEWS - -GRASS GIS 8 - o https://trac.osgeo.org/grass/wiki/Grass8/NewFeatures80 - o https://trac.osgeo.org/grass/wiki/Grass8/NewFeatures82 - -GRASS GIS 7 - o https://trac.osgeo.org/grass/wiki/Grass7/NewFeatures78 - o https://trac.osgeo.org/grass/wiki/Grass7/NewFeatures76 - o https://trac.osgeo.org/grass/wiki/Grass7/NewFeatures74 - o https://trac.osgeo.org/grass/wiki/Grass7/NewFeatures72 - o https://trac.osgeo.org/grass/wiki/Grass7/NewFeatures - - List of releases - o https://trac.osgeo.org/grass/wiki/Release - -GRASS GIS 1-6 - o List of older releases, starting in 1984 (!), see https://grass.osgeo.org/about/history/releases/ diff --git a/README.md b/README.md index b10bd51ec03..7dfdb49df82 100644 --- a/README.md +++ b/README.md @@ -31,11 +31,6 @@ In general: you don't really need write access as you can simply open a [pull request](https://github.com/OSGeo/grass/pulls) to contribute to GRASS GIS. See [CONTRIBUTING file](CONTRIBUTING.md) for more details. -How to get write access here - -Want to become a core developer? See -[Procedure for gaining Git write access](https://trac.osgeo.org/grass/wiki/HowToContribute#WriteaccesstotheGRASScorerepository) - ## How to compile GRASS > See the INSTALL.md file. @@ -111,6 +106,11 @@ this issue, clean all the compiled files from the source code: make distclean ``` +## Further documents + +- [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md) +- [Roadmap](https://grass.osgeo.org/about/roadmap/) + ## Thanks to all contributors ❤ [![GRASS contributors](https://contrib.rocks/image?repo=OSGeo/grass "GRASS contributors")](https://github.com/OSGeo/grass/graphs/contributors) diff --git a/SECURITY.md b/SECURITY.md index feef9649806..0b566dc899d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -25,7 +25,7 @@ vulnerability, please follow these steps: ## Supported Versions -Please refer to our [Release Schedule](https://trac.osgeo.org/grass/wiki/Release/Schedule) +Please refer to our [download section](https://grass.osgeo.org/download/) for details on which versions are currently supported. ## Security Measures diff --git a/configure b/configure index 7d8b9b1e5e7..56b203e0c13 100755 --- a/configure +++ b/configure @@ -666,10 +666,6 @@ USE_PTHREAD PTHREADLIB PTHREADLIBPATH PTHREADINCPATH -USE_OPENDWG -OPENDWGLIB -OPENDWGLIBPATH -OPENDWGINCPATH HAVE_NLS INTLLIB FTLIB @@ -765,8 +761,9 @@ SOCKLIB ICONVLIB DLLIB MATHLIB -HAVE_ASPRINTF HAVE_STRLCPY +HAVE_STRLCAT +HAVE_ASPRINTF DBMIEXTRALIB USE_X11 XTLIB @@ -904,14 +901,11 @@ with_sqlite with_opengl with_odbc with_fftw -with_blas -with_lapack with_libsvm with_cairo with_freetype with_nls with_readline -with_opendwg with_regex with_pthread with_openmp @@ -919,6 +913,8 @@ with_opencl with_bzlib with_zstd with_pdal +with_blas +with_lapack with_libpng with_gdal with_liblas @@ -949,10 +945,6 @@ with_odbc_includes with_odbc_libs with_fftw_includes with_fftw_libs -with_blas_includes -with_blas_libs -with_lapack_includes -with_lapack_libs with_libsvm_includes with_libsvm_libs with_cairo_includes @@ -963,8 +955,6 @@ with_freetype_libs with_proj_includes with_proj_libs with_proj_share -with_opendwg_includes -with_opendwg_libs with_regex_includes with_regex_libs with_pthread_includes @@ -1639,14 +1629,11 @@ Optional Packages: --with-opengl support OpenGL functionality (default: yes) --with-odbc support ODBC functionality (default: no) --with-fftw support FFTW functionality (default: yes) - --with-blas support BLAS functionality (default: no) - --with-lapack support LAPACK functionality (default: no) --with-libsvm support LIBSVM functionality (default: no) --with-cairo support Cairo functionality (default: yes) --with-freetype support FreeType functionality (default: yes) --with-nls support NLS functionality (default: no) --with-readline support Readline functionality (default: no) - --with-opendwg support openDWG functionality (default: no) --with-regex support regex functionality (default: yes) --with-pthread support POSIX threads functionality (default: no) --with-openmp support OpenMP functionality (default: no) @@ -1654,6 +1641,14 @@ Optional Packages: --with-bzlib support BZIP2 functionality (default: no) --with-zstd support Zstandard functionality (default: yes) --with-pdal support PDAL functionality (default: yes) + --with-blas=pkg-config-package + enable BLAS support with by adding name of + pkg-config package name for CBLAS library, e.g. + '--with-lapack-package=openblas', default: cblas + --with-lapack=pkg-config-package + enable LAPACK support with by adding name of + pkg-config package name for LAPACKE library, e.g. + '--with-lapack-package=openblas', default: lapacke --with-libpng=path/libpng-config enable PNG support (libpng-config with path, e.g. '--with-libpng=/usr/local/bin/libpng-config') @@ -1711,12 +1706,6 @@ Optional Packages: --with-fftw-includes=DIRS FFTW include files are in DIRS --with-fftw-libs=DIRS FFTW library files are in DIRS - --with-blas-includes=DIRS - BLAS include files are in DIRS - --with-blas-libs=DIRS BLAS library files are in DIRS - --with-lapack-includes=DIRS - LAPACK include files are in DIRS - --with-lapack-libs=DIRS LAPACK library files are in DIRS --with-libsvm-includes=DIRS LIBSVM include files are in DIRS --with-libsvm-libs=DIRS LIBSVM library files are in DIRS @@ -1733,10 +1722,6 @@ Optional Packages: External PROJ.4 include files are in DIRS --with-proj-libs=DIRS External PROJ.4 library files are in DIRS --with-proj-share=DIR External PROJ.4 data files are in DIR - --with-opendwg-includes=DIRS - openDWG include files are in DIRS - --with-opendwg-libs=DIRS - openDWG library files are in DIRS --with-regex-includes=DIRS regex include files are in DIRS --with-regex-libs=DIRS regex library files are in DIRS @@ -5488,28 +5473,6 @@ fi -# Check whether --with-blas was given. -if test ${with_blas+y} -then : - withval=$with_blas; -else $as_nop - with_blas=no -fi - - - - -# Check whether --with-lapack was given. -if test ${with_lapack+y} -then : - withval=$with_lapack; -else $as_nop - with_lapack=no -fi - - - - # Check whether --with-libsvm was given. if test ${with_libsvm+y} then : @@ -5565,17 +5528,6 @@ fi -# Check whether --with-opendwg was given. -if test ${with_opendwg+y} -then : - withval=$with_opendwg; -else $as_nop - with_opendwg=no -fi - - - - # Check whether --with-regex was given. if test ${with_regex+y} then : @@ -5653,6 +5605,27 @@ fi + +# Check whether --with-blas was given. +if test ${with_blas+y} +then : + withval=$with_blas; +else $as_nop + with_blas=no +fi + + + +# Check whether --with-lapack was given. +if test ${with_lapack+y} +then : + withval=$with_lapack; +else $as_nop + with_lapack=no +fi + + + # Check whether --with-libpng was given. if test ${with_libpng+y} then : @@ -5936,44 +5909,6 @@ fi -# Check whether --with-blas-includes was given. -if test ${with_blas_includes+y} -then : - withval=$with_blas_includes; -fi - - - - -# Check whether --with-blas-libs was given. -if test ${with_blas_libs+y} -then : - withval=$with_blas_libs; -fi - - - - - -# Check whether --with-lapack-includes was given. -if test ${with_lapack_includes+y} -then : - withval=$with_lapack_includes; -fi - - - - -# Check whether --with-lapack-libs was given. -if test ${with_lapack_libs+y} -then : - withval=$with_lapack_libs; -fi - - - - - # Check whether --with-libsvm-includes was given. if test ${with_libsvm_includes+y} then : @@ -6068,25 +6003,6 @@ fi -# Check whether --with-opendwg-includes was given. -if test ${with_opendwg_includes+y} -then : - withval=$with_opendwg_includes; -fi - - - - -# Check whether --with-opendwg-libs was given. -if test ${with_opendwg_libs+y} -then : - withval=$with_opendwg_libs; -fi - - - - - # Check whether --with-regex-includes was given. if test ${with_regex_includes+y} then : @@ -6940,18 +6856,6 @@ if test "x$ac_cv_header_values_h" = xyes then : printf "%s\n" "#define HAVE_VALUES_H 1" >>confdefs.h -fi -ac_fn_c_check_header_compile "$LINENO" "f2c.h" "ac_cv_header_f2c_h" "$ac_includes_default" -if test "x$ac_cv_header_f2c_h" = xyes -then : - printf "%s\n" "#define HAVE_F2C_H 1" >>confdefs.h - -fi -ac_fn_c_check_header_compile "$LINENO" "g2c.h" "ac_cv_header_g2c_h" "$ac_includes_default" -if test "x$ac_cv_header_g2c_h" = xyes -then : - printf "%s\n" "#define HAVE_G2C_H 1" >>confdefs.h - fi ac_fn_c_check_header_compile "$LINENO" "sys/ioctl.h" "ac_cv_header_sys_ioctl_h" "$ac_includes_default" @@ -8312,6 +8216,19 @@ then : fi + + +ac_fn_c_check_func "$LINENO" "strlcat" "ac_cv_func_strlcat" +if test "x$ac_cv_func_strlcat" = xyes +then : + printf "%s\n" "#define HAVE_STRLCAT 1" >>confdefs.h + +fi + + + +# Test if strlcpy exists +# This is a function part of *BSD libc (optionally available on Linux via libbsd) ac_fn_c_check_func "$LINENO" "strlcpy" "ac_cv_func_strlcpy" if test "x$ac_cv_func_strlcpy" = xyes then : @@ -8320,6 +8237,7 @@ then : fi + # Test if mathlib needs -lm flag or is included with libc ac_fn_c_check_func "$LINENO" "atan" "ac_cv_func_atan" if test "x$ac_cv_func_atan" = xyes @@ -13786,827 +13704,220 @@ fi # $USE_FFTW # Enable BLAS option - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to use BLAS" >&5 -printf %s "checking whether to use BLAS... " >&6; } -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: \"$with_blas\"" >&5 -printf "%s\n" "\"$with_blas\"" >&6; } -case "$with_blas" in - "no") USE_BLAS= ;; - "yes") USE_BLAS="1" ;; - *) as_fn_error $? "*** You must answer yes or no." "$LINENO" 5 ;; -esac - - +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to use (C)BLAS" >&5 +printf %s "checking whether to use (C)BLAS... " >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_blas" >&5 +printf "%s\n" "$with_blas" >&6; } BLASLIB= BLASINC= +USE_BLAS= +BLAS_PKGS="cblas blas-netlib openblas blas-atlas" +BLAS_PKG= -if test -n "$USE_BLAS"; then - -# With BLAS includes directory -# BLAS doesn't have includes (FORTRAN library) -# With BLAS library directory - - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for location of BLAS includes" >&5 -printf %s "checking for location of BLAS includes... " >&6; } -case "$with_blas_includes" in -y | ye | yes | n | no) - as_fn_error $? "*** You must supply a directory to --with-blas-includes." "$LINENO" 5 - ;; +case "$with_blas" in + no) + ;; + yes) + USE_BLAS=1 + ;; + *) + USE_BLAS=1 + BLAS_PKGS="$with_blas" + ;; esac -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_blas_includes" >&5 -printf "%s\n" "$with_blas_includes" >&6; } -if test -n "$with_blas_includes" ; then - for dir in $with_blas_includes; do - if test -d "$dir"; then - BLASINC="$BLASINC -I$dir" - else - as_fn_error $? "*** BLAS includes directory $dir does not exist." "$LINENO" 5 - fi - done -fi +if test -n "$USE_BLAS"; then + blas_ok=no -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for location of BLAS library" >&5 -printf %s "checking for location of BLAS library... " >&6; } -case "$with_blas_libs" in -y | ye | yes | n | no) - as_fn_error $? "*** You must supply a directory to --with-blas-libs." "$LINENO" 5 - ;; -esac -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_blas_libs" >&5 -printf "%s\n" "$with_blas_libs" >&6; } + for blas_chk in ${BLAS_PKGS} + do + if ! ${PKG_CONFIG} --exists ${blas_chk} ; then + continue + else + BLAS_PKG=${blas_chk} + break + fi + done -if test -n "$with_blas_libs"; then - for dir in $with_blas_libs; do - if test -d "$dir"; then - BLASLIB="$BLASLIB -L$dir" - else - as_fn_error $? "*** BLAS library directory $dir does not exist." "$LINENO" 5 - fi - done -fi + if test -z "$BLAS_PKG" ; then + as_fn_error $? "*** Unable to locate (C)BLAS pkg-conf package(s) + \"${BLAS_PKGS}\". Perhaps you need to set PKG_CONFIG_PATH." "$LINENO" 5 + fi + + BLASLIB=$(${PKG_CONFIG} --libs ${BLAS_PKG}) + BLASINC=$(${PKG_CONFIG} --cflags ${BLAS_PKG}) + save_CFLAGS="$CFLAGS"; CFLAGS="$BLASINC $CFLAGS" + save_LIBS="$LIBS"; LIBS="$BLASLIB" -# See if cblas.h exists (CBLAS,ATLAS,others) -save_CPPFLAGS="$CPPFLAGS" -CPPFLAGS="$BLASINC $CPPFLAGS" -ac_fn_c_check_header_compile "$LINENO" "cblas.h" "ac_cv_header_cblas_h" "$ac_includes_default" + for ac_header in cblas.h +do : + ac_fn_c_check_header_compile "$LINENO" "cblas.h" "ac_cv_header_cblas_h" "$ac_includes_default" if test "x$ac_cv_header_cblas_h" = xyes then : printf "%s\n" "#define HAVE_CBLAS_H 1" >>confdefs.h -fi - -CPPFLAGS="$save_CPPFLAGS" - - -ac_save_ldflags="$LDFLAGS" -LDFLAGS="$BLASLIB $LDFLAGS" - +else $as_nop + for ac_header in cblas-atlas.h +do : + ac_fn_c_check_header_compile "$LINENO" "cblas-atlas.h" "ac_cv_header_cblas_atlas_h" "$ac_includes_default" +if test "x$ac_cv_header_cblas_atlas_h" = xyes +then : + printf "%s\n" "#define HAVE_CBLAS_ATLAS_H 1" >>confdefs.h +else $as_nop + as_fn_error $? "*** Failed to find either \"cblas.h\" or \"cblas-atlas.h\" with \"$CFLAGS\"" "$LINENO" 5 +fi +done +fi -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dnrm2_ in -lblas" >&5 -printf %s "checking for dnrm2_ in -lblas... " >&6; } +done -ac_check_lib_save_LIBS=$LIBS -LIBS="-lblas $MATHLIB $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for linking to (C)BLAS" >&5 +printf %s "checking for linking to (C)BLAS... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char dnrm2_ (); +char cblas_dgemm(); int main (void) { -return dnrm2_ (); +return cblas_dgemm(); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : - ac_cv_lib_blas_dnrm2_=yes + blas_ok=yes else $as_nop - ac_cv_lib_blas_dnrm2_=no + + as_fn_error $? "*** Unable to link to (C)BLAS library with \"$LIBS\"." "$LINENO" 5 fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_blas_dnrm2_" >&5 -printf "%s\n" "$ac_cv_lib_blas_dnrm2_" >&6; } -if test "x$ac_cv_lib_blas_dnrm2_" = xyes -then : - BLASLIB="$BLASLIB -lblas " -else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $BLAS_PKG" >&5 +printf "%s\n" "$BLAS_PKG" >&6; } -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dnrm2_ in -lblas" >&5 -printf %s "checking for dnrm2_ in -lblas... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-lblas $MATHLIB -lg2c $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ + CFLAGS="$save_CFLAGS" + LIBS="$save_LIBS" -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char dnrm2_ (); -int -main (void) -{ -return dnrm2_ (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_blas_dnrm2_=yes -else $as_nop - ac_cv_lib_blas_dnrm2_=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_blas_dnrm2_" >&5 -printf "%s\n" "$ac_cv_lib_blas_dnrm2_" >&6; } -if test "x$ac_cv_lib_blas_dnrm2_" = xyes -then : - BLASLIB="$BLASLIB -lblas -lg2c" -else $as_nop -LDFLAGS=${ac_save_ldflags} +printf "%s\n" "#define HAVE_LIBBLAS 1" >>confdefs.h - as_fn_error $? "*** Unable to locate BLAS library." "$LINENO" 5 +fi # $USE_BLAS -fi +# Done checking BLAS -fi +# Enable LAPACK option +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to use LAPACK(E)" >&5 +printf %s "checking whether to use LAPACK(E)... " >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_lapack" >&5 +printf "%s\n" "$with_lapack" >&6; } +LAPACKLIB= +LAPACKINC= +USE_LAPACK= +LAPACK_PKGS="lapacke openblas" +LAPACK_PKG= +case "$with_lapack" in + no) + ;; + yes) + USE_LAPACK=1 + ;; + *) + USE_LAPACK=1 + LAPACK_PKG="$with_lapack" + ;; +esac +# LAPACK is useless without BLAS +if test -z "$USE_BLAS" && test -n "$USE_LAPACK"; then + USE_LAPACK= + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: LAPACK is disabled, BLAS configuration is missing" >&5 +printf "%s\n" "$as_me: WARNING: LAPACK is disabled, BLAS configuration is missing" >&2;} +fi +if test -n "$USE_BLAS" && test -n "$USE_LAPACK"; then -LDFLAGS=${ac_save_ldflags} + lapack_ok=no + for lapack_chk in ${LAPACK_PKGS} + do + if ! ${PKG_CONFIG} --exists ${lapack_chk} ; then + continue + else + LAPACK_PKG=${lapack_chk} + break + fi + done -blas_ok=no + if test -z "$LAPACK_PKG" ; then + as_fn_error $? "*** Unable to locate LAPACK(E) pkg-conf package(s) + \"$LAPACK_PKGS\". Perhaps you need to set PKG_CONFIG_PATH." "$LINENO" 5 + fi -# Check for ATLAS -save_LDFLAGS="$LDFLAGS" -LDFLAGS="$BLASLIB $LDFLAGS" -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ATL_xerbla in -latlas" >&5 -printf %s "checking for ATL_xerbla in -latlas... " >&6; } + LAPACKLIB=`${PKG_CONFIG} --libs ${LAPACK_PKG}` + LAPACKINC=`${PKG_CONFIG} --cflags ${LAPACK_PKG}` -ac_check_lib_save_LIBS=$LIBS -LIBS="-latlas $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ + save_CFLAGS="$CFLAGS"; CFLAGS="$LAPACKINC $CFLAGS" + save_LIBS="$LIBS"; LIBS="$LAPACKLIB" -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char ATL_xerbla (); -int -main (void) -{ -return ATL_xerbla (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" + for ac_header in lapacke.h +do : + ac_fn_c_check_header_compile "$LINENO" "lapacke.h" "ac_cv_header_lapacke_h" "$ac_includes_default" +if test "x$ac_cv_header_lapacke_h" = xyes then : - ac_cv_lib_atlas_ATL_xerbla=yes + printf "%s\n" "#define HAVE_LAPACKE_H 1" >>confdefs.h + else $as_nop - ac_cv_lib_atlas_ATL_xerbla=no + as_fn_error $? "*** Unable to find \"lapacke.h\" with \"$CFLAGS\"." "$LINENO" 5 fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_atlas_ATL_xerbla" >&5 -printf "%s\n" "$ac_cv_lib_atlas_ATL_xerbla" >&6; } -if test "x$ac_cv_lib_atlas_ATL_xerbla" = xyes -then : - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sgemm_ in -lf77blas" >&5 -printf %s "checking for sgemm_ in -lf77blas... " >&6; } -ac_check_lib_save_LIBS=$LIBS -LIBS="-lf77blas -latlas $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ +done -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char sgemm_ (); + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for linking to LAPACK(E)" >&5 +printf %s "checking for linking to LAPACK(E)... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +char LAPACKE_dgesv(); int main (void) { -return sgemm_ (); +return LAPACKE_dgesv(); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO" then : - ac_cv_lib_f77blas_sgemm_=yes + lapack_ok=yes else $as_nop - ac_cv_lib_f77blas_sgemm_=no + + as_fn_error $? "*** Unable to link to LAPACK(E) library with \"$LIBS\"." "$LINENO" 5 fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_f77blas_sgemm_" >&5 -printf "%s\n" "$ac_cv_lib_f77blas_sgemm_" >&6; } -if test "x$ac_cv_lib_f77blas_sgemm_" = xyes -then : - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for cblas_dgemm in -lcblas" >&5 -printf %s "checking for cblas_dgemm in -lcblas... " >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $LAPACK_PKG" >&5 +printf "%s\n" "$LAPACK_PKG" >&6; } -ac_check_lib_save_LIBS=$LIBS -LIBS="-lcblas -lf77blas -latlas $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char cblas_dgemm (); -int -main (void) -{ -return cblas_dgemm (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_cblas_cblas_dgemm=yes -else $as_nop - ac_cv_lib_cblas_cblas_dgemm=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_cblas_cblas_dgemm" >&5 -printf "%s\n" "$ac_cv_lib_cblas_cblas_dgemm" >&6; } -if test "x$ac_cv_lib_cblas_cblas_dgemm" = xyes -then : - blas_ok=yes; BLASLIB="-lcblas -lf77blas -latlas" -fi - -fi - - -fi - -LDFLAGS="$save_LDFLAGS" - -# Do we have ATLAS? -if test $blas_ok = yes; then - -printf "%s\n" "#define HAVE_LIBATLAS 1" >>confdefs.h - -fi - -# BLAS in Apple vecLib framework? (Mac OS-X) -# not dependent on APP build -#if test -n "$MACOSX_APP"; then -if test $blas_ok = no; then - vlib_flags="-framework vecLib" - save_LIBS="$LIBS" - LIBS="$vlib_flags $LIBS" - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sgemm in $vlib_flags" >&5 -printf %s "checking for sgemm in $vlib_flags... " >&6; } - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main (void) -{ -sgemm - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - blas_ok=yes; BLASLIB="$vlib_flags" -else $as_nop - BLASLIB="" -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $blas_ok" >&5 -printf "%s\n" "$blas_ok" >&6; } - LIBS="$save_LIBS" -fi -#fi # $MACOSX_APP - -# BLAS in PhiPACK libraries? (requires generic BLAS, too) -if test $blas_ok = no; then - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sgemm_ in -lblas" >&5 -printf %s "checking for sgemm_ in -lblas... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-lblas $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char sgemm_ (); -int -main (void) -{ -return sgemm_ (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_blas_sgemm_=yes -else $as_nop - ac_cv_lib_blas_sgemm_=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_blas_sgemm_" >&5 -printf "%s\n" "$ac_cv_lib_blas_sgemm_" >&6; } -if test "x$ac_cv_lib_blas_sgemm_" = xyes -then : - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dgemm_ in -ldgemm" >&5 -printf %s "checking for dgemm_ in -ldgemm... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-ldgemm -lblas $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char dgemm_ (); -int -main (void) -{ -return dgemm_ (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_dgemm_dgemm_=yes -else $as_nop - ac_cv_lib_dgemm_dgemm_=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dgemm_dgemm_" >&5 -printf "%s\n" "$ac_cv_lib_dgemm_dgemm_" >&6; } -if test "x$ac_cv_lib_dgemm_dgemm_" = xyes -then : - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sgemm_ in -lsgemm" >&5 -printf %s "checking for sgemm_ in -lsgemm... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-lsgemm -lblas $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char sgemm_ (); -int -main (void) -{ -return sgemm_ (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_sgemm_sgemm_=yes -else $as_nop - ac_cv_lib_sgemm_sgemm_=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_sgemm_sgemm_" >&5 -printf "%s\n" "$ac_cv_lib_sgemm_sgemm_" >&6; } -if test "x$ac_cv_lib_sgemm_sgemm_" = xyes -then : - blas_ok=yes; BLASLIB="-lsgemm -ldgemm -lblas" -fi - -fi - - -fi - -fi - -# BLAS in Sun Performance library? -if test $blas_ok = no; then - if test "x$GCC" != xyes; then # only works with Sun CC - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for acosp in -lsunmath" >&5 -printf %s "checking for acosp in -lsunmath... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-lsunmath $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char acosp (); -int -main (void) -{ -return acosp (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_sunmath_acosp=yes -else $as_nop - ac_cv_lib_sunmath_acosp=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_sunmath_acosp" >&5 -printf "%s\n" "$ac_cv_lib_sunmath_acosp" >&6; } -if test "x$ac_cv_lib_sunmath_acosp" = xyes -then : - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sgemm_ in -lsunperf" >&5 -printf %s "checking for sgemm_ in -lsunperf... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-lsunperf -lsunmath $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char sgemm_ (); -int -main (void) -{ -return sgemm_ (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_sunperf_sgemm_=yes -else $as_nop - ac_cv_lib_sunperf_sgemm_=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_sunperf_sgemm_" >&5 -printf "%s\n" "$ac_cv_lib_sunperf_sgemm_" >&6; } -if test "x$ac_cv_lib_sunperf_sgemm_" = xyes -then : - blas_ok=yes; BLASLIB="-xlic_lib=sunperf -lsunmath" -fi - - -fi - - fi -fi - -# Generic BLAS library -if test $blas_ok = no; then - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sgemm_ in -lblas" >&5 -printf %s "checking for sgemm_ in -lblas... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-lblas $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char sgemm_ (); -int -main (void) -{ -return sgemm_ (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_blas_sgemm_=yes -else $as_nop - ac_cv_lib_blas_sgemm_=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_blas_sgemm_" >&5 -printf "%s\n" "$ac_cv_lib_blas_sgemm_" >&6; } -if test "x$ac_cv_lib_blas_sgemm_" = xyes -then : - blas_ok=yes; BLASLIB="-lblas" -fi - -fi - -if test $blas_ok = yes; then - -printf "%s\n" "#define HAVE_LIBBLAS 1" >>confdefs.h - -fi - -fi # $USE_BLAS - - - - -# Done checking BLAS - -# Enable LAPACK option - - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to use LAPACK" >&5 -printf %s "checking whether to use LAPACK... " >&6; } -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: \"$with_lapack\"" >&5 -printf "%s\n" "\"$with_lapack\"" >&6; } -case "$with_lapack" in - "no") USE_LAPACK= ;; - "yes") USE_LAPACK="1" ;; - *) as_fn_error $? "*** You must answer yes or no." "$LINENO" 5 ;; -esac - - - -LAPACKLIB= -LAPACKINC= - -# LAPACK is useless without BLAS -if test -n "$USE_BLAS"; then -if test -n "$USE_LAPACK"; then - -# With LAPACK includes directory -# LAPACK doesn't have includes (FORTRAN library) -# With LAPACK library directory - -lapack_ok=no - - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for location of LAPACK includes" >&5 -printf %s "checking for location of LAPACK includes... " >&6; } -case "$with_lapack_includes" in -y | ye | yes | n | no) - as_fn_error $? "*** You must supply a directory to --with-lapack-includes." "$LINENO" 5 - ;; -esac -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_lapack_includes" >&5 -printf "%s\n" "$with_lapack_includes" >&6; } - -if test -n "$with_lapack_includes" ; then - for dir in $with_lapack_includes; do - if test -d "$dir"; then - LAPACKINC="$LAPACKINC -I$dir" - else - as_fn_error $? "*** LAPACK includes directory $dir does not exist." "$LINENO" 5 - fi - done -fi - - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for location of LAPACK library" >&5 -printf %s "checking for location of LAPACK library... " >&6; } -case "$with_lapack_libs" in -y | ye | yes | n | no) - as_fn_error $? "*** You must supply a directory to --with-lapack-libs." "$LINENO" 5 - ;; -esac -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_lapack_libs" >&5 -printf "%s\n" "$with_lapack_libs" >&6; } - -if test -n "$with_lapack_libs"; then - for dir in $with_lapack_libs; do - if test -d "$dir"; then - LAPACKLIB="$LAPACKLIB -L$dir" - else - as_fn_error $? "*** LAPACK library directory $dir does not exist." "$LINENO" 5 - fi - done -fi - - -# See if clapack.h exists (ATLAS) -save_CPPFLAGS="$CPPFLAGS" -CPPFLAGS="$LAPACKINC $CPPFLAGS" -ac_fn_c_check_header_compile "$LINENO" "clapack.h" "ac_cv_header_clapack_h" "$ac_includes_default" -if test "x$ac_cv_header_clapack_h" = xyes -then : - printf "%s\n" "#define HAVE_CLAPACK_H 1" >>confdefs.h - -fi - -CPPFLAGS="$save_CPPFLAGS" - -# LAPACK linked to by default? -if test lapack_ok=no; then - save_LIBS="$LIBS"; LIBS="$LIBS $BLASLIB $MATHLIB $FLIBS" - save_LDFLAGS="$LDFLAGS"; LDFLAGS="$LAPACKLIB $LDFLAGS" - ac_fn_c_check_func "$LINENO" "dsegv_" "ac_cv_func_dsegv_" -if test "x$ac_cv_func_dsegv_" = xyes -then : - lapack_ok=yes -fi - - LIBS="$save_LIBS" - LDFLAGS="$save_LDFLAGS" -fi - -# Generic LAPACK library? -if test $lapack_ok = no; then - save_libs="$LIBS"; LIBS="$BLASLIB $MATHLIB $LIBS" - save_LDFLAGS="$LDFLAGS"; LDFLAGS="$LAPACKLIB $LDFLAGS" - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for desgv_ in -llapack" >&5 -printf %s "checking for desgv_ in -llapack... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-llapack $FLIBS $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char desgv_ (); -int -main (void) -{ -return desgv_ (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_lapack_desgv_=yes -else $as_nop - ac_cv_lib_lapack_desgv_=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_lapack_desgv_" >&5 -printf "%s\n" "$ac_cv_lib_lapack_desgv_" >&6; } -if test "x$ac_cv_lib_lapack_desgv_" = xyes -then : - lapack_ok=yes; LAPACKLIB="-llapack" -fi - - LIBS="$save_LIBS" - LDFLAGS="$save_LDFLAGS" -fi - -if test $lapack_ok = no; then - -ac_save_ldflags="$LDFLAGS" -LDFLAGS="$LAPACKLIB $LDFLAGS" - - - - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dgesv_ in -llapack" >&5 -printf %s "checking for dgesv_ in -llapack... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-llapack $BLASLIB $MATHLIB $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char dgesv_ (); -int -main (void) -{ -return dgesv_ (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_lapack_dgesv_=yes -else $as_nop - ac_cv_lib_lapack_dgesv_=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_lapack_dgesv_" >&5 -printf "%s\n" "$ac_cv_lib_lapack_dgesv_" >&6; } -if test "x$ac_cv_lib_lapack_dgesv_" = xyes -then : - LAPACKLIB="$LAPACKLIB -llapack " -else $as_nop - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dgesv_ in -llapack" >&5 -printf %s "checking for dgesv_ in -llapack... " >&6; } - -ac_check_lib_save_LIBS=$LIBS -LIBS="-llapack $BLASLIB $MATHLIB -lg2c $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char dgesv_ (); -int -main (void) -{ -return dgesv_ (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO" -then : - ac_cv_lib_lapack_dgesv_=yes -else $as_nop - ac_cv_lib_lapack_dgesv_=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_lapack_dgesv_" >&5 -printf "%s\n" "$ac_cv_lib_lapack_dgesv_" >&6; } -if test "x$ac_cv_lib_lapack_dgesv_" = xyes -then : - LAPACKLIB="$LAPACKLIB -llapack -lg2c" -else $as_nop - -LDFLAGS=${ac_save_ldflags} - - as_fn_error $? "*** Unable to locate LAPACK library." "$LINENO" 5 - - -fi - - - - -fi - - - - - - -LDFLAGS=${ac_save_ldflags} - -fi + CFLAGS="$save_CFLAGS" + LIBS="$save_LIBS" printf "%s\n" "#define HAVE_LIBLAPACK 1" >>confdefs.h -fi # $USE_LAPACK -fi # $USE_BLAS +fi # $USE_BLAS $USE_LAPACK @@ -15192,113 +14503,6 @@ fi -# Enable openDWG option - - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether to use openDWG" >&5 -printf %s "checking whether to use openDWG... " >&6; } -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: \"$with_opendwg\"" >&5 -printf "%s\n" "\"$with_opendwg\"" >&6; } -case "$with_opendwg" in - "no") USE_OPENDWG= ;; - "yes") USE_OPENDWG="1" ;; - *) as_fn_error $? "*** You must answer yes or no." "$LINENO" 5 ;; -esac - - - -OPENDWGINCPATH= -OPENDWGLIBPATH= -OPENDWGLIB= - -if test -n "${USE_OPENDWG}"; then - -# With OPENDWG includes directory - - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for location of openDGW includes" >&5 -printf %s "checking for location of openDGW includes... " >&6; } -case "$with_opendwg_includes" in -y | ye | yes | n | no) - as_fn_error $? "*** You must supply a directory to --with-opendwg-includes." "$LINENO" 5 - ;; -esac -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_opendwg_includes" >&5 -printf "%s\n" "$with_opendwg_includes" >&6; } - -if test -n "$with_opendwg_includes" ; then - for dir in $with_opendwg_includes; do - if test -d "$dir"; then - OPENDWGINCPATH="$OPENDWGINCPATH -I$dir" - else - as_fn_error $? "*** openDGW includes directory $dir does not exist." "$LINENO" 5 - fi - done -fi - - - -ac_save_cppflags="$CPPFLAGS" -CPPFLAGS="$OPENDWGINCPATH $CPPFLAGS" - for ac_header in ad2.h -do : - ac_fn_c_check_header_compile "$LINENO" "ad2.h" "ac_cv_header_ad2_h" "$ac_includes_default" -if test "x$ac_cv_header_ad2_h" = xyes -then : - printf "%s\n" "#define HAVE_AD2_H 1" >>confdefs.h - -else $as_nop - - as_fn_error $? "*** Unable to locate openDWG includes." "$LINENO" 5 - -fi - -done -CPPFLAGS=$ac_save_cppflags - - -# With OPENDWG library directory - - -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for location of openDWG library" >&5 -printf %s "checking for location of openDWG library... " >&6; } -case "$with_opendwg_libs" in -y | ye | yes | n | no) - as_fn_error $? "*** You must supply a directory to --with-opendwg-libs." "$LINENO" 5 - ;; -esac -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_opendwg_libs" >&5 -printf "%s\n" "$with_opendwg_libs" >&6; } - -if test -n "$with_opendwg_libs"; then - for dir in $with_opendwg_libs; do - if test -d "$dir"; then - OPENDWGLIBPATH="$OPENDWGLIBPATH -L$dir" - else - as_fn_error $? "*** openDWG library directory $dir does not exist." "$LINENO" 5 - fi - done -fi - - -#search for ad2.a, ad3.a ... in openDWG toolkit directory: -#FIX ME how to program this test?? -#LOC_CHECK_LIBS(ad?.a,adSeekLayer,openDWG,$OPENDWGLIBPATH,OPENDWGLIB,,) -# -#for now hack (but working): -TRUEOPENDWGLIBPATH=`echo "$OPENDWGLIBPATH" | cut -b3-` -adlib=`ls -1 "$TRUEOPENDWGLIBPATH"/ad?.a | tail -1` -OPENDWGLIB="$adlib" - -fi # $USE_OPENDWG - - - - - - -# Done checking OPENDWG - # Enable pthread option @@ -17673,8 +16877,6 @@ echo " C++ support: `if test -n "${USE_CXX}" ; then echo yes ; e echo " Cairo support: `if test -n "${USE_CAIRO}" ; then echo yes ; else echo no ; fi`" -echo " DWG support: `if test -n "${USE_OPENDWG}" ; then echo yes ; else echo no ; fi`" - echo " FFTW support: `if test -n "${USE_FFTW}" ; then echo yes ; else echo no ; fi`" echo " FreeType support: `if test -n "${USE_FREETYPE}" ; then echo yes ; else echo no ; fi`" diff --git a/configure.ac b/configure.ac index 8ef6e1b9f7c..52a985960c3 100644 --- a/configure.ac +++ b/configure.ac @@ -305,14 +305,11 @@ LOC_ARG_WITH(sqlite, SQLite) LOC_ARG_WITH(opengl, OpenGL) LOC_ARG_WITH(odbc, ODBC, no) LOC_ARG_WITH(fftw, FFTW) -LOC_ARG_WITH(blas, BLAS, no) -LOC_ARG_WITH(lapack, LAPACK, no) LOC_ARG_WITH(libsvm, LIBSVM, no) LOC_ARG_WITH(cairo, Cairo) LOC_ARG_WITH(freetype, FreeType) LOC_ARG_WITH(nls, NLS, no) LOC_ARG_WITH(readline, Readline, no) -LOC_ARG_WITH(opendwg, openDWG, no) LOC_ARG_WITH(regex, regex) LOC_ARG_WITH(pthread, POSIX threads, no) LOC_ARG_WITH(openmp, OpenMP, no) @@ -321,6 +318,19 @@ LOC_ARG_WITH(bzlib, BZIP2, no) LOC_ARG_WITH(zstd, Zstandard) LOC_ARG_WITH(pdal, PDAL) + +AC_ARG_WITH([blas], + [AS_HELP_STRING([--with-blas=pkg-config-package], + [enable BLAS support with by adding name of pkg-config package name + for CBLAS library, e.g. '--with-lapack-package=openblas', + default: cblas])],, [with_blas=no]) + +AC_ARG_WITH([lapack], + [AS_HELP_STRING([--with-lapack=pkg-config-package], + [enable LAPACK support with by adding name of pkg-config package name + for LAPACKE library, e.g. '--with-lapack-package=openblas', + default: lapacke])],, [with_lapack=no]) + AC_ARG_WITH(libpng, [ --with-libpng[=path/libpng-config] enable PNG support (libpng-config with path, @@ -391,12 +401,6 @@ LOC_ARG_WITH_LIB(odbc, ODBC) LOC_ARG_WITH_INC(fftw, FFTW) LOC_ARG_WITH_LIB(fftw, FFTW) -LOC_ARG_WITH_INC(blas, BLAS) -LOC_ARG_WITH_LIB(blas, BLAS) - -LOC_ARG_WITH_INC(lapack, LAPACK) -LOC_ARG_WITH_LIB(lapack, LAPACK) - LOC_ARG_WITH_INC(libsvm, LIBSVM) LOC_ARG_WITH_LIB(libsvm, LIBSVM) @@ -411,9 +415,6 @@ LOC_ARG_WITH_INC(proj, External PROJ.4) LOC_ARG_WITH_LIB(proj, External PROJ.4) LOC_ARG_WITH_SHARE(proj, External PROJ.4) -LOC_ARG_WITH_INC(opendwg, openDWG) -LOC_ARG_WITH_LIB(opendwg, openDWG) - LOC_ARG_WITH_INC(regex, regex) LOC_ARG_WITH_LIB(regex, regex) @@ -505,7 +506,7 @@ AC_CHECK_PROGS(ENV, env) AC_PATH_PROG(PERL, perl, no) #AC_CHECK_HEADERS(curses.h limits.h termio.h termios.h unistd.h values.h) -AC_CHECK_HEADERS(limits.h termio.h termios.h unistd.h values.h f2c.h g2c.h) +AC_CHECK_HEADERS(limits.h termio.h termios.h unistd.h values.h) AC_CHECK_HEADERS(sys/ioctl.h sys/mtio.h sys/resource.h sys/time.h) AC_CHECK_HEADERS(sys/timeb.h sys/types.h sys/utsname.h) AC_CHECK_HEADERS(libintl.h iconv.h) @@ -595,6 +596,9 @@ AC_SUBST(DBMIEXTRALIB) AC_CHECK_FUNCS(asprintf) AC_SUBST(HAVE_ASPRINTF) +AC_CHECK_FUNCS(strlcat) +AC_SUBST(HAVE_STRLCAT) + # Test if strlcpy exists # This is a function part of *BSD libc (optionally available on Linux via libbsd) AC_CHECK_FUNCS(strlcpy) @@ -1577,91 +1581,67 @@ AC_SUBST(FFTWLIB) # Enable BLAS option -LOC_CHECK_USE(blas,BLAS,USE_BLAS) +AC_MSG_CHECKING([whether to use (C)BLAS]) +AC_MSG_RESULT([$with_blas]) BLASLIB= BLASINC= +USE_BLAS= +BLAS_PKGS="cblas blas-netlib openblas blas-atlas" +BLAS_PKG= + +case "$with_blas" in + no) + ;; + yes) + USE_BLAS=1 + ;; + *) + USE_BLAS=1 + BLAS_PKGS="$with_blas" + ;; +esac if test -n "$USE_BLAS"; then -# With BLAS includes directory -# BLAS doesn't have includes (FORTRAN library) -# With BLAS library directory - -LOC_CHECK_INC_PATH(blas, BLAS, BLASINC) -LOC_CHECK_LIB_PATH(blas, BLAS, BLASLIB) - -# See if cblas.h exists (CBLAS,ATLAS,others) -save_CPPFLAGS="$CPPFLAGS" -CPPFLAGS="$BLASINC $CPPFLAGS" -AC_CHECK_HEADERS(cblas.h) -CPPFLAGS="$save_CPPFLAGS" - -LOC_CHECK_LIBS(blas,dnrm2_,BLAS,$BLASLIB,BLASLIB,$MATHLIB,,,-lg2c) - -blas_ok=no - -# Check for ATLAS -save_LDFLAGS="$LDFLAGS" -LDFLAGS="$BLASLIB $LDFLAGS" -AC_CHECK_LIB(atlas, ATL_xerbla, - [AC_CHECK_LIB(f77blas, sgemm_, - [AC_CHECK_LIB(cblas, cblas_dgemm, - [blas_ok=yes; BLASLIB="-lcblas -lf77blas -latlas"], - [],[-lf77blas -latlas])], - [],[-latlas])] -) -LDFLAGS="$save_LDFLAGS" - -# Do we have ATLAS? -if test $blas_ok = yes; then - AC_DEFINE(HAVE_LIBATLAS, 1, [Define to 1 if ATLAS exists.]) -fi + blas_ok=no -# BLAS in Apple vecLib framework? (Mac OS-X) -# not dependent on APP build -#if test -n "$MACOSX_APP"; then -if test $blas_ok = no; then - vlib_flags="-framework vecLib" - save_LIBS="$LIBS" - LIBS="$vlib_flags $LIBS" - AC_MSG_CHECKING([for sgemm in $vlib_flags]) - AC_LINK_IFELSE([AC_LANG_PROGRAM([[]], [[sgemm]])],[blas_ok=yes; BLASLIB="$vlib_flags"],[BLASLIB=""]) - AC_MSG_RESULT($blas_ok) - LIBS="$save_LIBS" -fi -#fi # $MACOSX_APP - -# BLAS in PhiPACK libraries? (requires generic BLAS, too) -if test $blas_ok = no; then - AC_CHECK_LIB(blas, sgemm_, - [AC_CHECK_LIB(dgemm, dgemm_, - [AC_CHECK_LIB(sgemm, sgemm_, - [blas_ok=yes; BLASLIB="-lsgemm -ldgemm -lblas"], - [], [-lblas])], - [], [-lblas])] - ) -fi + for blas_chk in ${BLAS_PKGS} + do + if ! ${PKG_CONFIG} --exists ${blas_chk} ; then + continue + else + BLAS_PKG=${blas_chk} + break + fi + done -# BLAS in Sun Performance library? -if test $blas_ok = no; then - if test "x$GCC" != xyes; then # only works with Sun CC - AC_CHECK_LIB(sunmath, acosp, - [AC_CHECK_LIB(sunperf, sgemm_, - [blas_ok=yes; BLASLIB="-xlic_lib=sunperf -lsunmath"], - [], [-lsunmath])] - ) - fi -fi + if test -z "$BLAS_PKG" ; then + AC_MSG_ERROR([*** Unable to locate (C)BLAS pkg-conf package(s) + "${BLAS_PKGS}". Perhaps you need to set PKG_CONFIG_PATH.]) + fi -# Generic BLAS library -if test $blas_ok = no; then - AC_CHECK_LIB(blas, sgemm_, [blas_ok=yes; BLASLIB="-lblas"]) -fi + BLASLIB=$(${PKG_CONFIG} --libs ${BLAS_PKG}) + BLASINC=$(${PKG_CONFIG} --cflags ${BLAS_PKG}) -if test $blas_ok = yes; then -AC_DEFINE(HAVE_LIBBLAS, 1, [Define to 1 if BLAS exists.]) -fi + save_CFLAGS="$CFLAGS"; CFLAGS="$BLASINC $CFLAGS" + save_LIBS="$LIBS"; LIBS="$BLASLIB" + + AC_CHECK_HEADERS([cblas.h],, + AC_CHECK_HEADERS([cblas-atlas.h],, + AC_MSG_ERROR([*** Failed to find either "cblas.h" or "cblas-atlas.h" with "$CFLAGS"]))) + + AC_MSG_CHECKING([for linking to (C)BLAS]) + AC_LINK_IFELSE([AC_LANG_PROGRAM( + [[char cblas_dgemm();]], [[return cblas_dgemm();]])], + [blas_ok=yes] , [ + AC_MSG_ERROR([*** Unable to link to (C)BLAS library with "$LIBS".])]) + AC_MSG_RESULT([$BLAS_PKG]) + + CFLAGS="$save_CFLAGS" + LIBS="$save_LIBS" + + AC_DEFINE(HAVE_LIBBLAS, 1, [Define to 1 if BLAS exists.]) fi # $USE_BLAS @@ -1672,57 +1652,74 @@ AC_SUBST(BLASINC) # Enable LAPACK option -LOC_CHECK_USE(lapack,LAPACK,USE_LAPACK) +AC_MSG_CHECKING([whether to use LAPACK(E)]) +AC_MSG_RESULT([$with_lapack]) LAPACKLIB= LAPACKINC= +USE_LAPACK= +LAPACK_PKGS="lapacke openblas" +LAPACK_PKG= + +case "$with_lapack" in + no) + ;; + yes) + USE_LAPACK=1 + ;; + *) + USE_LAPACK=1 + LAPACK_PKG="$with_lapack" + ;; +esac # LAPACK is useless without BLAS -if test -n "$USE_BLAS"; then -if test -n "$USE_LAPACK"; then - -# With LAPACK includes directory -# LAPACK doesn't have includes (FORTRAN library) -# With LAPACK library directory - -lapack_ok=no - -LOC_CHECK_INC_PATH(lapack, LAPACK, LAPACKINC) -LOC_CHECK_LIB_PATH(lapack, LAPACK, LAPACKLIB) - -# See if clapack.h exists (ATLAS) -save_CPPFLAGS="$CPPFLAGS" -CPPFLAGS="$LAPACKINC $CPPFLAGS" -AC_CHECK_HEADERS(clapack.h) -CPPFLAGS="$save_CPPFLAGS" - -# LAPACK linked to by default? -if test lapack_ok=no; then - save_LIBS="$LIBS"; LIBS="$LIBS $BLASLIB $MATHLIB $FLIBS" - save_LDFLAGS="$LDFLAGS"; LDFLAGS="$LAPACKLIB $LDFLAGS" - AC_CHECK_FUNC(dsegv_, [lapack_ok=yes]) - LIBS="$save_LIBS" - LDFLAGS="$save_LDFLAGS" +if test -z "$USE_BLAS" && test -n "$USE_LAPACK"; then + USE_LAPACK= + AC_MSG_WARN([LAPACK is disabled, BLAS configuration is missing]) fi -# Generic LAPACK library? -if test $lapack_ok = no; then - save_libs="$LIBS"; LIBS="$BLASLIB $MATHLIB $LIBS" - save_LDFLAGS="$LDFLAGS"; LDFLAGS="$LAPACKLIB $LDFLAGS" - AC_CHECK_LIB(lapack, desgv_, - [lapack_ok=yes; LAPACKLIB="-llapack"], [], [$FLIBS]) - LIBS="$save_LIBS" - LDFLAGS="$save_LDFLAGS" -fi +if test -n "$USE_BLAS" && test -n "$USE_LAPACK"; then -if test $lapack_ok = no; then - LOC_CHECK_LIBS(lapack,dgesv_,LAPACK,$LAPACKLIB,LAPACKLIB,$BLASLIB $MATHLIB,,,-lg2c) -fi + lapack_ok=no -AC_DEFINE(HAVE_LIBLAPACK, 1, [Define to 1 if LAPACK exists.]) + for lapack_chk in ${LAPACK_PKGS} + do + if ! ${PKG_CONFIG} --exists ${lapack_chk} ; then + continue + else + LAPACK_PKG=${lapack_chk} + break + fi + done -fi # $USE_LAPACK -fi # $USE_BLAS + if test -z "$LAPACK_PKG" ; then + AC_MSG_ERROR([*** Unable to locate LAPACK(E) pkg-conf package(s) + "$LAPACK_PKGS". Perhaps you need to set PKG_CONFIG_PATH.]) + fi + + LAPACKLIB=`${PKG_CONFIG} --libs ${LAPACK_PKG}` + LAPACKINC=`${PKG_CONFIG} --cflags ${LAPACK_PKG}` + + save_CFLAGS="$CFLAGS"; CFLAGS="$LAPACKINC $CFLAGS" + save_LIBS="$LIBS"; LIBS="$LAPACKLIB" + + AC_CHECK_HEADERS([lapacke.h], [], + AC_MSG_ERROR([*** Unable to find "lapacke.h" with "$CFLAGS".])) + + AC_MSG_CHECKING([for linking to LAPACK(E)]) + AC_LINK_IFELSE([AC_LANG_PROGRAM( + [[char LAPACKE_dgesv();]], [[return LAPACKE_dgesv(); ]])], + [lapack_ok=yes] , [ + AC_MSG_ERROR([*** Unable to link to LAPACK(E) library with "$LIBS".])]) + AC_MSG_RESULT([$LAPACK_PKG]) + + CFLAGS="$save_CFLAGS" + LIBS="$save_LIBS" + + AC_DEFINE(HAVE_LIBLAPACK, 1, [Define to 1 if LAPACK exists.]) + +fi # $USE_BLAS $USE_LAPACK AC_SUBST(LAPACKLIB) AC_SUBST(LAPACKINC) @@ -1857,44 +1854,6 @@ fi AC_SUBST(INTLLIB) AC_SUBST(HAVE_NLS) -# Enable openDWG option - -LOC_CHECK_USE(opendwg,openDWG,USE_OPENDWG) - -OPENDWGINCPATH= -OPENDWGLIBPATH= -OPENDWGLIB= - -if test -n "${USE_OPENDWG}"; then - -# With OPENDWG includes directory - -LOC_CHECK_INC_PATH(opendwg,openDGW,OPENDWGINCPATH) - -LOC_CHECK_INCLUDES(ad2.h,openDWG,$OPENDWGINCPATH) - -# With OPENDWG library directory - -LOC_CHECK_LIB_PATH(opendwg,openDWG,OPENDWGLIBPATH) - -#search for ad2.a, ad3.a ... in openDWG toolkit directory: -#FIX ME how to program this test?? -#LOC_CHECK_LIBS(ad?.a,adSeekLayer,openDWG,$OPENDWGLIBPATH,OPENDWGLIB,,) -# -#for now hack (but working): -TRUEOPENDWGLIBPATH=`echo "$OPENDWGLIBPATH" | cut -b3-` -adlib=`ls -1 "$TRUEOPENDWGLIBPATH"/ad?.a | tail -1` -OPENDWGLIB="$adlib" - -fi # $USE_OPENDWG - -AC_SUBST(OPENDWGINCPATH) -AC_SUBST(OPENDWGLIBPATH) -AC_SUBST(OPENDWGLIB) -AC_SUBST(USE_OPENDWG) - -# Done checking OPENDWG - # Enable pthread option LOC_CHECK_USE(pthread,POSIX threads,USE_PTHREAD) @@ -2069,7 +2028,6 @@ LOC_MSG_USE(BLAS support,USE_BLAS) LOC_MSG_USE(BZIP2 support,USE_BZIP2) LOC_MSG_USE(C++ support,USE_CXX) LOC_MSG_USE(Cairo support,USE_CAIRO) -LOC_MSG_USE(DWG support,USE_OPENDWG) LOC_MSG_USE(FFTW support,USE_FFTW) LOC_MSG_USE(FreeType support,USE_FREETYPE) LOC_MSG_USE(GDAL support,USE_GDAL) diff --git a/db/drivers/sqlite/db.c b/db/drivers/sqlite/db.c index 518ba6c978c..cd86e4648f6 100644 --- a/db/drivers/sqlite/db.c +++ b/db/drivers/sqlite/db.c @@ -78,7 +78,11 @@ int db__driver_open_database(dbHandle *handle) G_free_tokens(tokens); } else { - strcpy(name2, name); + if (G_strlcpy(name2, name, sizeof(name2)) >= sizeof(name2)) { + db_d_append_error(_("Database name <%s> is too long"), name); + db_d_report_error(); + return DB_FAILED; + } } G_debug(2, "name2 = '%s'", name2); @@ -114,11 +118,20 @@ int db__driver_open_database(dbHandle *handle) else { G_warning(_("The sqlite config option '%s' is not supported"), "SQLITE_CONFIG_URI"); - strcpy(name3, name2); + if (G_strlcpy(name3, name2, sizeof(name3)) >= sizeof(name3)) { + db_d_append_error(_("Database name <%s> is too long"), name2); + db_d_report_error(); + return DB_FAILED; + } + } + } + else { + if (G_strlcpy(name3, name2, sizeof(name3)) >= sizeof(name3)) { + db_d_append_error(_("Database name <%s> is too long"), name2); + db_d_report_error(); + return DB_FAILED; } } - else - strcpy(name3, name2); if (sqlite3_open(name3, &sqlite) != SQLITE_OK) { db_d_append_error("%s %s\n%s", _("Unable to open database:"), name3, (char *)sqlite3_errmsg(sqlite)); @@ -184,11 +197,20 @@ int db__driver_create_database(dbHandle *handle) else { G_warning(_("The sqlite config option '%s' is not supported"), "SQLITE_CONFIG_URI"); - strcpy(name2, name); + if (G_strlcpy(name2, name, sizeof(name2)) >= sizeof(name2)) { + db_d_append_error(_("Database name <%s> is too long"), name); + db_d_report_error(); + return DB_FAILED; + } + } + } + else { + if (G_strlcpy(name2, name, sizeof(name2)) >= sizeof(name2)) { + db_d_append_error(_("Database name <%s> is too long"), name); + db_d_report_error(); + return DB_FAILED; } } - else - strcpy(name2, name); if (sqlite3_open(name2, &sqlite) != SQLITE_OK) { db_d_append_error("%s %s\n%s", _("Unable to create database:"), name, (char *)sqlite3_errmsg(sqlite)); diff --git a/display/d.histogram/d.histogram.html b/display/d.histogram/d.histogram.html index 6e99c940290..43cca2d7223 100644 --- a/display/d.histogram/d.histogram.html +++ b/display/d.histogram/d.histogram.html @@ -10,7 +10,7 @@

DESCRIPTION

NOTES

d.histogram respects the current geographic region settings -and the current MASK (if one exists). +and the current raster mask (if mask is active).

d.histogram uses the colors in the map's color look-up table (i.e., the map's colr or colr2 file). diff --git a/display/d.mon/list.c b/display/d.mon/list.c index ab346302a61..c61c1081991 100644 --- a/display/d.mon/list.c +++ b/display/d.mon/list.c @@ -14,11 +14,13 @@ char *get_path(const char *name, int fpath) char tmpdir[GPATH_MAX]; G_temp_element(tmpdir); - strcat(tmpdir, "/"); - strcat(tmpdir, "MONITORS"); + (void)G_strlcat(tmpdir, "/", sizeof(tmpdir)); + (void)G_strlcat(tmpdir, "MONITORS", sizeof(tmpdir)); if (name) { - strcat(tmpdir, "/"); - strcat(tmpdir, name); + (void)G_strlcat(tmpdir, "/", sizeof(tmpdir)); + if (G_strlcat(tmpdir, name, sizeof(tmpdir)) >= sizeof(tmpdir)) { + G_fatal_error(_("Failed to append <%s> to path"), name); + } } if (fpath) { @@ -132,10 +134,13 @@ void list_files(const char *name, FILE *fd_out) DIR *dirp; G_temp_element(tmpdir); - strcat(tmpdir, "/"); - strcat(tmpdir, "MONITORS"); - strcat(tmpdir, "/"); - strcat(tmpdir, name); + (void)G_strlcat(tmpdir, "/", sizeof(tmpdir)); + (void)G_strlcat(tmpdir, "MONITORS", sizeof(tmpdir)); + (void)G_strlcat(tmpdir, "/", sizeof(tmpdir)); + + if (G_strlcat(tmpdir, name, sizeof(tmpdir)) >= sizeof(tmpdir)) { + G_fatal_error(_("Failed to append <%s> to path"), name); + } G_file_name(mon_path, tmpdir, NULL, G_mapset()); fprintf(fd_out, "path=%s\n", mon_path); diff --git a/display/d.mon/render_cmd.py b/display/d.mon/render_cmd.py index 7678a1442e4..cf153c0b017 100644 --- a/display/d.mon/render_cmd.py +++ b/display/d.mon/render_cmd.py @@ -39,7 +39,7 @@ def remove_mapfile(mapfile): # read environment variables from file def read_env_file(env_file): width = height = legfile = None - fd = open(env_file, "r") + fd = open(env_file) if fd is None: grass.fatal("Unable to open file '{0}'".format(env_file)) lines = fd.readlines() diff --git a/display/d.vect/attr.c b/display/d.vect/attr.c index 5a28807cbca..747b98c59af 100644 --- a/display/d.vect/attr.c +++ b/display/d.vect/attr.c @@ -35,9 +35,11 @@ int display_attr(struct Map_info *Map, int type, char *attrcol, db_init_string(&text); fi = Vect_get_field(Map, lattr->field); - if (fi == NULL) + if (fi == NULL) { + Vect_destroy_line_struct(Points); + Vect_destroy_cats_struct(Cats); return 1; - + } driver = db_start_driver_open_database(fi->driver, fi->database); if (driver == NULL) G_fatal_error(_("Unable to open database <%s> by driver <%s>"), @@ -140,6 +142,7 @@ int display_attr(struct Map_info *Map, int type, char *attrcol, db_close_database_shutdown_driver(driver); Vect_destroy_line_struct(Points); Vect_destroy_cats_struct(Cats); + Vect_destroy_field_info(fi); return 0; } diff --git a/doc/development/README.md b/doc/development/README.md index 9845f20649e..db5244a5a72 100644 --- a/doc/development/README.md +++ b/doc/development/README.md @@ -1,43 +1,19 @@ # Development and Maintenance Documentation -Here is development and maitanance documentation. The API documentation -is at appropriate places, but here is the information relevant to -contributing to GRASS GIS and its maintanance. +Find below the development and maintenance documentation. +The API documentation is available in the appropriate places, +but here is the information relevant to contributing to and +maintaining GRASS GIS. -## How to generate the 'Programmer's Manual' +## Style and GitHub guide -You can locally generate the [GRASS GIS Programmer's Manual](https://grass.osgeo.org/programming8/). +- [GRASS Programming Style Guide](style_guide.md) +- [Guide to contributing on GitHub](github_guide.md) -This needs doxygen () and optionally -Graphviz dot (). +## Python API -To build the GRASS programmer's documentation, run +- ["grass" Python package documentation](https://grass.osgeo.org/grass-devel/manuals/libpython/) -```sh -make htmldocs -``` +## C API -Or to generate documentation as a single html file -(recommended for simple reading) - -```sh -make htmldocs-single -``` - -This takes quite some time. The result is in `lib/html/index.html` -which refers to further document repositories in - -```text -lib/vector/html/index.html -lib/db/html/index.html -lib/gis/html/index.html -``` - -The master file is: `./grasslib.dox` where all sub-documents have to -be linked to. - -To generate the documents in PDF format, run - -```sh -make pdfdocs -``` +- [GRASS Programmer's manual](https://grass.osgeo.org/programming8/) diff --git a/doc/development/rfc/README.md b/doc/development/rfc/README.md new file mode 100644 index 00000000000..590be34e169 --- /dev/null +++ b/doc/development/rfc/README.md @@ -0,0 +1,26 @@ +# Request For Comment (RFC) List + +GRASS Project Steering Committee: + +- [GRASS-PSC](https://grasswiki.osgeo.org/wiki/PSC) + +A list of all GRASS GIS RFC documents, with status: + +- [RFC 1: Project Steering Committee Guidelines](PSC_guidelines.md) (Adopted) +- [RFC 2: Legal aspects of code contributions](legal_aspects_of_code_contributions.md) + (Adopted) +- [RFC 3: PSC Voting Procedures](PSC_voting_procedures.md) (Adopted) +- [RFC 4: Release Procedure](https://github.com/OSGeo/grass/pull/2815) (Draft) +- [RFC 5: GRASS GIS Errata](https://github.com/OSGeo/grass/pull/2813) (Draft) +- [RFC 6: Migration from SVN to GitHub](migration_github.md) (Adopted) +- [RFC 7: Language Standards Support](language_standards_support.md) (Adopted) +- [RFC 8: Python Language Support](python_language_support.md) (Adopted) +- [RFC 9: Version Numbering](version_numbering.md) (Adopted) +- [RFC X: Release Policy](https://github.com/OSGeo/grass/pull/3673) (Draft) + +Status values: + +- Adopted: RFC is approved (and presumably implemented). +- Proposed: RFC is complete, and open for voting. +- Draft: RFC is being written/revised/discussed. +- Withdrawn: RFC is unapproved, and not being pursued further. diff --git a/doc/development/rfc/version_numbering.md b/doc/development/rfc/version_numbering.md index 7829b0eb513..3428a8b92aa 100644 --- a/doc/development/rfc/version_numbering.md +++ b/doc/development/rfc/version_numbering.md @@ -1,4 +1,4 @@ -# RFC: Version Numbering +# RFC 9: Version Numbering Author: Vaclav Petras diff --git a/doc/development/style_guide.md b/doc/development/style_guide.md index 8268114ad5d..3b065d9f838 100644 --- a/doc/development/style_guide.md +++ b/doc/development/style_guide.md @@ -75,7 +75,7 @@ flake8 --ignore=E203,E266,E501 --max-line-length=88 python_file.py C and C++ code is formatted with [ClangFormat](https://clang.llvm.org/docs/ClangFormat.html). Contributions are -expected to be formatted with `clang-format` (currently with version 15+). The +expected to be formatted with `clang-format` (currently with version 18+). The most convenient method to install clang-format and format files is [using pre-commit](#using-pre-commit). @@ -92,6 +92,38 @@ If using pre-commit is not an option, for whatever reason, there is a helper script [grass_clang_format.sh](./utils/grass_clang_format.sh), which simplifies bulk reformatting. +#### Order of include headers + +In general, headers should be included in the order: + +1. Core system headers (stdio.h, ctype.h, ...) +2. Headers for non-core system components (X11, libraries). +3. GRASS headers (grass/gis.h, grass/glocale.h, ...) +4. Headers for the specific library/program (geodesic.h, ...) + +Each class of headers has an obligation to be compatible with those above it in +the list, but not those below it. The header groups should be alphabetically +sorted and separated by a newline. + +```c +#include +#include +#include + +#include +#include +#include + +#include "local_proto.h" +#include "mask.h" +``` + +#### Naming conventions + +Use function names which fulfill the official [GNU naming +convention](https://www.gnu.org/prep/standards/html_node/Names.html). Instead of +naming a function like: `MyNewFunction()` use snake case: `my_new_function()`. + ### Using pre-commit It is highly recommended to install and use [pre-commit](https://pre-commit.com) @@ -160,7 +192,7 @@ There are three types of documentation: C API, Python API and tool documentation #### C API documentation We -[​use doxygen and document the functions](https://grass.osgeo.org/programming8/) +[use doxygen and document the functions](https://grass.osgeo.org/programming8/) directly in the source code. See `lib/gis/open.c` and `lib/gis/gislib.dox` for examples. @@ -652,6 +684,30 @@ standard tool output if it has one. ### Developing GRASS Addons +To streamline the development of a GRASS addon in python, you can use [this +template](https://github.com/OSGeo/grass-addon-cookiecutter) powered by +Cookiecutter. + +#### Copyright header + +Use the following header in your source code. + +```python +############################################################################## +# MODULE: r.foo +# +# AUTHOR(S): John Doe +# +# PURPOSE: Provide short description of module here... +# +# COPYRIGHT: (C) 2024 by John Doe and the GRASS Development Team +# +# This program is free software under the GNU General Public +# License (>=v2). Read the file COPYING that comes with GRASS +# for details. +############################################################################## +``` + #### Use Standard Options in Interface GRASS tools must use the GRASS parser to handle its command line parameters. To @@ -887,3 +943,82 @@ self.bwizard = wx.Button(..., # GTC %s will be replaced with name of current shell gs.message(_("Running through {}").format(shellname)) ``` + +### Developing C tools + +Refer to the [online GRASS Programmer's +Manual](https://grass.osgeo.org/programming8/) or generate it with `make +htmldocs` or `make pdfdocs`. + +#### Use GRASS library functions + +Use the GRASS library functions, when available, instead of the standard C +functions. The reason for this is that the following functions ensure good +programming practice (e.g. always checking if memory was allocated) and/or +improves portability. + +- Memory management: `G_malloc()`, `G_calloc()`, `G_realloc()`, `G_free()` +- Environmental variables: `G_getenv()`, `G_setenv()`, `G_unsetenv()` +- File seek: `G_fseek()`, `G_ftell()` +- Printing: `G_asprintf()`, `G_vsaprintf()`, `G_vfaprintf()`, ... + +Please refer to the [programmers manual](https://grass.osgeo.org/programming8/) +for the proper use (e.g., determining if any casts are needed for arguments or +return values) of these library functions. They may perform a task slightly +different from their corresponding C library function, and thus, their use may +not be the same. + +#### Returning value of main function + +Tool exit status is defined as `EXIT_SUCCESS` or `EXIT_FAILURE` (declared in +`stdlib.h`), e.g. + +```c + { + ... + if (G_parser (argc, argv)) + exit (EXIT_FAILURE); + + ... + exit (EXIT_SUCCESS); + } +``` + +#### Messages and data output + +See rules for [messages in Python scripts](#messages) for proper usage of +`G_fatal_error()`, `G_warning()`, etc. Message output is not expected to be sent +to pipe or file. + +For data output redirected to pipe or file, please use `fprintf()` and specify +the stdout stream as follows: + +```c + fprintf(stdout, ...); + fflush(stdout); + + fflush(stdout) /* always required when using fprintf(stdout, ...). */ +``` + +#### Header section + +Add a header section to file main.c of your tool and make sure you include the +copyright. If you are modifying an existing file you may under no circumstances +remove prior copyright or licensing text that is not your own, even for a major +rewrite. If any original code or code that is in part derived from another's +original work remains, it must be properly cited. + +```c +/**************************************************************************** + * + * MODULE: g.foo + * AUTHOR(S): John Doe + * PURPOSE: Provide short description of module here... + * COPYRIGHT: (C) 2010 by John Doe, and the GRASS Development Team + * + * This program is free software under the GNU General Public + * License (>=v2). Read the COPYING file that comes with GRASS + * for details. + * + *****************************************************************************/ +``` diff --git a/doc/gui/wxpython/example/dialogs.py b/doc/gui/wxpython/example/dialogs.py index 425ea57a4b2..98760e7202d 100644 --- a/doc/gui/wxpython/example/dialogs.py +++ b/doc/gui/wxpython/example/dialogs.py @@ -20,7 +20,7 @@ # So we need to import it before any of the GUI code. # NOTE: in this particular case, we don't really need the grass library; # NOTE: we import it just for the side effects of gettext.install() -import grass +import grass # noqa: F401 from core import globalvar from gui_core.dialogs import SimpleDialog diff --git a/doc/infrastructure.md b/doc/infrastructure.md index 4494a6cbd69..e5b59eee73b 100644 --- a/doc/infrastructure.md +++ b/doc/infrastructure.md @@ -1,11 +1,11 @@ # How the GRASS GIS Webserver and related infrastructure works Author: Markus Neteler -Last update: Dec 2023 +Last update: Sep 2024 ## GRASS GIS Source code repository -Maintainer: Markus Neteler, Martin Landa, OSGeo-SAC, +Maintainer: Markus Neteler, Martin Landa, OSGeo-SAC, Important update April 2019: The source code is now managed on GitHub (rather than in SVN). @@ -17,12 +17,12 @@ The GitHub repositories are: - GRASS GIS Add-ons: - GRASS GIS promotional material: - GRASS GIS Website (Hugo site): -- Github mirror at OSGeo: +- Github mirror at OSGeo (updated daily): Git usage: - [CONTRIBUTING.md file](../CONTRIBUTING.md) -- +- [Guide to contributing on GitHub](development/github_guide.md) Issues: @@ -39,8 +39,8 @@ Maintainer: M. Neteler - - - osgeo7-grass: LXD container on osgeo7 () - - OS: Debian Buster + - osgeo8-grass: LXD container on osgeo8 () + - OS: Debian GNU/Linux 11 bullseye - Apache Server with Hugo () - for migration details (7/2020), see - ssh login: via jumphost hop.osgeo8.osgeo.org @@ -48,17 +48,14 @@ Maintainer: M. Neteler - (CMSMS, replaced in 2020 by above Hugo based solution) - - Shared virtual OSGeo machine (osgeo6) hosted at Oregon State University - Open Source Lab server: osgeo6.osgeo.osuosl.org) - - Login: via OSGeo LDAP, there is a "grass" LDAP group - - Software: - - OS: Debian Wheezy - - Apache Server with PHP - - Login: via OSGeo LDAP, there is a "grass" LDAP group + - a static copy of the old site is found at + `neteler@grasslxd:old-grass-website/old.grass.osgeo.org/` (13 GB) + - otherwise: - Backups: - - osgeo7-grass: container on osgeo8 is backup'ed, see + - osgeo8-grass + wiki: container on osgeo8 is backup'ed, + see - Mirrors: @@ -70,18 +67,18 @@ Maintainer: M. Neteler - Weekly software snapshots (generated Saturday morning Portland (OR), US time): - Source code tarball of git (GitHub) - - Linux binary snapshot is compiled on osgeo7-grass + - Linux binary snapshot is compiled on osgeo8-grass - GRASS is compiled with GDAL, PROJ, SQLite, MySQL, PostgreSQL, FFTW, C++ support, see - binary tar.gz and manuals are moved into Web space - GRASS user manual HTML: - - generated during compilation of weekly Linux binary snapshot on osgeo7-grass + - generated during compilation of weekly Linux binary snapshot on osgeo8-grass - GRASS addons manual HTML: - - generated during compilation of weekly Linux binary snapshot on osgeo7-grass + - generated during compilation of weekly Linux binary snapshot on osgeo8-grass - GRASS programmer's manual () @@ -89,13 +86,15 @@ Maintainer: M. Neteler - HTML: cronjob run Saturday morning Portland (OR), US time - disabled: PDF: cronjob run Saturday morning Portland (OR), US time -- Mailman mailing lists + automated greylisting (at lists.osgeo.org since 11/2007) +- Mailman mailing lists + automated greylisting + (at , since 11/2007) - Mailman is doing the job, only registered users can post - messages from unsubscribed people is auto-discarded without notification - the open "weblist" operates instead like this: - - User -> grass-web at lists osgeo.org -> greylisting -> Mailman - - for greylisting, see + - mails goes to grass-web at lists osgeo.org -> greylisting -> Mailman + - for greylisting, see + - Moderation of queue: - Backup of mailing lists (mbox files) @@ -104,7 +103,7 @@ Maintainer: M. Neteler - Web statistics - Matomo: (not publicly accessible; access: Markus Neteler) - - Selected stats: + - Selected stats: and Summary: The system should run almost autonomously. @@ -148,11 +147,9 @@ Maintainer: Martin Landa, Markus Neteler - - Mediawiki software -- requires registration to keep spammers out - -Summary: The system should run almost autonomous. An eye must be be kept -on people trying to spam the site. Several layers of registration protection -are in place due to excessive spam. +- requires registration at + [OSGeo-LDAP](https://www.osgeo.org/community/getting-started-osgeo/osgeo_userid/) + (to keep spammers out) Macros for manual pages (src, cmd, API, ...): @@ -163,9 +160,15 @@ Macros for manual pages (src, cmd, API, ...): Channel: irc://irc.libera.chat/grass Web based client: See +Libera IRC: + +- Founder: jmckenna, markusN + +Former freenode IRC: + - channel owner: Alessandro Frigeri ("geoalf") - quasi guru level: Markus Neteler ("markusN") -- original (freenode) operators: +- original operators: - Jachym ("jachym") - Luca ("doktoreas") - Soeren ("huhabla") @@ -181,16 +184,16 @@ Old bugtrackers: see ## GRASS GIS Addons -Maintainer: Martin Landa and Markus Neteler +Maintainer: Martin Landa, Tomas Zigo, and Markus Neteler Details: -- Windows-addons: grass-addons/utils/addons/README.txt +- Windows-addons: `grass-addons/utils/addons/README.txt` - Addon manual pages cronjob: - Rendered manuals: -The redirect to the latest grassX directory is defined on grass.osgeo.org: -/etc/apache2/includes/grass.osgeo.org.inc +The redirect to the latest `grassX` directory is defined on grass.osgeo.org: +`/etc/apache2/includes/grass.osgeo.org.inc` Procedure building of binaries (Windows): @@ -199,8 +202,8 @@ Procedure building of binaries (Windows): - A new compilation is triggered every time a commit is done in the Addons repo. - Logs: - Linux log files: (compiled on - `grasslxd` on `osgeo7`) - - Windows log files: + `grasslxd` on `osgeo8`) + - Windows log files: Procedure of granting write access to Addons repo: @@ -213,14 +216,7 @@ Procedure of granting write access to Addons repo: XML file for g.extension: -- generated in grass-addons/utils/addons/grass-addons-publish.sh - -## GRASS Travis CI - -Maintainer: Martin Landa - -- -- +- generated in `grass-addons/utils/addons/grass-addons-publish.sh` ## GRASS CI: GitHub Actions diff --git a/doc/python/m.distance.py b/doc/python/m.distance.py index 5eddb1dcc56..576760c3b40 100755 --- a/doc/python/m.distance.py +++ b/doc/python/m.distance.py @@ -45,10 +45,21 @@ # %end import sys +from ctypes import byref, c_double import grass.script as gs - -from grass.lib.gis import * +from grass.lib.gis import ( + G_gisinit, + G_begin_distance_calculations, + G_scan_easting, + G_scan_northing, + G_distance, + G_begin_polygon_area_calculations, + G_area_of_polygon, + G_database_units_to_meters_factor, + G_database_unit_name, + PROJECTION_LL, +) def main(): diff --git a/doc/python/raster_example_ctypes.py b/doc/python/raster_example_ctypes.py index f62ce4a9492..67f7a2cf4cb 100644 --- a/doc/python/raster_example_ctypes.py +++ b/doc/python/raster_example_ctypes.py @@ -17,9 +17,23 @@ import os import sys - -from grass.lib.gis import * -from grass.lib.raster import * +import math + +from ctypes import POINTER, c_int, c_float, c_double, c_void_p, cast + +from grass.lib.gis import G_gisinit, G_find_raster2, G_free +from grass.lib.raster import ( + Rast_map_type, + CELL_TYPE, + FCELL_TYPE, + DCELL_TYPE, + Rast_open_old, + Rast_allocate_buf, + Rast_window_rows, + Rast_window_cols, + Rast_get_row, + Rast_close, +) # check if GRASS is running or not if "GISBASE" not in os.environ: diff --git a/doc/python/vector_example_ctypes.py b/doc/python/vector_example_ctypes.py index 9f8a90d6459..ae3877224d0 100644 --- a/doc/python/vector_example_ctypes.py +++ b/doc/python/vector_example_ctypes.py @@ -7,9 +7,28 @@ import os import sys +from ctypes import pointer, byref -from grass.lib.gis import * -from grass.lib.vector import * +# Import specific functions and classes instead of using wildcard imports +from grass.lib.gis import G_gisinit, G_find_vector2 +from grass.lib.vector import ( + Map_info, + Vect_set_open_level, + Vect_open_old, + Vect_get_full_name, + Vect_is_3d, + Vect_get_num_dblinks, + Vect_get_scale, + Vect_get_map_box, + Vect_point_in_box, + Vect_get_num_lines, + Vect_get_num_primitives, + Vect_get_num_areas, + Vect_close, + bound_box, + GV_POINT, + GV_LINE, +) if "GISBASE" not in os.environ: sys.exit("You must be in GRASS GIS to run this program.") diff --git a/docker/alpine/Dockerfile b/docker/alpine/Dockerfile index dfd840263e9..b6dbebf6666 100644 --- a/docker/alpine/Dockerfile +++ b/docker/alpine/Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:3.20@sha256:0a4eaa0eecf5f8c050e5bba433f58c052be7587ee8af3e8b3910ef9ab5fbe9f5 as common +FROM alpine:3.20@sha256:beefdbd8a1da6d2915566fde36db9db0b524eb737fc57cd1367effd16dc0d06d as common # Based on: # https://github.com/mundialis/docker-grass-gis/blob/master/Dockerfile @@ -11,9 +11,9 @@ ARG PYTHON_VERSION=3 # List of packages to be installed (proj-data omitted: 570.04 MB) ENV GRASS_RUN_PACKAGES="\ attr \ - build-base \ bash \ bison \ + build-base \ bzip2 \ cairo \ curl \ @@ -29,15 +29,15 @@ ENV GRASS_RUN_PACKAGES="\ gdal-driver-JP2OpenJPEG \ gdal-driver-LIBKML \ gdal-driver-MSSQLSpatial \ - gdal-driver-netCDF \ gdal-driver-ODBC \ gdal-driver-PG \ gdal-driver-PNG \ gdal-driver-WMS \ + gdal-driver-netCDF \ gdal-tools \ - gettext \ geos \ geos-dev \ + gettext \ git \ gnutls \ jsoncpp \ @@ -52,15 +52,15 @@ ENV GRASS_RUN_PACKAGES="\ musl \ musl-utils \ ncurses \ - openjpeg \ openblas \ - py3-numpy \ - py3-pillow \ - python3 \ + openjpeg \ pdal \ pdal-dev \ postgresql15-client \ proj-util \ + py3-numpy \ + py3-pillow \ + python3 \ sqlite \ sqlite-libs \ subversion \ @@ -89,23 +89,23 @@ FROM common as build # set configuration options, without wxGUI ENV GRASS_CONFIG="\ --enable-largefile \ + --with-bzlib \ + --with-cairo --with-cairo-ldflags=-lfontconfig \ --with-cxx \ - --with-proj-share=/usr/share/proj \ + --with-fftw \ --with-gdal \ - --with-pdal \ --with-geos \ + --with-openmp \ + --with-pdal \ + --with-postgres --with-postgres-includes=/usr/include/postgresql \ + --with-proj-share=/usr/share/proj \ --with-sqlite \ - --with-bzlib \ --with-zstd \ - --with-cairo --with-cairo-ldflags=-lfontconfig \ - --with-fftw \ - --with-postgres --with-postgres-includes=/usr/include/postgresql \ - --with-openmp \ --without-freetype \ - --without-opengl \ - --without-nls \ --without-mysql \ + --without-nls \ --without-odbc \ + --without-opengl \ " # Set environmental variables for GRASS GIS compilation, without debug symbols @@ -132,13 +132,13 @@ ENV GRASS_BUILD_PACKAGES="\ libjpeg-turbo-dev \ libpng-dev \ libpq-dev \ - openjpeg-dev \ openblas-dev \ + openjpeg-dev \ pdal \ pdal-dev \ proj-dev \ - python3-dev \ py3-numpy-dev \ + python3-dev \ sqlite-dev \ tar \ tiff-dev \ diff --git a/docker/debian/Dockerfile b/docker/debian/Dockerfile index 2ed59e1482e..8021ccf409e 100644 --- a/docker/debian/Dockerfile +++ b/docker/debian/Dockerfile @@ -18,8 +18,8 @@ WORKDIR /tmp RUN apt-get update && apt-get upgrade -y && \ apt-get install -y --no-install-recommends --no-install-suggests \ - build-essential \ bison \ + build-essential \ bzip2 \ cmake \ curl \ @@ -40,8 +40,8 @@ RUN apt-get update && apt-get upgrade -y && \ libgsl0-dev \ libjpeg-dev \ libjsoncpp-dev \ - libnetcdf-dev \ libncurses-dev \ + libnetcdf-dev \ libopenblas-dev \ libopenjp2-7 \ libopenjp2-7-dev \ @@ -153,24 +153,24 @@ ENV CXXFLAGS "$MYCXXFLAGS" ENV NUMTHREADS=4 RUN make distclean || echo "nothing to clean" RUN /src/grass_build/configure \ - --with-cxx \ --enable-largefile \ - --with-proj-share=/usr/share/proj \ - --with-gdal=/usr/bin/gdal-config \ - --with-geos \ - --with-sqlite \ + --with-bzlib \ --with-cairo --with-cairo-ldflags=-lfontconfig \ - --with-freetype --with-freetype-includes="/usr/include/freetype2/" \ + --with-cxx \ --with-fftw \ - --with-postgres --with-postgres-includes="/usr/include/postgresql" \ + --with-freetype --with-freetype-includes="/usr/include/freetype2/" \ + --with-gdal=/usr/bin/gdal-config \ + --with-geos \ --with-netcdf \ - --with-zstd \ - --with-bzlib \ --with-pdal \ + --with-postgres --with-postgres-includes="/usr/include/postgresql" \ + --with-proj-share=/usr/share/proj \ + --with-sqlite \ + --with-zstd \ --without-mysql \ --without-odbc \ - --without-openmp \ --without-opengl \ + --without-openmp \ && make -j $NUMTHREADS \ && make install && ldconfig diff --git a/docker/ubuntu/Dockerfile b/docker/ubuntu/Dockerfile index 23bf11ddf27..41fb3264c07 100644 --- a/docker/ubuntu/Dockerfile +++ b/docker/ubuntu/Dockerfile @@ -1,11 +1,11 @@ -# syntax=docker/dockerfile:1.9@sha256:fe40cf4e92cd0c467be2cfc30657a680ae2398318afd50b0c80585784c604f28 +# syntax=docker/dockerfile:1.10@sha256:865e5dd094beca432e8c0a1d5e1c465db5f998dca4e439981029b3b81fb39ed5 # Note: This file must be kept in sync in ./Dockerfile and ./docker/ubuntu/Dockerfile. # Changes to this file must be copied over to the other file. ARG GUI=without -FROM ubuntu:22.04@sha256:adbb90115a21969d2fe6fa7f9af4253e16d45f8d4c1e930182610c4731962658 as common_start +FROM ubuntu:22.04@sha256:58b87898e82351c6cf9cf5b9f3c20257bb9e2dcf33af051e12ce532d7f94e3fe as common_start LABEL authors="Carmen Tawalika,Markus Neteler,Anika Weinmann,Stefan Blumentrath" LABEL maintainer="tawalika@mundialis.de,neteler@mundialis.de,weinmann@mundialis.de" @@ -19,8 +19,9 @@ WORKDIR /tmp ARG GUI # Todo: re-consider required dev packages for addons (~400MB in dev packages) -ARG GRASS_RUN_PACKAGES="build-essential \ +ARG GRASS_RUN_PACKAGES="\ bison \ + build-essential \ bzip2 \ curl \ flex \ @@ -28,8 +29,6 @@ ARG GRASS_RUN_PACKAGES="build-essential \ gcc \ gdal-bin \ geos-bin \ - proj-bin \ - netcdf-bin \ git \ language-pack-en-base \ libcairo2 \ @@ -38,28 +37,29 @@ ARG GRASS_RUN_PACKAGES="build-essential \ libfftw3-dev \ libfreetype6 \ libgdal-dev \ + libgeos-dev \ + libgsl-dev \ libgsl27 \ libjpeg-turbo8 \ libjsoncpp-dev \ - libmagic1 \ + liblapacke-dev \ libmagic-mgc \ + libmagic1 \ libncurses5 \ - libopenblas-dev \ + libomp-dev \ + libomp5 \ libopenblas-base \ + libopenblas-dev \ libopenjp2-7 \ - libomp5 \ - libomp-dev \ - libgeos-dev \ - libpdal-dev \ - libproj-dev \ - libpq-dev \ - libgsl-dev \ libpdal-base13 \ + libpdal-dev \ libpdal-plugin-hdf \ libpdal-plugins \ libpdal-util13 \ libpnglite0 \ + libpq-dev \ libpq5 \ + libproj-dev \ libpython3-all-dev \ libreadline8 \ libsqlite3-0 \ @@ -70,7 +70,9 @@ ARG GRASS_RUN_PACKAGES="build-essential \ mesa-utils \ moreutils \ ncurses-bin \ + netcdf-bin \ pdal \ + proj-bin \ proj-data \ python-is-python3 \ python3 \ @@ -86,56 +88,58 @@ ARG GRASS_RUN_PACKAGES="build-essential \ ENV GRASS_RUN_PACKAGES=${GRASS_RUN_PACKAGES} # Define build packages -ARG GRASS_BUILD_PACKAGES="cmake \ +ARG GRASS_BUILD_PACKAGES="\ + cmake \ libbz2-dev \ libcairo2-dev \ libfreetype6-dev \ - zlib1g-dev \ + libjpeg-dev \ + libncurses5-dev \ libnetcdf-dev \ libopenjp2-7-dev \ - libreadline-dev \ - libjpeg-dev \ libpnglite-dev \ + libreadline-dev \ libsqlite3-dev \ libtiff-dev \ libzstd-dev \ - libncurses5-dev \ mesa-common-dev \ zlib1g-dev \ " ENV GRASS_BUILD_PACKAGES=${GRASS_BUILD_PACKAGES} -ARG GRASS_CONFIG="--with-cxx \ +ARG GRASS_CONFIG="\ --enable-largefile \ - --with-proj-share=/usr/share/proj \ - --with-gdal=/usr/bin/gdal-config \ - --with-geos \ - --with-sqlite \ + --with-blas \ + --with-bzlib \ --with-cairo --with-cairo-ldflags=-lfontconfig \ - --with-freetype --with-freetype-includes=/usr/include/freetype2/ \ + --with-cxx \ --with-fftw \ - --with-postgres --with-postgres-includes=/usr/include/postgresql \ - --with-netcdf \ - --with-zstd \ - --with-bzlib \ - --with-pdal \ - --without-mysql \ - --with-blas \ + --with-freetype --with-freetype-includes=/usr/include/freetype2/ \ + --with-gdal=/usr/bin/gdal-config \ + --with-geos \ --with-lapack \ - --with-readline \ + --with-netcdf \ --with-odbc \ --with-openmp \ + --with-pdal \ + --with-postgres --with-postgres-includes=/usr/include/postgresql \ + --with-proj-share=/usr/share/proj \ + --with-readline \ + --with-sqlite \ + --with-zstd \ + --without-mysql \ " -ARG GRASS_PYTHON_PACKAGES="pip \ - setuptools \ - python-dateutil \ - python-magic \ - numpy \ +ARG GRASS_PYTHON_PACKAGES="\ Pillow \ - ply \ matplotlib \ + numpy \ + pip \ + ply \ psycopg2 \ + python-dateutil \ + python-magic \ + setuptools \ " ENV GRASS_PYTHON_PACKAGES=${GRASS_PYTHON_PACKAGES} @@ -147,31 +151,33 @@ ENV GRASS_CONFIG=${GRASS_CONFIG} FROM common_start as grass_with_gui -ARG GRASS_RUN_PACKAGES="${GRASS_RUN_PACKAGES} adwaita-icon-theme-full \ - libglu1-mesa \ - libgtk-3-0 \ - libnotify4 \ - libsdl2-2.0-0 \ - libxtst6 \ - librsvg2-common \ - gettext \ +ARG GRASS_RUN_PACKAGES="${GRASS_RUN_PACKAGES} \ + adwaita-icon-theme-full \ freeglut3 \ + gettext \ + libglu1-mesa \ libgstreamer-plugins-base1.0 \ + libgtk-3-0 \ libjpeg8 \ + libnotify4 \ libpng16-16 \ + librsvg2-common \ + libsdl2-2.0-0 \ libsm6 \ libtiff5 \ libwebkit2gtk-4.0 \ + libxtst6 \ " # librsvg2-common \ # (fix error (wxgui.py:7782): Gtk-WARNING **: 19:53:09.774: # Could not load a pixbuf from /org/gtk/libgtk/theme/Adwaita/assets/check-symbolic.svg. # This may indicate that pixbuf loaders or the mime database could not be found.) -ARG GRASS_BUILD_PACKAGES="${GRASS_BUILD_PACKAGES} adwaita-icon-theme-full \ +ARG GRASS_BUILD_PACKAGES="${GRASS_BUILD_PACKAGES} \ + adwaita-icon-theme-full \ + freeglut3-dev \ libgl1-mesa-dev \ libglu1-mesa-dev \ - freeglut3-dev \ libgstreamer-plugins-base1.0-dev \ libgtk-3-dev \ libjpeg-dev \ @@ -184,10 +190,11 @@ ARG GRASS_BUILD_PACKAGES="${GRASS_BUILD_PACKAGES} adwaita-icon-theme-full \ libxtst-dev \ " -ARG GRASS_CONFIG="${GRASS_CONFIG} --with-opengl \ - --with-x \ +ARG GRASS_CONFIG="${GRASS_CONFIG} \ --with-nls \ + --with-opengl \ --with-readline \ + --with-x \ " ARG GRASS_PYTHON_PACKAGES="${GRASS_PYTHON_PACKAGES} wxPython" # If you do not use any Gnome Accessibility features, to suppress warning diff --git a/docker/ubuntu_wxgui/Dockerfile b/docker/ubuntu_wxgui/Dockerfile index 21426eca886..e15d5dcf478 100644 --- a/docker/ubuntu_wxgui/Dockerfile +++ b/docker/ubuntu_wxgui/Dockerfile @@ -1,4 +1,4 @@ -FROM ubuntu:22.04@sha256:adbb90115a21969d2fe6fa7f9af4253e16d45f8d4c1e930182610c4731962658 +FROM ubuntu:22.04@sha256:58b87898e82351c6cf9cf5b9f3c20257bb9e2dcf33af051e12ce532d7f94e3fe LABEL authors="Carmen Tawalika,Markus Neteler,Anika Weinmann,Tomas Zigo" LABEL maintainer="tawalika@mundialis.de,neteler@mundialis.de,weinmann@mundialis.de" @@ -29,8 +29,8 @@ WORKDIR /tmp RUN apt-get update && apt-get upgrade -y && \ apt-get install -y --no-install-recommends --no-install-suggests \ adwaita-icon-theme-full \ - build-essential \ bison \ + build-essential \ bzip2 \ cmake \ curl \ @@ -48,17 +48,17 @@ RUN apt-get update && apt-get upgrade -y && \ libfftw3-bin \ libfftw3-dev \ libfreetype6-dev \ - libgl1-mesa-dev \ libgdal-dev \ libgeos-dev \ + libgl1-mesa-dev \ libglu1-mesa-dev \ libgsl0-dev \ libgtk-3-0 \ libgtk-3-dev \ libjpeg-dev \ libjsoncpp-dev \ - libnetcdf-dev \ libncurses5-dev \ + libnetcdf-dev \ libnotify4 \ libopenblas-base \ libopenblas-dev \ @@ -68,8 +68,8 @@ RUN apt-get update && apt-get upgrade -y && \ libpq-dev \ libproj-dev \ libpython3-all-dev \ - librsvg2-common \ libreadline-dev \ + librsvg2-common \ libsdl2-2.0-0 \ libsqlite3-dev \ libtiff-dev \ @@ -191,26 +191,26 @@ ENV CXXFLAGS "$MYCXXFLAGS" ENV NUMTHREADS=4 RUN make distclean || echo "nothing to clean" RUN /src/grass_build/configure \ - --with-cxx \ --enable-largefile \ - --with-proj-share=/usr/share/proj \ - --with-gdal=/usr/bin/gdal-config \ - --with-geos \ - --with-sqlite \ + --with-bzlib \ --with-cairo --with-cairo-ldflags=-lfontconfig \ - --with-freetype --with-freetype-includes="/usr/include/freetype2/" \ + --with-cxx \ --with-fftw \ - --with-postgres --with-postgres-includes="/usr/include/postgresql" \ + --with-freetype --with-freetype-includes="/usr/include/freetype2/" \ + --with-gdal=/usr/bin/gdal-config \ + --with-geos \ --with-netcdf \ - --with-zstd \ - --with-bzlib \ + --with-nls \ --with-pdal \ + --with-postgres --with-postgres-includes="/usr/include/postgresql" \ + --with-proj-share=/usr/share/proj \ + --with-readline \ + --with-sqlite \ + --with-x \ + --with-zstd \ --without-mysql \ --without-odbc \ --without-openmp \ - --with-x \ - --with-nls \ - --with-readline \ && make -j $NUMTHREADS \ && make install && ldconfig diff --git a/flake.lock b/flake.lock index 257ec2317b7..eacc92d3c4f 100644 --- a/flake.lock +++ b/flake.lock @@ -5,11 +5,11 @@ "nixpkgs-lib": "nixpkgs-lib" }, "locked": { - "lastModified": 1725234343, - "narHash": "sha256-+ebgonl3NbiKD2UD0x4BszCZQ6sTfL4xioaM49o5B3Y=", + "lastModified": 1727826117, + "narHash": "sha256-K5ZLCyfO/Zj9mPFldf3iwS6oZStJcU4tSpiXTMYaaL0=", "owner": "hercules-ci", "repo": "flake-parts", - "rev": "567b938d64d4b4112ee253b9274472dc3a346eb6", + "rev": "3d04084d54bedc3d6b8b736c70ef449225c361b1", "type": "github" }, "original": { @@ -19,11 +19,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1725194671, - "narHash": "sha256-tLGCFEFTB5TaOKkpfw3iYT9dnk4awTP/q4w+ROpMfuw=", + "lastModified": 1728538411, + "narHash": "sha256-f0SBJz1eZ2yOuKUr5CA9BHULGXVSn6miBuUWdTyhUhU=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "b833ff01a0d694b910daca6e2ff4a3f26dee478c", + "rev": "b69de56fac8c2b6f8fd27f2eca01dcda8e0a4221", "type": "github" }, "original": { @@ -35,14 +35,14 @@ }, "nixpkgs-lib": { "locked": { - "lastModified": 1725233747, - "narHash": "sha256-Ss8QWLXdr2JCBPcYChJhz4xJm+h/xjl4G0c0XlP6a74=", + "lastModified": 1727825735, + "narHash": "sha256-0xHYkMkeLVQAMa7gvkddbPqpxph+hDzdu1XdGPJR+Os=", "type": "tarball", - "url": "https://github.com/NixOS/nixpkgs/archive/356624c12086a18f2ea2825fed34523d60ccc4e3.tar.gz" + "url": "https://github.com/NixOS/nixpkgs/archive/fb192fec7cc7a4c26d51779e9bab07ce6fa5597a.tar.gz" }, "original": { "type": "tarball", - "url": "https://github.com/NixOS/nixpkgs/archive/356624c12086a18f2ea2825fed34523d60ccc4e3.tar.gz" + "url": "https://github.com/NixOS/nixpkgs/archive/fb192fec7cc7a4c26d51779e9bab07ce6fa5597a.tar.gz" } }, "root": { diff --git a/general/g.gisenv/g.gisenv.html b/general/g.gisenv/g.gisenv.html index 833e5051b36..4f5d9e165b3 100644 --- a/general/g.gisenv/g.gisenv.html +++ b/general/g.gisenv/g.gisenv.html @@ -149,6 +149,32 @@

NOTES

variables are stored in <gisdbase>/<project>/<mapset>/VAR after the current GRASS session is closed. +

EXAMPLES

+ +

Cache for raster operations

+ +The maximum memory to be used, i.e. the cache size for raster rows, is set +to 300 MB by default (GRASS variable MEMORYMB). To speed up +raster operations, it is recommended to increase this setting if enough RAM +is available. It is important to note that parallel processes will each +consume this amount of RAM. + +Set the maximum memory to be used (in MB), i.e. the cache size for raster rows: + +
+# set to 6 GB (default: 300 MB)
+g.gisenv set="MEMORYMB=6000"
+
+ +

Number of threads for parallel computing

+ +Set the number of threads for parallel computing: + +
+# set to use 12 threads (default: 1)
+g.gisenv set="NPROCS=12"
+
+

GRASS Debugging

To print debugging messages, the variable DEBUG must be set to level @@ -189,7 +215,8 @@

SEE ALSO

-See also variables list +See also +list of selected GRASS gisenv variables

AUTHOR

diff --git a/general/g.mapsets/tests/g_mapsets_list_format_test.py b/general/g.mapsets/tests/g_mapsets_list_format_test.py index 79555085bb0..05fe946a6ae 100644 --- a/general/g.mapsets/tests/g_mapsets_list_format_test.py +++ b/general/g.mapsets/tests/g_mapsets_list_format_test.py @@ -14,6 +14,7 @@ """Test parsing and structure of CSV and JSON outputs from g.mapsets""" import json +import sys import pytest import grass.script as gs from grass.script import utils as gutils @@ -30,6 +31,10 @@ def _check_parsed_list(mapsets, text, sep="|"): assert text == sep.join(mapsets) + "\n" +@pytest.mark.xfail( + sys.platform == "win32", + reason="universal_newlines or text subprocess option not used", +) @pytest.mark.parametrize("separator", SEPARATORS) def test_plain_list_output(simple_dataset, separator): """Test that the separators are properly applied with list flag""" @@ -38,6 +43,10 @@ def test_plain_list_output(simple_dataset, separator): _check_parsed_list(mapsets, text, gutils.separator(separator)) +@pytest.mark.xfail( + sys.platform == "win32", + reason="universal_newlines or text subprocess option not used", +) @pytest.mark.parametrize("separator", SEPARATORS) def test_plain_print_output(simple_dataset, separator): """Test that the separators are properly applied with print flag""" diff --git a/general/g.parser/g.parser.html b/general/g.parser/g.parser.html index 1c0154cca09..b1de89a3a08 100644 --- a/general/g.parser/g.parser.html +++ b/general/g.parser/g.parser.html @@ -673,7 +673,7 @@

SEE ALSO

Overview table: Parser standard options

-Submitting rules for Python +Style Guide: Developing Python scripts

Related Wiki pages: diff --git a/general/g.parser/test.py b/general/g.parser/test.py index 3b56230eb14..8166b354a37 100755 --- a/general/g.parser/test.py +++ b/general/g.parser/test.py @@ -53,10 +53,10 @@ def main(): # test if parameter present: if option1: - gs.message(_("Value of option1 option: '%s'" % option1)) + gs.message(_("Value of option1 option: '%s'") % option1) - gs.message(_("Value of raster option: '%s'" % raster)) - gs.message(_("Value of vector option: '%s'" % vector)) + gs.message(_("Value of raster option: '%s'") % raster) + gs.message(_("Value of vector option: '%s'") % vector) # End of your main code here diff --git a/general/g.proj/input.c b/general/g.proj/input.c index 7f07b9bdcbf..c4232bdb9dd 100644 --- a/general/g.proj/input.c +++ b/general/g.proj/input.c @@ -230,8 +230,12 @@ int input_proj4(char *proj4params) if (fgets(buff, sizeof(buff), infd) == NULL) G_warning(_("Failed to read PROJ.4 parameter from stdin")); } - else - strcpy(buff, proj4params); + else { + if (G_strlcpy(buff, proj4params, sizeof(buff)) >= sizeof(buff)) { + G_fatal_error(_("PROJ.4 parameter string is too long: %s"), + proj4params); + } + } #if PROJ_VERSION_MAJOR >= 6 if (!strstr(buff, "+type=crs")) diff --git a/general/g.remove/testsuite/test_g_remove.py b/general/g.remove/testsuite/test_g_remove.py index 955466f29ca..10c3018f67a 100644 --- a/general/g.remove/testsuite/test_g_remove.py +++ b/general/g.remove/testsuite/test_g_remove.py @@ -52,7 +52,7 @@ def tearDownClass(cls): def test_remove_procedure(self): """Test that maps are removed only with -f""" - for i in range(0, 10): + for i in range(10): rmapcalc("test_map_%i = 100" % i) rmapcalc("test_two = 2") diff --git a/general/g.version/tests/conftest.py b/general/g.version/tests/conftest.py new file mode 100644 index 00000000000..e4357b2f672 --- /dev/null +++ b/general/g.version/tests/conftest.py @@ -0,0 +1,17 @@ +import os +import pytest +import grass.script as gs + + +@pytest.fixture(scope="module") +def session(tmp_path_factory): + """Set up a GRASS session for the tests.""" + tmp_path = tmp_path_factory.mktemp("grass_session") + project = "test_project" + + # Create a test location + gs.create_project(tmp_path, project) + + # Initialize the GRASS session + with gs.setup.init(tmp_path / project, env=os.environ.copy()) as session: + yield session diff --git a/general/g.version/tests/g_version_test.py b/general/g.version/tests/g_version_test.py new file mode 100644 index 00000000000..805518382a2 --- /dev/null +++ b/general/g.version/tests/g_version_test.py @@ -0,0 +1,83 @@ +import grass.script as gs + + +def test_g_version_no_flag(session): + """Test that g.version output contains the word 'GRASS'.""" + output = gs.read_command("g.version", env=session.env).strip() + assert ( + "GRASS" in output + ), "Expected 'GRASS' in g.version output, but it was not found." + + +def test_c_flag(session): + """Test the output of g.version -c for Copyright and License Statement.""" + expected_text = "Copyright and License Statement" + output = gs.read_command("g.version", flags="c", env=session.env).strip() + assert ( + expected_text in output + ), f"Expected '{expected_text}' in g.version -c output, but got: '{output}'" + + +def test_e_flag(session): + """Test that g.version -e contains the expected keys.""" + expected_keys = ["PROJ:", "GDAL/OGR:", "SQLite:"] + output = gs.read_command("g.version", flags="e", env=session.env).strip() + for key in expected_keys: + assert ( + key in output + ), f"Expected key '{key}' in g.version -e output, but it was not found." + + +def test_b_flag(session): + """Test that g.version -b output contains the word 'GRASS'.""" + output = gs.read_command("g.version", flags="b", env=session.env).strip() + assert ( + "GRASS" in output + ), "Expected 'GRASS' in g.version -b output, but it was not found." + + +def test_g_flag(session): + """Test that g.version -g contains the expected keys.""" + expected_keys = [ + "version", + "date", + "revision", + "build_date", + "build_platform", + "build_off_t_size", + ] + output = gs.parse_command("g.version", flags="g", env=session.env) + for key in expected_keys: + assert ( + key in output + ), f"Expected key '{key}' in g.version -g output, but it was not found." + + +def test_r_flag(session): + """Test that g.version -r contains the expected keys.""" + expected_texts = ["libgis revision:", "libgis date:"] + output = gs.read_command("g.version", flags="r", env=session.env).strip() + for text in expected_texts: + assert ( + text in output + ), f"Expected key '{text}' in g.version -r output, but it was not found." + + +def test_x_flag(session): + """Test that g.version -x output has paired curly brackets.""" + output = gs.read_command("g.version", flags="x", env=session.env).strip() + + def curly_brackets_paired(text): + counter = 0 + for character in text: + if character == "{": + counter += 1 + elif character == "}": + counter -= 1 + if counter < 0: + return False + return counter == 0 + + assert curly_brackets_paired( + output + ), "Curly brackets are not properly paired in the g.version -x output." diff --git a/gui/wxpython/animation/controller.py b/gui/wxpython/animation/controller.py index 1a920f77de7..1a8cb1fe9cc 100644 --- a/gui/wxpython/animation/controller.py +++ b/gui/wxpython/animation/controller.py @@ -465,9 +465,7 @@ def EvaluateInput(self, animationData): mapCount.add(len(layer.maps)) windowIndex.append(anim.windowIndex) - if maps and stds: - temporalMode = TemporalMode.NONTEMPORAL - elif maps: + if (maps and stds) or maps: temporalMode = TemporalMode.NONTEMPORAL elif stds: temporalMode = TemporalMode.TEMPORAL diff --git a/gui/wxpython/animation/dialogs.py b/gui/wxpython/animation/dialogs.py index 154bdc9fce6..bc7e7fe2482 100644 --- a/gui/wxpython/animation/dialogs.py +++ b/gui/wxpython/animation/dialogs.py @@ -24,6 +24,9 @@ import wx import copy import datetime + +from pathlib import Path + import wx.lib.filebrowsebutton as filebrowse import wx.lib.scrolledpanel as SP import wx.lib.colourselect as csel @@ -488,7 +491,7 @@ def _create3DPanel(self, parent): labelText=_("Workspace file:"), dialogTitle=_("Choose workspace file to import 3D view parameters"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=0, fileMask="GRASS Workspace File (*.gxw)|*.gxw", ) @@ -1089,7 +1092,7 @@ def _createDecorationsProperties(self, panel): labelText=_("Image file:"), dialogTitle=_("Choose image file"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=wx.FD_OPEN, changeCallback=self.OnSetImage, ) @@ -1191,7 +1194,7 @@ def _createExportFormatPanel(self, notebook): labelText=_("Directory:"), dialogTitle=_("Choose directory for export"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), ) dirGridSizer = wx.GridBagSizer(hgap=5, vgap=5) @@ -1219,7 +1222,7 @@ def _createExportFormatPanel(self, notebook): labelText=_("GIF file:"), dialogTitle=_("Choose file to save animation"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=wx.FD_SAVE, ) gifGridSizer = wx.GridBagSizer(hgap=5, vgap=5) @@ -1242,7 +1245,7 @@ def _createExportFormatPanel(self, notebook): labelText=_("SWF file:"), dialogTitle=_("Choose file to save animation"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=wx.FD_SAVE, ) swfGridSizer = wx.GridBagSizer(hgap=5, vgap=5) @@ -1273,7 +1276,7 @@ def _createExportFormatPanel(self, notebook): labelText=_("AVI file:"), dialogTitle=_("Choose file to save animation"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=wx.FD_SAVE, ) encodingLabel = StaticText( @@ -1545,37 +1548,36 @@ def _export_file_validation(self, filebrowsebtn, file_path, file_postfix): if not file_path: GError(parent=self, message=_("Export file is missing.")) return False - else: - if not file_path.endswith(file_postfix): - filebrowsebtn.SetValue(file_path + file_postfix) - file_path += file_postfix - - base_dir = os.path.dirname(file_path) - if not os.path.exists(base_dir): - GError( - parent=self, - message=file_path_does_not_exist_err_message.format( - base_dir=base_dir, - ), - ) - return False + if not file_path.endswith(file_postfix): + filebrowsebtn.SetValue(file_path + file_postfix) + file_path += file_postfix - if os.path.exists(file_path): - overwrite_dlg = wx.MessageDialog( - self.GetParent(), - message=_( - "Exported animation file <{file}> exists. " - "Do you want to overwrite it?".format( - file=file_path, - ), - ), - caption=_("Overwrite?"), - style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, - ) - if not overwrite_dlg.ShowModal() == wx.ID_YES: - overwrite_dlg.Destroy() - return False + base_dir = os.path.dirname(file_path) + if not os.path.exists(base_dir): + GError( + parent=self, + message=file_path_does_not_exist_err_message.format( + base_dir=base_dir, + ), + ) + return False + + if os.path.exists(file_path): + overwrite_dlg = wx.MessageDialog( + self.GetParent(), + message=_( + "Exported animation file <{file}> exists. " + "Do you want to overwrite it?" + ).format( + file=file_path, + ), + caption=_("Overwrite?"), + style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, + ) + if overwrite_dlg.ShowModal() != wx.ID_YES: overwrite_dlg.Destroy() + return False + overwrite_dlg.Destroy() return True diff --git a/gui/wxpython/animation/mapwindow.py b/gui/wxpython/animation/mapwindow.py index 749a2da147d..4a6822e0841 100644 --- a/gui/wxpython/animation/mapwindow.py +++ b/gui/wxpython/animation/mapwindow.py @@ -61,7 +61,7 @@ def Draw(self, dc): def OnPaint(self, event): Debug.msg(5, "BufferedWindow.OnPaint()") # All that is needed here is to draw the buffer to screen - dc = wx.BufferedPaintDC(self, self._Buffer) + wx.BufferedPaintDC(self, self._Buffer) def OnSize(self, event): Debug.msg(5, "BufferedWindow.OnSize()") diff --git a/gui/wxpython/animation/provider.py b/gui/wxpython/animation/provider.py index 46eddea7294..43929a1873d 100644 --- a/gui/wxpython/animation/provider.py +++ b/gui/wxpython/animation/provider.py @@ -328,9 +328,8 @@ def LoadOverlay(self, cmd): if returncode == 0: return BitmapFromImage(autoCropImageFromFile(filename)) - else: - os.remove(filename) - raise GException(messages) + os.remove(filename) + raise GException(messages) class BitmapRenderer: @@ -924,7 +923,7 @@ def test(): prov.mapsLoaded.connect(lambda: sys.stdout.write("Maps loading finished\n")) cmdMatrix = layerListToCmdsMatrix(layerList) prov.SetCmds(cmdMatrix, [layer.opacity for layer in layerList]) - app = wx.App() + wx.App() prov.Load(bgcolor=(13, 156, 230), nprocs=4) diff --git a/gui/wxpython/animation/temporal_manager.py b/gui/wxpython/animation/temporal_manager.py index 9f9eafd41d0..ef782543089 100644 --- a/gui/wxpython/animation/temporal_manager.py +++ b/gui/wxpython/animation/temporal_manager.py @@ -18,6 +18,7 @@ """ import datetime +from operator import itemgetter import grass.script as gs import grass.temporal as tgis @@ -195,9 +196,9 @@ def GetLabelsAndMaps(self): # by a temporary dataset, I don't know how it would work with point # data if self.temporalType == TemporalType.ABSOLUTE: - timestamps = sorted(list(labelListSet), key=lambda x: x[0]) + timestamps = sorted(list(labelListSet), key=itemgetter(0)) else: - timestamps = sorted(list(labelListSet), key=lambda x: x[0]) + timestamps = sorted(list(labelListSet), key=itemgetter(0)) newMapLists = [] for mapList, labelList in zip(mapLists, labelLists): @@ -342,7 +343,7 @@ def _gatherInformation(self, timeseries, etype, timeseriesList, infoDict): maps = sp.get_registered_maps_as_objects() if not sp.check_temporal_topology(maps): - raise GException(_("Topology of Space time dataset %s is invalid." % id)) + raise GException(_("Topology of Space time dataset %s is invalid.") % id) timeseriesList.append(id) infoDict[id] = {} diff --git a/gui/wxpython/animation/utils.py b/gui/wxpython/animation/utils.py index 9e5f685545e..5f69bc40d35 100644 --- a/gui/wxpython/animation/utils.py +++ b/gui/wxpython/animation/utils.py @@ -69,8 +69,7 @@ def validateTimeseriesName(timeseries, etype="strds"): nameShort, mapset = timeseries.split("@", 1) if nameShort in trastDict[mapset]: return timeseries - else: - raise GException(_("Space time dataset <%s> not found.") % timeseries) + raise GException(_("Space time dataset <%s> not found.") % timeseries) mapsets = tgis.get_tgis_c_library_interface().available_mapsets() for mapset in mapsets: diff --git a/gui/wxpython/core/debug.py b/gui/wxpython/core/debug.py index cf642d1df4c..b6c12a60b62 100644 --- a/gui/wxpython/core/debug.py +++ b/gui/wxpython/core/debug.py @@ -49,8 +49,8 @@ def SetLevel(self): sys.stderr.write( _( "WARNING: Ignoring unsupported wx debug level (must be >=0 and " - "<=5). {0}\n".format(e) - ) + "<=5). {0}\n" + ).format(e) ) def msg(self, level, message, *args): diff --git a/gui/wxpython/core/gcmd.py b/gui/wxpython/core/gcmd.py index 7d4ed678d79..a173e28c7f8 100644 --- a/gui/wxpython/core/gcmd.py +++ b/gui/wxpython/core/gcmd.py @@ -36,6 +36,12 @@ from threading import Thread import wx +from core.debug import Debug +from core.globalvar import SCT_EXT + +from grass.script import core as grass +from grass.script.utils import decode, encode + is_mswindows = sys.platform == "win32" if is_mswindows: from win32file import ReadFile, WriteFile @@ -45,12 +51,6 @@ import select import fcntl -from core.debug import Debug -from core.globalvar import SCT_EXT - -from grass.script import core as grass -from grass.script.utils import decode, encode - def DecodeString(string): """Decode string using system encoding @@ -202,11 +202,10 @@ def kill(self): handle = win32api.OpenProcess(1, 0, self.pid) return win32api.TerminateProcess(handle, 0) != 0 - else: - try: - os.kill(-self.pid, signal.SIGTERM) # kill whole group - except OSError: - pass + try: + os.kill(-self.pid, signal.SIGTERM) # kill whole group + except OSError: + pass if sys.platform == "win32": @@ -645,11 +644,11 @@ def _formatMsg(text): for line in text.splitlines(): if len(line) == 0: continue - elif "GRASS_INFO_MESSAGE" in line: - message += line.split(":", 1)[1].strip() + "\n" - elif "GRASS_INFO_WARNING" in line: - message += line.split(":", 1)[1].strip() + "\n" - elif "GRASS_INFO_ERROR" in line: + elif ( + "GRASS_INFO_MESSAGE" in line + or "GRASS_INFO_WARNING" in line + or "GRASS_INFO_ERROR" in line + ): message += line.split(":", 1)[1].strip() + "\n" elif "GRASS_INFO_END" in line: return message @@ -750,8 +749,7 @@ def RunCommand( if not read: if not getErrorMsg: return ret - else: - return ret, _formatMsg(stderr) + return ret, _formatMsg(stderr) if stdout: Debug.msg(3, "gcmd.RunCommand(): return stdout\n'%s'" % stdout) diff --git a/gui/wxpython/core/gconsole.py b/gui/wxpython/core/gconsole.py index bad4aac29cd..a4b58435cf4 100644 --- a/gui/wxpython/core/gconsole.py +++ b/gui/wxpython/core/gconsole.py @@ -552,114 +552,111 @@ def RunCmd( wx.PostEvent(self, event) return - else: - # other GRASS commands (r|v|g|...) - try: - task = GUI(show=None).ParseCommand(command) - except GException as e: - GError(parent=self._guiparent, message=str(e), showTraceback=False) - return - - hasParams = False - if task: - options = task.get_options() - hasParams = options["params"] and options["flags"] - # check for =- - for p in options["params"]: - if ( - p.get("prompt", "") == "input" - and p.get("element", "") == "file" - and p.get("age", "new") == "old" - and p.get("value", "") == "-" - ): - GError( - parent=self._guiparent, - message=_( - "Unable to run command:\n%(cmd)s\n\n" - "Option <%(opt)s>: read from standard input is not " - "supported by wxGUI" - ) - % {"cmd": " ".join(command), "opt": p.get("name", "")}, - ) - return - - if len(command) == 1: - if command[0].startswith("g.gui."): - import inspect - import importlib.util - import importlib.machinery + # other GRASS commands (r|v|g|...) + try: + task = GUI(show=None).ParseCommand(command) + except GException as e: + GError(parent=self._guiparent, message=str(e), showTraceback=False) + return - def load_source(modname, filename): - loader = importlib.machinery.SourceFileLoader( - modname, filename - ) - spec = importlib.util.spec_from_file_location( - modname, filename, loader=loader - ) - module = importlib.util.module_from_spec(spec) - # Module is always executed and not cached in sys.modules. - # Uncomment the following line to cache the module. - # sys.modules[module.__name__] = module - loader.exec_module(module) - return module - - pyFile = command[0] - if sys.platform == "win32": - pyFile += ".py" - pyPath = os.path.join(os.environ["GISBASE"], "scripts", pyFile) - if not os.path.exists(pyPath): - pyPath = os.path.join( - os.environ["GRASS_ADDON_BASE"], "scripts", pyFile - ) - if not os.path.exists(pyPath): - GError( - parent=self._guiparent, - message=_("Module <%s> not found.") % command[0], + hasParams = False + if task: + options = task.get_options() + hasParams = options["params"] and options["flags"] + # check for =- + for p in options["params"]: + if ( + p.get("prompt", "") == "input" + and p.get("element", "") == "file" + and p.get("age", "new") == "old" + and p.get("value", "") == "-" + ): + GError( + parent=self._guiparent, + message=_( + "Unable to run command:\n%(cmd)s\n\n" + "Option <%(opt)s>: read from standard input is not " + "supported by wxGUI" ) - pymodule = load_source(command[0].replace(".", "_"), pyPath) - pymain = inspect.getfullargspec(pymodule.main) - if pymain and "giface" in pymain.args: - pymodule.main(self._giface) - return - - # no arguments given - if hasParams and not isinstance(self._guiparent, FormNotebook): - # also parent must be checked, see #3135 for details - try: - GUI( - parent=self._guiparent, giface=self._giface - ).ParseCommand(command) - self.UpdateHistory(status=Status.SUCCESS) - except GException as e: - print(e, file=sys.stderr) + % {"cmd": " ".join(command), "opt": p.get("name", "")}, + ) + return + if len(command) == 1: + if command[0].startswith("g.gui."): + import inspect + import importlib.util + import importlib.machinery + + def load_source(modname, filename): + loader = importlib.machinery.SourceFileLoader(modname, filename) + spec = importlib.util.spec_from_file_location( + modname, filename, loader=loader + ) + module = importlib.util.module_from_spec(spec) + # Module is always executed and not cached in sys.modules. + # Uncomment the following line to cache the module. + # sys.modules[module.__name__] = module + loader.exec_module(module) + return module + + pyFile = command[0] + if sys.platform == "win32": + pyFile += ".py" + pyPath = os.path.join(os.environ["GISBASE"], "scripts", pyFile) + if not os.path.exists(pyPath): + pyPath = os.path.join( + os.environ["GRASS_ADDON_BASE"], "scripts", pyFile + ) + if not os.path.exists(pyPath): + GError( + parent=self._guiparent, + message=_("Module <%s> not found.") % command[0], + ) + pymodule = load_source(command[0].replace(".", "_"), pyPath) + pymain = inspect.getfullargspec(pymodule.main) + if pymain and "giface" in pymain.args: + pymodule.main(self._giface) return - if env: - env = env.copy() - else: - env = os.environ.copy() - # activate computational region (set with g.region) - # for all non-display commands. - if compReg and "GRASS_REGION" in env: - del env["GRASS_REGION"] + # no arguments given + if hasParams and not isinstance(self._guiparent, FormNotebook): + # also parent must be checked, see #3135 for details + try: + GUI(parent=self._guiparent, giface=self._giface).ParseCommand( + command + ) + self.UpdateHistory(status=Status.SUCCESS) + except GException as e: + print(e, file=sys.stderr) - # process GRASS command with argument - self.cmdThread.RunCmd( - command, - stdout=self.cmdStdOut, - stderr=self.cmdStdErr, - onDone=onDone, - onPrepare=onPrepare, - userData=userData, - addLayer=addLayer, - env=env, - notification=notification, - ) - self.cmdOutputTimer.Start(50) + return + + if env: + env = env.copy() + else: + env = os.environ.copy() + # activate computational region (set with g.region) + # for all non-display commands. + if compReg and "GRASS_REGION" in env: + del env["GRASS_REGION"] + + # process GRASS command with argument + self.cmdThread.RunCmd( + command, + stdout=self.cmdStdOut, + stderr=self.cmdStdErr, + onDone=onDone, + onPrepare=onPrepare, + userData=userData, + addLayer=addLayer, + env=env, + notification=notification, + ) + self.cmdOutputTimer.Start(50) - # we don't need to change computational region settings - # because we work on a copy + # we don't need to change computational region settings + # because we work on a copy else: # Send any other command to the shell. Send output to # console output window @@ -678,7 +675,7 @@ def load_source(modname, filename): skipInterface = True if os.path.splitext(command[0])[1] in {".py", ".sh"}: try: - with open(command[0], "r") as sfile: + with open(command[0]) as sfile: for line in sfile: if len(line) < 3: continue @@ -691,7 +688,7 @@ def load_source(modname, filename): if len(command) == 1 and not skipInterface: try: task = gtask.parse_interface(command[0]) - except: + except Exception: task = None else: task = None diff --git a/gui/wxpython/core/giface.py b/gui/wxpython/core/giface.py index 864044593c0..3a1d8c61612 100644 --- a/gui/wxpython/core/giface.py +++ b/gui/wxpython/core/giface.py @@ -60,7 +60,7 @@ def GetSelectedLayers(self, checkedOnly=True): However, this may be the same for some implementations (e.g. it d.mon has all layers checked and selected). """ - raise NotImplementedError() + raise NotImplementedError def GetSelectedLayer(self, checkedOnly=False): """Returns selected layer or None when there is no selected layer. @@ -69,7 +69,7 @@ def GetSelectedLayer(self, checkedOnly=False): Parameter checkedOnly is here False by default. This might change if we find the right way of handling unchecked layers. """ - raise NotImplementedError() + raise NotImplementedError def AddLayer(self, ltype, name=None, checked=None, opacity=1.0, cmd=None): """Adds a new layer to the layer list. @@ -82,7 +82,7 @@ def AddLayer(self, ltype, name=None, checked=None, opacity=1.0, cmd=None): :param opacity: layer opacity level :param cmd: command (given as a list) """ - raise NotImplementedError() + raise NotImplementedError def GetLayersByName(self, name): """Returns list of layers with a given name. @@ -93,7 +93,7 @@ def GetLayersByName(self, name): if common usage is just to check the presence of layer, intoroduce a new method ContainsLayerByName(name) """ - raise NotImplementedError() + raise NotImplementedError def GetLayerByData(self, key, value): """Returns layer with specified. @@ -104,7 +104,7 @@ def GetLayerByData(self, key, value): .. warning:: Avoid using this method, it might be removed in the future. """ - raise NotImplementedError() + raise NotImplementedError class GrassInterface: @@ -118,31 +118,31 @@ class GrassInterface: def RunCmd(self, *args, **kwargs): """Executes a command.""" - raise NotImplementedError() + raise NotImplementedError def Help(self, entry): """Shows a manual page for a given entry.""" - raise NotImplementedError() + raise NotImplementedError def WriteLog(self, text, wrap=None, notification=Notification.HIGHLIGHT): """Writes log message.""" - raise NotImplementedError() + raise NotImplementedError def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE): """Writes message related to start or end of the command.""" - raise NotImplementedError() + raise NotImplementedError def WriteWarning(self, text): """Writes warning message for the user.""" - raise NotImplementedError() + raise NotImplementedError def WriteError(self, text): """Writes error message for the user.""" - raise NotImplementedError() + raise NotImplementedError def GetLog(self, err=False): """Returns file-like object for writing.""" - raise NotImplementedError() + raise NotImplementedError def GetLayerTree(self): """Returns LayerManager's tree GUI object. @@ -150,11 +150,11 @@ def GetLayerTree(self): Will be removed from the interface. """ - raise NotImplementedError() + raise NotImplementedError def GetLayerList(self): """Returns a layer management object.""" - raise NotImplementedError() + raise NotImplementedError def GetMapDisplay(self): """Returns current map display. @@ -166,7 +166,7 @@ def GetMapDisplay(self): :return: MapFrame instance :return: None when no mapdisplay open """ - raise NotImplementedError() + raise NotImplementedError def GetAllMapDisplays(self): """Get list of all map displays. @@ -177,7 +177,7 @@ def GetAllMapDisplays(self): :return: list of MapFrame instances """ - raise NotImplementedError() + raise NotImplementedError def GetMapWindow(self): """Returns current map window. @@ -186,7 +186,7 @@ def GetMapWindow(self): For layer related tasks use GetLayerList(). """ - raise NotImplementedError() + raise NotImplementedError def GetProgress(self): """Returns object which shows the progress. @@ -195,7 +195,7 @@ def GetProgress(self): Some implementations may not implement this method. """ - raise NotImplementedError() + raise NotImplementedError class StandaloneGrassInterface(GrassInterface): @@ -343,9 +343,9 @@ def GetAllMapDisplays(self): return [] def GetMapWindow(self): - raise NotImplementedError() + raise NotImplementedError def GetProgress(self): # TODO: implement some progress with same inface as gui one # (probably using g.message or similarly to Write... functions) - raise NotImplementedError() + raise NotImplementedError diff --git a/gui/wxpython/core/gthread.py b/gui/wxpython/core/gthread.py index 7bd8929c553..3437d04bf56 100644 --- a/gui/wxpython/core/gthread.py +++ b/gui/wxpython/core/gthread.py @@ -95,8 +95,6 @@ def run(self): else: vars()[key] = None - requestTime = time.time() - ret = None exception = None time.sleep(0.01) @@ -154,15 +152,14 @@ def __run(self): def globaltrace(self, frame, event, arg): if event == "call": return self.localtrace - else: - return None + return None def localtrace(self, frame, event, arg): if self.terminate: if event == "line": # Send event wx.PostEvent(self, self._terminate_evt) - raise SystemExit() + raise SystemExit return self.localtrace def OnTerminate(self, event): diff --git a/gui/wxpython/core/layerlist.py b/gui/wxpython/core/layerlist.py index b1a9448227d..5b14a4039fd 100644 --- a/gui/wxpython/core/layerlist.py +++ b/gui/wxpython/core/layerlist.py @@ -125,7 +125,7 @@ def GetLayerByData(self, key, value): .. warning:: Avoid using this method, it might be removed in the future. """ - raise NotImplementedError() + raise NotImplementedError def GetLayerIndex(self, layer): """Get index of layer.""" diff --git a/gui/wxpython/core/menutree.py b/gui/wxpython/core/menutree.py index 4c55d7e9521..fba33daf705 100644 --- a/gui/wxpython/core/menutree.py +++ b/gui/wxpython/core/menutree.py @@ -160,10 +160,9 @@ def GetModel(self, separators=False): """ if separators: return copy.deepcopy(self.model) - else: - model = copy.deepcopy(self.model) - removeSeparators(model) - return model + model = copy.deepcopy(self.model) + removeSeparators(model) + return model def PrintTree(self, fh): for child in self.model.root.children: diff --git a/gui/wxpython/core/render.py b/gui/wxpython/core/render.py index 021f3aa6500..2db3287bf78 100644 --- a/gui/wxpython/core/render.py +++ b/gui/wxpython/core/render.py @@ -229,10 +229,8 @@ def GetCmd(self, string=False): scmd.append(utils.GetCmdString(c)) return ";".join(scmd) - else: - return utils.GetCmdString(self.cmd) - else: - return self.cmd + return utils.GetCmdString(self.cmd) + return self.cmd def GetType(self): """Get map layer type""" @@ -462,8 +460,7 @@ def _render(self, cmd, env): stdout, stderr = p.communicate() if p.returncode: return grass.decode(stderr) - else: - return None + return None def Abort(self): """Abort rendering process""" @@ -666,8 +663,6 @@ def OnRenderDone(self, env): Make image composiotion, emits updateMap event. """ - stopTime = time.time() - maps = [] masks = [] opacities = [] @@ -706,7 +701,7 @@ def OnRenderDone(self, env): self._rendering = False if wx.IsBusy(): wx.EndBusyCursor() - raise GException(_("Rendering failed: %s" % msg)) + raise GException(_("Rendering failed: %s") % msg) stop = time.time() Debug.msg( @@ -898,7 +893,7 @@ def GetWindow(self): env["GISDBASE"], env["LOCATION_NAME"], env["MAPSET"], "WIND" ) try: - windfile = open(filename, "r") + windfile = open(filename) except OSError as e: sys.exit( _("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n") @@ -1239,7 +1234,7 @@ def SetRegion(self, windres=False, windres3=False): return grass_region - except: + except Exception: return None def GetListOfLayers( @@ -1692,8 +1687,7 @@ def GetOverlay(self, id, list=False): if not list: if len(ovl) != 1: return None - else: - return ovl[0] + return ovl[0] return ovl diff --git a/gui/wxpython/core/settings.py b/gui/wxpython/core/settings.py index 45620220aed..5cc2fddaf44 100644 --- a/gui/wxpython/core/settings.py +++ b/gui/wxpython/core/settings.py @@ -59,8 +59,7 @@ def color(item): return [color(e) for e in item] if isinstance(item, dict): return {key: color(value) for key, value in item.items()} - else: - return item + return item return super().iterencode(color(obj)) @@ -110,7 +109,7 @@ def _generateLocale(self): self.locs.sort() # Add a default choice to not override system locale self.locs.insert(0, "system") - except: + except Exception: # No NLS self.locs = ["system"] @@ -922,7 +921,7 @@ def update_nested_dict_by_dict(dictionary, update): return dictionary try: - with open(self.filePath, "r") as f: + with open(self.filePath) as f: update = json.load(f, object_hook=settings_JSON_decode_hook) update_nested_dict_by_dict(settings, update) except json.JSONDecodeError as e: @@ -942,7 +941,7 @@ def _readLegacyFile(self, settings=None): settings = self.userSettings try: - fd = open(self.legacyFilePath, "r") + fd = open(self.legacyFilePath) except OSError: sys.stderr.write( _("Unable to read settings file <%s>\n") % self.legacyFilePath @@ -992,7 +991,7 @@ def SaveToFile(self, settings=None): if not os.path.exists(dirPath): try: os.mkdir(dirPath) - except: + except OSError: GError(_("Unable to create settings directory")) return try: diff --git a/gui/wxpython/core/testsuite/test_gcmd.py b/gui/wxpython/core/testsuite/test_gcmd.py index 121ede99b77..75d3bf5932b 100644 --- a/gui/wxpython/core/testsuite/test_gcmd.py +++ b/gui/wxpython/core/testsuite/test_gcmd.py @@ -1,5 +1,6 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows class Rcv: @@ -16,6 +17,8 @@ def recv(self): class Recv_SomeTest(TestCase): + + @xfail_windows def test_decode(self): """ Multibyte chars should not be split diff --git a/gui/wxpython/core/toolboxes.py b/gui/wxpython/core/toolboxes.py index 441898fa8f6..46b886e4996 100644 --- a/gui/wxpython/core/toolboxes.py +++ b/gui/wxpython/core/toolboxes.py @@ -209,7 +209,7 @@ def getMenudataFile(userRootFile, newFile, fallback): fh.write(xml) fh.close() return menudataFile - except: + except Exception: _debug( 2, ( @@ -855,15 +855,14 @@ def module_test(): someDiff = False for line in result: - if line.startswith("+") or line.startswith("-"): + if line.startswith(("+", "-")): sys.stdout.write(line) someDiff = True if someDiff: print("Difference between files.") return 1 - else: - print("OK") - return 0 + print("OK") + return 0 def validate_file(filename): diff --git a/gui/wxpython/core/treemodel.py b/gui/wxpython/core/treemodel.py index dd84fed7bf9..fb18384ba36 100644 --- a/gui/wxpython/core/treemodel.py +++ b/gui/wxpython/core/treemodel.py @@ -137,8 +137,7 @@ def GetChildrenByIndex(self, index): def _getNode(self, node, index): if len(index) == 1: return node.children[index[0]] - else: - return self._getNode(node.children[index[0]], index[1:]) + return self._getNode(node.children[index[0]], index[1:]) def RemoveNode(self, node): """Removes node. If node is root, removes root's children, root is kept.""" @@ -257,7 +256,7 @@ def match(self, method="exact", **kwargs): if method == "exact": return self._match_exact(**kwargs) - elif method == "filtering": + if method == "filtering": return self._match_filtering(**kwargs) def _match_exact(self, **kwargs): diff --git a/gui/wxpython/core/utils.py b/gui/wxpython/core/utils.py index fe4f40c359a..3c1b4a7dd14 100644 --- a/gui/wxpython/core/utils.py +++ b/gui/wxpython/core/utils.py @@ -45,8 +45,7 @@ def split(s): try: if sys.platform == "win32": return shlex.split(s.replace("\\", r"\\")) - else: - return shlex.split(s) + return shlex.split(s) except ValueError as e: sys.stderr.write(_("Syntax error: %s") % e) @@ -75,9 +74,8 @@ def GetTempfile(pref=None): path, file = os.path.split(tempfile) if pref: return os.path.join(pref, file) - else: - return tempfile - except: + return tempfile + except Exception: return None @@ -255,7 +253,7 @@ def ListOfCatsToRange(cats): try: cats = list(map(int, cats)) - except: + except ValueError: return catstr i = 0 @@ -341,8 +339,7 @@ def GetVectorNumberOfLayers(vector): _("Vector map <%(map)s>: %(msg)s\n") % {"map": fullname, "msg": msg} ) return layers - else: - Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret) + Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret) for layer in out.splitlines(): layers.append(layer) @@ -374,8 +371,7 @@ def Deg2DMS(lon, lat, string=True, hemisphere=True, precision=3): except ValueError: if string: return "" - else: - return None + return None # fix longitude while flon > 180.0: @@ -457,38 +453,38 @@ def __ll_parts(value, reverse=False, precision=3): s = "%.*f" % (precision, s) return str(d) + ":" + m + ":" + s - else: # -> reverse + # -> reverse + try: + d, m, s = value.split(":") + hs = s[-1] + s = s[:-1] + except ValueError: try: - d, m, s = value.split(":") - hs = s[-1] - s = s[:-1] + d, m = value.split(":") + hs = m[-1] + m = m[:-1] + s = "0.0" except ValueError: try: - d, m = value.split(":") - hs = m[-1] - m = m[:-1] + d = value + hs = d[-1] + d = d[:-1] + m = "0" s = "0.0" except ValueError: - try: - d = value - hs = d[-1] - d = d[:-1] - m = "0" - s = "0.0" - except ValueError: - raise ValueError + raise ValueError - if hs not in {"N", "S", "E", "W"}: - raise ValueError + if hs not in {"N", "S", "E", "W"}: + raise ValueError - coef = 1.0 - if hs in {"S", "W"}: - coef = -1.0 + coef = 1.0 + if hs in {"S", "W"}: + coef = -1.0 - fm = int(m) / 60.0 - fs = float(s) / (60 * 60) + fm = int(m) / 60.0 + fs = float(s) / (60 * 60) - return coef * (float(d) + fm + fs) + return coef * (float(d) + fm + fs) def GetCmdString(cmd): @@ -555,11 +551,10 @@ def ReprojectCoordinates(coord, projOut, projIn=None, flags=""): proj = "" if proj in {"ll", "latlong", "longlat"} and "d" not in flags: return (proj, (e, n)) - else: - try: - return (proj, (float(e), float(n))) - except ValueError: - return (None, None) + try: + return (proj, (float(e), float(n))) + except ValueError: + return (None, None) return (None, None) @@ -579,7 +574,7 @@ def GetListOfLocations(dbase): os.path.join(location, "*") ): listOfLocations.append(os.path.basename(location)) - except: + except OSError: pass ListSortLower(listOfLocations) @@ -632,7 +627,7 @@ def _getGDALFormats(): """Get dictionary of available GDAL drivers""" try: ret = grass.read_command("r.in.gdal", quiet=True, flags="f") - except: + except grass.CalledModuleError: ret = None return _parseFormats(ret), _parseFormats(ret, writableOnly=True) @@ -642,7 +637,7 @@ def _getOGRFormats(): """Get dictionary of available OGR drivers""" try: ret = grass.read_command("v.in.ogr", quiet=True, flags="f") - except: + except grass.CalledModuleError: ret = None return _parseFormats(ret), _parseFormats(ret, writableOnly=True) @@ -827,8 +822,12 @@ def StoreEnvVariable(key, value=None, envFile=None): if os.path.exists(envFile): try: fd = open(envFile) - except OSError as e: - sys.stderr.write(_("Unable to open file '%s'\n") % envFile) + except OSError as error: + sys.stderr.write( + _("Unable to open file '{name}': {error}\n").format( + name=envFile, error=error + ) + ) return for line in fd: line = line.rstrip(os.linesep) @@ -857,8 +856,12 @@ def StoreEnvVariable(key, value=None, envFile=None): # write update env file try: fd = open(envFile, "w") - except OSError as e: - sys.stderr.write(_("Unable to create file '%s'\n") % envFile) + except OSError as error: + sys.stderr.write( + _("Unable to create file '{name}': {error}\n").format( + name=envFile, error=error + ) + ) return if windows: expCmd = "set" diff --git a/gui/wxpython/core/watchdog.py b/gui/wxpython/core/watchdog.py index 9315a1010d6..76302aeea0a 100644 --- a/gui/wxpython/core/watchdog.py +++ b/gui/wxpython/core/watchdog.py @@ -20,6 +20,13 @@ import os import time +from pathlib import Path + +import wx +from wx.lib.newevent import NewEvent + +from grass.script import core as grass + watchdog_used = True try: from watchdog.observers import Observer @@ -32,11 +39,6 @@ PatternMatchingEventHandler = object FileSystemEventHandler = object -import wx -from wx.lib.newevent import NewEvent - -from grass.script import core as grass - updateMapset, EVT_UPDATE_MAPSET = NewEvent() currentMapsetChanged, EVT_CURRENT_MAPSET_CHANGED = NewEvent() @@ -60,13 +62,13 @@ def on_modified(self, event): not event.is_directory and os.path.basename(event.src_path) == self.rcfile_name ): - timestamp = os.stat(event.src_path).st_mtime + timestamp = Path(event.src_path).stat().st_mtime if timestamp - self.modified_time < 0.5: return self.modified_time = timestamp # wait to make sure file writing is done time.sleep(0.1) - with open(event.src_path, "r") as f: + with open(event.src_path) as f: gisrc = {} for line in f: key, val = line.split(":") diff --git a/gui/wxpython/core/workspace.py b/gui/wxpython/core/workspace.py index 7e5f85d6649..22aa56bfe62 100644 --- a/gui/wxpython/core/workspace.py +++ b/gui/wxpython/core/workspace.py @@ -123,7 +123,7 @@ def __processFile(self): try: self.layerManager["pos"] = (posVal[0], posVal[1]) self.layerManager["size"] = (posVal[2], posVal[3]) - except: + except IndexError: pass # current working directory cwdPath = self.__getNodeText(node_lm, "cwd") @@ -155,7 +155,7 @@ def __processFile(self): try: pos = (posVal[0], posVal[1]) size = (posVal[2], posVal[3]) - except: + except IndexError: pos = None size = None # this happens on Windows when mapwindow is minimized when @@ -933,7 +933,7 @@ def __init__(self, lmgr, file): file.write("{indent}\n".format(indent=" " * self.indent)) # list of displays - for page in range(0, self.lmgr.GetLayerNotebook().GetPageCount()): + for page in range(self.lmgr.GetLayerNotebook().GetPageCount()): dispName = self.lmgr.GetLayerNotebook().GetPageText(page) mapTree = self.lmgr.GetLayerNotebook().GetPage(page).maptree region = mapTree.GetMap().GetCurrentRegion() @@ -1608,15 +1608,15 @@ def __writeNvizState(self, view, iview, light, constants): if constants: self.file.write("%s\n" % (" " * self.indent)) self.indent += 4 - for idx, plane in enumerate(constants): + for plane in constants: self.file.write("%s\n" % (" " * self.indent)) self.indent += 4 - self.__writeTagWithValue("height", constants[idx]["constant"]["value"]) + self.__writeTagWithValue("height", plane["constant"]["value"]) self.__writeTagWithValue( - "fine_resolution", constants[idx]["constant"]["resolution"] + "fine_resolution", plane["constant"]["resolution"] ) self.__writeTagWithValue( - "color", constants[idx]["constant"]["color"], format="s" + "color", plane["constant"]["color"], format="s" ) self.indent -= 4 self.file.write("%s\n" % (" " * self.indent)) @@ -1742,7 +1742,7 @@ def read(self, parent): :return: list of map layers """ try: - file = open(self.filename, "r") + file = open(self.filename) except OSError: wx.MessageBox( parent=parent, @@ -2019,7 +2019,7 @@ def _get_value(self, line): """Get value of element""" try: return line.strip(" ").split(" ")[1].strip(" ") - except: + except IndexError: return "" def _get_element(self, line): diff --git a/gui/wxpython/core/ws.py b/gui/wxpython/core/ws.py index 156cd0166f9..010deac824f 100644 --- a/gui/wxpython/core/ws.py +++ b/gui/wxpython/core/ws.py @@ -99,7 +99,6 @@ def Render(self, cmd, env): self.updateMap = True fetchData = True # changed to True when calling Render() - zoomChanged = False if self.renderedRegion is None or cmd != self.fetched_data_cmd: fetchData = True @@ -111,7 +110,6 @@ def Render(self, cmd, env): for c in ["e-w resol", "n-s resol"]: if self.renderedRegion and region[c] != self.renderedRegion[c]: - zoomChanged = True break if fetchData: diff --git a/gui/wxpython/datacatalog/catalog.py b/gui/wxpython/datacatalog/catalog.py index 880190b0943..4835061d968 100644 --- a/gui/wxpython/datacatalog/catalog.py +++ b/gui/wxpython/datacatalog/catalog.py @@ -19,6 +19,8 @@ import wx import os +from pathlib import Path + from core.debug import Debug from datacatalog.tree import DataCatalogTree from datacatalog.toolbars import DataCatalogToolbar, DataCatalogSearch @@ -200,7 +202,10 @@ def OnReloadCurrentMapset(self, event): def OnAddGrassDB(self, event): """Add grass database""" dlg = wx.DirDialog( - self, _("Choose GRASS data directory:"), os.getcwd(), wx.DD_DEFAULT_STYLE + self, + _("Choose GRASS data directory:"), + str(Path.cwd()), + wx.DD_DEFAULT_STYLE, ) if dlg.ShowModal() == wx.ID_OK: grassdatabase = dlg.GetPath() diff --git a/gui/wxpython/datacatalog/tree.py b/gui/wxpython/datacatalog/tree.py index faa0a6aac73..176f5231712 100644 --- a/gui/wxpython/datacatalog/tree.py +++ b/gui/wxpython/datacatalog/tree.py @@ -184,13 +184,13 @@ def label(self): owner = data["owner"] or _("name unknown") if data["current"]: return _("{name} (current)").format(**data) - elif data["is_different_owner"] and data["lock"]: + if data["is_different_owner"] and data["lock"]: return _("{name} (in use, owner: {owner})").format( name=data["name"], owner=owner ) - elif data["lock"]: + if data["lock"]: return _("{name} (in use)").format(**data) - elif data["is_different_owner"]: + if data["is_different_owner"]: return _("{name} (owner: {owner})").format( name=data["name"], owner=owner ) @@ -957,7 +957,7 @@ def OnGetItemTextColour(self, index): if node.data["type"] == "mapset": if node.data["current"]: return wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) - elif node.data["lock"] or node.data["is_different_owner"]: + if node.data["lock"] or node.data["is_different_owner"]: return wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT) return wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT) @@ -1378,15 +1378,20 @@ def OnPasteMap(self, event): ) if not new_name: continue - callback = lambda gisrc2=gisrc2, gisrc=gisrc, cLayer=self.copy_layer[ - i - ], cMapset=self.copy_mapset[ - i - ], cMode=self.copy_mode, sMapset=self.selected_mapset[ - 0 - ], name=new_name: self._onDoneReprojection( - env2, gisrc2, gisrc, cLayer, cMapset, cMode, sMapset, name - ) + + def callback( + gisrc2=gisrc2, + gisrc=gisrc, + cLayer=self.copy_layer[i], + cMapset=self.copy_mapset[i], + cMode=self.copy_mode, + sMapset=self.selected_mapset[0], + name=new_name, + ): + self._onDoneReprojection( + env2, gisrc2, gisrc, cLayer, cMapset, cMode, sMapset, name + ) + dlg = CatalogReprojectionDialog( self, self._giface, @@ -2047,8 +2052,7 @@ def _isCurrent(self, genv): currentMapset = False break return currentGrassDb, currentLocation, currentMapset - else: - return True, True, True + return True, True, True def _popupMenuLayer(self): """Create popup menu for layers""" diff --git a/gui/wxpython/dbmgr/base.py b/gui/wxpython/dbmgr/base.py index 66321fcafda..1af8d6fccb1 100644 --- a/gui/wxpython/dbmgr/base.py +++ b/gui/wxpython/dbmgr/base.py @@ -208,7 +208,7 @@ def LoadData(self, layer, columns=None, where=None, sql=None): try: # for maps connected via v.external keyId = columns.index(keyColumn) - except: + except ValueError: keyId = -1 # read data @@ -706,8 +706,7 @@ def Sorter(self, key1, key2): if ascending: return cmpVal - else: - return -cmpVal + return -cmpVal def GetSortImages(self): """Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py""" @@ -961,7 +960,7 @@ def OnLayerPageChanged(self, event): self.layerPage[self.selLayer]["data"] ).GetItemCount() ) - except: + except Exception: pass if idCol: @@ -1640,7 +1639,7 @@ def OnDataItemAdd(self, event): if dlg.ShowModal() == wx.ID_OK: try: # get category number cat = int(dlg.GetValues(columns=[keyColumn])[0]) - except: + except ValueError: cat = -1 try: @@ -1672,7 +1671,7 @@ def OnDataItemAdd(self, event): values[i] = int(float(values[i])) elif tlist.columns[columnName[i]]["ctype"] == float: values[i] = float(values[i]) - except: + except ValueError: raise ValueError( _("Value '%(value)s' needs to be entered as %(type)s.") % { @@ -1680,6 +1679,13 @@ def OnDataItemAdd(self, event): "type": tlist.columns[columnName[i]]["type"], } ) + except KeyError: + raise KeyError( + _("Column '%(column)s' does not exist.") + % { + "column": columnName[i], + } + ) columnsString += "%s," % columnName[i] if tlist.columns[columnName[i]]["ctype"] == str: @@ -1997,37 +2003,36 @@ def OnExtractSelected(self, event): if len(cats) == 0: GMessage(parent=self, message=_("Nothing to extract.")) return - else: - # dialog to get file name - dlg = CreateNewVector( - parent=self, - title=_("Extract selected features"), - giface=self.giface, - cmd=( - ( - "v.extract", - { - "input": self.dbMgrData["vectName"], - "cats": ListOfCatsToRange(cats), - }, - "output", - ) - ), - disableTable=True, - ) - if not dlg: - return + # dialog to get file name + dlg = CreateNewVector( + parent=self, + title=_("Extract selected features"), + giface=self.giface, + cmd=( + ( + "v.extract", + { + "input": self.dbMgrData["vectName"], + "cats": ListOfCatsToRange(cats), + }, + "output", + ) + ), + disableTable=True, + ) + if not dlg: + return - name = dlg.GetName(full=True) + name = dlg.GetName(full=True) - if not self.mapdisplay and self.mapdisplay.tree: - pass - elif name and dlg.IsChecked("add"): - # add layer to map layer tree - self.mapdisplay.tree.AddLayer( - ltype="vector", lname=name, lcmd=["d.vect", "map=%s" % name] - ) - dlg.Destroy() + if not self.mapdisplay and self.mapdisplay.tree: + pass + elif name and dlg.IsChecked("add"): + # add layer to map layer tree + self.mapdisplay.tree.AddLayer( + ltype="vector", lname=name, lcmd=["d.vect", "map=%s" % name] + ) + dlg.Destroy() def OnDeleteSelected(self, event): """Delete vector objects selected in attribute browse window @@ -2599,43 +2604,41 @@ def OnTableItemChange(self, event): message=_("Unable to rename column. No column name defined."), ) return - else: - item = tlist.FindItem(start=-1, str=name) - if item > -1: - if tlist.FindItem(start=-1, str=nameTo) > -1: - GError( - parent=self, - message=_( - "Unable to rename column <%(column)s> to " - "<%(columnTo)s>. Column already exists " - "in the table <%(table)s>." - ) - % {"column": name, "columnTo": nameTo, "table": table}, - ) - return - else: - tlist.SetItemText(item, nameTo) - - self.listOfCommands.append( - ( - "v.db.renamecolumn", - { - "map": self.dbMgrData["vectName"], - "layer": self.selLayer, - "column": "%s,%s" % (name, nameTo), - }, - ) - ) - else: + item = tlist.FindItem(start=-1, str=name) + if item > -1: + if tlist.FindItem(start=-1, str=nameTo) > -1: GError( parent=self, message=_( - "Unable to rename column. " - "Column <%(column)s> doesn't exist in the table <%(table)s>." + "Unable to rename column <%(column)s> to " + "<%(columnTo)s>. Column already exists " + "in the table <%(table)s>." ) - % {"column": name, "table": table}, + % {"column": name, "columnTo": nameTo, "table": table}, ) return + tlist.SetItemText(item, nameTo) + + self.listOfCommands.append( + ( + "v.db.renamecolumn", + { + "map": self.dbMgrData["vectName"], + "layer": self.selLayer, + "column": "%s,%s" % (name, nameTo), + }, + ) + ) + else: + GError( + parent=self, + message=_( + "Unable to rename column. " + "Column <%(column)s> doesn't exist in the table <%(table)s>." + ) + % {"column": name, "table": table}, + ) + return # apply changes self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements) @@ -3809,7 +3812,7 @@ def OnDeleteLayer(self, event): """Delete layer""" try: layer = int(self.deleteLayer.GetValue()) - except: + except ValueError: return RunCommand( @@ -3856,10 +3859,10 @@ def OnChangeLayer(self, event): """Layer number of layer to be deleted is changed""" try: layer = int(event.GetString()) - except: + except ValueError: try: - layer = self.mapDBInfo.layers.keys()[0] - except: + layer = list(self.mapDBInfo.layers.keys())[0] + except IndexError: return if self.GetCurrentPage() == self.modifyPanel: diff --git a/gui/wxpython/dbmgr/dialogs.py b/gui/wxpython/dbmgr/dialogs.py index 26e6d876371..0d7c6e9e523 100644 --- a/gui/wxpython/dbmgr/dialogs.py +++ b/gui/wxpython/dbmgr/dialogs.py @@ -222,10 +222,11 @@ def GetSQLString(self, updateValues=False): ctype = columns[name]["ctype"] value = columns[name]["values"][idx] id = columns[name]["ids"][idx] + widget = self.FindWindowById(id) try: - newvalue = self.FindWindowById(id).GetValue() - except: - newvalue = self.FindWindowById(id).GetLabel() + newvalue = widget.GetValue() + except AttributeError: + newvalue = widget.GetLabel() if newvalue: try: diff --git a/gui/wxpython/dbmgr/manager.py b/gui/wxpython/dbmgr/manager.py index c866bd55650..b1cbd93ab71 100644 --- a/gui/wxpython/dbmgr/manager.py +++ b/gui/wxpython/dbmgr/manager.py @@ -70,7 +70,7 @@ def __init__( self.parent = parent try: mapdisplay = self.parent.GetMapDisplay() - except: + except AttributeError: mapdisplay = None DbMgrBase.__init__( diff --git a/gui/wxpython/dbmgr/sqlbuilder.py b/gui/wxpython/dbmgr/sqlbuilder.py index 36827698efc..5e6fe0e7706 100644 --- a/gui/wxpython/dbmgr/sqlbuilder.py +++ b/gui/wxpython/dbmgr/sqlbuilder.py @@ -359,7 +359,7 @@ def OnUniqueValues(self, event, justsample=False): try: idx = self.list_columns.GetSelections()[0] column = self.list_columns.GetString(idx) - except: + except IndexError: self.list_values.Clear() return diff --git a/gui/wxpython/dbmgr/vinfo.py b/gui/wxpython/dbmgr/vinfo.py index 6b04ee7a64e..c32ac5572b4 100644 --- a/gui/wxpython/dbmgr/vinfo.py +++ b/gui/wxpython/dbmgr/vinfo.py @@ -37,8 +37,7 @@ def GetUnicodeValue(value): if isinstance(value, bytes): enc = GetDbEncoding() return str(value, enc, errors="replace") - else: - return str(value) + return str(value) def GetDbEncoding(): diff --git a/gui/wxpython/docs/wxgui_sphinx/conf.py b/gui/wxpython/docs/wxgui_sphinx/conf.py index 3641c2aab48..f0b61a31996 100644 --- a/gui/wxpython/docs/wxgui_sphinx/conf.py +++ b/gui/wxpython/docs/wxgui_sphinx/conf.py @@ -10,21 +10,9 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys -import os from datetime import date import string from shutil import copy - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -if not os.getenv("GISBASE"): - sys.exit("GISBASE not defined") -sys.path.insert( - 0, os.path.abspath(os.path.join(os.environ["GISBASE"], "etc", "python", "grass")) -) - from grass.script import core footer_tmpl = string.Template( diff --git a/gui/wxpython/gcp/g.gui.gcp.py b/gui/wxpython/gcp/g.gui.gcp.py index 32ef2c4fc0d..12f0a152090 100755 --- a/gui/wxpython/gcp/g.gui.gcp.py +++ b/gui/wxpython/gcp/g.gui.gcp.py @@ -65,7 +65,7 @@ def main(): app = wx.App() - wizard = GCPWizard(parent=None, giface=StandaloneGrassInterface()) + GCPWizard(parent=None, giface=StandaloneGrassInterface()) app.MainLoop() diff --git a/gui/wxpython/gcp/manager.py b/gui/wxpython/gcp/manager.py index ac006a95cbf..3b6dd398b51 100644 --- a/gui/wxpython/gcp/manager.py +++ b/gui/wxpython/gcp/manager.py @@ -119,7 +119,7 @@ def __init__(self, parent, giface): self.target_gisrc = os.environ["GISRC"] self.gisrc_dict = {} try: - f = open(self.target_gisrc, "r") + f = open(self.target_gisrc) for line in f: line = line.replace("\n", "").strip() if len(line) < 1: @@ -880,20 +880,6 @@ def OnSrcSelection(self, event): else: wx.FindWindowById(wx.ID_FORWARD).Enable(True) - try: - # set computational region to match selected map and zoom display - # to region - if maptype == "raster": - p = RunCommand("g.region", "raster=src_map") - elif maptype == "vector": - p = RunCommand("g.region", "vector=src_map") - - if p.returncode == 0: - print("returncode = ", str(p.returncode)) - self.parent.Map.region = self.parent.Map.GetRegion() - except: - pass - def OnTgtRastSelection(self, event): """Source map to display selected""" global tgt_map @@ -1272,7 +1258,7 @@ def InitMapDisplay(self): # initialize column sorter self.itemDataMap = self.mapcoordlist ncols = self.list.GetColumnCount() - ColumnSorterMixin(self, ncols) + ColumnSorterMixin.__init__(self, ncols) # noqa: PLC2801, C2801 # init to ascending sort on first click self._colSortFlag = [1] * ncols @@ -1603,7 +1589,7 @@ def ReadGCPs(self): GError(parent=self, message=_("target mapwin not defined")) try: - f = open(self.file["points"], "r") + f = open(self.file["points"]) GCPcnt = 0 for line in f: @@ -1785,11 +1771,10 @@ def _getOverWriteDialog(self, maptype, overwrite): return wx.MessageDialog( self.GetParent(), message=_( - "The {map_type} map {map_name} exists. " - "Do you want to overwrite?".format( - map_type=maptype, - map_name=map_name, - ), + "The {map_type} map {map_name} exists. Do you want to overwrite?" + ).format( + map_type=maptype, + map_name=map_name, ), caption=_("Overwrite?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, @@ -1811,7 +1796,7 @@ def OnGeorect(self, event): overwrite=self.overwrite, ) if overwrite_dlg: - if not overwrite_dlg.ShowModal() == wx.ID_YES: + if overwrite_dlg.ShowModal() != wx.ID_YES: overwrite_dlg.Destroy() return overwrite_dlg.Destroy() @@ -1826,23 +1811,21 @@ def OnGeorect(self, event): else: flags = "a" - busy = wx.BusyInfo(_("Rectifying images, please wait..."), parent=self) - wx.GetApp().Yield() - - ret, msg = RunCommand( - "i.rectify", - parent=self, - getErrorMsg=True, - quiet=True, - group=self.xygroup, - extension=self.extension, - order=self.gr_order, - method=self.gr_method, - flags=flags, - overwrite=overwrite, - ) + with wx.BusyInfo(_("Rectifying images, please wait..."), parent=self): + wx.GetApp().Yield() - del busy + ret, msg = RunCommand( + "i.rectify", + parent=self, + getErrorMsg=True, + quiet=True, + group=self.xygroup, + extension=self.extension, + order=self.gr_order, + method=self.gr_method, + flags=flags, + overwrite=overwrite, + ) # provide feedback on failure if ret != 0: @@ -1873,7 +1856,7 @@ def OnGeorect(self, event): overwrite=self.overwrite, ) if overwrite_dlg: - if not overwrite_dlg.ShowModal() == wx.ID_YES: + if overwrite_dlg.ShowModal() != wx.ID_YES: overwrite_dlg.Destroy() return overwrite_dlg.Destroy() @@ -1886,24 +1869,22 @@ def OnGeorect(self, event): ) ret = msg = "" - busy = wx.BusyInfo( + with wx.BusyInfo( _("Rectifying vector map <%s>, please wait...") % vect, parent=self - ) - wx.GetApp().Yield() - - ret, msg = RunCommand( - "v.rectify", - parent=self, - getErrorMsg=True, - quiet=True, - input=vect, - output=self.outname, - group=self.xygroup, - order=self.gr_order, - overwrite=overwrite, - ) - - del busy + ): + wx.GetApp().Yield() + + ret, msg = RunCommand( + "v.rectify", + parent=self, + getErrorMsg=True, + quiet=True, + input=vect, + output=self.outname, + group=self.xygroup, + order=self.gr_order, + overwrite=overwrite, + ) # provide feedback on failure if ret != 0: @@ -2028,7 +2009,6 @@ def OnGROrder(self, event): elif self.gr_order == 2: minNumOfItems = 6 - diff = 6 - numOfItems # self.SetStatusText( # _('Insufficient points, 6+ points needed for 2nd order')) @@ -2306,7 +2286,7 @@ def AdjustMap(self, newreg): def OnZoomToSource(self, event): """Set target map window to match extents of source map window""" - if not self.MapWindow == self.TgtMapWindow: + if self.MapWindow != self.TgtMapWindow: self.MapWindow = self.TgtMapWindow self.Map = self.TgtMap self.UpdateActive(self.TgtMapWindow) @@ -2319,7 +2299,7 @@ def OnZoomToSource(self, event): def OnZoomToTarget(self, event): """Set source map window to match extents of target map window""" - if not self.MapWindow == self.SrcMapWindow: + if self.MapWindow != self.SrcMapWindow: self.MapWindow = self.SrcMapWindow self.Map = self.SrcMap self.UpdateActive(self.SrcMapWindow) @@ -2331,7 +2311,6 @@ def OnZoomToTarget(self, event): def OnZoomMenuGCP(self, event): """Popup Zoom menu""" - point = wx.GetMousePosition() zoommenu = Menu() # Add items to the menu @@ -3330,7 +3309,7 @@ def OnSrcSelection(self, event): tmp_map = self.srcselection.GetValue() - if not tmp_map == "" and not tmp_map == src_map: + if tmp_map not in ("", src_map): self.new_src_map = tmp_map def OnTgtRastSelection(self, event): @@ -3433,7 +3412,6 @@ def UpdateSettings(self): srcrenderVector = False tgtrender = False tgtrenderVector = False - reload_target = False if self.new_src_map != src_map: # remove old layer layers = self.parent.grwiz.SrcMap.GetListOfLayers() @@ -3471,7 +3449,6 @@ def UpdateSettings(self): del layers[0] layers = self.parent.grwiz.TgtMap.GetListOfLayers() # self.parent.grwiz.TgtMap.DeleteAllLayers() - reload_target = True tgt_map["raster"] = self.new_tgt_map["raster"] tgt_map["vector"] = self.new_tgt_map["vector"] diff --git a/gui/wxpython/gcp/mapdisplay.py b/gui/wxpython/gcp/mapdisplay.py index 13872b807cf..0681b03e4e8 100644 --- a/gui/wxpython/gcp/mapdisplay.py +++ b/gui/wxpython/gcp/mapdisplay.py @@ -484,7 +484,6 @@ def PrintMenu(self, event): """ Print options and output menu for map display """ - point = wx.GetMousePosition() printmenu = Menu() # Add items to the menu setup = wx.MenuItem(printmenu, wx.ID_ANY, _("Page setup")) @@ -528,7 +527,6 @@ def SaveDisplayRegion(self, event): def OnZoomMenu(self, event): """Popup Zoom menu""" - point = wx.GetMousePosition() zoommenu = Menu() # Add items to the menu @@ -577,7 +575,7 @@ def GetMapToolbar(self): return self.toolbars["gcpdisp"] def _setActiveMapWindow(self, mapWindow): - if not self.MapWindow == mapWindow: + if self.MapWindow != mapWindow: self.MapWindow = mapWindow self.Map = mapWindow.Map self.UpdateActive(mapWindow) diff --git a/gui/wxpython/gmodeler/canvas.py b/gui/wxpython/gmodeler/canvas.py index 7c604ec6624..bfe5f7a90af 100644 --- a/gui/wxpython/gmodeler/canvas.py +++ b/gui/wxpython/gmodeler/canvas.py @@ -320,19 +320,19 @@ def OnRightClick(self, x, y, keys=0, attachment=0): popupMenu = Menu() popupMenu.Append(self.popupID["remove"], _("Remove")) self.frame.Bind(wx.EVT_MENU, self.OnRemove, id=self.popupID["remove"]) - if isinstance(shape, ModelAction) or isinstance(shape, ModelLoop): + if isinstance(shape, (ModelAction, ModelLoop)): if shape.IsEnabled(): popupMenu.Append(self.popupID["enable"], _("Disable")) self.frame.Bind(wx.EVT_MENU, self.OnDisable, id=self.popupID["enable"]) else: popupMenu.Append(self.popupID["enable"], _("Enable")) self.frame.Bind(wx.EVT_MENU, self.OnEnable, id=self.popupID["enable"]) - if isinstance(shape, ModelAction) or isinstance(shape, ModelComment): + if isinstance(shape, (ModelAction, ModelComment)): popupMenu.AppendSeparator() if isinstance(shape, ModelAction): popupMenu.Append(self.popupID["label"], _("Set label")) self.frame.Bind(wx.EVT_MENU, self.OnSetLabel, id=self.popupID["label"]) - if isinstance(shape, ModelAction) or isinstance(shape, ModelComment): + if isinstance(shape, (ModelAction, ModelComment)): popupMenu.Append(self.popupID["comment"], _("Set comment")) self.frame.Bind(wx.EVT_MENU, self.OnSetComment, id=self.popupID["comment"]) @@ -377,11 +377,7 @@ def OnRightClick(self, x, y, keys=0, attachment=0): if self.GetShape().IsIntermediate(): popupMenu.Enable(self.popupID["display"], False) - if ( - isinstance(shape, ModelData) - or isinstance(shape, ModelAction) - or isinstance(shape, ModelLoop) - ): + if isinstance(shape, (ModelData, ModelAction, ModelLoop)): popupMenu.AppendSeparator() popupMenu.Append(self.popupID["props"], _("Properties")) self.frame.Bind(wx.EVT_MENU, self.OnProperties, id=self.popupID["props"]) diff --git a/gui/wxpython/gmodeler/dialogs.py b/gui/wxpython/gmodeler/dialogs.py index 0b4038b7b50..7cd7cbd1147 100644 --- a/gui/wxpython/gmodeler/dialogs.py +++ b/gui/wxpython/gmodeler/dialogs.py @@ -56,17 +56,10 @@ def __init__(self, parent, shape, title=_("Data properties")): self.parent = parent self.shape = shape - label, etype = self._getLabel() - self.etype = etype + label, self.etype = self._getLabel() SimpleDialog.__init__(self, parent, title) - self.element = Select( - parent=self.panel, - type=self.shape.GetPrompt(), - validator=SimpleValidator(callback=self.ValidatorCallback), - ) - if shape.GetValue(): - self.element.SetValue(shape.GetValue()) + self.element = self._createElementControl(shape) self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK) self.Bind(wx.EVT_BUTTON, self.OnCancel, self.btnCancel) @@ -86,6 +79,18 @@ def __init__(self, parent, shape, title=_("Data properties")): self._layout() self.SetMinSize(self.GetSize()) + def _createElementControl(self, shape): + """Create Select element and set its value.""" + element = Select( + parent=self.panel, + type=self.shape.GetPrompt(), + validator=SimpleValidator(callback=self.ValidatorCallback), + ) + if shape.GetValue(): + element.SetValue(shape.GetValue()) + + return element + def _getLabel(self): etype = False prompt = self.shape.GetPrompt() @@ -549,6 +554,11 @@ def GetCondition(self): """Get loop condition""" return self.condText.GetValue() + def SetSizes(self): + """Set default and minimal size.""" + self.SetMinSize(self.GetSize()) + self.SetSize((500, 400)) + class ModelLoopDialog(ModelItemDialog): """Loop properties dialog""" @@ -573,8 +583,7 @@ def __init__( self.btnSeries.Bind(wx.EVT_BUTTON, self.OnSeries) self._layout() - self.SetMinSize(self.GetSize()) - self.SetSize((500, 400)) + self.SetSizes() def _layout(self): """Do layout""" @@ -664,8 +673,7 @@ def __init__( self.itemListElse.Populate(self.parent.GetModel().GetItems()) self._layout() - self.SetMinSize(self.GetSize()) - self.SetSize((500, 400)) + self.SetSizes() def _layout(self): """Do layout""" @@ -745,21 +753,27 @@ def __init__( listmix.ListCtrlAutoWidthMixin.__init__(self) listmix.TextEditMixin.__init__(self) - i = 0 - for col in columns: - self.InsertColumn(i, col) - self.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER) - i += 1 + self.InsertColumns(columns) self.itemDataMap = {} # requested by sorter self.itemCount = 0 + self.BindButtons() + + def BindButtons(self): + """Bind signals to buttons.""" self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit) self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnEndEdit) self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick) self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp) # wxMSW self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp) # wxGTK + def InsertColumns(self, columns): + """INsert columns and set their width.""" + for i, col in enumerate(columns): + self.InsertColumn(i, col) + self.SetColumnWidth(i, wx.LIST_AUTOSIZE_USEHEADER) + def OnBeginEdit(self, event): """Editing of item started""" column = event.GetColumn() @@ -799,7 +813,7 @@ def GetData(self): def Populate(self, data): """Populate the list""" - self.itemDataMap = {} + self.DeleteAllItems() i = 0 for name, values in data.items(): self.itemDataMap[i] = [ @@ -808,20 +822,16 @@ def Populate(self, data): values.get("value", ""), values.get("description", ""), ] - i += 1 - - self.itemCount = len(self.itemDataMap.keys()) - self.DeleteAllItems() - i = 0 - for name, vtype, value, desc in self.itemDataMap.values(): index = self.InsertItem(i, name) self.SetItem(index, 0, name) - self.SetItem(index, 1, vtype) - self.SetItem(index, 2, value) - self.SetItem(index, 3, desc) + self.SetItem(index, 1, values["type"]) + self.SetItem(index, 2, values.get("value", "")) + self.SetItem(index, 3, values.get("description", "")) self.SetItemData(index, i) i += 1 + self.itemCount = len(data) + def Append(self, name, vtype, value, desc): """Append new item to the list @@ -1140,11 +1150,12 @@ def OnBeginEdit(self, event): def OnCheckItem(self, index, flag): """Item checked/unchecked""" - name = self.GetLabel() - if name == "IfBlockList" and self.window: - self.window.OnCheckItemIf(index, flag) - elif name == "ElseBlockList" and self.window: - self.window.OnCheckItemElse(index, flag) + if self.window: + name = self.GetLabel() + if name == "IfBlockList": + self.window.OnCheckItemIf(index, flag) + elif name == "ElseBlockList": + self.window.OnCheckItemElse(index, flag) def GetItems(self): """Get list of selected actions""" diff --git a/gui/wxpython/gmodeler/model.py b/gui/wxpython/gmodeler/model.py index b243f0beb5c..23e308037ff 100644 --- a/gui/wxpython/gmodeler/model.py +++ b/gui/wxpython/gmodeler/model.py @@ -546,7 +546,7 @@ def _substituteFile(self, item, params=None, checkOnly=False): for finput in self.fileInput: # read lines - fd = open(finput, "r") + fd = open(finput) try: data = self.fileInput[finput] = fd.read() finally: @@ -941,8 +941,9 @@ def GetRelations(self, fdir=None): result = [] for rel in self.rels: - if fdir == "from" and rel.GetFrom() == self: - result.append(rel) + if fdir == "from": + if rel.GetFrom() == self: + result.append(rel) elif rel.GetTo() == self: result.append(rel) @@ -1232,8 +1233,7 @@ def GetLog(self, string=True, substitute=None): if string: if cmd is None: return "" - else: - return " ".join(cmd) + return " ".join(cmd) return cmd @@ -1419,8 +1419,7 @@ def GetLog(self, string=True): name.append(rel.GetLabel()) if name: return "/".join(name) + "=" + self.value + " (" + self.prompt + ")" - else: - return self.value + " (" + self.prompt + ")" + return self.value + " (" + self.prompt + ")" def GetLabel(self): """Get list of names""" @@ -1577,7 +1576,7 @@ def _defineShape(self, width, height, x, y): :param width, height: dimension of the shape :param x, y: position of the shape """ - ogl.EllipseShape(self, width, height) + ogl.EllipseShape.__init__(self, width, height) # noqa: PLC2801, C2801 if self.parent.GetCanvas(): self.SetCanvas(self.parent.GetCanvas()) @@ -1592,7 +1591,7 @@ def _defineShape(self, width, height, x, y): :param width, height: dimension of the shape :param x, y: position of the shape """ - ogl.CompositeShape(self) + ogl.CompositeShape.__init__(self) # noqa: PLC2801, C2801 if self.parent.GetCanvas(): self.SetCanvas(self.parent.GetCanvas()) @@ -1671,7 +1670,7 @@ def GetData(self): """ if isinstance(self.fromShape, ModelData): return self.fromShape - elif isinstance(self.toShape, ModelData): + if isinstance(self.toShape, ModelData): return self.toShape return None @@ -1742,8 +1741,7 @@ def GetLog(self): """Get log info""" if self.label: return _("Condition: ") + self.label - else: - return _("Condition: not defined") + return _("Condition: not defined") def AddRelation(self, rel): """Record relation""" @@ -2023,8 +2021,7 @@ def _getNodeText(self, node, tag, default=""): if p is not None: if p.text: return utils.normalize_whitespace(p.text) - else: - return "" + return "" return default @@ -2640,7 +2637,7 @@ def _writeItem(self, item, ignoreBlock=True, variables={}): self._writePythonAction( item, variables, self.model.GetIntermediateData()[:3] ) - elif isinstance(item, ModelLoop) or isinstance(item, ModelCondition): + elif isinstance(item, (ModelLoop, ModelCondition)): # substitute condition cond = item.GetLabel() for variable in self.model.GetVariables(): @@ -2818,12 +2815,11 @@ def _getPythonActionCmd(self, item, task, cmdIndent, variables={}): dlg = wx.MessageDialog( self.model.canvas, message=_( - f"Module {task.get_name()} in your model contains " - f"parameterized flags. actinia does not support " - f"parameterized flags. The following flags are therefore " - f"not being written in the generated json: " - f"{itemParameterizedFlags}" - ), + "Module {task_name} in your model contains " + "parameterized flags. Actinia does not support " + "parameterized flags. The following flags are therefore " + "not being written in the generated JSON: {flags}" + ).format(task_name=task.get_name(), flags=itemParameterizedFlags), caption=_("Warning"), style=wx.OK_DEFAULT | wx.ICON_WARNING, ) @@ -3322,15 +3318,15 @@ def _getStandardizedOption(self, string): """ if string == "raster": return "G_OPT_R_MAP" - elif string == "vector": + if string == "vector": return "G_OPT_V_MAP" - elif string == "mapset": + if string == "mapset": return "G_OPT_M_MAPSET" - elif string == "file": + if string == "file": return "G_OPT_F_INPUT" - elif string == "dir": + if string == "dir": return "G_OPT_M_DIR" - elif string == "region": + if string == "region": return "G_OPT_M_REGION" return None diff --git a/gui/wxpython/gmodeler/panels.py b/gui/wxpython/gmodeler/panels.py index 300220b9f7c..416a9b85592 100644 --- a/gui/wxpython/gmodeler/panels.py +++ b/gui/wxpython/gmodeler/panels.py @@ -25,6 +25,8 @@ import random import math +from pathlib import Path + import wx from wx.lib import ogl @@ -268,19 +270,15 @@ def OnPageChanged(self, event): if self.pythonPanel.IsModified(): self.SetStatusText( - _( - "{} script contains local modifications".format( - self.pythonPanel.body.script_type - ) + _("{} script contains local modifications").format( + self.pythonPanel.body.script_type ), 0, ) else: self.SetStatusText( - _( - "{} script is up-to-date".format( - self.pythonPanel.body.script_type - ) + _("{} script is up-to-date").format( + self.pythonPanel.body.script_type ), 0, ) @@ -838,7 +836,7 @@ def OnModelOpen(self, event): dlg = wx.FileDialog( parent=self, message=_("Choose model file"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("GRASS Model File (*.gxm)|*.gxm"), ) if dlg.ShowModal() == wx.ID_OK: @@ -896,7 +894,7 @@ def OnModelSaveAs(self, event=None): dlg = wx.FileDialog( parent=self, message=_("Choose file to save current model"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("GRASS Model File (*.gxm)|*.gxm"), style=wx.FD_SAVE, ) @@ -1261,7 +1259,7 @@ def OnDeleteData(self, event): dlg = wx.MessageDialog( parent=self, - message=_("Do you want to permanently delete data?%s" % msg), + message=_("Do you want to permanently delete data?%s") % msg, caption=_("Delete intermediate data?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, ) @@ -1645,9 +1643,7 @@ def _layout(self): bodySizer.Add(self.body, proportion=1, flag=wx.EXPAND | wx.ALL, border=3) btnSizer.Add( - StaticText( - parent=self, id=wx.ID_ANY, label="%s:" % _("Python script type") - ), + StaticText(parent=self, id=wx.ID_ANY, label=_("Python script type:")), flag=wx.ALIGN_CENTER_VERTICAL, ) btnSizer.Add(self.script_type_box, proportion=0, flag=wx.RIGHT, border=5) @@ -1676,7 +1672,7 @@ def GetScriptExt(self): return ext def SetWriteObject(self, script_type): - """Set correct self.write_object dependng on the script type. + """Set correct self.write_object depending on the script type. :param script_type: script type name as a string """ if script_type == "PyWPS": @@ -1704,8 +1700,8 @@ def RefreshScript(self): message=_( "{} script is locally modified. " "Refresh will discard all changes. " - "Do you really want to continue?".format(self.body.script_type) - ), + "Do you really want to continue?" + ).format(self.body.script_type), caption=_("Update"), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE, ) @@ -1746,7 +1742,7 @@ def SaveAs(self, force=False): parent=self, message=_("Choose file to save"), defaultFile=os.path.basename(self.parent.GetModelFile(ext=False)), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=fn_wildcard, style=wx.FD_SAVE, ) @@ -1835,7 +1831,7 @@ def OnChangeScriptType(self, event): if self.RefreshScript(): self.body.script_type = new_script_type self.parent.SetStatusText( - _("{} script is up-to-date".format(self.body.script_type)), + _("{} script is up-to-date").format(self.body.script_type), 0, ) @@ -1854,7 +1850,7 @@ def OnRefresh(self, event): """Refresh the script.""" if self.RefreshScript(): self.parent.SetStatusText( - _("{} script is up-to-date".format(self.body.script_type)), + _("{} script is up-to-date").format(self.body.script_type), 0, ) event.Skip() diff --git a/gui/wxpython/gui_core/dialogs.py b/gui/wxpython/gui_core/dialogs.py index c31939312a7..a38836ac23e 100644 --- a/gui/wxpython/gui_core/dialogs.py +++ b/gui/wxpython/gui_core/dialogs.py @@ -180,7 +180,6 @@ def OnLocation(self, event): dbase = grass.gisenv()["GISDBASE"] self.element2.UpdateItems(dbase=dbase, location=location) self.element2.SetSelection(0) - mapset = self.element2.GetStringSelection() def GetValues(self): """Get location, mapset""" @@ -284,8 +283,7 @@ def GetName(self, full=False): if full: if "@" in name: return name - else: - return name + "@" + grass.gisenv()["MAPSET"] + return name + "@" + grass.gisenv()["MAPSET"] return name.split("@", 1)[0] @@ -428,7 +426,7 @@ def IsChecked(self, key): """ if key == "add": return self.addbox.IsChecked() - elif key == "table": + if key == "table": return self.table.IsChecked() return None @@ -1214,7 +1212,7 @@ def _filter(self, data): try: if re.compile(self.flt_pattern).search(dt): flt_data.append(dt) - except: + except re.error: pass return flt_data @@ -1657,7 +1655,7 @@ def OnFilter(self, event): try: if re.compile(event.GetString()).search(layer): list.append(layer) - except: + except re.error: pass list = naturally_sorted(list) diff --git a/gui/wxpython/gui_core/forms.py b/gui/wxpython/gui_core/forms.py index f9829cd9d9b..2636b213df3 100644 --- a/gui/wxpython/gui_core/forms.py +++ b/gui/wxpython/gui_core/forms.py @@ -58,6 +58,7 @@ import codecs from threading import Thread +from pathlib import Path import wx @@ -139,8 +140,7 @@ def text_beautify(someString, width=70): textwrap.wrap(utils.normalize_whitespace(someString), width) ).strip(".,;:") ) - else: - return escape_ampersand(utils.normalize_whitespace(someString).strip(".,;:")) + return escape_ampersand(utils.normalize_whitespace(someString).strip(".,;:")) def escape_ampersand(text): @@ -307,8 +307,6 @@ def run(self): pTable = self.task.get_param( "dbtable", element="element", raiseError=False ) - if pTable: - table = pTable.get("value", "") if name == "LayerSelect": # determine format @@ -1546,7 +1544,6 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar if value: selection.SetValue(value) - formatSelector = True # A gselect.Select is a combobox with two children: a textctl # and a popupwindow; we target the textctl here textWin = selection.GetTextCtrl() @@ -2018,7 +2015,7 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar # check wildcard try: fExt = os.path.splitext(p.get("key_desc", ["*.*"])[0])[1] - except: + except IndexError: fExt = None if not fExt: fMask = "*" @@ -2037,7 +2034,7 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar dialogTitle=_("Choose %s") % p.get("description", _("file")).lower(), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=fmode, changeCallback=self.OnSetValue, ) @@ -2148,7 +2145,7 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar dialogTitle=_("Choose %s") % p.get("description", _("Directory")), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), newDirectory=True, changeCallback=self.OnSetValue, ) @@ -2590,7 +2587,7 @@ def OnFileLoad(self, event): data = "" try: - f = open(path, "r") + f = open(path) except OSError as e: gcmd.GError( parent=self, @@ -2627,7 +2624,7 @@ def OnFileSave(self, event): dlg = wx.FileDialog( parent=self, message=_("Save input as..."), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT, ) @@ -3208,8 +3205,7 @@ def ParseCommand(self, cmd, completed=None): if self.checkError: return self.grass_task, err - else: - return self.grass_task + return self.grass_task def GetCommandInputMapParamKey(self, cmd): """Get parameter key for input raster/vector map diff --git a/gui/wxpython/gui_core/ghelp.py b/gui/wxpython/gui_core/ghelp.py index 0602aeaea0c..0c4f6cdadfb 100644 --- a/gui/wxpython/gui_core/ghelp.py +++ b/gui/wxpython/gui_core/ghelp.py @@ -25,6 +25,7 @@ import sys import wx from wx.html import HtmlWindow +from operator import itemgetter try: from wx.lib.agw.hyperlink import HyperLinkCtrl @@ -273,7 +274,7 @@ def _pageCopyright(self): """Copyright information""" copyfile = os.path.join(os.getenv("GISBASE"), "COPYING") if os.path.exists(copyfile): - copyrightFile = open(copyfile, "r") + copyrightFile = open(copyfile) copytext = copyrightFile.read() copyrightFile.close() else: @@ -302,7 +303,7 @@ def _pageLicense(self): """Licence about""" licfile = os.path.join(os.getenv("GISBASE"), "GPL.TXT") if os.path.exists(licfile): - licenceFile = open(licfile, "r") + licenceFile = open(licfile) license = "".join(licenceFile.readlines()) licenceFile.close() else: @@ -450,7 +451,7 @@ def _pageContributors(self, extra=False): text = StaticText(parent=contribwin, id=wx.ID_ANY, label=item) text.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, "")) contribBox.Add(text) - for vals in sorted(contribs, key=lambda x: x[0]): + for vals in sorted(contribs, key=itemgetter(0)): for item in vals: contribBox.Add( StaticText(parent=contribwin, id=wx.ID_ANY, label=item) @@ -564,16 +565,16 @@ def _langString(self, k, v): """Return string for the status of translation""" allStr = "%s :" % k.upper() try: - allStr += _(" %d translated" % v["good"]) - except: + allStr += _(" %d translated") % v["good"] + except KeyError: pass try: - allStr += _(" %d fuzzy" % v["fuzzy"]) - except: + allStr += _(" %d fuzzy") % v["fuzzy"] + except KeyError: pass try: - allStr += _(" %d untranslated" % v["bad"]) - except: + allStr += _(" %d untranslated") % v["bad"] + except KeyError: pass return allStr @@ -584,29 +585,29 @@ def _langBox(self, par, k, v): langBox.Add(tkey) try: tgood = StaticText( - parent=par, id=wx.ID_ANY, label=_("%d translated" % v["good"]) + parent=par, id=wx.ID_ANY, label=_("%d translated") % v["good"] ) tgood.SetForegroundColour(wx.Colour(35, 142, 35)) langBox.Add(tgood) - except: + except KeyError: tgood = StaticText(parent=par, id=wx.ID_ANY, label="") langBox.Add(tgood) try: tfuzzy = StaticText( - parent=par, id=wx.ID_ANY, label=_(" %d fuzzy" % v["fuzzy"]) + parent=par, id=wx.ID_ANY, label=_(" %d fuzzy") % v["fuzzy"] ) tfuzzy.SetForegroundColour(wx.Colour(255, 142, 0)) langBox.Add(tfuzzy) - except: + except KeyError: tfuzzy = StaticText(parent=par, id=wx.ID_ANY, label="") langBox.Add(tfuzzy) try: tbad = StaticText( - parent=par, id=wx.ID_ANY, label=_(" %d untranslated" % v["bad"]) + parent=par, id=wx.ID_ANY, label=_(" %d untranslated") % v["bad"] ) tbad.SetForegroundColour(wx.Colour(255, 0, 0)) langBox.Add(tbad) - except: + except KeyError: tbad = StaticText(parent=par, id=wx.ID_ANY, label="") langBox.Add(tbad) return langBox @@ -843,7 +844,7 @@ def fillContentsFromFile(self, htmlFile, skipDescription=True): contents.append(line) self.SetPage("".join(contents)) self.loaded = True - except: # The Manual file was not found + except Exception: # The Manual file was not found self.loaded = False diff --git a/gui/wxpython/gui_core/goutput.py b/gui/wxpython/gui_core/goutput.py index 6aca497f365..3c8927f2233 100644 --- a/gui/wxpython/gui_core/goutput.py +++ b/gui/wxpython/gui_core/goutput.py @@ -619,11 +619,7 @@ def AddStyledMessage(self, message, style=None): if c == "\b": self.linePos -= 1 else: - if c == "\r": - pos = self.GetCurLine()[1] - # self.SetCurrentPos(pos) - else: - self.SetCurrentPos(self.linePos) + self.SetCurrentPos(self.linePos) self.ReplaceSelection(c) self.linePos = self.GetCurrentPos() if c != " ": diff --git a/gui/wxpython/gui_core/gselect.py b/gui/wxpython/gui_core/gselect.py index 7dc51b75935..ff256803a97 100644 --- a/gui/wxpython/gui_core/gselect.py +++ b/gui/wxpython/gui_core/gselect.py @@ -47,6 +47,8 @@ import glob import ctypes +from pathlib import Path + import wx from core import globalvar @@ -279,8 +281,7 @@ def GetControl(self): def GetComboCtrl(self): if globalvar.wxPythonPhoenix: return super().GetComboCtrl() - else: - return self.GetCombo() + return self.GetCombo() def GetStringValue(self): """Get value as a string separated by commas""" @@ -414,7 +415,7 @@ def SetData(self, **kargs): self.multiple = kargs["multiple"] if "onPopup" in kargs: self.onPopup = kargs["onPopup"] - if kargs.get("layerTree", None): + if kargs.get("layerTree"): self.filterItems = [] # reset ltype = kargs["type"] for layer in kargs["layerTree"].GetVisibleLayers(skipDigitized=True): @@ -482,7 +483,7 @@ def GetElementList(self, elements=None, exclude=False): try: self.seltree.EnsureVisible(item) self.seltree.SelectItem(item) - except: + except Exception: pass def _getElementList(self, element, mapsets=None, elements=None, exclude=False): @@ -522,8 +523,7 @@ def _getElementList(self, element, mapsets=None, elements=None, exclude=False): if elem not in elementdict: self.AddItem(_("Not selectable element"), node=False) return - else: - renamed_elements.append(elementdict[elem]) + renamed_elements.append(elementdict[elem]) if element in {"stds", "strds", "str3ds", "stvds"}: if not self.tgis_error: @@ -921,7 +921,7 @@ def GetTable(self, layer): :param layer: vector layer number """ if layer not in self.layers: - raise GException(_("No table linked to layer <{}>.".format(layer))) + raise GException(_("No table linked to layer <{}>.").format(layer)) return self.layers[layer]["table"] def GetDbSettings(self, layer): @@ -1289,7 +1289,7 @@ def __init__( style = 0 # disabled, read-only widget has no TextCtrl children (TODO: rewrite) # if not new and not multiple: - ### style = wx.CB_READONLY + # style = wx.CB_READONLY wx.ComboBox.__init__(self, parent, id, size=size, style=style, **kwargs) self.searchPath = searchPath @@ -1373,12 +1373,6 @@ def Insert(self, group): """Insert subgroups for defined group""" if not group: return - gisenv = gs.gisenv() - try: - name, mapset = group.split("@", 1) - except ValueError: - name = group - mapset = gisenv["MAPSET"] mlist = RunCommand("i.group", group=group, read=True, flags="sg").splitlines() try: @@ -1564,7 +1558,7 @@ def __init__( labelText=_("File:"), dialogTitle=_("Choose file to import"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), changeCallback=self.OnUpdate, fileMask=fileMask, ) @@ -1581,7 +1575,7 @@ def __init__( labelText=_("Directory:"), dialogTitle=_("Choose input directory"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), changeCallback=self.OnUpdate, ) browse.GetChildren()[1].SetName("GdalSelectDataSource") @@ -1634,7 +1628,7 @@ def __init__( labelText=_("Name:"), dialogTitle=_("Choose file"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), changeCallback=self.OnUpdate, ) browse.GetChildren()[1].SetName("GdalSelectDataSource") @@ -1669,7 +1663,7 @@ def __init__( labelText=_("Directory:"), dialogTitle=_("Choose input directory"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), changeCallback=self.OnUpdate, ) self.dbWidgets["dirbrowse"] = browse @@ -2259,18 +2253,18 @@ def hasRastSameProjAsLocation(dsn, table=None): message=_( "Getting raster <{table}> SRID from PostgreSQL" " DB <{db}>, host <{host}> failed." - " {error}.".format( - table=table, - db=self._getPDDBConnectionParam( - dsn, - conn_param="dbname", - ), - host=self._getPDDBConnectionParam( - dsn, - conn_param="host", - ), - error=gs.utils.decode(error), + " {error}." + ).format( + table=table, + db=self._getPDDBConnectionParam( + dsn, + conn_param="dbname", + ), + host=self._getPDDBConnectionParam( + dsn, + conn_param="host", ), + error=gs.utils.decode(error), ), ) if ret: @@ -2522,17 +2516,17 @@ def _getPGDBtables(self, dsn): parent=self, message=_( "Getting list of tables from PostgreSQL DB <{db}>," - " host <{host}> failed. {error}.".format( - db=self._getPGDBConnectionParam( - dsn, - conn_param="dbname", - ), - host=self._getPGDBConnectionParam( - dsn, - conn_param="host", - ), - error=gs.utils.decode(error), + " host <{host}> failed. {error}." + ).format( + db=self._getPGDBConnectionParam( + dsn, + conn_param="dbname", + ), + host=self._getPGDBConnectionParam( + dsn, + conn_param="host", ), + error=gs.utils.decode(error), ), ) if ret: @@ -2614,17 +2608,17 @@ def _getPGDBRasters(self, dsn): message=_( "Getting list of tables columns data types" " from PostGIS DB <{db}>, host <{host}> failed." - " {error}.".format( - db=self._getPGDBConnectionParam( - dsn, - conn_param="dbname", - ), - host=self._getPGDBConnectionParam( - dsn, - conn_param="host", - ), - error=gs.utils.decode(error), + " {error}." + ).format( + db=self._getPGDBConnectionParam( + dsn, + conn_param="dbname", + ), + host=self._getPGDBConnectionParam( + dsn, + conn_param="host", ), + error=gs.utils.decode(error), ), ) if ret: @@ -2644,8 +2638,8 @@ def _getPGDBRasters(self, dsn): parent=self, message=_( "PostgreSQL DB <{psql}> program was not found." - " Please, install it.".format(psql=self._psql) - ), + " Please, install it." + ).format(psql=self._psql), ) Debug.msg(3, f"GdalSelect._getPGDBRasters(): return {rasters}") return rasters @@ -2749,7 +2743,7 @@ def __init__( if elements: values = [] valuesDesc = [] - for idx in range(0, len(self.values)): + for idx in range(len(self.values)): value = self.values[idx] if value in elements: values.append(value) @@ -2809,9 +2803,9 @@ def GetType(self): sel = self.ftype.GetSelection() if sel == 0: return "point" - elif sel == 1: + if sel == 1: return "line" - elif sel == 2: + if sel == 2: return "boundary" diff --git a/gui/wxpython/gui_core/mapdisp.py b/gui/wxpython/gui_core/mapdisp.py index 4fe1c25ac18..a2810c9892b 100644 --- a/gui/wxpython/gui_core/mapdisp.py +++ b/gui/wxpython/gui_core/mapdisp.py @@ -176,8 +176,7 @@ def GetProperty(self, name): """Returns property""" if hasattr(self.mapWindowProperties, name): return getattr(self.mapWindowProperties, name) - else: - return self.statusbarManager.GetProperty(name) + return self.statusbarManager.GetProperty(name) def HasProperty(self, name): """Checks whether object has property""" diff --git a/gui/wxpython/gui_core/menu.py b/gui/wxpython/gui_core/menu.py index 71d6d153f8b..b284461af0a 100644 --- a/gui/wxpython/gui_core/menu.py +++ b/gui/wxpython/gui_core/menu.py @@ -68,8 +68,6 @@ def _createMenu(self, node): self._createMenuItem(menu, label=child.label, **data) - self.parent.Bind(wx.EVT_MENU_HIGHLIGHT_ALL, self.OnMenuHighlight) - return menu def _createMenuItem( @@ -136,19 +134,6 @@ def GetCmd(self): """ return self.menucmd - def OnMenuHighlight(self, event): - """ - Default menu help handler - """ - # Show how to get menu item info from this event handler - id = event.GetMenuId() - item = self.FindItemById(id) - if item: - help = item.GetHelp() - - # but in this case just call Skip so the default is done - event.Skip() - class Menu(MenuBase, wx.MenuBar): def __init__(self, parent, model, class_handler=None): @@ -459,7 +444,7 @@ def RemoveFileFromHistory(self, file_index): def RemoveNonExistentFiles(self): """Remove non existent files from the history""" - for i in reversed(range(0, self._filehistory.GetCount())): + for i in reversed(range(self._filehistory.GetCount())): file = self._filehistory.GetHistoryFile(index=i) if not os.path.exists(file): self._filehistory.RemoveFileFromHistory(i=i) diff --git a/gui/wxpython/gui_core/preferences.py b/gui/wxpython/gui_core/preferences.py index 3c3df8e8e42..724e4a5aec0 100644 --- a/gui/wxpython/gui_core/preferences.py +++ b/gui/wxpython/gui_core/preferences.py @@ -28,6 +28,8 @@ import os import sys +from pathlib import Path + try: import pwd @@ -2021,8 +2023,6 @@ def OnCheckColorTable(self, event): def OnLoadEpsgCodes(self, event): """Load EPSG codes from the file""" - win = self.FindWindowById(self.winId["projection:statusbar:projFile"]) - path = win.GetValue() epsgCombo = self.FindWindowById(self.winId["projection:statusbar:epsg"]) wx.BeginBusyCursor() try: @@ -2421,28 +2421,27 @@ def LoadData(self): """Load data into list""" self.InsertColumn(0, _("Mapset")) self.InsertColumn(1, _("Owner")) - ### self.InsertColumn(2, _('Group')) + # self.InsertColumn(2, _('Group')) gisenv = gs.gisenv() locationPath = os.path.join(gisenv["GISDBASE"], gisenv["LOCATION_NAME"]) for mapset in self.parent.all_mapsets_ordered: index = self.InsertItem(self.GetItemCount(), mapset) - mapsetPath = os.path.join(locationPath, mapset) - stat_info = os.stat(mapsetPath) + stat_info = Path(locationPath, mapset).stat() if havePwd: try: self.SetItem(index, 1, "%s" % pwd.getpwuid(stat_info.st_uid)[0]) except KeyError: self.SetItem(index, 1, "nobody") # FIXME: get group name - ### self.SetStringItem(index, 2, "%-8s" % stat_info.st_gid) + # self.SetStringItem(index, 2, "%-8s" % stat_info.st_gid) else: # FIXME: no pwd under MS Windows (owner: 0, group: 0) self.SetItem(index, 1, "%-8s" % stat_info.st_uid) - ### self.SetStringItem(index, 2, "%-8s" % stat_info.st_gid) + # self.SetStringItem(index, 2, "%-8s" % stat_info.st_gid) self.SetColumnWidth(col=0, width=wx.LIST_AUTOSIZE) - ### self.SetColumnWidth(col = 1, width = wx.LIST_AUTOSIZE) + # self.SetColumnWidth(col = 1, width = wx.LIST_AUTOSIZE) def OnCheckItem(self, index, flag): """Mapset checked/unchecked""" diff --git a/gui/wxpython/gui_core/prompt.py b/gui/wxpython/gui_core/prompt.py index 6ac9219f827..6734de169a9 100644 --- a/gui/wxpython/gui_core/prompt.py +++ b/gui/wxpython/gui_core/prompt.py @@ -511,7 +511,6 @@ def OnChar(self, event): # complete command after pressing '.' if event.GetKeyCode() == 46: self.autoCompList = [] - entry = self.GetTextLeft() self.InsertText(pos, ".") self.CharRight() self.toComplete = self.EntityToComplete() @@ -538,7 +537,6 @@ def OnChar(self, event): or event.GetKeyCode() == wx.WXK_SUBTRACT ): self.autoCompList = [] - entry = self.GetTextLeft() self.InsertText(pos, "-") self.CharRight() self.toComplete = self.EntityToComplete() diff --git a/gui/wxpython/gui_core/pyedit.py b/gui/wxpython/gui_core/pyedit.py index 9fa75fa74c1..5958ffb6d68 100644 --- a/gui/wxpython/gui_core/pyedit.py +++ b/gui/wxpython/gui_core/pyedit.py @@ -306,14 +306,14 @@ def _openFile(self, file_path): GError( message=_( "Permission denied <{}>. Please change file " - "permission for reading.".format(file_path) - ), + "permission for reading." + ).format(file_path), parent=self.guiparent, showTraceback=False, ) except OSError: GError( - message=_("Couldn't read file <{}>.".format(file_path)), + message=_("Couldn't read file <{}>.").format(file_path), parent=self.guiparent, ) @@ -333,20 +333,18 @@ def _writeFile(self, file_path, content, additional_err_message=""): GError( message=_( "Permission denied <{}>. Please change file " - "permission for writing.{}".format( - file_path, - additional_err_message, - ), + "permission for writing.{}" + ).format( + file_path, + additional_err_message, ), parent=self.guiparent, showTraceback=False, ) except OSError: GError( - message=_( - "Couldn't write file <{}>.{}".format( - file_path, additional_err_message - ), + message=_("Couldn't write file <{}>.{}").format( + file_path, additional_err_message ), parent=self.guiparent, ) @@ -359,7 +357,7 @@ def OnRun(self, event): file_is_written = self._writeFile( file_path=self.filename, content=self.body.GetText(), - additional_err_message=" Unable to launch Python script.", + additional_err_message=_(" Unable to launch Python script."), ) if file_is_written: mode = stat.S_IMODE(os.lstat(self.filename)[stat.ST_MODE]) @@ -369,7 +367,7 @@ def OnRun(self, event): file_is_written = self._writeFile( file_path=self.filename, content=self.body.GetText(), - additional_err_message=" Unable to launch Python script.", + additional_err_message=_(" Unable to launch Python script."), ) if file_is_written: # set executable file @@ -397,7 +395,7 @@ def SaveAs(self): dlg = wx.FileDialog( parent=self.guiparent, message=_("Choose file to save"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("Python script (*.py)|*.py"), style=wx.FD_SAVE, ) @@ -468,7 +466,7 @@ def Open(self): dlg = wx.FileDialog( parent=self.guiparent, message=_("Open file"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("Python script (*.py)|*.py"), style=wx.FD_OPEN, ) @@ -509,9 +507,8 @@ def OpenRecentFile(self, path, file_exists, file_history): if not file_exists: GError( _( - "File <{}> doesn't exist." - "It was probably moved or deleted.".format(path) - ), + "File <{path}> doesn't exist. It was probably moved or deleted." + ).format(path=path), parent=self.guiparent, ) return @@ -634,10 +631,14 @@ def OnModulesHelp(self, event): self.giface.Help("full_index") def OnSubmittingHelp(self, event): - open_url("https://trac.osgeo.org/grass/wiki/Submitting/Python") + open_url( + "https://github.com/OSGeo/grass/blob/main/doc/development/style_guide.md#python" # noqa: E501 + ) def OnAddonsHelp(self, event): - open_url("https://grass.osgeo.org/development/code-submission/") + open_url( + "https://github.com/OSGeo/grass/blob/main/doc/development/style_guide.md#developing-grass-addons" # noqa: E501 + ) def OnSupport(self, event): open_url("https://grass.osgeo.org/support/") diff --git a/gui/wxpython/gui_core/pystc.py b/gui/wxpython/gui_core/pystc.py index a1dfc543320..d545ccb21e4 100644 --- a/gui/wxpython/gui_core/pystc.py +++ b/gui/wxpython/gui_core/pystc.py @@ -98,7 +98,6 @@ def __init__(self, parent, id=wx.ID_ANY, statusbar=None): 9, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL ) face = font.GetFaceName() - size = font.GetPointSize() # setting the monospace here to not mess with the rest of the code # TODO: review the whole styling @@ -262,10 +261,8 @@ def OnKeyPressed(self, event): self.modified = True if self.statusbar: self.statusbar.SetStatusText( - _( - "{} script contains local modifications".format( - self.script_type - ) + _("{} script contains local modifications").format( + self.script_type ), 0, ) diff --git a/gui/wxpython/gui_core/query.py b/gui/wxpython/gui_core/query.py index 6250095cb29..5e0f734fa6a 100644 --- a/gui/wxpython/gui_core/query.py +++ b/gui/wxpython/gui_core/query.py @@ -136,11 +136,11 @@ def ShowContextMenu(self, node): ) else: label1 = nodes[0].label - texts.append((_("Copy '%s'" % self._cutLabel(label1)), label1)) + texts.append((_("Copy '%s'") % self._cutLabel(label1), label1)) col1 = self._colNames[1] if nodes[0].data and col1 in nodes[0].data and nodes[0].data[col1]: label2 = nodes[0].data[col1] - texts.insert(0, (_("Copy '%s'" % self._cutLabel(label2)), label2)) + texts.insert(0, (_("Copy '%s'") % self._cutLabel(label2), label2)) texts.append((_("Copy line"), label1 + ": " + label2)) ids = [] diff --git a/gui/wxpython/gui_core/treeview.py b/gui/wxpython/gui_core/treeview.py index 4c20885599c..a7660308843 100644 --- a/gui/wxpython/gui_core/treeview.py +++ b/gui/wxpython/gui_core/treeview.py @@ -256,8 +256,7 @@ def OnGetItemText(self, index, column=0): # remove & because of & needed in menu (&Files) if column > 0: return node.data.get(self._columns[column], "") - else: - return node.label.replace("&", "") + return node.label.replace("&", "") def OnRightClick(self, event): """Select item on right click. @@ -303,17 +302,19 @@ def main(): root = tree.root n1 = tree.AppendNode(parent=root, data={"label": "node1"}) n2 = tree.AppendNode(parent=root, data={"label": "node2"}) - n3 = tree.AppendNode(parent=root, data={"label": "node3"}) # pylint: disable=W0612 + n3 = tree.AppendNode( # noqa: F841 # pylint: disable=W0612 + parent=root, data={"label": "node3"} + ) n11 = tree.AppendNode(parent=n1, data={"label": "node11", "xxx": "A"}) - n12 = tree.AppendNode( + n12 = tree.AppendNode( # noqa: F841 # pylint: disable=W0612 parent=n1, data={"label": "node12", "xxx": "B"} - ) # pylint: disable=W0612 - n21 = tree.AppendNode( + ) + n21 = tree.AppendNode( # noqa: F841 # pylint: disable=W0612 parent=n2, data={"label": "node21", "xxx": "A"} - ) # pylint: disable=W0612 - n111 = tree.AppendNode( + ) + n111 = tree.AppendNode( # noqa: F841 # pylint: disable=W0612 parent=n11, data={"label": "node111", "xxx": "A"} - ) # pylint: disable=W0612 + ) app = wx.App() frame = TreeFrame(model=tree) diff --git a/gui/wxpython/gui_core/vselect.py b/gui/wxpython/gui_core/vselect.py index 0ff30afaafd..16bb64b7a57 100644 --- a/gui/wxpython/gui_core/vselect.py +++ b/gui/wxpython/gui_core/vselect.py @@ -232,7 +232,7 @@ def AddVecInfo(self, vInfoDictTMP) -> bool: if self._dialog: self.slist.AddItem(vInfoDictTMP) - return not len(self.selectedFeatures) == 0 + return len(self.selectedFeatures) != 0 def _draw(self): """Call class 'VectorSelectHighlighter' to draw selected features""" diff --git a/gui/wxpython/gui_core/widgets.py b/gui/wxpython/gui_core/widgets.py index 035c70e6fbd..87a09a590d8 100644 --- a/gui/wxpython/gui_core/widgets.py +++ b/gui/wxpython/gui_core/widgets.py @@ -170,7 +170,7 @@ def InsertPage(self, *args, **kwargs): self.classObject.InsertPage(self.widget, *args, **kwargs) except ( TypeError - ) as e: # documentation says 'index', but certain versions of wx require 'n' + ): # documentation says 'index', but certain versions of wx require 'n' kwargs["n"] = kwargs["index"] del kwargs["index"] self.classObject.InsertPage(self.widget, *args, **kwargs) @@ -188,8 +188,7 @@ def DeletePage(self, page): if ret: del self.notebookPages[page] return ret - else: - return False + return False def RemovePage(self, page): """Delete page without deleting the associated window. @@ -203,8 +202,7 @@ def RemovePage(self, page): if ret: del self.notebookPages[page] return ret - else: - return False + return False def SetSelectionByName(self, page): """Set active notebook page. @@ -435,7 +433,6 @@ class NumTextCtrl(TextCtrl): """Class derived from wx.TextCtrl for numerical values only""" def __init__(self, parent, **kwargs): - ## self.precision = kwargs.pop('prec') TextCtrl.__init__( self, parent=parent, validator=NTCValidator(flag="DIGIT_ONLY"), **kwargs ) @@ -753,7 +750,7 @@ def _validate(self, win): if text: try: datetime.strptime(text, "%Y-%m-%d") - except: + except ValueError: self._notvalid() return False @@ -815,8 +812,7 @@ def Validate(self, win): if len(text) == 0: self.callback(ctrl) return False - else: - return True + return True def TransferToWindow(self): """Transfer data from validator to window. @@ -866,8 +862,7 @@ def Validate(self, win): if not self._condition(text): self._callback(ctrl) return False - else: - return True + return True def TransferToWindow(self): """Transfer data from validator to window.""" @@ -1184,8 +1179,7 @@ def GetData(self, checked=None): if checked is not None: return tuple(data) - else: - return (tuple(data), tuple(checkedList)) + return (tuple(data), tuple(checkedList)) def LoadData(self, data=None, selectOne=True): """Load data into list""" @@ -1567,7 +1561,7 @@ def _loadSettings(self): return data try: - fd = open(self.settingsFile, "r") + fd = open(self.settingsFile) except OSError: return data diff --git a/gui/wxpython/gui_core/wrap.py b/gui/wxpython/gui_core/wrap.py index 29299bbbbe2..b971e5e6eab 100644 --- a/gui/wxpython/gui_core/wrap.py +++ b/gui/wxpython/gui_core/wrap.py @@ -99,36 +99,31 @@ def luminance(c): def BitmapFromImage(image, depth=-1): if wxPythonPhoenix: return wx.Bitmap(img=image, depth=depth) - else: - return wx.BitmapFromImage(image, depth=depth) + return wx.BitmapFromImage(image, depth=depth) def ImageFromBitmap(bitmap): if wxPythonPhoenix: return bitmap.ConvertToImage() - else: - return wx.ImageFromBitmap(bitmap) + return wx.ImageFromBitmap(bitmap) def EmptyBitmap(width, height, depth=-1): if wxPythonPhoenix: return wx.Bitmap(width=width, height=height, depth=depth) - else: - return wx.EmptyBitmap(width=width, height=height, depth=depth) + return wx.EmptyBitmap(width=width, height=height, depth=depth) def EmptyImage(width, height, clear=True): if wxPythonPhoenix: return wx.Image(width=width, height=height, clear=clear) - else: - return wx.EmptyImage(width=width, height=height, clear=clear) + return wx.EmptyImage(width=width, height=height, clear=clear) def StockCursor(cursorId): if wxPythonPhoenix: return wx.Cursor(cursorId=cursorId) - else: - return wx.StockCursor(cursorId) + return wx.StockCursor(cursorId) class Window(wx.Window): @@ -437,20 +432,18 @@ def InsertItem(self, index, label, imageIndex=-1): return wx.ListCtrl.InsertItem( self, index=index, label=label, imageIndex=imageIndex ) - else: - return wx.ListCtrl.InsertStringItem( - self, index=index, label=label, imageIndex=imageIndex - ) + return wx.ListCtrl.InsertStringItem( + self, index=index, label=label, imageIndex=imageIndex + ) def SetItem(self, index, column, label, imageId=-1): if wxPythonPhoenix: return wx.ListCtrl.SetItem( self, index=index, column=column, label=label, imageId=imageId ) - else: - return wx.ListCtrl.SetStringItem( - self, index=index, col=column, label=label, imageId=imageId - ) + return wx.ListCtrl.SetStringItem( + self, index=index, col=column, label=label, imageId=imageId + ) def CheckItem(self, item, check=True): """Uses either deprecated listmix.CheckListCtrlMixin @@ -463,8 +456,7 @@ def CheckItem(self, item, check=True): def IsItemChecked(self, item): if hasattr(self, "HasCheckBoxes"): return wx.ListCtrl.IsItemChecked(self, item) - else: - return super().IsChecked(item) + return super().IsChecked(item) if CheckWxVersion([4, 1, 0]): @@ -497,16 +489,14 @@ def __init__(self, *args, **kwargs): def AppendItem(self, parent, text, image=-1, selImage=-1, data=None): if wxPythonPhoenix: return wx.TreeCtrl.AppendItem(self, parent, text, image, selImage, data) - else: - return wx.TreeCtrl.AppendItem( - self, parent, text, image, selImage, wx.TreeItemData(data) - ) + return wx.TreeCtrl.AppendItem( + self, parent, text, image, selImage, wx.TreeItemData(data) + ) def GetItemData(self, item): if wxPythonPhoenix: return wx.TreeCtrl.GetItemData(self, item) - else: - return wx.TreeCtrl.GetPyData(self, item) + return wx.TreeCtrl.GetPyData(self, item) class CustomTreeCtrl(CT.CustomTreeCtrl): @@ -553,18 +543,17 @@ def AddLabelTool( longHelp=longHelpString, clientData=clientData, ) - else: - return wx.ToolBar.AddLabelTool( - self, - toolId, - label, - bitmap, - bmpDisabled, - kind, - shortHelpString, - longHelpString, - clientData, - ) + return wx.ToolBar.AddLabelTool( + self, + toolId, + label, + bitmap, + bmpDisabled, + kind, + shortHelpString, + longHelpString, + clientData, + ) def InsertLabelTool( self, @@ -591,19 +580,18 @@ def InsertLabelTool( longHelp=longHelpString, clientData=clientData, ) - else: - return wx.ToolBar.InsertLabelTool( - self, - pos, - toolId, - label, - bitmap, - bmpDisabled, - kind, - shortHelpString, - longHelpString, - clientData, - ) + return wx.ToolBar.InsertLabelTool( + self, + pos, + toolId, + label, + bitmap, + bmpDisabled, + kind, + shortHelpString, + longHelpString, + clientData, + ) class Menu(wx.Menu): @@ -689,8 +677,7 @@ def __init__(self, *args, **kwargs): def GetFullMultiLineTextExtent(self, string, font=None): if wxPythonPhoenix: return super().GetFullMultiLineTextExtent(string, font) - else: - return super().GetMultiLineTextExtent(string, font) + return super().GetMultiLineTextExtent(string, font) class Rect(wx.Rect): @@ -705,20 +692,17 @@ def __init__(self, *args, **kwargs): def ContainsXY(self, x, y): if wxPythonPhoenix: return wx.Rect.Contains(self, x=int(x), y=int(y)) - else: - return wx.Rect.ContainsXY(self, int(x), int(y)) + return wx.Rect.ContainsXY(self, int(x), int(y)) def ContainsRect(self, rect): if wxPythonPhoenix: return wx.Rect.Contains(self, rect=rect) - else: - return wx.Rect.ContainsRect(self, rect) + return wx.Rect.ContainsRect(self, rect) def OffsetXY(self, dx, dy): if wxPythonPhoenix: return wx.Rect.Offset(self, int(dx), int(dy)) - else: - return wx.Rect.OffsetXY(self, int(dx), int(dy)) + return wx.Rect.OffsetXY(self, int(dx), int(dy)) class CheckBox(wx.CheckBox): diff --git a/gui/wxpython/history/browser.py b/gui/wxpython/history/browser.py index 6a31523d51f..03e39a884a3 100644 --- a/gui/wxpython/history/browser.py +++ b/gui/wxpython/history/browser.py @@ -59,11 +59,11 @@ def get_translated_value(key, value): if key == "timestamp": exec_datetime = datetime.fromisoformat(value) return exec_datetime.strftime("%Y-%m-%d %H:%M:%S") - elif key == "runtime": - return _("{} sec".format(value)) - elif key == "status": + if key == "runtime": + return _("{} sec").format(value) + if key == "status": return _(value.capitalize()) - elif key in {"mask2d", "mask3d"}: + if key in {"mask2d", "mask3d"}: return _(str(value)) @@ -480,7 +480,7 @@ def OnCmdExportHistory(self, event): try: history.copy(history_path, target_path) self.showNotification.emit( - message=_("Command history saved to '{}'".format(target_path)) + message=_("Command history saved to '{}'").format(target_path) ) except OSError as e: GError(str(e)) diff --git a/gui/wxpython/history/tree.py b/gui/wxpython/history/tree.py index 929f2d9f53b..3701fefb001 100644 --- a/gui/wxpython/history/tree.py +++ b/gui/wxpython/history/tree.py @@ -62,8 +62,7 @@ def __init__(self, data=None): def label(self): if "day" in self.data.keys(): return self.dayToLabel(self.data["day"]) - else: - return self.data["name"] + return self.data["name"] @property def time_sort(self): @@ -91,14 +90,13 @@ def dayToLabel(self, day): if day == current_date: return _("{base_date} (today)").format(base_date=base_date) - elif day == current_date - datetime.timedelta(days=1): + if day == current_date - datetime.timedelta(days=1): return _("{base_date} (yesterday)").format(base_date=base_date) - elif day >= (current_date - datetime.timedelta(days=current_date.weekday())): + if day >= (current_date - datetime.timedelta(days=current_date.weekday())): return _("{base_date} (this week)").format(base_date=base_date) - elif day.year == current_date.year: + if day.year == current_date.year: return _("{base_date}").format(base_date=base_date) - else: - return _("{base_date}, {year}").format(base_date=base_date, year=day.year) + return _("{base_date}, {year}").format(base_date=base_date, year=day.year) class HistoryTreeModel(TreeModel): @@ -338,12 +336,11 @@ def _getIndexFromFile(self, command_node): """ if not command_node.data["timestamp"]: return self._model.GetIndexOfNode(command_node)[1] - else: - return history.filter( - json_data=self.ReadFromHistory(), - command=command_node.data["name"], - timestamp=self._timestampToISO(command_node.data["timestamp"]), - ) + return history.filter( + json_data=self.ReadFromHistory(), + command=command_node.data["name"], + timestamp=self._timestampToISO(command_node.data["timestamp"]), + ) def ReadFromHistory(self): """Read content of command history log. @@ -409,13 +406,10 @@ def GetHistoryNode(self, entry, command_index=None): if command_index is None: # If no command index is specified, return the first found day node return day_nodes[0] - else: - # Search for command nodes under the first day node - command_nodes = self._model.SearchNodes( - parent=day_nodes[0], type=COMMAND - ) - if 0 <= command_index < len(command_nodes): - return command_nodes[command_index] + # Search for command nodes under the first day node + command_nodes = self._model.SearchNodes(parent=day_nodes[0], type=COMMAND) + if 0 <= command_index < len(command_nodes): + return command_nodes[command_index] return None @@ -557,14 +551,12 @@ def Run(self, node=None): selected_command = self.selected_command[0] command = selected_command.data["name"] - lst = re.split(r"\s+", command) if ( globalvar.ignoredCmdPattern and re.compile(globalvar.ignoredCmdPattern).search(command) and "--help" not in command and "--ui" not in command ): - self.runIgnoredCmdPattern.emit(cmd=lst) self.runIgnoredCmdPattern.emit(cmd=split(command)) return if re.compile(r"^r[3]?\.mapcalc").search(command): @@ -587,7 +579,7 @@ def OnGetItemImage(self, index, which=wx.TreeItemIcon_Normal, column=0): try: if node.data["type"] == TIME_PERIOD: return self._iconTypes.index(node.data["type"]) - elif node.data["type"] == COMMAND: + if node.data["type"] == COMMAND: return self._iconTypes.index(node.data["status"]) except ValueError: return 0 diff --git a/gui/wxpython/iclass/dialogs.py b/gui/wxpython/iclass/dialogs.py index 8aaac14c4c8..322bfcf5721 100644 --- a/gui/wxpython/iclass/dialogs.py +++ b/gui/wxpython/iclass/dialogs.py @@ -835,10 +835,10 @@ def OnOK(self, event): qdlg = wx.MessageDialog( parent=self, message=_( - "Vector map <%s> already exists." - " Do you want to overwrite it?" % vName - ), - caption=_("Vector <%s> exists" % vName), + "Vector map <%s> already exists. Do you want to overwrite it?" + ) + % vName, + caption=_("Vector <%s> exists") % vName, style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE, ) if qdlg.ShowModal() == wx.ID_YES: diff --git a/gui/wxpython/iclass/frame.py b/gui/wxpython/iclass/frame.py index 52af10d85e0..606c364c76f 100644 --- a/gui/wxpython/iclass/frame.py +++ b/gui/wxpython/iclass/frame.py @@ -570,7 +570,7 @@ def OnZoomMenu(self, event): def OnZoomToTraining(self, event): """Set preview display to match extents of training display""" - if not self.MapWindow == self.GetSecondWindow(): + if self.MapWindow != self.GetSecondWindow(): self.MapWindow = self.GetSecondWindow() self.Map = self.GetSecondMap() self.UpdateActive(self.GetSecondWindow()) @@ -583,7 +583,7 @@ def OnZoomToTraining(self, event): def OnZoomToPreview(self, event): """Set preview display to match extents of training display""" - if not self.MapWindow == self.GetFirstWindow(): + if self.MapWindow != self.GetFirstWindow(): self.MapWindow = self.GetFirstWindow() self.Map = self.GetFirstMap() self.UpdateActive(self.GetFirstWindow()) @@ -646,11 +646,14 @@ def _checkImportedTopo(self, vector): warning = "" if topo["areas"] == 0: - warning = _("No areas in vector map <%s>.\n" % vector) + warning = _("No areas in vector map <%s>.\n") % vector if topo["points"] or topo["lines"]: - warning += _( - "Vector map <%s> contains points or lines, " - "these features are ignored." % vector + warning += ( + _( + "Vector map <%s> contains points or lines, " + "these features are ignored." + ) + % vector ) return warning diff --git a/gui/wxpython/iclass/g.gui.iclass.html b/gui/wxpython/iclass/g.gui.iclass.html index f6169b1d8f6..dd789cd75b5 100644 --- a/gui/wxpython/iclass/g.gui.iclass.html +++ b/gui/wxpython/iclass/g.gui.iclass.html @@ -35,7 +35,6 @@

DESCRIPTION

  • write signature file
  • import vector map
  • export vector map with attribute table
  • -
    @@ -62,6 +61,13 @@

    DESCRIPTION

    By doing this, the user can see how much of the image is likely to be put into the class associated with the signature. +

    wxIClass can also import training areas defined in a vector layer. In that case the program expects the vector layer to have the following columns defined: +

      +
    • cat: category value
    • +
    • class: a string with the class name
    • +
    • color: a color defined using format "RRR:GGG:BBB"
    • +
    +

    The spectral signatures are composed of region means and covariance matrices. These region means and covariance matrices are used in diff --git a/gui/wxpython/iclass/plots.py b/gui/wxpython/iclass/plots.py index 786fa920d17..510953bb5b1 100644 --- a/gui/wxpython/iclass/plots.py +++ b/gui/wxpython/iclass/plots.py @@ -88,9 +88,12 @@ def _createScatterPlotPanel(self): ) self.iscatt_panel.Hide() except ImportError as e: - self.scatt_error = _( - "Scatter plot functionality is disabled.\n\nReason: " - "Unable to import packages needed for scatter plot.\n%s" % e + self.scatt_error = ( + _( + "Scatter plot functionality is disabled.\n\nReason: " + "Unable to import packages needed for scatter plot.\n%s" + ) + % e ) wx.CallAfter(GError, self.scatt_error, showTraceback=False, parent=self) self.iscatt_panel = None diff --git a/gui/wxpython/image2target/g.gui.image2target.py b/gui/wxpython/image2target/g.gui.image2target.py index 97c67b20354..e2704dc371b 100755 --- a/gui/wxpython/image2target/g.gui.image2target.py +++ b/gui/wxpython/image2target/g.gui.image2target.py @@ -30,76 +30,9 @@ # % keyword: GCP # %end -##%option G_OPT_M_LOCATION -##% key: source_project -##% label: The name of the source project (has no projection) -##% description: The source project (location) has no CRS -###% section: source -##% required: yes -##%end - -##%option G_OPT_M_MAPSET -##% key: source_mapset -##% label: The name of the source mapset (has no projection) -##% description: The name of the source mapset (has no projection) -###% section: source -##% required: yes -##%end - -##%option G_OPT_I_GROUP -##% key: source_group -##% required: yes -##% section: source -##%end - -##%option G_OPT_R_INPUT -##% key: source_image -##% required: yes -###% section: source -##%end - -##%option G_OPT_R_INPUT -##% key: target_image -##% label: The name of the image that is already georeferenced used to find location of GCPs -##% description: The name of the image that is already georeferenced used to find the location of GCPs -###% section: target -##% required: no -##%end - -##%option -##% key: camera -##% type: string -##% label: The name of the camera (generated in i.ortho.camera) -##% description: The name of the camera (generated in i.ortho.camera) -##% required: yes -###% section: parameters -##%end - -##%option -##% key: order -##% type: string -##% label: The rectification order -##% description: The rectification order -##% required: yes -##% answer: 1 -###% section: parameters -##%end - -##%option -##% key: extension -##% type: string -##% label: The name of the output files extension -##% description: The name of the output files extension -##% required: yes -##% answer: _ii2t_out -##% section: target -##%end - """ Module to run GCP management tool as stadalone application. - -@author Vaclav Petras (standalone module) """ import os @@ -129,55 +62,10 @@ def main(): else: os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo" - # if options["source_location"]: - # src_loc = options["source_location"] - # else: - # gscript.fatal(_("No georeferenced source location provided")) - - # if options["source_mapset"]: - # src_mpt = options["source_mapset"] - # else: - # gscript.fatal(_("No georeferenced source mapset provided")) - - # if options["source_group"]: - # src_grp = options["source_group"] - # else: - # gscript.fatal(_("Please provide a source group name to process")) - - # if options['source_image']: - # src_ras = options["source_image"] - # else: - # gscript.fatal(_("Please provide a source image map name to process")) - - # if options["target_image"]: - # tgt_ras = options["target_image"] - # else: - # gscript.fatal(_("No georeferenced target map provided")) - - # if options["camera"]: - # camera = options["camera"] - # else: - # gscript.fatal(_( - # "Please provide a camera name (generated by i.ortho.camera)" - # )) - - # if options["order"]: - # order = options["order"] - # else: - # gscript.fatal(_("Please provive an order value")) - - # if options["extension"]: - # extension = options["extension"] - # else: - # gscript.fatal(_("Please provide an output file extension")) - app = wx.App() - # wizard = GCPWizard(parent=None, giface=StandaloneGrassInterface(), - # srcloc=src_loc,srcmpt=src_mpt,srcgrp=src_grp,srcras=src_ras, - # tgtras=tgt_ras,camera=camera, order=order, extension=extension) + GCPWizard(parent=None, giface=StandaloneGrassInterface()) - wizard = GCPWizard(parent=None, giface=StandaloneGrassInterface()) app.MainLoop() diff --git a/gui/wxpython/image2target/ii2t_gis_set.py b/gui/wxpython/image2target/ii2t_gis_set.py index e3cb0257af1..6ed97bc46c1 100644 --- a/gui/wxpython/image2target/ii2t_gis_set.py +++ b/gui/wxpython/image2target/ii2t_gis_set.py @@ -27,6 +27,8 @@ import platform import getpass +from pathlib import Path + from core import globalvar import wx import wx.lib.mixins.listctrl as listmix @@ -94,7 +96,7 @@ def __init__(self, parent=None, id=wx.ID_ANY, style=wx.DEFAULT_FRAME_STYLE): self.hbitmap = wx.StaticBitmap( self.panel, wx.ID_ANY, wx.Bitmap(name=name, type=wx.BITMAP_TYPE_PNG) ) - except: + except Exception: self.hbitmap = wx.StaticBitmap( self.panel, wx.ID_ANY, BitmapFromImage(wx.EmptyImage(530, 150)) ) @@ -315,7 +317,7 @@ def _set_properties(self, version, revision): if os.path.isdir(os.getenv("HOME")): self.gisdbase = os.getenv("HOME") else: - self.gisdbase = os.getcwd() + self.gisdbase = str(Path.cwd()) try: self.tgisdbase.SetValue(self.gisdbase) except UnicodeDecodeError: @@ -541,13 +543,13 @@ def _readGisRC(self): if gisrc and os.path.isfile(gisrc): try: - rc = open(gisrc, "r") + rc = open(gisrc) for line in rc: try: key, val = line.split(":", 1) except ValueError as e: sys.stderr.write( - _("Invalid line in GISRC file (%s):%s\n" % (e, line)) + _("Invalid line in GISRC file (%s):%s\n") % (e, line) ) grassrc[key.strip()] = DecodeString(val.strip()) finally: @@ -594,8 +596,7 @@ def GetRCValue(self, value): """Return GRASS variable (read from GISRC)""" if value in self.grassrc: return self.grassrc[value] - else: - return None + return None def OnWizard(self, event): """Location wizard started""" @@ -822,8 +823,8 @@ def DeleteMapset(self, event): shutil.rmtree(os.path.join(self.gisdbase, location, mapset)) self.OnSelectLocation(None) self.lbmapsets.SetSelection(0) - except: - wx.MessageBox(message=_("Unable to delete mapset")) + except OSError as e: + wx.MessageBox(message=_("Unable to delete mapset: %s") % str(e)) dlg.Destroy() @@ -854,8 +855,8 @@ def DeleteLocation(self, event): self.lblocations.SetSelection(0) self.OnSelectLocation(None) self.lbmapsets.SetSelection(0) - except: - wx.MessageBox(message=_("Unable to delete location")) + except OSError as e: + wx.MessageBox(message=_("Unable to delete location: %s") % str(e)) dlg.Destroy() @@ -1044,8 +1045,7 @@ def OnCreateMapset(self, event): if dlg.ShowModal() == wx.ID_OK: mapset = dlg.GetValue() return self.CreateNewMapset(mapset=mapset) - else: - return False + return False def CreateNewMapset(self, mapset): if mapset in self.listOfMapsets: @@ -1161,7 +1161,7 @@ def _getDefaultMapsetName(self): defaultName = getpass.getuser() # raise error if not ascii (not valid mapset name) defaultName.encode("ascii") - except: # whatever might go wrong + except Exception: # whatever might go wrong defaultName = "user" return defaultName diff --git a/gui/wxpython/image2target/ii2t_manager.py b/gui/wxpython/image2target/ii2t_manager.py index 4aec0eeba5e..3adcf5ef9bd 100644 --- a/gui/wxpython/image2target/ii2t_manager.py +++ b/gui/wxpython/image2target/ii2t_manager.py @@ -159,7 +159,7 @@ def __init__(self, parent, giface): self.target_gisrc = os.environ["GISRC"] self.gisrc_dict = {} try: - f = open(self.target_gisrc, "r") + f = open(self.target_gisrc) for line in f: line = line.replace("\n", "").strip() if len(line) < 1: @@ -884,20 +884,6 @@ def OnSrcSelection(self, event): else: wx.FindWindowById(wx.ID_FORWARD).Enable(True) - try: - # set computational region to match selected map and zoom display - # to region - if maptype == "raster": - p = RunCommand("g.region", "raster=src_map") - elif maptype == "vector": - p = RunCommand("g.region", "vector=src_map") - - if p.returncode == 0: - print("returncode = ", str(p.returncode)) - self.parent.Map.region = self.parent.Map.GetRegion() - except: - pass - def OnTgtRastSelection(self, event): """Source map to display selected""" global tgt_map @@ -1257,7 +1243,7 @@ def InitMapDisplay(self): # initialize column sorter self.itemDataMap = self.mapcoordlist ncols = self.list.GetColumnCount() - ColumnSorterMixin(self, ncols) + ColumnSorterMixin.__init__(self, ncols) # noqa: PLC2801, C2801 # init to ascending sort on first click self._colSortFlag = [1] * ncols @@ -1627,7 +1613,7 @@ def ReadGCPs(self): GError(parent=self, message=_("target mapwin not defined")) try: - f = open(self.file["control_points"], "r") + f = open(self.file["control_points"]) GCPcnt = 0 for line in f: @@ -1781,22 +1767,20 @@ def OnGeorect(self, event): else: flags = "a" - busy = wx.BusyInfo(_("Rectifying images, please wait..."), parent=self) - wx.GetApp().Yield() - - ret, msg = RunCommand( - "i.ortho.rectify", - parent=self, - getErrorMsg=True, - quiet=True, - group=self.xygroup, - extension=self.extension, - method=self.gr_method, - angle=self.grwiz.cam_angle, - flags=flags, - ) + with wx.BusyInfo(_("Rectifying images, please wait..."), parent=self): + wx.GetApp().Yield() - del busy + ret, msg = RunCommand( + "i.ortho.rectify", + parent=self, + getErrorMsg=True, + quiet=True, + group=self.xygroup, + extension=self.extension, + method=self.gr_method, + angle=self.grwiz.cam_angle, + flags=flags, + ) # provide feedback on failure if ret != 0: @@ -1828,23 +1812,21 @@ def OnGeorect(self, event): ) ret = msg = "" - busy = wx.BusyInfo( + with wx.BusyInfo( _("Rectifying vector map <%s>, please wait...") % vect, parent=self - ) - wx.GetApp().Yield() - - ret, msg = RunCommand( - "v.rectify", - parent=self, - getErrorMsg=True, - quiet=True, - input=vect, - output=self.outname, - group=self.xygroup, - order=self.gr_order, - ) - - del busy + ): + wx.GetApp().Yield() + + ret, msg = RunCommand( + "v.rectify", + parent=self, + getErrorMsg=True, + quiet=True, + input=vect, + output=self.outname, + group=self.xygroup, + order=self.gr_order, + ) # provide feedback on failure if ret != 0: @@ -1971,7 +1953,6 @@ def OnGROrder(self, event): elif self.gr_order == 2: minNumOfItems = 6 - diff = 6 - numOfItems # self.SetStatusText(_( # "Insufficient points, 6+ points needed for 2nd order")) @@ -2245,7 +2226,7 @@ def AdjustMap(self, newreg): def OnZoomToSource(self, event): """Set target map window to match extents of source map window""" - if not self.MapWindow == self.TgtMapWindow: + if self.MapWindow != self.TgtMapWindow: self.MapWindow = self.TgtMapWindow self.Map = self.TgtMap self.UpdateActive(self.TgtMapWindow) @@ -2258,7 +2239,7 @@ def OnZoomToSource(self, event): def OnZoomToTarget(self, event): """Set source map window to match extents of target map window""" - if not self.MapWindow == self.SrcMapWindow: + if self.MapWindow != self.SrcMapWindow: self.MapWindow = self.SrcMapWindow self.Map = self.SrcMap self.UpdateActive(self.SrcMapWindow) @@ -2270,7 +2251,6 @@ def OnZoomToTarget(self, event): def OnZoomMenuGCP(self, event): """Popup Zoom menu""" - point = wx.GetMousePosition() zoommenu = Menu() # Add items to the menu @@ -3282,7 +3262,7 @@ def OnSrcSelection(self, event): tmp_map = self.srcselection.GetValue() - if not tmp_map == "" and not tmp_map == src_map: + if tmp_map not in ("", src_map): self.new_src_map = tmp_map def OnTgtRastSelection(self, event): @@ -3376,7 +3356,6 @@ def UpdateSettings(self): srcrenderVector = False tgtrender = False tgtrenderVector = False - reload_target = False if self.new_src_map != src_map: # remove old layer layers = self.parent.grwiz.SrcMap.GetListOfLayers() @@ -3414,7 +3393,6 @@ def UpdateSettings(self): del layers[0] layers = self.parent.grwiz.TgtMap.GetListOfLayers() # self.parent.grwiz.TgtMap.DeleteAllLayers() - reload_target = True tgt_map["raster"] = self.new_tgt_map["raster"] tgt_map["vector"] = self.new_tgt_map["vector"] diff --git a/gui/wxpython/image2target/ii2t_mapdisplay.py b/gui/wxpython/image2target/ii2t_mapdisplay.py index b85a70a152f..9ee3b77d118 100644 --- a/gui/wxpython/image2target/ii2t_mapdisplay.py +++ b/gui/wxpython/image2target/ii2t_mapdisplay.py @@ -474,7 +474,6 @@ def PrintMenu(self, event): """ Print options and output menu for map display """ - point = wx.GetMousePosition() printmenu = Menu() # Add items to the menu setup = wx.MenuItem(printmenu, wx.ID_ANY, _("Page setup")) @@ -518,7 +517,6 @@ def SaveDisplayRegion(self, event): def OnZoomMenu(self, event): """Popup Zoom menu""" - point = wx.GetMousePosition() zoommenu = Menu() # Add items to the menu @@ -567,7 +565,7 @@ def GetMapToolbar(self): return self.toolbars["gcpdisp"] def _setActiveMapWindow(self, mapWindow): - if not self.MapWindow == mapWindow: + if self.MapWindow != mapWindow: self.MapWindow = mapWindow self.Map = mapWindow.Map self.UpdateActive(mapWindow) diff --git a/gui/wxpython/image2target/ii2t_statusbar.py b/gui/wxpython/image2target/ii2t_statusbar.py index 3c5ee378a1e..7ff80e621d3 100644 --- a/gui/wxpython/image2target/ii2t_statusbar.py +++ b/gui/wxpython/image2target/ii2t_statusbar.py @@ -11,9 +11,6 @@ This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details. - -@author Vaclav Petras (statusbar refactoring) -@author Anna Kratochvilova (statusbar refactoring) """ import wx diff --git a/gui/wxpython/iscatt/controllers.py b/gui/wxpython/iscatt/controllers.py index 38e61e34133..fef4e95505e 100644 --- a/gui/wxpython/iscatt/controllers.py +++ b/gui/wxpython/iscatt/controllers.py @@ -192,9 +192,7 @@ def SetDataDone(self, event): del self.busy self.data_set = True - todo = event.ret self.bad_bands = event.ret - bands = self.core.GetBands() self.bad_rasts = event.ret self.cats_mgr.SetData() @@ -234,12 +232,13 @@ def AddScattPlot(self): "Number of cells (rows*cols) <%d> in current region" "is higher than maximum limit <%d>.\n\n" "You can reduce number of cells in current region using " - " command." % (ncells, MAX_NCELLS) - ), + " command." + ) + % (ncells, MAX_NCELLS), ) ) return - elif ncells > WARN_NCELLS: + if ncells > WARN_NCELLS: dlg = wx.MessageDialog( parent=self.guiparent, message=_( @@ -250,8 +249,8 @@ def AddScattPlot(self): "It can be done by command.\n\n" "Do you want to continue using " "Interactive Scatter Plot Tool with this region?" - % (ncells, WARN_NCELLS) - ), + ) + % (ncells, WARN_NCELLS), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING, ) ret = dlg.ShowModal() @@ -318,11 +317,11 @@ def CheckBands(self, b_1, b_2): err = "" for b in [b_1_name, b_2_name]: if self.bands_info[b] is None: - err += _("Band <%s> is not CELL (integer) type.\n" % b) + err += _("Band <%s> is not CELL (integer) type.\n") % b if err: GMessage( parent=self.guiparent, - message=_("Scatter plot cannot be added.\n" + err), + message=_("Scatter plot cannot be added.\n") + err, ) return False @@ -334,18 +333,18 @@ def CheckBands(self, b_1, b_2): "Scatter plot cannot be added.\n" "Multiple of bands ranges <%s:%d * %s:%d = %d> " "is higher than maximum limit <%d>.\n" - % ( - b_1_name, - b_1_i["range"], - b_1_name, - b_2_i["range"], - mrange, - MAX_SCATT_SIZE, - ) + ) + % ( + b_1_name, + b_1_i["range"], + b_1_name, + b_2_i["range"], + mrange, + MAX_SCATT_SIZE, ), ) return False - elif mrange > WARN_SCATT_SIZE: + if mrange > WARN_SCATT_SIZE: dlg = wx.MessageDialog( parent=self.guiparent, message=_( @@ -354,14 +353,14 @@ def CheckBands(self, b_1, b_2): "It is strongly advised to reduce range extend of bands" "(e. g. using r.rescale) below recommended threshold.\n\n" "Do you really want to add this scatter plot?" - % ( - b_1_name, - b_1_i["range"], - b_1_name, - b_2_i["range"], - mrange, - WARN_SCATT_SIZE, - ) + ) + % ( + b_1_name, + b_1_i["range"], + b_1_name, + b_2_i["range"], + mrange, + WARN_SCATT_SIZE, ), style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING, ) @@ -596,7 +595,7 @@ def _renderscattplts(self, scatt_ids, cats, cats_attrs): try: self.cat_ids.remove(c) scatt_dt[c]["render"] = True - except: + except ValueError: scatt_dt[c]["render"] = False if self.scatt_mgr.pol_sel_mode[0]: @@ -673,7 +672,7 @@ def ChangePosition(self, cat_id, new_pos): try: pos = self.cats_ids.index(cat_id) - except: + except ValueError: return False if pos > new_pos: @@ -808,7 +807,6 @@ def ExportCatRast(self, cat_id): def OnExportCatRastDone(self, event): ret, err = event.ret if ret == 0: - cat_attrs = self.GetCategoryAttrs(event.kwds["cat_id"]) GMessage( _("Scatter plot raster of class <%s> exported to raster map <%s>.") % (event.userdata["name"], event.kwds["rast_name"]) diff --git a/gui/wxpython/iscatt/core_c.py b/gui/wxpython/iscatt/core_c.py index a2a3d5da9da..8be04964b90 100644 --- a/gui/wxpython/iscatt/core_c.py +++ b/gui/wxpython/iscatt/core_c.py @@ -11,17 +11,36 @@ @author Stepan Turek (mentor: Martin Landa) """ +import ctypes import sys -import numpy as np +from ctypes import POINTER, c_char_p, c_double, c_int, c_uint8, pointer from multiprocessing import Process, Queue -from ctypes import * +import numpy as np try: - from grass.lib.imagery import * from grass.lib.gis import G_get_window + from grass.lib.imagery import ( + SC_SCATT_CONDITIONS, + SC_SCATT_DATA, + I_apply_colormap, + I_compute_scatts, + I_create_cat_rast, + I_insert_patch_to_cat_rast, + I_merge_arrays, + I_rasterize, + I_sc_add_cat, + I_sc_free_cats, + I_sc_init_cats, + I_sc_insert_scatt_data, + I_scd_init_scatt_data, + scdScattData, + struct_Cell_head, + struct_Range, + struct_scCats, + ) except ImportError as e: - sys.stderr.write(_("Loading ctypes libs failed")) + sys.stderr.write(_("Loading ctypes libs failed: %s") % e) from core.gcmd import GException from grass.script import encode @@ -238,7 +257,7 @@ def _getComputationStruct(cats, cats_rasts, cats_type, n_bands): scatt_vals = scdScattData() - c_void_p = ctypes.POINTER(ctypes.c_void_p) + c_void_p = POINTER(ctypes.c_void_p) if cats_type == SC_SCATT_DATA: vals[:] = 0 @@ -269,7 +288,6 @@ def _updateCatRastProcess(patch_rast, region, cat_rast, output_queue): def _rasterize(polygon, rast, region, value, output_queue): - pol_size = len(polygon) * 2 pol = np.array(polygon, dtype=float) c_uint8_p = POINTER(c_uint8) diff --git a/gui/wxpython/iscatt/dialogs.py b/gui/wxpython/iscatt/dialogs.py index 4129015e88d..a2d054b64a4 100644 --- a/gui/wxpython/iscatt/dialogs.py +++ b/gui/wxpython/iscatt/dialogs.py @@ -90,8 +90,6 @@ def _layout(self): border = wx.BoxSizer(wx.VERTICAL) dialogSizer = wx.BoxSizer(wx.VERTICAL) - regionSizer = wx.BoxSizer(wx.HORIZONTAL) - dialogSizer.Add( self._addSelectSizer(title=self.band_1_label, sel=self.band_1_ch) ) @@ -327,10 +325,10 @@ def OnOK(self, event): qdlg = wx.MessageDialog( parent=self, message=_( - "Raster map <%s> already exists." - " Do you want to overwrite it?" % rast_name - ), - caption=_("Raster <%s> exists" % rast_name), + "Raster map <%s> already exists. Do you want to overwrite it?" + ) + % rast_name, + caption=_("Raster <%s> exists") % rast_name, style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE, ) if qdlg.ShowModal() == wx.ID_YES: @@ -356,7 +354,6 @@ def __init__( self.scatt_mgr = scatt_mgr - maxValue = 1e8 self.parent = parent self.settings = {} diff --git a/gui/wxpython/iscatt/frame.py b/gui/wxpython/iscatt/frame.py index 6d87a90e273..122aa053b9b 100644 --- a/gui/wxpython/iscatt/frame.py +++ b/gui/wxpython/iscatt/frame.py @@ -221,9 +221,6 @@ def __init__(self, parent, scatt_mgr, id=wx.ID_ANY): self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPlotPaneClosed) - dlgSize = (-1, 400) - # self.SetBestSize(dlgSize) - # self.SetInitialSize(dlgSize) self.SetAutoLayout(1) # fix goutput's pane size (required for Mac OSX) # if self.gwindow: @@ -249,7 +246,7 @@ def CursorPlotMove(self, x, y, scatt_id): x = int(round(x)) y = int(round(y)) coords = True - except: + except TypeError: coords = False pane = self._getPane(scatt_id) @@ -681,7 +678,7 @@ def OnPopupOpacityLevel(self, event): name = cat_attrs["name"] dlg = SetOpacityDialog( - self, opacity=value, title=_("Change opacity of class <%s>" % name) + self, opacity=value, title=_("Change opacity of class <%s>") % name ) dlg.applyOpacity.connect( diff --git a/gui/wxpython/iscatt/iscatt_core.py b/gui/wxpython/iscatt/iscatt_core.py index 97da83415e8..86321ed2ff1 100644 --- a/gui/wxpython/iscatt/iscatt_core.py +++ b/gui/wxpython/iscatt/iscatt_core.py @@ -295,7 +295,7 @@ def _rasterize(self, grass_region, layer, cat, out_rast): ) if ret != 0: - GException(_("v.build failed:\n%s" % msg)) + GException(_("v.build failed:\n%s") % msg) environs = os.environ.copy() environs["GRASS_REGION"] = grass_region["GRASS_REGION"] @@ -315,7 +315,7 @@ def _rasterize(self, grass_region, layer, cat, out_rast): ) if ret != 0: - GException(_("v.to.rast failed:\n%s" % msg)) + GException(_("v.to.rast failed:\n{messages}").format(messages=msg)) def _create_grass_region_env(self, bbox): r = self.an_data.GetRegion() @@ -323,7 +323,7 @@ def _create_grass_region_env(self, bbox): if bbox["maxy"] <= r["s"]: return 0 - elif bbox["maxy"] >= r["n"]: + if bbox["maxy"] >= r["n"]: new_r["n"] = bbox["maxy"] else: new_r["n"] = ( @@ -332,7 +332,7 @@ def _create_grass_region_env(self, bbox): if bbox["miny"] >= r["n"]: return 0 - elif bbox["miny"] <= r["s"]: + if bbox["miny"] <= r["s"]: new_r["s"] = bbox["miny"] else: new_r["s"] = ( @@ -341,7 +341,7 @@ def _create_grass_region_env(self, bbox): if bbox["maxx"] <= r["w"]: return 0 - elif bbox["maxx"] >= r["e"]: + if bbox["maxx"] >= r["e"]: new_r["e"] = bbox["maxx"] else: new_r["e"] = ( @@ -350,7 +350,7 @@ def _create_grass_region_env(self, bbox): if bbox["minx"] >= r["e"]: return 0 - elif bbox["minx"] <= r["w"]: + if bbox["minx"] <= r["w"]: new_r["w"] = bbox["minx"] else: new_r["w"] = ( @@ -531,7 +531,7 @@ def SetData(self, cats): # if key is missing condition is always True (full scatter plor # is computed) if scatt_id in self.cats[cat_id]: - self.cats[cat_id][scatt_id]["np_vals"] = cats[cat_id][scatt_id][ + self.cats[cat_id][scatt_id]["np_vals"] = scatt_ids[scatt_id][ "np_vals" ] diff --git a/gui/wxpython/iscatt/plots.py b/gui/wxpython/iscatt/plots.py index 08afe5906ed..9c6f50b3b9f 100644 --- a/gui/wxpython/iscatt/plots.py +++ b/gui/wxpython/iscatt/plots.py @@ -168,7 +168,7 @@ def SetEmpty(self): return self.polygon_drawer.SetEmpty() def OnRelease(self, event): - if not self.mode == "zoom": + if self.mode != "zoom": return self.zoom_rect.set_visible(False) self.ZoomRectangle(event) @@ -255,7 +255,6 @@ def Plot(self, cats_order, scatts, ellipses, styles): if not e: continue - colors = styles[cat_id]["color"].split(":") if self.transpose: e["theta"] = 360 - e["theta"] + 90 if e["theta"] >= 360: @@ -348,16 +347,13 @@ def ZoomWheel(self, event): def ZoomRectangle(self, event): # get the current x and y limits - if not self.mode == "zoom": + if self.mode != "zoom": return if event.inaxes is None: return if event.button != 1: return - cur_xlim = self.axes.get_xlim() - cur_ylim = self.axes.get_ylim() - x1, y1 = event.xdata, event.ydata x2 = deepcopy(self.zoom_rect_coords["x"]) y2 = deepcopy(self.zoom_rect_coords["y"]) @@ -394,7 +390,7 @@ def OnCanvasLeave(self, event): def PanMotion(self, event): "on mouse movement" - if not self.mode == "pan": + if self.mode != "pan": return if event.inaxes is None: return @@ -426,7 +422,7 @@ def PanMotion(self, event): self.canvas.draw() def ZoomRectMotion(self, event): - if not self.mode == "zoom": + if self.mode != "zoom": return if event.inaxes is None: return @@ -651,13 +647,11 @@ def __init__(self, ax, pol, empty_pol): x, y = zip(*self.pol.xy) - style = self._getPolygonStyle() - self.line = Line2D(x, y, marker="o", markerfacecolor="r", animated=True) self.ax.add_line(self.line) # self._update_line(pol) - cid = self.pol.add_callback(self.poly_changed) + self.pol.add_callback(self.poly_changed) self.moving_ver_idx = None # the active vert self.mode = None @@ -811,11 +805,11 @@ def _deleteVertex(self, event): coords = [] for i, tup in enumerate(self.pol.xy): - if i == ind: - continue - elif i == 0 and ind == len(self.pol.xy) - 1: - continue - elif i == len(self.pol.xy) - 1 and ind == 0: + if ( + i == ind + or (i == 0 and ind == len(self.pol.xy) - 1) + or (i == len(self.pol.xy) - 1 and ind == 0) + ): continue coords.append(tup) @@ -866,7 +860,7 @@ def _addVertex(self, event): def motion_notify_callback(self, event): "on mouse movement" - if not self.mode == "move_vertex": + if self.mode != "move_vertex": return if not self.showverts: return diff --git a/gui/wxpython/lmgr/frame.py b/gui/wxpython/lmgr/frame.py index de06305086f..2413d3b7c4a 100644 --- a/gui/wxpython/lmgr/frame.py +++ b/gui/wxpython/lmgr/frame.py @@ -24,6 +24,8 @@ import platform import re +from pathlib import Path + from core import globalvar import wx import wx.aui @@ -269,7 +271,7 @@ def show_menu_errors(messages): y = client_disp[1] self.SetPosition((x, y)) self.SetSize((w, h)) - except: + except (ValueError, IndexError): pass else: # does center (of screen) make sense for lmgr? @@ -383,8 +385,7 @@ def _createNotebook(self): """Initialize notebook widget""" if sys.platform == "win32": return GNotebook(parent=self, style=globalvar.FNPageDStyle) - else: - return FormNotebook(parent=self, style=wx.NB_BOTTOM) + return FormNotebook(parent=self, style=wx.NB_BOTTOM) def _createDataCatalog(self, parent): """Initialize Data Catalog widget""" @@ -848,7 +849,7 @@ def OnRunModel(self, event): dlg = wx.FileDialog( parent=self, message=_("Choose model to run"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("GRASS Model File (*.gxm)|*.gxm"), ) if dlg.ShowModal() == wx.ID_OK: @@ -883,7 +884,7 @@ def OnCBPageChanged(self, event): try: self.GetMapDisplay().SetFocus() self.GetMapDisplay().Raise() - except: + except AttributeError: pass event.Skip() @@ -1087,14 +1088,13 @@ def GetMapDisplay(self, onlyCurrent=True): if onlyCurrent: if self.currentPage: return self.GetLayerTree().GetMapDisplay() - else: - return None - else: # -> return list of all mapdisplays - mlist = [] - for idx in range(0, self.notebookLayers.GetPageCount()): - mlist.append(self.notebookLayers.GetPage(idx).maptree.GetMapDisplay()) + return None + # -> return list of all mapdisplays + mlist = [] + for idx in range(self.notebookLayers.GetPageCount()): + mlist.append(self.notebookLayers.GetPage(idx).maptree.GetMapDisplay()) - return mlist + return mlist def GetAllMapDisplays(self): """Get all (open) map displays""" @@ -1123,7 +1123,7 @@ def GetMenuCmd(self, event): try: cmdlist = cmd.split(" ") - except: # already list? + except AttributeError: # already list? cmdlist = cmd # check list of dummy commands for GUI modules that do not have GRASS @@ -1135,7 +1135,7 @@ def GetMenuCmd(self, event): layer = self.GetLayerTree().layer_selected name = self.GetLayerTree().GetLayerInfo(layer, key="maplayer").name type = self.GetLayerTree().GetLayerInfo(layer, key="type") - except: + except AttributeError: layer = None if layer and len(cmdlist) == 1: # only if no parameters given @@ -1183,7 +1183,7 @@ def OnVDigit(self, event): # available only for vector map layers try: mapLayer = tree.GetLayerInfo(layer, key="maplayer") - except: + except AttributeError: mapLayer = None if not mapLayer or mapLayer.GetType() != "vector": @@ -1223,7 +1223,7 @@ def OnRunScript(self, event): dlg = wx.FileDialog( parent=self, message=_("Choose script file to run"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("Python script (*.py)|*.py|Bash script (*.sh)|*.sh"), ) @@ -1251,8 +1251,8 @@ def OnRunScript(self, event): "Do you want to set the permissions " "that allows you to run this script " "(note that you must be the owner of the file)?" - % os.path.basename(filename) - ), + ) + % os.path.basename(filename), caption=_("Set permission?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, ) @@ -1377,9 +1377,7 @@ def write_beginning(parameter=None, command=None): self._giface.WriteCmdLog(" ".join(command)) def write_changed(): - self._giface.WriteLog( - _('Working directory changed to:\n"%s"') % os.getcwd() - ) + self._giface.WriteLog(_('Working directory changed to:\n"%s"') % Path.cwd()) def write_end(): self._giface.WriteCmdLog(" ") @@ -1433,7 +1431,7 @@ def write_help(): dlg = wx.DirDialog( parent=self, message=_("Choose a working directory"), - defaultPath=os.getcwd(), + defaultPath=str(Path.cwd()), ) if dlg.ShowModal() == wx.ID_OK: @@ -1862,7 +1860,7 @@ def OnShowAttributeTable(self, event, selection=None): # available only for vector map layers try: maptype = tree.GetLayerInfo(layer, key="maplayer").type - except: + except AttributeError: maptype = None if not maptype or maptype != "vector": @@ -1906,7 +1904,7 @@ def _onMapDisplayStarting3dMode(self, mapDisplayPage): """Disables 3D mode for all map displays except for @p mapDisplay""" # TODO: it should be disabled also for newly created map windows # moreover mapdisp.Disable3dMode() does not work properly - for page in range(0, self.GetLayerNotebook().GetPageCount()): + for page in range(self.GetLayerNotebook().GetPageCount()): mapdisp = self.GetLayerNotebook().GetPage(page).maptree.GetMapDisplay() if self.GetLayerNotebook().GetPage(page) != mapDisplayPage: mapdisp.Disable3dMode() @@ -1950,7 +1948,7 @@ def AddMaps(self, mapLayers, ltype, check=False): ) return - newItem = maptree.AddLayer( + maptree.AddLayer( ltype=ltype, lname=layerName, lchecked=check, diff --git a/gui/wxpython/lmgr/giface.py b/gui/wxpython/lmgr/giface.py index aa5af7223aa..67669039d5d 100644 --- a/gui/wxpython/lmgr/giface.py +++ b/gui/wxpython/lmgr/giface.py @@ -54,7 +54,9 @@ def __init__(self, tree): self._tree = tree def __len__(self): - return len([layer for layer in self]) + # The list constructor calls __len__ as an optimization if available, + # causing a RecursionError + return len([layer for layer in self]) # noqa: C416 def __iter__(self): """Iterates over the contents of the list.""" @@ -66,11 +68,11 @@ def __iter__(self): def __getitem__(self, index): """Select a layer from the LayerList using the index.""" - return [layer for layer in self][index] + return list(self)[index] def __repr__(self): """Return a representation of the object.""" - return "LayerList(%r)" % [layer for layer in self] + return "LayerList(%r)" % list(self) def GetSelectedLayers(self, checkedOnly=True): items = self._tree.GetSelectedLayer(multi=True, checkedOnly=checkedOnly) @@ -86,9 +88,8 @@ def GetSelectedLayer(self, checkedOnly=False): item = self._tree.GetSelectedLayer(multi=False, checkedOnly=checkedOnly) if item is None: return None - else: - data = self._tree.GetPyData(item) - return Layer(item, data) + data = self._tree.GetPyData(item) + return Layer(item, data) def GetLayerInfo(self, layer): """For compatibility only, will be removed.""" @@ -147,12 +148,11 @@ def GetLayersByName(self, name): items = self._tree.FindItemByData(key="name", value=name) if items is None: return [] - else: - layers = [] - for item in items: - layer = Layer(item, self._tree.GetPyData(item)) - layers.append(layer) - return layers + layers = [] + for item in items: + layer = Layer(item, self._tree.GetPyData(item)) + layers.append(layer) + return layers def GetLayerByData(self, key, value): """Returns layer with specified. @@ -168,8 +168,7 @@ def GetLayerByData(self, key, value): item = self._tree.FindItemByData(key=key, value=value) if item is None: return None - else: - return Layer(item, self._tree.GetPyData(item)) + return Layer(item, self._tree.GetPyData(item)) class LayerManagerGrassInterface: @@ -268,8 +267,7 @@ def GetAllMapDisplays(self): def GetMapWindow(self): if self.lmgr.GetMapDisplay(onlyCurrent=True): return self.lmgr.GetMapDisplay(onlyCurrent=True).GetMapWindow() - else: - return None + return None def GetProgress(self): return self.lmgr.goutput.GetProgressBar() diff --git a/gui/wxpython/lmgr/layertree.py b/gui/wxpython/lmgr/layertree.py index 4779a40db9b..86531bcb5ad 100644 --- a/gui/wxpython/lmgr/layertree.py +++ b/gui/wxpython/lmgr/layertree.py @@ -756,7 +756,7 @@ def OnLayerContextMenu(self, event): # self.popupMenu.Enable(self.popupID['bgmap'], False) self.popupMenu.Enable(self.popupID["topo"], False) # else: - ### self.popupMenu.Enable(self.popupID['bgmap'], True) + # self.popupMenu.Enable(self.popupID['bgmap'], True) item = wx.MenuItem( self.popupMenu, id=self.popupID["meta"], text=_("Metadata") @@ -1742,7 +1742,7 @@ def OnDeleteLayer(self, event): try: item.properties.Close(True) - except: + except AttributeError: pass if item != self.root: @@ -1758,7 +1758,7 @@ def OnDeleteLayer(self, event): try: if self.GetLayerInfo(item, key="type") != "group": self.Map.DeleteLayer(self.GetLayerInfo(item, key="maplayer")) - except: + except AttributeError: pass # redraw map if auto-rendering is enabled @@ -1997,10 +1997,7 @@ def OnEndDrag(self, event): def OnDrop(self, dropTarget, dragItem): # save everything associated with item to drag - try: - old = dragItem # make sure this member exists - except: - return + old = dragItem # make sure this member exists Debug.msg(4, "LayerTree.OnDrop(): layer=%s" % (self.GetItemText(dragItem))) @@ -2046,7 +2043,7 @@ def RecreateItem(self, dragItem, dropTarget, parent=None): newctrl.SetValue( self.GetLayerInfo(dragItem, key="maplayer").GetCmd(string=True) ) - except: + except Exception: pass newctrl.Bind(wx.EVT_TEXT_ENTER, self.OnCmdChanged) data = self.GetPyData(dragItem) @@ -2336,8 +2333,7 @@ def FindItemByData(self, key, value): item = self.GetFirstChild(self.root)[0] if key == "name": return self.__FindSubItemByName(item, value) - else: - return self.__FindSubItemByData(item, key, value) + return self.__FindSubItemByData(item, key, value) def FindItemByIndex(self, index): """Find item by index (starting at 0) diff --git a/gui/wxpython/lmgr/workspace.py b/gui/wxpython/lmgr/workspace.py index febb3922dd7..774c22bf4ed 100644 --- a/gui/wxpython/lmgr/workspace.py +++ b/gui/wxpython/lmgr/workspace.py @@ -18,6 +18,8 @@ import xml.etree.ElementTree as ET +from pathlib import Path + import wx import wx.aui @@ -103,7 +105,7 @@ def Open(self): dlg = wx.FileDialog( parent=self.lmgr, message=_("Choose workspace file"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"), ) @@ -177,9 +179,10 @@ def Load(self, filename): parent=self.lmgr, message=_( "Reading workspace file <%s> failed.\n" - "Invalid file, unable to parse XML document." + "Invalid file, unable to parse XML document.\n" + "Error details: %s" ) - % filename, + % (filename, str(e)), ) return False @@ -362,7 +365,7 @@ def SaveAs(self): dlg = wx.FileDialog( parent=self.lmgr, message=_("Choose file to save current workspace"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"), style=wx.FD_SAVE, ) @@ -434,7 +437,11 @@ def SaveToFile(self, filename): except Exception as e: GError( parent=self.lmgr, - message=_("Writing current settings to workspace file failed."), + message=_( + "Writing current settings to workspace file <%s> failed.\n" + "Error details: %s" + ) + % (tmpfile, str(e)), ) return False @@ -548,9 +555,8 @@ def OpenRecentFile(self, path, file_exists, file_history): """ if not file_exists: GError( - _( - "File <{}> doesn't exist." - " It was probably moved or deleted.".format(path) + _("File <{}> doesn't exist. It was probably moved or deleted.").format( + path ), parent=self.lmgr, ) diff --git a/gui/wxpython/location_wizard/dialogs.py b/gui/wxpython/location_wizard/dialogs.py index 16325ddfbe1..079fca1f6d4 100644 --- a/gui/wxpython/location_wizard/dialogs.py +++ b/gui/wxpython/location_wizard/dialogs.py @@ -594,8 +594,8 @@ def __UpdateInfo(self): self.lcols.SetLabel(_("Cols: %d") % self.cols) self.lcells.SetLabel(_("Cells: %d") % self.cells) # 3D - self.ldepth.SetLabel(_("Depth: %d" % self.depth)) - self.lcells3.SetLabel(_("3D Cells: %d" % self.cells3)) + self.ldepth.SetLabel(_("Depth: %d") % self.depth) + self.lcells3.SetLabel(_("3D Cells: %d") % self.cells3) def OnSetButton(self, event=None): """Set default region""" diff --git a/gui/wxpython/location_wizard/wizard.py b/gui/wxpython/location_wizard/wizard.py index 155346b3467..d8b6b4180ba 100644 --- a/gui/wxpython/location_wizard/wizard.py +++ b/gui/wxpython/location_wizard/wizard.py @@ -38,6 +38,8 @@ import locale import functools +from pathlib import Path + import wx import wx.lib.mixins.listctrl as listmix from core import globalvar @@ -318,7 +320,10 @@ def OnChangeName(self, event): def OnBrowse(self, event): """Choose GRASS data directory""" dlg = wx.DirDialog( - self, _("Choose GRASS data directory:"), os.getcwd(), wx.DD_DEFAULT_STYLE + self, + _("Choose GRASS data directory:"), + str(Path.cwd()), + wx.DD_DEFAULT_STYLE, ) if dlg.ShowModal() == wx.ID_OK: self.grassdatabase = dlg.GetPath() @@ -586,7 +591,7 @@ def OnText(self, event): self.tproj.SetValue(self.proj) nextButton.Enable(False) return - elif self.proj.lower() == "ll": + if self.proj.lower() == "ll": self.p4proj = "+proj=longlat" else: self.p4proj = "+proj=" + self.proj.lower() @@ -766,8 +771,7 @@ def Sorter(self, key1, key2): if ascending: return cmpVal - else: - return -cmpVal + return -cmpVal def GetListCtrl(self): """Used by listmix.ColumnSorterMixin""" @@ -799,12 +803,10 @@ def Search(self, index, pattern, firstOnly=True): if len(data) > 0: if firstOnly: return data[0] - else: - return data - elif firstOnly: + return data + if firstOnly: return None - else: - return [] + return [] class ProjParamsPage(TitledPage): @@ -1493,7 +1495,7 @@ def OnText(self, event): def OnBrowse(self, event): """Choose file""" dlg = wx.FileDialog( - self, _("Select georeferenced file"), os.getcwd(), "", "*.*", wx.FD_OPEN + self, _("Select georeferenced file"), str(Path.cwd()), "", "*.*", wx.FD_OPEN ) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() @@ -1655,29 +1657,28 @@ def OnPageChanging(self, event): if not self.epsgcode: event.Veto() return - else: - # check for datum transforms - ret = RunCommand( - "g.proj", read=True, epsg=self.epsgcode, datum_trans="-1", flags="t" - ) + # check for datum transforms + ret = RunCommand( + "g.proj", read=True, epsg=self.epsgcode, datum_trans="-1", flags="t" + ) - if ret != "": - dtrans = "" - # open a dialog to select datum transform number - dlg = SelectTransformDialog(self.parent.parent, transforms=ret) + if ret != "": + dtrans = "" + # open a dialog to select datum transform number + dlg = SelectTransformDialog(self.parent.parent, transforms=ret) - if dlg.ShowModal() == wx.ID_OK: - dtrans = dlg.GetTransform() - if dtrans == "": - dlg.Destroy() - event.Veto() - return "Datum transform is required." - else: + if dlg.ShowModal() == wx.ID_OK: + dtrans = dlg.GetTransform() + if dtrans == "": dlg.Destroy() event.Veto() return "Datum transform is required." + else: + dlg.Destroy() + event.Veto() + return "Datum transform is required." - self.parent.datum_trans = dtrans + self.parent.datum_trans = dtrans self.GetNext().SetPrev(self) def EnableNext(self, enable=True): @@ -1875,55 +1876,51 @@ def OnPageChanging(self, event): if not self.epsgcode: event.Veto() return - else: - # check for datum transforms - ret = RunCommand( - "g.proj", - read=True, - proj4=self.epsgparams, - datum_trans="-1", - flags="t", - ) + # check for datum transforms + ret = RunCommand( + "g.proj", + read=True, + proj4=self.epsgparams, + datum_trans="-1", + flags="t", + ) - if ret != "": - dtrans = "" - # open a dialog to select datum transform number - dlg = SelectTransformDialog(self.parent.parent, transforms=ret) + if ret != "": + dtrans = "" + # open a dialog to select datum transform number + dlg = SelectTransformDialog(self.parent.parent, transforms=ret) - if dlg.ShowModal() == wx.ID_OK: - dtrans = dlg.GetTransform() - if dtrans == "": - dlg.Destroy() - event.Veto() - return "Datum transform is required." - else: + if dlg.ShowModal() == wx.ID_OK: + dtrans = dlg.GetTransform() + if dtrans == "": dlg.Destroy() event.Veto() return "Datum transform is required." + else: + dlg.Destroy() + event.Veto() + return "Datum transform is required." - self.parent.datum_trans = dtrans - self.parent.epsgcode = self.epsgcode - self.parent.epsgdesc = self.epsgdesc + self.parent.datum_trans = dtrans + self.parent.epsgcode = self.epsgcode + self.parent.epsgdesc = self.epsgdesc - # prepare +nadgrids or +towgs84 terms for Summary page. first - # convert them: - ret, projlabel, err = RunCommand( - "g.proj", - flags="jft", - proj4=self.epsgparams, - datum_trans=self.parent.datum_trans, - getErrorMsg=True, - read=True, - ) - # splitting on space alone would break for grid files with - # space in pathname - for projterm in projlabel.split(" +"): - if ( - projterm.find("towgs84=") != -1 - or projterm.find("nadgrids=") != -1 - ): - self.custom_dtrans_string = " +%s" % projterm - break + # prepare +nadgrids or +towgs84 terms for Summary page. first + # convert them: + ret, projlabel, err = RunCommand( + "g.proj", + flags="jft", + proj4=self.epsgparams, + datum_trans=self.parent.datum_trans, + getErrorMsg=True, + read=True, + ) + # splitting on space alone would break for grid files with + # space in pathname + for projterm in projlabel.split(" +"): + if projterm.find("towgs84=") != -1 or projterm.find("nadgrids=") != -1: + self.custom_dtrans_string = " +%s" % projterm + break self.GetNext().SetPrev(self) @@ -1977,7 +1974,7 @@ def OnBrowse(self, event): """Define path for IAU code file""" path = os.path.dirname(self.tfile.GetValue()) if not path: - path = os.getcwd() + path = str(Path.cwd()) dlg = wx.FileDialog( parent=self, @@ -2538,7 +2535,7 @@ def __readData(self): """Get georeferencing information from tables in $GISBASE/etc/proj""" # read projection and parameters - f = open(os.path.join(globalvar.ETCDIR, "proj", "parms.table"), "r") + f = open(os.path.join(globalvar.ETCDIR, "proj", "parms.table")) self.projections = {} self.projdesc = {} for line in f: @@ -2561,7 +2558,7 @@ def __readData(self): f.close() # read datum definitions - f = open(os.path.join(globalvar.ETCDIR, "proj", "datum.table"), "r") + f = open(os.path.join(globalvar.ETCDIR, "proj", "datum.table")) self.datums = {} paramslist = [] for line in f: @@ -2579,7 +2576,7 @@ def __readData(self): f.close() # read Earth-based ellipsiod definitions - f = open(os.path.join(globalvar.ETCDIR, "proj", "ellipse.table"), "r") + f = open(os.path.join(globalvar.ETCDIR, "proj", "ellipse.table")) self.ellipsoids = {} for line in f: line = line.expandtabs(1) @@ -2595,9 +2592,7 @@ def __readData(self): f.close() # read Planetary ellipsiod definitions - f = open( - os.path.join(globalvar.ETCDIR, "proj", "ellipse.table.solar.system"), "r" - ) + f = open(os.path.join(globalvar.ETCDIR, "proj", "ellipse.table.solar.system")) self.planetary_ellipsoids = {} for line in f: line = line.expandtabs(1) @@ -2613,7 +2608,7 @@ def __readData(self): f.close() # read projection parameter description and parsing table - f = open(os.path.join(globalvar.ETCDIR, "proj", "desc.table"), "r") + f = open(os.path.join(globalvar.ETCDIR, "proj", "desc.table")) self.paramdesc = {} for line in f: line = line.strip() @@ -2723,7 +2718,7 @@ def OnWizFinished(self): if not self.filepage.georeffile or not os.path.isfile( self.filepage.georeffile ): - return _("File <%s> not found." % self.filepage.georeffile) + return _("File <%s> not found.") % self.filepage.georeffile grass.create_location( dbase=self.startpage.grassdatabase, diff --git a/gui/wxpython/main_window/frame.py b/gui/wxpython/main_window/frame.py index facb3f8195a..cef4aee7121 100644 --- a/gui/wxpython/main_window/frame.py +++ b/gui/wxpython/main_window/frame.py @@ -25,6 +25,8 @@ import platform import re +from pathlib import Path + from core import globalvar try: @@ -971,7 +973,7 @@ def OnRunModel(self, event): dlg = wx.FileDialog( parent=self, message=_("Choose model to run"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("GRASS Model File (*.gxm)|*.gxm"), ) if dlg.ShowModal() == wx.ID_OK: @@ -1238,14 +1240,13 @@ def GetMapDisplay(self, onlyCurrent=True): if onlyCurrent: if self.currentPage: return self.GetLayerTree().GetMapDisplay() - else: - return None - else: # -> return list of all mapdisplays - mlist = [] - for idx in range(0, self.notebookLayers.GetPageCount()): - mlist.append(self.notebookLayers.GetPage(idx).maptree.GetMapDisplay()) + return None + # -> return list of all mapdisplays + mlist = [] + for idx in range(self.notebookLayers.GetPageCount()): + mlist.append(self.notebookLayers.GetPage(idx).maptree.GetMapDisplay()) - return mlist + return mlist def GetAllMapDisplays(self): """Get all (open) map displays""" @@ -1374,7 +1375,7 @@ def OnRunScript(self, event): dlg = wx.FileDialog( parent=self, message=_("Choose script file to run"), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("Python script (*.py)|*.py|Bash script (*.sh)|*.sh"), ) @@ -1402,8 +1403,8 @@ def OnRunScript(self, event): "Do you want to set the permissions " "that allows you to run this script " "(note that you must be the owner of the file)?" - % os.path.basename(filename) - ), + ) + % os.path.basename(filename), caption=_("Set permission?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, ) @@ -1528,9 +1529,7 @@ def write_beginning(parameter=None, command=None): self._giface.WriteCmdLog(" ".join(command)) def write_changed(): - self._giface.WriteLog( - _('Working directory changed to:\n"%s"') % os.getcwd() - ) + self._giface.WriteLog(_('Working directory changed to:\n"%s"') % Path.cwd()) def write_end(): self._giface.WriteCmdLog(" ") @@ -1584,7 +1583,7 @@ def write_help(): dlg = wx.DirDialog( parent=self, message=_("Choose a working directory"), - defaultPath=os.getcwd(), + defaultPath=str(Path.cwd()), ) if dlg.ShowModal() == wx.ID_OK: @@ -2054,7 +2053,7 @@ def _onStarting3dMode(self, mapDisplayPage): """Disables 3D mode for all map displays except for @p mapDisplay""" # TODO: it should be disabled also for newly created map windows # moreover mapdisp.Disable3dMode() does not work properly - for page in range(0, self.GetLayerNotebook().GetPageCount()): + for page in range(self.GetLayerNotebook().GetPageCount()): mapdisp = self.GetLayerNotebook().GetPage(page).maptree.GetMapDisplay() if self.GetLayerNotebook().GetPage(page) != mapDisplayPage: mapdisp.Disable3dMode() diff --git a/gui/wxpython/mapdisp/frame.py b/gui/wxpython/mapdisp/frame.py index 8cb8a51d407..c9b5d86e4ba 100644 --- a/gui/wxpython/mapdisp/frame.py +++ b/gui/wxpython/mapdisp/frame.py @@ -411,8 +411,9 @@ def AddNviz(self): message=_( "Unable to switch to 3D display mode.\nThe Nviz python extension " "was not found or loaded properly.\n" - "Switching back to 2D display mode.\n\nDetails: %s" % errorMsg - ), + "Switching back to 2D display mode.\n\nDetails: %s" + ) + % errorMsg, ) return @@ -830,7 +831,7 @@ def _DToRastDone(): overwrite=overwrite, getErrorMsg=True, ) - if not returncode == 0: + if returncode != 0: self._giface.WriteError(_("Failed to run d.to.rast:\n") + messages) return # set region for composite @@ -838,7 +839,7 @@ def _DToRastDone(): returncode, messages = RunCommand( "g.region", raster=tmpName + ".red", quiet=True, getErrorMsg=True ) - if not returncode == 0: + if returncode != 0: gs.del_temp_region() self._giface.WriteError(_("Failed to run d.to.rast:\n") + messages) return @@ -861,7 +862,7 @@ def _DToRastDone(): quiet=True, name=[tmpName + ".red", tmpName + ".green", tmpName + ".blue"], ) - if not returncode == 0: + if returncode != 0: self._giface.WriteError(_("Failed to run d.to.rast:\n") + messages) gs.try_remove(pngFile) return @@ -1229,8 +1230,7 @@ def AddTmpVectorMapLayer(self, name, cats, useId=False, addLayer=True): render=True, **args, ) - else: - return cmd + return cmd def OnMeasureDistance(self, event): self._onMeasure(MeasureDistanceController) diff --git a/gui/wxpython/mapdisp/main.py b/gui/wxpython/mapdisp/main.py index 1e94d3d8ba2..6449bc35d7c 100644 --- a/gui/wxpython/mapdisp/main.py +++ b/gui/wxpython/mapdisp/main.py @@ -108,7 +108,7 @@ def __init__(self, giface, cmdfile=None, mapfile=None): self.renderMgr = RenderMapMgr(self) # update legend file variable with the one d.mon uses - with open(monFile["env"], "r") as f: + with open(monFile["env"]) as f: lines = f.readlines() for line in lines: if "GRASS_LEGEND_FILE" in line: @@ -123,7 +123,7 @@ def GetLayersFromCmdFile(self): nlayers = 0 try: - fd = open(self.cmdfile, "r") + fd = open(self.cmdfile) lines = fd.readlines() fd.close() # detect d.out.file, delete the line from the cmd file and export @@ -334,14 +334,14 @@ def __init__(self, maplayer): def __getattr__(self, name): if name == "cmd": return cmdtuple_to_list(self._maplayer.GetCmd()) - elif hasattr(self._maplayer, name): + if hasattr(self._maplayer, name): return getattr(self._maplayer, name) - elif name == "maplayer": + if name == "maplayer": return self._maplayer - elif name == "type": + if name == "type": return self._maplayer.GetType() # elif name == 'ctrl': - elif name == "label": + if name == "label": return self._maplayer.GetName() # elif name == 'propwin': @@ -386,8 +386,7 @@ def GetSelectedLayer(self, checkedOnly=False): layers = self.GetSelectedLayers() if len(layers) > 0: return layers[0] - else: - return None + return None def AddLayer(self, ltype, name=None, checked=None, opacity=1.0, cmd=None): """Adds a new layer to the layer list. diff --git a/gui/wxpython/mapdisp/statusbar.py b/gui/wxpython/mapdisp/statusbar.py index 72e9d0afdbc..4fea1ffcc81 100644 --- a/gui/wxpython/mapdisp/statusbar.py +++ b/gui/wxpython/mapdisp/statusbar.py @@ -138,7 +138,7 @@ def DisableStatusbarItemsByClass(self, itemClasses): :param itemClasses list of classes of items to be disabled """ for itemClass in itemClasses: - for i in range(0, len(self.statusbarItems.values())): + for i in range(len(self.statusbarItems.values())): item = list(self.statusbarItems.values())[i] if item.__class__ == itemClass: self.disabledItems[i] = item @@ -631,10 +631,8 @@ def GetCenterString(self, map): return "%s" % utils.Deg2DMS( coord[0], coord[1], precision=precision ) - else: - return "%.*f; %.*f" % (precision, coord[0], precision, coord[1]) - else: - raise SbException(_("Error in projection (check the settings)")) + return "%.*f; %.*f" % (precision, coord[0], precision, coord[1]) + raise SbException(_("Error in projection (check the settings)")) elif self.mapFrame.GetMap().projinfo["proj"] == "ll" and format == "DMS": return "%s" % utils.Deg2DMS( region["center_easting"], @@ -806,10 +804,8 @@ def ReprojectENFromMap(self, e, n, useDefinedProjection, precision, format): e, n = coord if proj in {"ll", "latlong", "longlat"} and format == "DMS": return utils.Deg2DMS(e, n, precision=precision) - else: - return "%.*f; %.*f" % (precision, e, precision, n) - else: - raise SbException(_("Error in projection (check the settings)")) + return "%.*f; %.*f" % (precision, e, precision, n) + raise SbException(_("Error in projection (check the settings)")) elif self.mapFrame.GetMap().projinfo["proj"] == "ll" and format == "DMS": return utils.Deg2DMS(e, n, precision=precision) else: @@ -860,8 +856,7 @@ def _formatRegion(self, w, e, s, n, nsres, ewres, precision=None): precision, n, ) - else: - return "%s - %s, %s - %s" % (w, e, s, n) + return "%s - %s, %s - %s" % (w, e, s, n) def ReprojectRegionFromMap(self, region, useDefinedProjection, precision, format): """Reproject region values @@ -910,21 +905,19 @@ def ReprojectRegionFromMap(self, region, useDefinedProjection, precision, format return self._formatRegion( w=w, s=s, e=e, n=n, ewres=ewres, nsres=nsres ) - else: - w, s = coord1 - e, n = coord2 - ewres, nsres = coord3 - return self._formatRegion( - w=w, - s=s, - e=e, - n=n, - ewres=ewres, - nsres=nsres, - precision=precision, - ) - else: - raise SbException(_("Error in projection (check the settings)")) + w, s = coord1 + e, n = coord2 + ewres, nsres = coord3 + return self._formatRegion( + w=w, + s=s, + e=e, + n=n, + ewres=ewres, + nsres=nsres, + precision=precision, + ) + raise SbException(_("Error in projection (check the settings)")) elif self.mapFrame.GetMap().projinfo["proj"] == "ll" and format == "DMS": w, s = utils.Deg2DMS( @@ -971,8 +964,7 @@ def _formatRegion(self, w, e, s, n, ewres, nsres, precision=None): precision, nsres, ) - else: - return "%s - %s, %s - %s (%s, %s)" % (w, e, s, n, ewres, nsres) + return "%s - %s, %s - %s (%s, %s)" % (w, e, s, n, ewres, nsres) def _getRegion(self): """Returns computational region.""" diff --git a/gui/wxpython/mapdisp/test_mapdisp.py b/gui/wxpython/mapdisp/test_mapdisp.py index 7a61e196ba9..1494988fafb 100755 --- a/gui/wxpython/mapdisp/test_mapdisp.py +++ b/gui/wxpython/mapdisp/test_mapdisp.py @@ -356,7 +356,7 @@ def main(): tester.testMapWindowRlisetup(map_) else: # TODO: this should not happen but happens - gs.fatal(_("Unknown value %s of test parameter." % test)) + gs.fatal(_("Unknown value %s of test parameter.") % test) app.MainLoop() diff --git a/gui/wxpython/mapswipe/dialogs.py b/gui/wxpython/mapswipe/dialogs.py index 945aee590ea..a765f3774ce 100644 --- a/gui/wxpython/mapswipe/dialogs.py +++ b/gui/wxpython/mapswipe/dialogs.py @@ -241,8 +241,7 @@ def GetValues(self): """Get raster maps""" if self.IsSimpleMode(): return (self._firstRaster.GetValue(), self._secondRaster.GetValue()) - else: - return (self._firstLayerList, self._secondLayerList) + return (self._firstLayerList, self._secondLayerList) def IsSimpleMode(self) -> bool: return bool(self._switchSizer.IsShown(self._firstPanel)) diff --git a/gui/wxpython/mapswipe/mapwindow.py b/gui/wxpython/mapswipe/mapwindow.py index dbb181eb62b..a203ef2e6d1 100644 --- a/gui/wxpython/mapswipe/mapwindow.py +++ b/gui/wxpython/mapswipe/mapwindow.py @@ -81,8 +81,7 @@ def GetClientSize(self): """Overridden method which returns simulated window size.""" if self._mode == "swipe": return self.specialSize - else: - return super().GetClientSize() + return super().GetClientSize() def SetClientSize(self, size): """Overridden method which sets simulated window size.""" @@ -100,8 +99,7 @@ def GetImageCoords(self): """Returns coordinates of rendered image""" if self._mode == "swipe": return self.specialCoords - else: - return (0, 0) + return (0, 0) def SetImageCoords(self, coords): """Sets coordinates of rendered image""" diff --git a/gui/wxpython/mapwin/analysis.py b/gui/wxpython/mapwin/analysis.py index 490a9d7e866..4c9ac37a5e0 100644 --- a/gui/wxpython/mapwin/analysis.py +++ b/gui/wxpython/mapwin/analysis.py @@ -93,20 +93,20 @@ def _doAnalysis(self, coords): :param coords: EN coordinates """ - raise NotImplementedError() + raise NotImplementedError def _disconnectAll(self): """Disconnect all mouse signals to stop drawing.""" - raise NotImplementedError() + raise NotImplementedError def _connectAll(self): """Connect all mouse signals to draw.""" - raise NotImplementedError() + raise NotImplementedError def _getPen(self): """Returns wx.Pen instance.""" - raise NotImplementedError() + raise NotImplementedError def Stop(self, restore=True): """Analysis mode is stopped. @@ -262,11 +262,7 @@ def Start(self): self._useCtypes = True except ImportError as e: self._giface.WriteWarning( - _( - "Geodesic distance calculation " - "is not available.\n" - "Reason: %s" % e - ) + _("Geodesic distance calculation is not available.\nReason: %s") % e ) def MeasureDist(self, beginpt, endpt): diff --git a/gui/wxpython/mapwin/base.py b/gui/wxpython/mapwin/base.py index e9752caf953..c05cc8f840b 100644 --- a/gui/wxpython/mapwin/base.py +++ b/gui/wxpython/mapwin/base.py @@ -370,10 +370,10 @@ def UnregisterMouseEventHandler(self, event, handler): return True def Pixel2Cell(self, xyCoords): - raise NotImplementedError() + raise NotImplementedError def Cell2Pixel(self, enCoords): - raise NotImplementedError() + raise NotImplementedError def OnMotion(self, event): """Tracks mouse motion and update statusbar @@ -453,8 +453,8 @@ def SetModeQuery(self): def DisactivateWin(self): """Use when the class instance is hidden in MapFrame.""" - raise NotImplementedError() + raise NotImplementedError def ActivateWin(self): """Used when the class instance is activated in MapFrame.""" - raise NotImplementedError() + raise NotImplementedError diff --git a/gui/wxpython/mapwin/buffered.py b/gui/wxpython/mapwin/buffered.py index e0442ed94ae..c4b07a94fd2 100644 --- a/gui/wxpython/mapwin/buffered.py +++ b/gui/wxpython/mapwin/buffered.py @@ -28,6 +28,8 @@ import wx +from operator import itemgetter + from grass.pydispatch.signal import Signal from core.globalvar import wxPythonPhoenix @@ -462,10 +464,10 @@ def Draw( brush = wx.TRANSPARENT_BRUSH pdc.SetBrush(brush) pdc.DrawPolygon(points=coords) - x = min(coords, key=lambda x: x[0])[0] - y = min(coords, key=lambda x: x[1])[1] - w = max(coords, key=lambda x: x[0])[0] - x - h = max(coords, key=lambda x: x[1])[1] - y + x = min(coords, key=itemgetter(0))[0] + y = min(coords, key=itemgetter(1))[1] + w = max(coords, key=itemgetter(0))[0] - x + h = max(coords, key=itemgetter(1))[1] - y pdc.SetIdBounds(drawid, Rect(x, y, w, h)) elif pdctype == "circle": # draw circle @@ -558,8 +560,7 @@ def TextBounds(self, textinfo, relcoords=False): bbox[2], bbox[3] = w, h if relcoords: return coords, bbox, relCoords - else: - return coords, bbox + return coords, bbox boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h @@ -578,8 +579,7 @@ def TextBounds(self, textinfo, relcoords=False): bbox.Inflate(h, h) if relcoords: return coords, bbox, relCoords - else: - return coords, bbox + return coords, bbox def OnPaint(self, event): """Draw PseudoDC's to buffered paint DC diff --git a/gui/wxpython/mapwin/decorations.py b/gui/wxpython/mapwin/decorations.py index 7ab010a1d3f..24db63d8492 100644 --- a/gui/wxpython/mapwin/decorations.py +++ b/gui/wxpython/mapwin/decorations.py @@ -209,9 +209,7 @@ def CmdIsValid(self) -> bool: inputs = 0 for param in self._cmd[1:]: param = param.split("=") - if len(param) == 1: - inputs += 1 - elif param[0] == "text" and len(param) == 2: + if len(param) == 1 or (param[0] == "text" and len(param) == 2): inputs += 1 return inputs >= 1 @@ -313,11 +311,11 @@ def CmdIsValid(self) -> bool: inputs = 0 for param in self._cmd[1:]: param = param.split("=") - if len(param) == 1: - inputs += 1 - elif param[0] == "raster" and len(param) == 2: - inputs += 1 - elif param[0] == "raster_3d" and len(param) == 2: + if ( + len(param) == 1 + or (param[0] == "raster" and len(param) == 2) + or (param[0] == "raster_3d" and len(param) == 2) + ): inputs += 1 return inputs == 1 diff --git a/gui/wxpython/modules/colorrules.py b/gui/wxpython/modules/colorrules.py index b5b1047382e..3dfdde8c42b 100644 --- a/gui/wxpython/modules/colorrules.py +++ b/gui/wxpython/modules/colorrules.py @@ -27,6 +27,8 @@ import copy import tempfile +from pathlib import Path + import wx import wx.lib.colourselect as csel import wx.lib.scrolledpanel as scrolled @@ -316,7 +318,9 @@ def LoadRules(self): int, self.ruleslines[item][self.attributeType].split(":") ) except ValueError as e: - message = _("Bad color format. Use color format '0:0:0'") + message = ( + _("Bad color format '%s'. Use color format '0:0:0'") % e + ) self.mainPanel.FindWindowById(item + 2000).SetValue((r, g, b)) else: value = float(self.ruleslines[item][self.attributeType]) @@ -408,7 +412,6 @@ def _initLayer(self): if layer: mapLayer = self.layerTree.GetLayerInfo(layer, key="maplayer") name = mapLayer.GetName() - type = mapLayer.GetType() self.selectionInput.SetValue(name) self.inmap = name @@ -448,7 +451,7 @@ def _createFileSelection(self, parent): dialogTitle=_("Choose file to load color table"), buttonText=_("Load"), toolTip=_("Type filename or click to choose file and load color table"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=wx.FD_OPEN, changeCallback=self.OnLoadRulesFile, ) @@ -460,7 +463,7 @@ def _createFileSelection(self, parent): dialogTitle=_("Choose file to save color table"), toolTip=_("Type filename or click to choose file and save color table"), buttonText=_("Save"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=wx.FD_SAVE, changeCallback=self.OnSaveRulesFile, ) @@ -698,7 +701,7 @@ def OnLoadRulesFile(self, event): self.rulesPanel.Clear() - fd = open(path, "r") + fd = open(path) self.ReadColorTable(ctable=fd.read()) fd.close() @@ -1410,7 +1413,7 @@ def AddTemporaryColumn(self, type): modul = "v.db.addcolumn" else: modul = "v.db.addcol" - ret = RunCommand( + RunCommand( modul, parent=self, map=self.inmap, @@ -1428,7 +1431,7 @@ def DeleteTemporaryColumn(self): modul = "v.db.dropcolumn" else: modul = "v.db.dropcol" - ret = RunCommand( + RunCommand( modul, map=self.inmap, layer=self.properties["layer"], @@ -1503,7 +1506,7 @@ def OnAddColumn(self, event): modul = "v.db.addcolumn" else: modul = "v.db.addcol" - ret = RunCommand( + RunCommand( modul, map=self.inmap, layer=self.properties["layer"], diff --git a/gui/wxpython/modules/import_export.py b/gui/wxpython/modules/import_export.py index 15d4f76b586..f2f70e47831 100644 --- a/gui/wxpython/modules/import_export.py +++ b/gui/wxpython/modules/import_export.py @@ -22,6 +22,8 @@ import os +from pathlib import Path + import wx from core import globalvar import wx.lib.filebrowsebutton as filebrowse @@ -234,15 +236,15 @@ def doLayout(self): def _getCommand(self): """Get command""" - raise NotImplementedError() + raise NotImplementedError def _getBlackListedParameters(self): """Get parameters which will not be showed in Settings page""" - raise NotImplementedError() + raise NotImplementedError def _getBlackListedFlags(self): """Get flags which will not be showed in Settings page""" - raise NotImplementedError() + raise NotImplementedError def _nameValidationFailed(self, layers_list): """Output map name validation callback @@ -536,8 +538,7 @@ def _getCommand(self): """Get command""" if self.link: return "r.external" - else: - return "r.import" + return "r.import" def _getBlackListedParameters(self): """Get flags which will not be showed in Settings page""" @@ -691,8 +692,7 @@ def _getCommand(self): """Get command""" if self.link: return "v.external" - else: - return "v.import" + return "v.import" def _getBlackListedParameters(self): """Get parametrs which will not be showed in Settings page""" @@ -836,7 +836,7 @@ def __init__(self, parent, giface): labelText="", dialogTitle=_("Choose DXF file to import"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=0, changeCallback=self.OnSetDsn, fileMask="DXF File (*.dxf)|*.dxf", diff --git a/gui/wxpython/modules/mcalc_builder.py b/gui/wxpython/modules/mcalc_builder.py index e157375b4a4..b0f2f280409 100644 --- a/gui/wxpython/modules/mcalc_builder.py +++ b/gui/wxpython/modules/mcalc_builder.py @@ -759,7 +759,7 @@ def OnLoadExpression(self, event): return try: - fobj = open(path, "r") + fobj = open(path) mctxt = fobj.read() finally: fobj.close() diff --git a/gui/wxpython/nviz/mapwindow.py b/gui/wxpython/nviz/mapwindow.py index eaf0d266d4e..8cf972704e2 100644 --- a/gui/wxpython/nviz/mapwindow.py +++ b/gui/wxpython/nviz/mapwindow.py @@ -534,7 +534,7 @@ def OnKeyDown(self, event): Used for fly-through mode. """ - if not self.mouse["use"] == "fly": + if self.mouse["use"] != "fly": return key = event.GetKeyCode() @@ -596,7 +596,7 @@ def OnKeyUp(self, event): Used for fly-through mode. """ - if not self.mouse["use"] == "fly": + if self.mouse["use"] != "fly": return key = event.GetKeyCode() @@ -2358,10 +2358,10 @@ def GetLayerId(self, type, name, vsubtyp=None): try: if type == "raster": return data["surface"]["object"]["id"] - elif type == "vector": + if type == "vector": if vsubtyp == "vpoint": return data["vector"]["points"]["object"]["id"] - elif vsubtyp == "vline": + if vsubtyp == "vline": return data["vector"]["lines"]["object"]["id"] elif type == "raster_3d": return data["volume"]["object"]["id"] diff --git a/gui/wxpython/nviz/tools.py b/gui/wxpython/nviz/tools.py index a1b0a9fcb1b..20b1df1ffbd 100644 --- a/gui/wxpython/nviz/tools.py +++ b/gui/wxpython/nviz/tools.py @@ -23,6 +23,8 @@ import sys import copy +from pathlib import Path + import wx import wx.lib.colourselect as csel import wx.lib.scrolledpanel as SP @@ -668,7 +670,7 @@ def _createAnimationPage(self): vSizer = wx.BoxSizer(wx.VERTICAL) gridSizer = wx.GridBagSizer(vgap=5, hgap=10) - pwd = os.getcwd() + pwd = str(Path.cwd()) dir = filebrowse.DirBrowseButton( parent=panel, id=wx.ID_ANY, @@ -2644,9 +2646,9 @@ def GetLayerData(self, nvizType, nameOnly=False): if nvizType in {"surface", "fringe"}: return self._getLayerPropertiesByName(name, mapType="raster") - elif nvizType == "vector": + if nvizType == "vector": return self._getLayerPropertiesByName(name, mapType="vector") - elif nvizType == "volume": + if nvizType == "volume": return self._getLayerPropertiesByName(name, mapType="raster_3d") return None @@ -2855,7 +2857,7 @@ def OnSaveAnimation(self, event): if not prefix: GMessage(parent=self, message=_("No file prefix given.")) return - elif not os.path.exists(dir): + if not os.path.exists(dir): GMessage(parent=self, message=_("Directory %s does not exist.") % dir) return @@ -4574,7 +4576,7 @@ def OnVolumeSelect(self, event): selection = event.GetSelection() if selection == -1: return - elif selection == 0: + if selection == 0: winUp.Enable(False) if not winDown.IsEnabled(): winDown.Enable() diff --git a/gui/wxpython/nviz/wxnviz.py b/gui/wxpython/nviz/wxnviz.py index 8002d6f32d2..47cf99c079d 100644 --- a/gui/wxpython/nviz/wxnviz.py +++ b/gui/wxpython/nviz/wxnviz.py @@ -83,7 +83,7 @@ def print_progress(value): """Redirect progress info""" global progress if progress: - if not progress.GetRange() == 100: + if progress.GetRange() != 100: progress.SetRange(100) progress.SetValue(value) else: @@ -246,8 +246,7 @@ def GetFocus(self): z = c_float() Nviz_get_focus(self.data, byref(x), byref(y), byref(z)) return x.value, y.value, z.value - else: - return -1, -1, -1 + return -1, -1, -1 def SetFocus(self, x, y, z): """Set focus""" @@ -1873,8 +1872,7 @@ def SetCPlaneInteractively(self, x, y): Nviz_draw_cplane(self.data, -1, -1) x, y, z = self.GetCPlaneTranslation() return x, y, z - else: - return None, None, None + return None, None, None def SelectCPlane(self, index): """Select cutting plane diff --git a/gui/wxpython/photo2image/g.gui.photo2image.py b/gui/wxpython/photo2image/g.gui.photo2image.py index 21635175374..65b4141873e 100755 --- a/gui/wxpython/photo2image/g.gui.photo2image.py +++ b/gui/wxpython/photo2image/g.gui.photo2image.py @@ -68,7 +68,6 @@ """ Module to run GCP management tool as stadalone application. -@author Vaclav Petras (standalone module) """ import os import grass.script as gs diff --git a/gui/wxpython/photo2image/ip2i_manager.py b/gui/wxpython/photo2image/ip2i_manager.py index 2a9ae19d26a..5a2a1f14f21 100644 --- a/gui/wxpython/photo2image/ip2i_manager.py +++ b/gui/wxpython/photo2image/ip2i_manager.py @@ -118,7 +118,7 @@ def __init__( self.source_gisrc = os.environ["GISRC"] self.gisrc_dict = {} try: - f = open(self.target_gisrc, "r") + f = open(self.target_gisrc) for line in f: line = line.replace("\n", "").strip() if len(line) < 1: @@ -429,7 +429,7 @@ def __init__( import re try: - fc = open(self.file["camera"], mode="r") + fc = open(self.file["camera"]) fc_count = 0 for line in fc: fc_count += 1 @@ -438,7 +438,7 @@ def __init__( numberOfFiducial = int(line.split()[-1]) dataFiducialX = [] dataFiducialY = [] - fc = open(self.file["camera"], mode="r") + fc = open(self.file["camera"]) fc_count = 0 for line in fc: fc_count += 1 @@ -625,7 +625,7 @@ def InitMapDisplay(self): # initialize column sorter self.itemDataMap = self.mapcoordlist ncols = self.list.GetColumnCount() - ColumnSorterMixin(self, ncols) + ColumnSorterMixin.__init__(self, ncols) # noqa: PLC2801, C2801 # init to ascending sort on first click self._colSortFlag = [1] * ncols @@ -955,7 +955,7 @@ def ReadGCPs(self): GError(parent=self, message=_("target mapwin not defined")) try: - f = open(self.file["points"], "r") + f = open(self.file["points"]) GCPcnt = 0 for line in f: @@ -1531,7 +1531,7 @@ def AdjustMap(self, newreg): def OnZoomToSource(self, event): """Set target map window to match extents of source map window""" - if not self.MapWindow == self.TgtMapWindow: + if self.MapWindow != self.TgtMapWindow: self.MapWindow = self.TgtMapWindow self.Map = self.TgtMap self.UpdateActive(self.TgtMapWindow) @@ -1544,7 +1544,7 @@ def OnZoomToSource(self, event): def OnZoomToTarget(self, event): """Set source map window to match extents of target map window""" - if not self.MapWindow == self.SrcMapWindow: + if self.MapWindow != self.SrcMapWindow: self.MapWindow = self.SrcMapWindow self.Map = self.SrcMap self.UpdateActive(self.SrcMapWindow) @@ -2381,7 +2381,7 @@ def OnSrcSelection(self, event): tmp_map = self.srcselection.GetValue() - if not tmp_map == "" and not tmp_map == src_map: + if tmp_map not in ("", src_map): self.new_src_map = tmp_map def OnTgtRastSelection(self, event): diff --git a/gui/wxpython/photo2image/ip2i_mapdisplay.py b/gui/wxpython/photo2image/ip2i_mapdisplay.py index f85be35ec4a..aa085f2b43a 100644 --- a/gui/wxpython/photo2image/ip2i_mapdisplay.py +++ b/gui/wxpython/photo2image/ip2i_mapdisplay.py @@ -559,7 +559,7 @@ def GetMapToolbar(self): return self.toolbars["gcpdisp"] def _setActiveMapWindow(self, mapWindow): - if not self.MapWindow == mapWindow: + if self.MapWindow != mapWindow: self.MapWindow = mapWindow self.Map = mapWindow.Map self.UpdateActive(mapWindow) diff --git a/gui/wxpython/photo2image/ip2i_statusbar.py b/gui/wxpython/photo2image/ip2i_statusbar.py index 336dcd6903f..75a39b8141e 100644 --- a/gui/wxpython/photo2image/ip2i_statusbar.py +++ b/gui/wxpython/photo2image/ip2i_statusbar.py @@ -11,9 +11,6 @@ This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details. - -@author Vaclav Petras (statusbar refactoring) -@author Anna Kratochvilova (statusbar refactoring) """ import wx diff --git a/gui/wxpython/psmap/dialogs.py b/gui/wxpython/psmap/dialogs.py index 216782037be..66ac66d9348 100644 --- a/gui/wxpython/psmap/dialogs.py +++ b/gui/wxpython/psmap/dialogs.py @@ -37,6 +37,8 @@ import os import string from copy import deepcopy +from operator import itemgetter +from pathlib import Path import wx import wx.lib.agw.floatspin as fs @@ -524,8 +526,7 @@ def OnApply(self, event): if ok: self.parent.DialogDataChanged(id=self.id) return True - else: - return False + return False def OnOK(self, event): """Apply changes, close dialog""" @@ -3622,9 +3623,7 @@ def _vectorLegend(self, notebook): self.vectorListCtrl.InsertColumn(0, _("Vector map")) self.vectorListCtrl.InsertColumn(1, _("Label")) if self.vectorId: - vectors = sorted( - self.instruction[self.vectorId]["list"], key=lambda x: x[3] - ) + vectors = sorted(self.instruction[self.vectorId]["list"], key=itemgetter(3)) for vector in vectors: index = self.vectorListCtrl.InsertItem( @@ -4455,7 +4454,7 @@ def updateDialog(self): if self.instruction.FindInstructionByType("vector"): vectors = sorted( self.instruction.FindInstructionByType("vector")["list"], - key=lambda x: x[3], + key=itemgetter(3), ) self.vectorListCtrl.DeleteAllItems() for vector in vectors: @@ -5965,7 +5964,7 @@ def OnPositionType(self, event): def _getImageDirectory(self): """Default image directory""" - return os.getcwd() + return str(Path.cwd()) def _addConvergence(self, panel, gridBagSizer): pass diff --git a/gui/wxpython/psmap/frame.py b/gui/wxpython/psmap/frame.py index 3effc33cd4d..b3196d348fa 100644 --- a/gui/wxpython/psmap/frame.py +++ b/gui/wxpython/psmap/frame.py @@ -308,7 +308,7 @@ def OnPsMapDialog(self, event): def OnPDFFile(self, event): """Generate PDF from PS with ps2pdf if available""" - if not sys.platform == "win32": + if sys.platform != "win32": try: p = gs.Popen(["ps2pdf"], stderr=gs.PIPE) p.stderr.close() @@ -994,8 +994,7 @@ def getModifiedTextBounds(self, x, y, textExtent, rotation): Y = y - H if rotation == 0: return Rect(x, y, *textExtent) - else: - return Rect(X, Y, abs(W), abs(H)).Inflate(h, h) + return Rect(X, Y, abs(W), abs(H)).Inflate(h, h) def makePSFont(self, textDict): """creates a wx.Font object from selected postscript font. To be diff --git a/gui/wxpython/psmap/instructions.py b/gui/wxpython/psmap/instructions.py index 2ae68a91069..9db64679422 100644 --- a/gui/wxpython/psmap/instructions.py +++ b/gui/wxpython/psmap/instructions.py @@ -86,10 +86,7 @@ def __getitem__(self, id): def __contains__(self, id): """Test if instruction is included""" - for each in self.instruction: - if each.id == id: - return True - return False + return any(each.id == id for each in self.instruction) def __delitem__(self, id): """Delete instruction""" @@ -1211,7 +1208,7 @@ def GetImageOrigSize(self, imagePath): # if eps, read info from header if os.path.splitext(fileName)[1].lower() == ".eps": bbInfo = "%%BoundingBox" - file = open(imagePath, "r") + file = open(imagePath) w = h = 0 while file: line = file.readline() @@ -1220,9 +1217,9 @@ def GetImageOrigSize(self, imagePath): break file.close() return float(w), float(h) - else: # we can use wx.Image - img = wx.Image(fileName, type=wx.BITMAP_TYPE_ANY) - return img.GetWidth(), img.GetHeight() + # we can use wx.Image + img = wx.Image(fileName, type=wx.BITMAP_TYPE_ANY) + return img.GetWidth(), img.GetHeight() class NorthArrow(Image): @@ -1936,11 +1933,7 @@ def Read(self, instruction, text, **kwargs): instr = {} for line in text: - if ( - line.startswith("vpoints") - or line.startswith("vlines") - or line.startswith("vareas") - ): + if line.startswith(("vpoints", "vlines", "vareas")): # subtype if line.startswith("vpoints"): subType = "points" diff --git a/gui/wxpython/psmap/utils.py b/gui/wxpython/psmap/utils.py index d54a45a52be..6bb53acd9f0 100644 --- a/gui/wxpython/psmap/utils.py +++ b/gui/wxpython/psmap/utils.py @@ -162,17 +162,15 @@ def convertRGB(rgb): return name return str(rgb.Red()) + ":" + str(rgb.Green()) + ":" + str(rgb.Blue()) # transform a GRASS named color or an r:g:b string into a wx.Colour tuple - else: - color = ( - int(gs.parse_color(rgb)[0] * 255), - int(gs.parse_color(rgb)[1] * 255), - int(gs.parse_color(rgb)[2] * 255), - ) - color = wx.Colour(*color) - if color.IsOk(): - return color - else: - return None + color = ( + int(gs.parse_color(rgb)[0] * 255), + int(gs.parse_color(rgb)[1] * 255), + int(gs.parse_color(rgb)[2] * 255), + ) + color = wx.Colour(*color) + if color.IsOk(): + return color + return None def PaperMapCoordinates(mapInstr, x, y, paperToMap=True, env=None): @@ -198,18 +196,16 @@ def PaperMapCoordinates(mapInstr, x, y, paperToMap=True, env=None): if projInfo()["proj"] == "ll": return e, n - else: - return int(e), int(n) + return int(e), int(n) - else: - diffEW = x - region["w"] - diffNS = region["n"] - y - diffX = mapWidthPaper * diffEW / mapWidthEN - diffY = mapHeightPaper * diffNS / mapHeightEN - xPaper = mapInstr["rect"].GetX() + diffX - yPaper = mapInstr["rect"].GetY() + diffY + diffEW = x - region["w"] + diffNS = region["n"] - y + diffX = mapWidthPaper * diffEW / mapWidthEN + diffY = mapHeightPaper * diffNS / mapHeightEN + xPaper = mapInstr["rect"].GetX() + diffX + yPaper = mapInstr["rect"].GetY() + diffY - return xPaper, yPaper + return xPaper, yPaper def AutoAdjust(self, scaleType, rect, env, map=None, mapType=None, region=None): @@ -403,8 +399,7 @@ def getRasterType(map): file = gs.find_file(name=map, element="cell") if file.get("file"): return gs.raster_info(map)["datatype"] - else: - return None + return None def BBoxAfterRotation(w, h, angle): diff --git a/gui/wxpython/rdigit/controller.py b/gui/wxpython/rdigit/controller.py index 2e98ca32ccc..8018ee04e5c 100644 --- a/gui/wxpython/rdigit/controller.py +++ b/gui/wxpython/rdigit/controller.py @@ -421,28 +421,26 @@ def SelectNewMap( ) return False return True - else: - dlg = NewRasterDialog(parent=self._mapWindow) - dlg.CenterOnParent() - if dlg.ShowModal() == wx.ID_OK: - try: - self._createNewMap( - mapName=dlg.GetMapName(), - backgroundMap=dlg.GetBackgroundMapName(), - mapType=dlg.GetMapType(), - ) - except ScriptError: - GError( - parent=self._mapWindow, - message=_("Failed to create new raster map."), - ) - return False - finally: - dlg.Destroy() - return True - else: - dlg.Destroy() + dlg = NewRasterDialog(parent=self._mapWindow) + dlg.CenterOnParent() + if dlg.ShowModal() == wx.ID_OK: + try: + self._createNewMap( + mapName=dlg.GetMapName(), + backgroundMap=dlg.GetBackgroundMapName(), + mapType=dlg.GetMapType(), + ) + except ScriptError: + GError( + parent=self._mapWindow, + message=_("Failed to create new raster map."), + ) return False + finally: + dlg.Destroy() + return True + dlg.Destroy() + return False def _createNewMap(self, mapName, backgroundMap, mapType): """Creates a new raster map based on specified background and type.""" diff --git a/gui/wxpython/rdigit/dialogs.py b/gui/wxpython/rdigit/dialogs.py index 650b75feb63..fa9f57b8253 100644 --- a/gui/wxpython/rdigit/dialogs.py +++ b/gui/wxpython/rdigit/dialogs.py @@ -114,12 +114,11 @@ def OnOK(self, event): caption=_("Overwrite?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION, ) - if not dlgOverwrite.ShowModal() == wx.ID_YES: + if dlgOverwrite.ShowModal() != wx.ID_YES: dlgOverwrite.Destroy() return - else: - dlgOverwrite.Destroy() - self.EndModal(wx.ID_OK) + dlgOverwrite.Destroy() + self.EndModal(wx.ID_OK) else: self.EndModal(wx.ID_OK) diff --git a/gui/wxpython/rdigit/g.gui.rdigit.py b/gui/wxpython/rdigit/g.gui.rdigit.py index d740b1c3e78..ae8d9ed41d8 100755 --- a/gui/wxpython/rdigit/g.gui.rdigit.py +++ b/gui/wxpython/rdigit/g.gui.rdigit.py @@ -193,10 +193,8 @@ def OnMapCreated(self, name, ltype, add: bool | None = None): if not edit_map: gs.fatal( - _( - "Raster map <{}> not found in current mapset.".format( - options["edit"], - ), + _("Raster map <{}> not found in current mapset.").format( + options["edit"], ), ) else: @@ -209,11 +207,8 @@ def OnMapCreated(self, name, ltype, add: bool | None = None): )["fullname"] if not base_map: gs.fatal( - _( - "Base raster map <{}> not found in " - "current mapset.".format( - options["base"], - ), + _("Base raster map <{}> not found in current mapset.").format( + options["base"], ), ) kwargs["base_map"] = base_map diff --git a/gui/wxpython/rlisetup/frame.py b/gui/wxpython/rlisetup/frame.py index 00e35f66110..3905fa9b09d 100644 --- a/gui/wxpython/rlisetup/frame.py +++ b/gui/wxpython/rlisetup/frame.py @@ -40,9 +40,8 @@ def __init__( self.confilesBox = StaticBox( parent=self.panel, id=wx.ID_ANY, - label=_( - "View and modify the " - "configuration file '{name}'".format(name=self.confile) + label=_("View and modify the configuration file '{name}'").format( + name=self.confile ), ) self.textCtrl = TextCtrl( diff --git a/gui/wxpython/rlisetup/functions.py b/gui/wxpython/rlisetup/functions.py index 28f186fa396..fc9d3c3d202 100644 --- a/gui/wxpython/rlisetup/functions.py +++ b/gui/wxpython/rlisetup/functions.py @@ -60,9 +60,8 @@ def retRLiPath(): rlipath = os.path.join(grass_config_dir, "r.li") if os.path.exists(rlipath): return rlipath - else: - os.mkdir(rlipath) - return rlipath + os.mkdir(rlipath) + return rlipath def checkMapExists(name, typ="raster") -> bool: @@ -153,8 +152,9 @@ def sampleAreaVector( "The raster map <%s> already exists." " Please remove or rename the maps " "with the prefix '%s' or select the " - "option to overwrite existing maps" % (rast_name, outpref) + "option to overwrite existing maps" ) + % (rast_name, outpref) ) return None convertFeature(vect, rast_name, cat, rast, layer, overwrite) diff --git a/gui/wxpython/rlisetup/sampling_frame.py b/gui/wxpython/rlisetup/sampling_frame.py index 860c0b91d8f..a379ef8c09c 100644 --- a/gui/wxpython/rlisetup/sampling_frame.py +++ b/gui/wxpython/rlisetup/sampling_frame.py @@ -550,33 +550,32 @@ def _toolbarData(self): ), ) ) - else: - return self._getToolbarData( + return self._getToolbarData( + ( + drawTool, + (None,), ( - drawTool, - (None,), - ( - ("pan", BaseIcons["pan"].label), - BaseIcons["pan"], - self.parent.OnPan, - wx.ITEM_CHECK, - ), - ( - ("zoomIn", BaseIcons["zoomIn"].label), - BaseIcons["zoomIn"], - self.parent.OnZoomIn, - wx.ITEM_CHECK, - ), - ( - ("zoomOut", BaseIcons["zoomOut"].label), - BaseIcons["zoomOut"], - self.parent.OnZoomOut, - wx.ITEM_CHECK, - ), - ( - ("zoomExtent", BaseIcons["zoomExtent"].label), - BaseIcons["zoomExtent"], - self.parent.OnZoomToMap, - ), - ) + ("pan", BaseIcons["pan"].label), + BaseIcons["pan"], + self.parent.OnPan, + wx.ITEM_CHECK, + ), + ( + ("zoomIn", BaseIcons["zoomIn"].label), + BaseIcons["zoomIn"], + self.parent.OnZoomIn, + wx.ITEM_CHECK, + ), + ( + ("zoomOut", BaseIcons["zoomOut"].label), + BaseIcons["zoomOut"], + self.parent.OnZoomOut, + wx.ITEM_CHECK, + ), + ( + ("zoomExtent", BaseIcons["zoomExtent"].label), + BaseIcons["zoomExtent"], + self.parent.OnZoomToMap, + ), ) + ) diff --git a/gui/wxpython/rlisetup/wizard.py b/gui/wxpython/rlisetup/wizard.py index 54c6dbcd78a..6fb7988159d 100644 --- a/gui/wxpython/rlisetup/wizard.py +++ b/gui/wxpython/rlisetup/wizard.py @@ -720,13 +720,12 @@ def CheckVector(self, vector): % vector ) return False, [] - elif links > 0: + if links > 0: layers = [] for i in range(1, links + 1): layers.append(str(i)) return True, layers - else: - return False, [] + return False, [] def CheckInput(self): """Check input fields. @@ -1819,14 +1818,13 @@ def afterRegionDrawn(self): self.areaOK.Enable(False) self.areaNO.Enable(False) return True - else: - self.title.SetLabel( - _("Select sample area {areas_count} of {area_num}").format( - areas_count=self.areascount + 1, area_num=self.areanum - ) + self.title.SetLabel( + _("Select sample area {areas_count} of {area_num}").format( + areas_count=self.areascount + 1, area_num=self.areanum ) - wx.FindWindowById(wx.ID_FORWARD).Enable(False) - return False + ) + wx.FindWindowById(wx.ID_FORWARD).Enable(False) + return False def OnYes(self, event): """Function to create the string for the conf file if the area @@ -1859,8 +1857,8 @@ def newCat(self): "The raster map <%s> already exists." " Please remove or rename the maps " "with the prefix '%s' or select the " - "option to overwrite existing maps" % (self.outname, self.outpref) - ), + "option to overwrite existing maps" + ).format(self.outname, self.outpref), ) self.parent.wizard.ShowPage(self.parent.samplingareapage) return diff --git a/gui/wxpython/startup/locdownload.py b/gui/wxpython/startup/locdownload.py index f0a1ab13fd2..ccbeaa8fb0c 100644 --- a/gui/wxpython/startup/locdownload.py +++ b/gui/wxpython/startup/locdownload.py @@ -156,12 +156,12 @@ def reporthook(count, block_size, total_size): sys.stdout.write( _( "Download in progress, wait until it is finished " - "{0}%, {1} MB, {2} KB/s, {3:.0f} seconds passed".format( - percent, - progress_size / (1024 * 1024), - speed, - duration, - ), + "{0}%, {1} MB, {2} KB/s, {3:.0f} seconds passed" + ).format( + percent, + progress_size / (1024 * 1024), + speed, + duration, ), ) @@ -386,8 +386,7 @@ def CheckItem(self, item): ) self.parent.download_button.SetLabel(label=_("Download")) return - else: - self._clearMessage() + self._clearMessage() def GetLocation(self): """Get the name of the last location downloaded by the user""" @@ -496,9 +495,8 @@ def OnCancel(self, event=None): if ret == wx.ID_NO: return - else: - self.panel.thread.Terminate() - self.panel._change_download_btn_label() + self.panel.thread.Terminate() + self.panel._change_download_btn_label() if event: self.EndModal(wx.ID_CANCEL) diff --git a/gui/wxpython/timeline/frame.py b/gui/wxpython/timeline/frame.py index f69dcc89aef..7ca51cd8989 100644 --- a/gui/wxpython/timeline/frame.py +++ b/gui/wxpython/timeline/frame.py @@ -22,6 +22,7 @@ import wx from functools import reduce +from operator import add try: import matplotlib as mpl @@ -495,16 +496,11 @@ def _checkDatasets(self, datasets): ] # flatten this list if allDatasets: - allDatasets = reduce( - lambda x, y: x + y, reduce(lambda x, y: x + y, allDatasets) - ) + allDatasets = reduce(add, reduce(add, allDatasets)) mapsets = tgis.get_tgis_c_library_interface().available_mapsets() - allDatasets = [ - i - for i in sorted( - allDatasets, key=lambda dataset_info: mapsets.index(dataset_info[1]) - ) - ] + allDatasets = sorted( + allDatasets, key=lambda dataset_info: mapsets.index(dataset_info[1]) + ) for dataset in datasets: errorMsg = _("Space time dataset <%s> not found.") % dataset @@ -527,7 +523,7 @@ def _checkDatasets(self, datasets): elif len(indices) >= 2: dlg = wx.SingleChoiceDialog( self, - message=_("Please specify the space time dataset <%s>." % dataset), + message=_("Please specify the space time dataset <%s>.") % dataset, caption=_("Ambiguous dataset name"), choices=[ ( diff --git a/gui/wxpython/tplot/frame.py b/gui/wxpython/tplot/frame.py index 62147f54ad6..f52c5a4d190 100755 --- a/gui/wxpython/tplot/frame.py +++ b/gui/wxpython/tplot/frame.py @@ -20,6 +20,7 @@ """ import os from itertools import cycle +from pathlib import Path import numpy as np import wx @@ -68,6 +69,7 @@ from gui_core.widgets import GNotebook from gui_core.wrap import CheckBox, TextCtrl, Button, StaticText +from operator import add ALPHA = 0.5 COLORS = ["b", "g", "r", "c", "m", "y", "k"] @@ -371,7 +373,7 @@ def _layout(self): labelText="", dialogTitle=_("CVS path"), buttonText=_("Browse"), - startDirectory=os.getcwd(), + startDirectory=str(Path.cwd()), fileMode=wx.FD_SAVE, ) self.headerLabel = StaticText( @@ -669,8 +671,8 @@ def _getSTVDData(self, timeseries): showTraceback=False, message=_( "No connection between vector map {vmap} " - "and layer {la}".format(vmap=row["name"], la=lay) - ), + "and layer {la}" + ).format(vmap=row["name"], la=lay), ) return vals = gs.vector_db_select( @@ -740,7 +742,7 @@ def _setLabels(self, x): if self.drawX != "": self.axes2d.set_xlabel(self.drawX) elif self.temporalType == "absolute": - self.axes2d.set_xlabel(_("Temporal resolution: %s" % x)) + self.axes2d.set_xlabel(_("Temporal resolution: %s") % x) else: self.axes2d.set_xlabel(_("Time [%s]") % self.unit) if self.drawY != "": @@ -917,8 +919,8 @@ def drawVCats(self): message=_( "Problem getting data from vector temporal" " dataset. Empty list of values for cat " - "{ca}.".format(ca=name_cat[1].replace("cat", "")) - ), + "{ca}." + ).format(ca=name_cat[1].replace("cat", "")), ) continue self.lookUp.AddDataset(yranges=ydata, xranges=xdata, datasetName=name) @@ -1007,9 +1009,8 @@ def OnRedraw(self, event=None): if os.path.exists(self.csvpath) and not self.overwrite: dlg = wx.MessageDialog( self, - _( - "{pa} already exists, do you want " - "to overwrite?".format(pa=self.csvpath) + _("{pa} already exists, do you want to overwrite?").format( + pa=self.csvpath ), _("File exists"), wx.OK | wx.CANCEL | wx.ICON_QUESTION, @@ -1153,16 +1154,11 @@ def _checkDatasets(self, datasets, typ): ] # flatten this list if allDatasets: - allDatasets = reduce( - lambda x, y: x + y, reduce(lambda x, y: x + y, allDatasets) - ) + allDatasets = reduce(add, reduce(add, allDatasets)) mapsets = tgis.get_tgis_c_library_interface().available_mapsets() - allDatasets = [ - i - for i in sorted( - allDatasets, key=lambda dataset_info: mapsets.index(dataset_info[1]) - ) - ] + allDatasets = sorted( + allDatasets, key=lambda dataset_info: mapsets.index(dataset_info[1]) + ) for dataset in datasets: errorMsg = _("Space time dataset <%s> not found.") % dataset @@ -1185,7 +1181,7 @@ def _checkDatasets(self, datasets, typ): elif len(indices) >= 2: dlg = wx.SingleChoiceDialog( self, - message=_("Please specify the space time dataset <%s>." % dataset), + message=_("Please specify the space time dataset <%s>.") % dataset, caption=_("Ambiguous dataset name"), choices=[ ( @@ -1368,7 +1364,7 @@ def InfoFormat(timeData, values): text.append(_("Space time 3D raster dataset: %s") % key) text.extend( - (_("Value for {date} is {val}".format(date=val[0], val=val[1])), "\n") + (_("Value for {date} is {val}").format(date=val[0], val=val[1]), "\n") ) text.append(_("Press Del to dismiss.")) diff --git a/gui/wxpython/vdigit/wxdigit.py b/gui/wxpython/vdigit/wxdigit.py index ddcdc5a2755..eda912284a0 100644 --- a/gui/wxpython/vdigit/wxdigit.py +++ b/gui/wxpython/vdigit/wxdigit.py @@ -294,10 +294,8 @@ def _getSnapMode(self): if threshold > 0.0: if UserSettings.Get(group="vdigit", key="snapToVertex", subkey="enabled"): return SNAPVERTEX - else: - return SNAP - else: - return NO_SNAP + return SNAP + return NO_SNAP def _getNewFeaturesLayer(self): """Returns layer of new feature (from settings)""" @@ -672,8 +670,7 @@ def _getLineAreaBboxCats(self, ln_id): # TODO centroid opttimization, can be edited also its area -> it # will appear two times in new_ lists return self._getCentroidAreaBboxCats(ln_id) - else: - return [self._getBbox(ln_id)], [self._getLineAreasCategories(ln_id)] + return [self._getBbox(ln_id)], [self._getLineAreasCategories(ln_id)] def _getCentroidAreaBboxCats(self, centroid): """Helper function @@ -688,8 +685,7 @@ def _getCentroidAreaBboxCats(self, centroid): area = Vect_get_centroid_area(self.poMapInfo, centroid) if area > 0: return self._getaAreaBboxCats(area) - else: - return None + return None def _getaAreaBboxCats(self, area): """Helper function @@ -1084,7 +1080,7 @@ def EditLine(self, line, coords): # apply snapping (node or vertex) snap = self._getSnapMode() if snap != NO_SNAP: - modeSnap = not (snap == SNAP) + modeSnap = snap != SNAP Vedit_snap_line( self.poMapInfo, self.popoBgMapInfo, @@ -1889,7 +1885,7 @@ def _addFeature(self, ftype, coords, layer, cat, snap, threshold): if snap != NO_SNAP: # apply snapping (node or vertex) - modeSnap = not (snap == SNAP) + modeSnap = snap != SNAP Vedit_snap_line( self.poMapInfo, self.popoBgMapInfo, @@ -1946,8 +1942,7 @@ def _addFeature(self, ftype, coords, layer, cat, snap, threshold): if newc < 0: self._error.WriteLine() return (len(fids), fids) - else: - fids.append(newc) + fids.append(newc) if right > 0 and Vect_get_area_centroid(self.poMapInfo, right) == 0: # if Vect_get_area_points(byref(self.poMapInfo), right, bpoints) > 0 and @@ -1964,8 +1959,7 @@ def _addFeature(self, ftype, coords, layer, cat, snap, threshold): if newc < 0: self._error.WriteLine() return len(fids, fids) - else: - fids.append(newc) + fids.append(newc) Vect_destroy_line_struct(bpoints) diff --git a/gui/wxpython/vdigit/wxdisplay.py b/gui/wxpython/vdigit/wxdisplay.py index b747f3fa44f..d8e4d0a14bf 100644 --- a/gui/wxpython/vdigit/wxdisplay.py +++ b/gui/wxpython/vdigit/wxdisplay.py @@ -824,7 +824,7 @@ def SetSelected(self, ids, layer=-1): found = False cats = self.poCats.contents - for i in range(0, cats.n_cats): + for i in range(cats.n_cats): for cat in self.selected["cats"]: if cats.cat[i] == cat: found = True @@ -868,10 +868,7 @@ def GetSelectedVertex(self, pos): pos[0], pos[1], 0.0, points.x[idx], points.y[idx], points.z[idx], 0 ) - if idx == 0: - minDist = dist - Gid = idx - elif minDist > dist: + if idx == 0 or minDist > dist: minDist = dist Gid = idx diff --git a/gui/wxpython/vnet/dialogs.py b/gui/wxpython/vnet/dialogs.py index 3d829ffd7be..39cf2e4ae84 100644 --- a/gui/wxpython/vnet/dialogs.py +++ b/gui/wxpython/vnet/dialogs.py @@ -766,7 +766,7 @@ def OnVectSel(self, event): for sel in ["arc_column", "arc_backward_column", "node_column"]: self.inputData[sel].SetValue("") return - elif itemsLen == 1: + if itemsLen == 1: self.inputData["arc_layer"].SetSelection(0) self.inputData["node_layer"].SetSelection(0) elif itemsLen >= 1: @@ -1648,7 +1648,7 @@ def InputSel(self): self._updateInputDbMgrPage(show=False) self.inputData["arc_layer"].SetValue("") return - elif itemsLen == 1: + if itemsLen == 1: self.inputData["arc_layer"].SetSelection(0) elif itemsLen >= 1: if "1" in items: @@ -1952,9 +1952,7 @@ def SetVirtualData(self, row, column, text): text = DegreesToRadians(text) # Tested allowed range of values - if text > math.pi: - text = 0.0 - elif text < -math.pi: + if text > math.pi or text < -math.pi: text = 0.0 self.data.SetValue(text, row, column) diff --git a/gui/wxpython/vnet/vnet_core.py b/gui/wxpython/vnet/vnet_core.py index 17d85ef6ca4..8dda73b6770 100644 --- a/gui/wxpython/vnet/vnet_core.py +++ b/gui/wxpython/vnet/vnet_core.py @@ -144,8 +144,7 @@ def RunAnalysis(self): ) if not ret: return -3 - else: - return 1 + return 1 def RunAnDone(self, cmd, returncode, results): self.results["analysis"] = cmd[0] @@ -307,19 +306,18 @@ def _createTtbDone(self, event): if event.returncode != 0: GMessage(parent=self.guiparent, message=_("Creation of turntable failed.")) return - else: - params = {} - for c in event.cmd: - spl_c = c.split("=") - if len(spl_c) != 2: - continue + params = {} + for c in event.cmd: + spl_c = c.split("=") + if len(spl_c) != 2: + continue - if spl_c[0] and spl_c != "input": - params[spl_c[0]] = spl_c[1] - if spl_c[0] == "output": - params["input"] = spl_c[1] + if spl_c[0] and spl_c != "input": + params[spl_c[0]] = spl_c[1] + if spl_c[0] == "output": + params["input"] = spl_c[1] - self.vnet_data.SetParams(params, {}) + self.vnet_data.SetParams(params, {}) self.ttbCreated.emit(returncode=event.returncode) @@ -828,9 +826,7 @@ def _prepareCmd(self, cmd): if c.find("=") == -1: continue v = c.split("=") - if len(v) != 2: - cmd.remove(c) - elif not v[1].strip(): + if len(v) != 2 or not v[1].strip(): cmd.remove(c) def _setCmdForSpecificAn(self, cmdParams): @@ -1149,14 +1145,10 @@ def ComputeNodes(self, activate): return 0 # map is already created and up to date for input data - else: - self.snapPts.AddRenderLayer() - - self.giface.updateMap.emit(render=True, renderVector=True) - - self.snapping.emit(evt="computing_points_done") - - return 1 + self.snapPts.AddRenderLayer() + self.giface.updateMap.emit(render=True, renderVector=True) + self.snapping.emit(evt="computing_points_done") + return 1 def _onNodesDone(self, event): """Update map window, when map with nodes to snap is created""" diff --git a/gui/wxpython/vnet/vnet_data.py b/gui/wxpython/vnet/vnet_data.py index a1332398a1e..3adc5fa64e9 100644 --- a/gui/wxpython/vnet/vnet_data.py +++ b/gui/wxpython/vnet/vnet_data.py @@ -78,16 +78,14 @@ def GetGlobalTurnsData(self): def GetRelevantParams(self, analysis=None): if analysis: return self.an_props.GetRelevantParams(analysis) - else: - analysis, valid = self.an_params.GetParam("analysis") - return self.an_props.GetRelevantParams(analysis) + analysis, valid = self.an_params.GetParam("analysis") + return self.an_props.GetRelevantParams(analysis) def GetAnalysisProperties(self, analysis=None): if analysis: return self.an_props[analysis] - else: - analysis, valid = self.an_params.GetParam("analysis") - return self.an_props[analysis] + analysis, valid = self.an_params.GetParam("analysis") + return self.an_props[analysis] def GetParam(self, param): return self.an_params.GetParam(param) @@ -154,7 +152,7 @@ def InputsErrorMsgs( if flags["t"] and "turn_layer" not in relevant_params: GMessage( parent=self.guiparent, - message=_("Module <%s> does not support turns costs." % analysis), + message=_("Module <%s> does not support turns costs.") % analysis, ) return False @@ -1070,7 +1068,7 @@ def GetLastModified(self): "head", ) try: - head = open(headPath, "r") + head = open(headPath) for line in head: i = line.find( "MAP DATE:", diff --git a/gui/wxpython/vnet/widgets.py b/gui/wxpython/vnet/widgets.py index 2690ba57ab4..ed1f2aa514c 100644 --- a/gui/wxpython/vnet/widgets.py +++ b/gui/wxpython/vnet/widgets.py @@ -133,7 +133,7 @@ def __init__( # initialize column sorter self.itemDataMap = [] ncols = self.GetColumnCount() - ColumnSorterMixin.__init__(self, ncols) + ColumnSorterMixin.__init__(self, ncols) # noqa: PLC2801, C2801 # init to ascending sort on first click self._colSortFlag = [1] * ncols @@ -542,7 +542,7 @@ def IsShown(self, colName) -> bool: :return: False - if is not shown """ - return not self._getColumnNum(colName) == -1 + return self._getColumnNum(colName) != -1 class EditItem(wx.Dialog): diff --git a/gui/wxpython/web_services/cap_interface.py b/gui/wxpython/web_services/cap_interface.py index 4287375dd47..38cc7c3c72f 100644 --- a/gui/wxpython/web_services/cap_interface.py +++ b/gui/wxpython/web_services/cap_interface.py @@ -49,8 +49,7 @@ def GetRootLayer(self): """Get children layers""" if self.layers_by_id: return self.layers_by_id[0] - else: - return None + return None class LayerBase: @@ -137,15 +136,13 @@ def GetLayerData(self, param): title_node = self.layer_node.find(title) if title_node is not None: return title_node.text - else: - return None + return None if param == "name": name_node = self.layer_node.find(name) if name_node is not None: return name_node.text - else: - return None + return None if param == "format": return self.cap.GetFormats() @@ -228,22 +225,20 @@ def GetLayerData(self, param): if self.layer_node is None and param in {"title", "name"}: return None - elif self.layer_node is None: + if self.layer_node is None: return [] if param == "title": title_node = self.layer_node.find(title) if title_node is not None: return title_node.text - else: - return None + return None if param == "name": name_node = self.layer_node.find(name) if name_node is not None: return name_node.text - else: - return None + return None if param == "styles": styles = [] @@ -366,22 +361,20 @@ def GetLayerData(self, param): """Get layer data""" if self.layer_node is None and param in {"title", "name"}: return None - elif self.layer_node is None: + if self.layer_node is None: return [] if param == "title": title_node = self.layer_node.find("Title") if title_node is not None: return title_node.text - else: - return None + return None if param == "name": name_node = self.layer_node.find("Name") if name_node is not None: return name_node.text - else: - return None + return None if param == "styles": return [] diff --git a/gui/wxpython/web_services/dialogs.py b/gui/wxpython/web_services/dialogs.py index d67a2b34f7d..e47400cae70 100644 --- a/gui/wxpython/web_services/dialogs.py +++ b/gui/wxpython/web_services/dialogs.py @@ -331,7 +331,6 @@ def OnSettingsChanged(self, data): def OnClose(self, event): """Close the dialog""" - """Close dialog""" if not self.IsModal(): self.Destroy() event.Skip() @@ -378,7 +377,7 @@ def OnConnect(self, event): self.Fit() self.statusbar.SetStatusText( - _("Connecting to <%s>..." % self.server.GetValue().strip()) + _("Connecting to <$s>...") % self.server.GetValue().strip() ) # number of panels already connected @@ -464,14 +463,14 @@ def UpdateDialogAfterConnection(self): ) self._showWsPanel(self.web_service_sel[self.choose_ws_rb.GetSelection()]) self.statusbar.SetStatusText( - _("Connected to <%s>" % self.server.GetValue().strip()) + _("Connected to <%s>") % self.server.GetValue().strip() ) for btn in self.run_btns: btn.Enable(True) # no web service found on server else: self.statusbar.SetStatusText( - _("Unable to connect to <%s>" % self.server.GetValue().strip()) + _("Unable to connect to <%s>") % self.server.GetValue().strip() ) for btn in self.run_btns: btn.Enable(False) @@ -1029,7 +1028,7 @@ def OnSave(self, event): not self.overwrite.IsChecked() and gs.find_file(self.output, "cell", ".")["fullname"] ): - msg = _("Output map <%s> already exists" % self.output) + msg = _("Output map <%s> already exists") % self.output if msg: GMessage(parent=self, message=msg) @@ -1047,8 +1046,8 @@ def OnSave(self, event): if self.region_types["named"].GetValue(): if not gs.find_file(reg_spl[0], "windows", reg_mapset)["fullname"]: - msg = _( - "Region <%s> does not exist." % self.params["region"].GetValue() + msg = ( + _("Region <%s> does not exist.") % self.params["region"].GetValue() ) GWarning(parent=self, message=msg) return diff --git a/gui/wxpython/web_services/widgets.py b/gui/wxpython/web_services/widgets.py index 83fe7a5706c..473a8fb58a2 100644 --- a/gui/wxpython/web_services/widgets.py +++ b/gui/wxpython/web_services/widgets.py @@ -538,10 +538,8 @@ def OnCapDownloadDone(self, event): if event.returncode != 0: if self.cmd_err_str: self.cmd_err_str = ( - _( - "Unable to download %s capabilities file\nfrom <%s>:\n" - % (self.ws.replace("_", " "), self.conn["url"]) - ) + _("Unable to download %s capabilities file\nfrom <%s>:\n") + % (self.ws.replace("_", " "), self.conn["url"]) + self.cmd_err_str ) self._postCapParsedEvt(error_msg=self.cmd_err_str) @@ -559,8 +557,9 @@ def _parseCapFile(self, cap_file): except (OSError, ParseError) as error: error_msg = _( "%s web service was not found in fetched capabilities file from " - "<%s>:\n%s\n" % (self.ws, self.conn["url"], str(error)) - ) + "<%s>:\n%s\n" + ) % (self.ws, self.conn["url"], str(error)) + if Debug.GetLevel() != 0: Debug.msg(1, error_msg) self._postCapParsedEvt(None) @@ -634,7 +633,7 @@ def UpdateWidgetsByCmd(self, cmd): # WMS standard - first layer in params is most bottom... # therefore layers order need to be reversed - l_st_list = [layer for layer in reversed(l_st_list)] + l_st_list.reverse() self.list.SelectLayers(l_st_list) params = {} diff --git a/gui/wxpython/wxgui.py b/gui/wxpython/wxgui.py index 201eb0fe738..447821c6724 100644 --- a/gui/wxpython/wxgui.py +++ b/gui/wxpython/wxgui.py @@ -100,10 +100,10 @@ def show_main_gui(): warning( _( "Current version of wxPython {} is lower than " - "minimum required version {}".format( - wx.__version__, - ".".join(map(str, min_required_wx_version)), - ) + "minimum required version {}" + ).format( + wx.__version__, + ".".join(map(str, min_required_wx_version)), ) ) else: diff --git a/gui/wxpython/wxplot/histogram.py b/gui/wxpython/wxplot/histogram.py index f8319747dab..ef252f0b052 100644 --- a/gui/wxpython/wxplot/histogram.py +++ b/gui/wxpython/wxplot/histogram.py @@ -243,8 +243,7 @@ def CreatePlotList(self): if len(self.plotlist) > 0: return self.plotlist - else: - return None + return None def Update(self): """Update histogram after changing options""" diff --git a/gui/wxpython/wxplot/profile.py b/gui/wxpython/wxplot/profile.py index 1d3de6681af..240290e5b7b 100644 --- a/gui/wxpython/wxplot/profile.py +++ b/gui/wxpython/wxplot/profile.py @@ -20,6 +20,8 @@ import math import numpy as np +from pathlib import Path + import wx from wx.lib import plot @@ -396,8 +398,7 @@ def CreatePlotList(self): if len(self.plotlist) > 0: return self.plotlist - else: - return None + return None def Update(self): """Update profile after changing options""" @@ -410,7 +411,7 @@ def SaveProfileToFile(self, event): dlg = wx.FileDialog( parent=self, message=_("Choose prefix for file(s) where to save profile values..."), - defaultDir=os.getcwd(), + defaultDir=str(Path.cwd()), wildcard=_("Comma separated value (*.csv)|*.csv"), style=wx.FD_SAVE, ) diff --git a/imagery/i.atcorr/create_iwave.py b/imagery/i.atcorr/create_iwave.py index 8afc6bebd36..21faa21ac2c 100644 --- a/imagery/i.atcorr/create_iwave.py +++ b/imagery/i.atcorr/create_iwave.py @@ -59,7 +59,7 @@ def read_input(csvfile): first column is wavelength values are those of the discrete band filter functions """ - infile = open(csvfile, "r") + infile = open(csvfile) # get number of bands and band names bands = infile.readline().split(",") @@ -235,7 +235,7 @@ def write_cpp(bands, values, sensor, folder): while c < len(fi) - 1 and fi[c + 1] > rthresh: c += 1 max_wavelength = np.floor(li[0] * 1000 + (2.5 * c)) - print(" %s (%inm - %inm)" % (bands[b], min_wavelength, max_wavelength)) + print(" %s (%inm - %inm)" % (bands[0], min_wavelength, max_wavelength)) else: filter_f = [] diff --git a/imagery/i.atcorr/i.atcorr.html b/imagery/i.atcorr/i.atcorr.html index 7808705d440..779ca7c7ef7 100644 --- a/imagery/i.atcorr/i.atcorr.html +++ b/imagery/i.atcorr/i.atcorr.html @@ -4,7 +4,7 @@

    DESCRIPTION

    map using the 6S algorithm (Second Simulation of Satellite Signal in the Solar Spectrum). A detailed algorithm description is available at the -Land Surface +Land Surface Reflectance Science Computing Facility website.

    Important: Current region settings are ignored! The @@ -507,6 +507,16 @@

    F. Sensor band

    Define your own spectral conditions: +Note that "wlinf" and "wlsup" refer to the limits of the wavelength range +defined by the user for a given simulation. Specifically: + +

      +
    • wlinf: This represents the lower wavelength limit (or minimum wavelength) + of the spectral band for which the simulation is being performed.
    • +
    • wlsup: This represents the upper wavelength limit (or maximum wavelength) + of the spectral band for the simulation.
    • +
    + @@ -786,13 +796,13 @@

    F. Sensor band

    - - + + - + diff --git a/imagery/i.fft/main.c b/imagery/i.fft/main.c index ad9a87a7890..051428b77ef 100644 --- a/imagery/i.fft/main.c +++ b/imagery/i.fft/main.c @@ -105,8 +105,9 @@ int main(int argc, char *argv[]) inputfd = Rast_open_old(Cellmap_orig, ""); if (Rast_maskfd() >= 0) - G_warning(_("Raster MASK found, consider to remove " - "(see man-page). Will continue...")); + G_warning(_("Raster mask active, consider removing it" + " and running again without it (see documentation for" + " details). This current process will now continue...")); G_get_set_window(&window); /* get the current window for later */ diff --git a/imagery/i.gensig/testsuite/test_i_gensig.py b/imagery/i.gensig/testsuite/test_i_gensig.py index 0498cabaf79..d75e3da2af4 100644 --- a/imagery/i.gensig/testsuite/test_i_gensig.py +++ b/imagery/i.gensig/testsuite/test_i_gensig.py @@ -13,6 +13,7 @@ import stat import ctypes import shutil +from pathlib import Path from grass.pygrass import utils from grass.pygrass.gis import Mapset @@ -107,7 +108,7 @@ def test_creation(self): ) # File must be present - sig_stat = os.stat(f"{self.sig_dir1}/sig") + sig_stat = Path(self.sig_dir1, "sig").stat() self.assertTrue(stat.S_ISREG(sig_stat.st_mode)) # Compare values within sig file diff --git a/imagery/i.maxlik/testsuite/test_i_maxlik.py b/imagery/i.maxlik/testsuite/test_i_maxlik.py index 1f6829e92b4..e7fbf6c1a79 100644 --- a/imagery/i.maxlik/testsuite/test_i_maxlik.py +++ b/imagery/i.maxlik/testsuite/test_i_maxlik.py @@ -19,6 +19,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows from grass.lib.gis import G_mapset_path from grass.lib.raster import Rast_write_semantic_label @@ -172,6 +173,7 @@ def tearDownClass(cls): ) cls.runModule("g.remove", flags="f", type="group", name=cls.group, quiet=True) + @xfail_windows def test_v1(self): """Test v1 signature""" self.assertModule( @@ -193,6 +195,7 @@ def test_v1(self): self.assertEqual(res.get_cat(0)[1], 1) res.close() + @xfail_windows def test_v2(self): """Test v2 signature""" self.assertModule( diff --git a/imagery/i.ortho.photo/lib/find_init.c b/imagery/i.ortho.photo/lib/find_init.c index 906203a7f90..f8cea9b9387 100644 --- a/imagery/i.ortho.photo/lib/find_init.c +++ b/imagery/i.ortho.photo/lib/find_init.c @@ -4,15 +4,19 @@ * Find the a camera initial file in the current group (if it exists) **************************************************************/ #include +#include int I_find_initial(char *group) { - char *element; - - element = (char *)G_malloc(80 * sizeof(char)); + char element[GNAME_MAX + 6]; if (group == NULL || *group == 0) return 0; - sprintf(element, "group/%s", group); + + if (snprintf(element, GNAME_MAX, "group/%s", group) >= GNAME_MAX) { + G_warning(_("Group name <%s> is too long"), group); + return 0; + } + return G_find_file(element, "INIT_EXP", G_mapset()) != NULL; } diff --git a/imagery/i.pca/i.pca.html b/imagery/i.pca/i.pca.html index 17b3f5ed163..6fee184c618 100644 --- a/imagery/i.pca/i.pca.html +++ b/imagery/i.pca/i.pca.html @@ -11,7 +11,7 @@

    DESCRIPTION

    principal component with the highest importance.

    -The current geographic region definition and MASK settings are +The current geographic region definition and raster mask settings are respected when reading the input raster map layers. When the rescale option is used, the output files are rescaled to fit the min,max range. diff --git a/imagery/i.pca/testsuite/test_pca.py b/imagery/i.pca/testsuite/test_pca.py index 8e9df84f2eb..f42fc6ddcc0 100644 --- a/imagery/i.pca/testsuite/test_pca.py +++ b/imagery/i.pca/testsuite/test_pca.py @@ -48,7 +48,7 @@ def test_pca_sample(self): cells=250325 datatype=CELL ncats=0 - comments=\"Eigen values, (vectors), and [percent importance]:PC1 4334.35 ( 0.2824, 0.3342, 0.5092,-0.0087, 0.5264, 0.5217) [83.04%]PC2 588.31 ( 0.2541, 0.1885, 0.2923,-0.7428,-0.5110,-0.0403) [11.27%]PC3 239.22 ( 0.3801, 0.3819, 0.2681, 0.6238,-0.4000,-0.2980) [ 4.58%]PC4 32.85 ( 0.1752,-0.0191,-0.4053, 0.1593,-0.4435, 0.7632) [ 0.63%]PC5 20.73 (-0.6170,-0.2514, 0.6059, 0.1734,-0.3235, 0.2330) [ 0.40%]PC6 4.08 (-0.5475, 0.8021,-0.2282,-0.0607,-0.0208, 0.0252) [ 0.08%]i.pca input=\"lsat7_2002_10,lsat7_2002_20,lsat7_2002_30,lsat7_2002_40\,lsat7_2002_50,lsat7_2002_70\" output=\"lsat7_2002_pca\" rescale=0,255 \percent=99" """ + comments=\"Eigen values, (vectors), and [percent importance]:PC1 4334.35 ( 0.2824, 0.3342, 0.5092,-0.0087, 0.5264, 0.5217) [83.04%]PC2 588.31 ( 0.2541, 0.1885, 0.2923,-0.7428,-0.5110,-0.0403) [11.27%]PC3 239.22 ( 0.3801, 0.3819, 0.2681, 0.6238,-0.4000,-0.2980) [ 4.58%]PC4 32.85 ( 0.1752,-0.0191,-0.4053, 0.1593,-0.4435, 0.7632) [ 0.63%]PC5 20.73 (-0.6170,-0.2514, 0.6059, 0.1734,-0.3235, 0.2330) [ 0.40%]PC6 4.08 (-0.5475, 0.8021,-0.2282,-0.0607,-0.0208, 0.0252) [ 0.08%]i.pca input=\"lsat7_2002_10,lsat7_2002_20,lsat7_2002_30,lsat7_2002_40\\,lsat7_2002_50,lsat7_2002_70\" output=\"lsat7_2002_pca\" rescale=0,255 \\percent=99" """ lsat7_2002_pca_univar_out = [ """n=250325 diff --git a/imagery/i.rectify/main.c b/imagery/i.rectify/main.c index 3bbe830e3cd..a740a07a0ae 100644 --- a/imagery/i.rectify/main.c +++ b/imagery/i.rectify/main.c @@ -26,6 +26,8 @@ #include #include "global.h" +#include + int seg_mb_img; func interpolate; @@ -151,8 +153,14 @@ int main(int argc, char *argv[]) interpolate = menu[method].method; G_strip(grp->answer); - strcpy(group.name, grp->answer); - strcpy(extension, ext->answer); + if (G_strlcpy(group.name, grp->answer, sizeof(group.name)) >= + sizeof(group.name)) { + G_fatal_error(_("Group name <%s> is too long"), grp->answer); + } + if (G_strlcpy(extension, ext->answer, sizeof(extension)) >= + sizeof(extension)) { + G_fatal_error(_("Extension <%s> is too long"), ext->answer); + } order = atoi(val->answer); seg_mb = NULL; diff --git a/imagery/i.segment/i.segment.html b/imagery/i.segment/i.segment.html index 1e2596c1d7e..e30f21d3743 100644 --- a/imagery/i.segment/i.segment.html +++ b/imagery/i.segment/i.segment.html @@ -118,7 +118,7 @@

    Mean shift

    Boundary Constraints

    Boundary constraints limit the adjacency of pixels and segments. Each unique value present in the bounds raster are -considered as a MASK. Thus no segments in the final segmentated map +considered as a mask. Thus, no segments in the final segmented map will cross a boundary, even if their spectral data is very similar.

    Minimum Segment Size

    diff --git a/imagery/i.segment/iseg.h b/imagery/i.segment/iseg.h index 1e301d2cefa..a8dfb5542c3 100644 --- a/imagery/i.segment/iseg.h +++ b/imagery/i.segment/iseg.h @@ -118,7 +118,7 @@ struct globals { /* processing flags */ FLAG *candidate_flag, - *null_flag; /*TODO, need some way to remember MASK/NULL values. Was + *null_flag; /*TODO, need some way to remember mask/NULL values. Was using -1, 0, 1 in int array. Better to use 2 FLAG structures, better readability? */ diff --git a/imagery/i.segment/mean_shift.c b/imagery/i.segment/mean_shift.c index 833ff5ca8a8..1d838335352 100644 --- a/imagery/i.segment/mean_shift.c +++ b/imagery/i.segment/mean_shift.c @@ -179,8 +179,9 @@ int mean_shift(struct globals *globals) hspec = globals->hr; if (hspec < 0 || hspec >= 1) { - hspec = sqrt(avgdiffavg / 10.0); - hspec = avgdiffavg; + // Other ideas how to compute this are: + // sqrt(avgdiffavg / 10.0) + // avgdiffavg (as is) hspec = mindiffzeroavg; if (do_progressive) diff --git a/include/Make/Platform.make.in b/include/Make/Platform.make.in index c65ed28c686..a66ddf801d3 100644 --- a/include/Make/Platform.make.in +++ b/include/Make/Platform.make.in @@ -203,12 +203,6 @@ PROJINC = @PROJINC@ PROJLIB = @PROJLIB@ PROJSHARE = @PROJSHARE@ -#OPENDWG: -OPENDWGINCPATH = @OPENDWGINCPATH@ -OPENDWGLIBPATH = @OPENDWGLIBPATH@ -OPENDWGLIB = @OPENDWGLIB@ -USE_OPENDWG = @USE_OPENDWG@ - #cairo CAIROINC = @CAIROINC@ CAIROLIB = @CAIROLIB@ diff --git a/include/grass/blas.h b/include/grass/blas.h deleted file mode 100644 index 2e7fe0a31f2..00000000000 --- a/include/grass/blas.h +++ /dev/null @@ -1,412 +0,0 @@ -#ifndef BLAS_WRAP_H -#define BLAS_WRAP_H - -extern int caxpy_(integer *n, complex *ca, complex *cx, integer *incx, - complex *cy, integer *incy); -extern int ccopy_(integer *n, complex *cx, integer *incx, complex *cy, - integer *incy); -extern C_f cdotc_(complex *ret_val, integer *n, complex *cx, integer *incx, - complex *cy, integer *incy); -extern C_f cdotu_(complex *ret_val, integer *n, complex *cx, integer *incx, - complex *cy, integer *incy); -extern int cgbmv_(char *trans, integer *m, integer *n, integer *kl, integer *ku, - complex *alpha, complex *a, integer *lda, complex *x, - integer *incx, complex *beta, complex *y, integer *incy, - ftnlen trans_len); -extern int cgemm_(char *transa, char *transb, integer *m, integer *n, - integer *k, complex *alpha, complex *a, integer *lda, - complex *b, integer *ldb, complex *beta, complex *c__, - integer *ldc, ftnlen transa_len, ftnlen transb_len); -extern int cgemv_(char *trans, integer *m, integer *n, complex *alpha, - complex *a, integer *lda, complex *x, integer *incx, - complex *beta, complex *y, integer *incy, ftnlen trans_len); -extern int cgerc_(integer *m, integer *n, complex *alpha, complex *x, - integer *incx, complex *y, integer *incy, complex *a, - integer *lda); -extern int cgeru_(integer *m, integer *n, complex *alpha, complex *x, - integer *incx, complex *y, integer *incy, complex *a, - integer *lda); -extern int chbmv_(char *uplo, integer *n, integer *k, complex *alpha, - complex *a, integer *lda, complex *x, integer *incx, - complex *beta, complex *y, integer *incy, ftnlen uplo_len); -extern int chemm_(char *side, char *uplo, integer *m, integer *n, - complex *alpha, complex *a, integer *lda, complex *b, - integer *ldb, complex *beta, complex *c__, integer *ldc, - ftnlen side_len, ftnlen uplo_len); -extern int chemv_(char *uplo, integer *n, complex *alpha, complex *a, - integer *lda, complex *x, integer *incx, complex *beta, - complex *y, integer *incy, ftnlen uplo_len); -extern int cher_(char *uplo, integer *n, real *alpha, complex *x, integer *incx, - complex *a, integer *lda, ftnlen uplo_len); -extern int cher2_(char *uplo, integer *n, complex *alpha, complex *x, - integer *incx, complex *y, integer *incy, complex *a, - integer *lda, ftnlen uplo_len); -extern int cher2k_(char *uplo, char *trans, integer *n, integer *k, - complex *alpha, complex *a, integer *lda, complex *b, - integer *ldb, real *beta, complex *c__, integer *ldc, - ftnlen uplo_len, ftnlen trans_len); -extern int cherk_(char *uplo, char *trans, integer *n, integer *k, real *alpha, - complex *a, integer *lda, real *beta, complex *c__, - integer *ldc, ftnlen uplo_len, ftnlen trans_len); -extern int chpmv_(char *uplo, integer *n, complex *alpha, complex *ap, - complex *x, integer *incx, complex *beta, complex *y, - integer *incy, ftnlen uplo_len); -extern int chpr_(char *uplo, integer *n, real *alpha, complex *x, integer *incx, - complex *ap, ftnlen uplo_len); -extern int chpr2_(char *uplo, integer *n, complex *alpha, complex *x, - integer *incx, complex *y, integer *incy, complex *ap, - ftnlen uplo_len); -extern int crotg_(complex *ca, complex *cb, real *c__, complex *s); -extern int cscal_(integer *n, complex *ca, complex *cx, integer *incx); -extern int csrot_(integer *n, complex *cx, integer *incx, complex *cy, - integer *incy, real *c__, real *s); -extern int csscal_(integer *n, real *sa, complex *cx, integer *incx); -extern int cswap_(integer *n, complex *cx, integer *incx, complex *cy, - integer *incy); -extern int csymm_(char *side, char *uplo, integer *m, integer *n, - complex *alpha, complex *a, integer *lda, complex *b, - integer *ldb, complex *beta, complex *c__, integer *ldc, - ftnlen side_len, ftnlen uplo_len); -extern int csyr2k_(char *uplo, char *trans, integer *n, integer *k, - complex *alpha, complex *a, integer *lda, complex *b, - integer *ldb, complex *beta, complex *c__, integer *ldc, - ftnlen uplo_len, ftnlen trans_len); -extern int csyrk_(char *uplo, char *trans, integer *n, integer *k, - complex *alpha, complex *a, integer *lda, complex *beta, - complex *c__, integer *ldc, ftnlen uplo_len, - ftnlen trans_len); -extern int ctbmv_(char *uplo, char *trans, char *diag, integer *n, integer *k, - complex *a, integer *lda, complex *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ctbsv_(char *uplo, char *trans, char *diag, integer *n, integer *k, - complex *a, integer *lda, complex *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ctpmv_(char *uplo, char *trans, char *diag, integer *n, complex *ap, - complex *x, integer *incx, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int ctpsv_(char *uplo, char *trans, char *diag, integer *n, complex *ap, - complex *x, integer *incx, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int ctrmm_(char *side, char *uplo, char *transa, char *diag, integer *m, - integer *n, complex *alpha, complex *a, integer *lda, - complex *b, integer *ldb, ftnlen side_len, ftnlen uplo_len, - ftnlen transa_len, ftnlen diag_len); -extern int ctrmv_(char *uplo, char *trans, char *diag, integer *n, complex *a, - integer *lda, complex *x, integer *incx, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int ctrsm_(char *side, char *uplo, char *transa, char *diag, integer *m, - integer *n, complex *alpha, complex *a, integer *lda, - complex *b, integer *ldb, ftnlen side_len, ftnlen uplo_len, - ftnlen transa_len, ftnlen diag_len); -extern int ctrsv_(char *uplo, char *trans, char *diag, integer *n, complex *a, - integer *lda, complex *x, integer *incx, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern doublereal dasum_(integer *n, doublereal *dx, integer *incx); -extern int daxpy_(integer *n, doublereal *da, doublereal *dx, integer *incx, - doublereal *dy, integer *incy); -extern doublereal dcabs1_(doublecomplex *z__); -extern int dcopy_(integer *n, doublereal *dx, integer *incx, doublereal *dy, - integer *incy); -extern doublereal ddot_(integer *n, doublereal *dx, integer *incx, - doublereal *dy, integer *incy); -extern int dgbmv_(char *trans, integer *m, integer *n, integer *kl, integer *ku, - doublereal *alpha, doublereal *a, integer *lda, doublereal *x, - integer *incx, doublereal *beta, doublereal *y, integer *incy, - ftnlen trans_len); -extern int dgemm_(char *transa, char *transb, integer *m, integer *n, - integer *k, doublereal *alpha, doublereal *a, integer *lda, - doublereal *b, integer *ldb, doublereal *beta, - doublereal *c__, integer *ldc); -extern int dgemv_(char *trans, integer *m, integer *n, doublereal *alpha, - doublereal *a, integer *lda, doublereal *x, integer *incx, - doublereal *beta, doublereal *y, integer *incy, - ftnlen trans_len); -extern int dger_(integer *m, integer *n, doublereal *alpha, doublereal *x, - integer *incx, doublereal *y, integer *incy, doublereal *a, - integer *lda); -extern doublereal dnrm2_(integer *n, doublereal *x, integer *incx); -extern int drot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, - integer *incy, doublereal *c__, doublereal *s); -extern int drotg_(doublereal *da, doublereal *db, doublereal *c__, - doublereal *s); -extern int drotm_(integer *n, doublereal *dx, integer *incx, doublereal *dy, - integer *incy, doublereal *dparam); -extern int drotmg_(doublereal *dd1, doublereal *dd2, doublereal *dx1, - doublereal *dy1, doublereal *dparam); -extern int dsbmv_(char *uplo, integer *n, integer *k, doublereal *alpha, - doublereal *a, integer *lda, doublereal *x, integer *incx, - doublereal *beta, doublereal *y, integer *incy, - ftnlen uplo_len); -extern int dscal_(integer *n, doublereal *da, doublereal *dx, integer *incx); -extern doublereal dsdot_(integer *n, real *sx, integer *incx, real *sy, - integer *incy); -extern int dspmv_(char *uplo, integer *n, doublereal *alpha, doublereal *ap, - doublereal *x, integer *incx, doublereal *beta, doublereal *y, - integer *incy, ftnlen uplo_len); -extern int dspr_(char *uplo, integer *n, doublereal *alpha, doublereal *x, - integer *incx, doublereal *ap, ftnlen uplo_len); -extern int dspr2_(char *uplo, integer *n, doublereal *alpha, doublereal *x, - integer *incx, doublereal *y, integer *incy, doublereal *ap, - ftnlen uplo_len); -extern int dswap_(integer *n, doublereal *dx, integer *incx, doublereal *dy, - integer *incy); -extern int dsymm_(char *side, char *uplo, integer *m, integer *n, - doublereal *alpha, doublereal *a, integer *lda, doublereal *b, - integer *ldb, doublereal *beta, doublereal *c__, integer *ldc, - ftnlen side_len, ftnlen uplo_len); -extern int dsymv_(char *uplo, integer *n, doublereal *alpha, doublereal *a, - integer *lda, doublereal *x, integer *incx, doublereal *beta, - doublereal *y, integer *incy, ftnlen uplo_len); -extern int dsyr_(char *uplo, integer *n, doublereal *alpha, doublereal *x, - integer *incx, doublereal *a, integer *lda, ftnlen uplo_len); -extern int dsyr2_(char *uplo, integer *n, doublereal *alpha, doublereal *x, - integer *incx, doublereal *y, integer *incy, doublereal *a, - integer *lda, ftnlen uplo_len); -extern int dsyr2k_(char *uplo, char *trans, integer *n, integer *k, - doublereal *alpha, doublereal *a, integer *lda, - doublereal *b, integer *ldb, doublereal *beta, - doublereal *c__, integer *ldc, ftnlen uplo_len, - ftnlen trans_len); -extern int dsyrk_(char *uplo, char *trans, integer *n, integer *k, - doublereal *alpha, doublereal *a, integer *lda, - doublereal *beta, doublereal *c__, integer *ldc, - ftnlen uplo_len, ftnlen trans_len); -extern int dtbmv_(char *uplo, char *trans, char *diag, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int dtbsv_(char *uplo, char *trans, char *diag, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int dtpmv_(char *uplo, char *trans, char *diag, integer *n, - doublereal *ap, doublereal *x, integer *incx, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int dtpsv_(char *uplo, char *trans, char *diag, integer *n, - doublereal *ap, doublereal *x, integer *incx, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int dtrmm_(char *side, char *uplo, char *transa, char *diag, integer *m, - integer *n, doublereal *alpha, doublereal *a, integer *lda, - doublereal *b, integer *ldb, ftnlen side_len, ftnlen uplo_len, - ftnlen transa_len, ftnlen diag_len); -extern int dtrmv_(char *uplo, char *trans, char *diag, integer *n, - doublereal *a, integer *lda, doublereal *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int dtrsm_(char *side, char *uplo, char *transa, char *diag, integer *m, - integer *n, doublereal *alpha, doublereal *a, integer *lda, - doublereal *b, integer *ldb, ftnlen side_len, ftnlen uplo_len, - ftnlen transa_len, ftnlen diag_len); -extern int dtrsv_(char *uplo, char *trans, char *diag, integer *n, - doublereal *a, integer *lda, doublereal *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern doublereal dzasum_(integer *n, doublecomplex *zx, integer *incx); -extern doublereal dznrm2_(integer *n, doublecomplex *x, integer *incx); -extern integer icamax_(integer *n, complex *cx, integer *incx); -extern integer idamax_(integer *n, doublereal *dx, integer *incx); -extern integer isamax_(integer *n, real *sx, integer *incx); -extern integer izamax_(integer *n, doublecomplex *zx, integer *incx); -extern logical lsame_(char *ca, char *cb, ftnlen ca_len, ftnlen cb_len); -extern E_f sasum_(integer *n, real *sx, integer *incx); -extern int saxpy_(integer *n, real *sa, real *sx, integer *incx, real *sy, - integer *incy); -extern E_f scasum_(integer *n, complex *cx, integer *incx); -extern E_f scnrm2_(integer *n, complex *x, integer *incx); -extern int scopy_(integer *n, real *sx, integer *incx, real *sy, integer *incy); -extern E_f sdot_(integer *n, real *sx, integer *incx, real *sy, integer *incy); -extern E_f sdsdot_(integer *n, real *sb, real *sx, integer *incx, real *sy, - integer *incy); -extern int sgbmv_(char *trans, integer *m, integer *n, integer *kl, integer *ku, - real *alpha, real *a, integer *lda, real *x, integer *incx, - real *beta, real *y, integer *incy, ftnlen trans_len); -extern int sgemm_(char *transa, char *transb, integer *m, integer *n, - integer *k, real *alpha, real *a, integer *lda, real *b, - integer *ldb, real *beta, real *c__, integer *ldc, - ftnlen transa_len, ftnlen transb_len); -extern int sgemv_(char *trans, integer *m, integer *n, real *alpha, real *a, - integer *lda, real *x, integer *incx, real *beta, real *y, - integer *incy, ftnlen trans_len); -extern int sger_(integer *m, integer *n, real *alpha, real *x, integer *incx, - real *y, integer *incy, real *a, integer *lda); -extern E_f snrm2_(integer *n, real *x, integer *incx); -extern int srot_(integer *n, real *sx, integer *incx, real *sy, integer *incy, - real *c__, real *s); -extern int srotg_(real *sa, real *sb, real *c__, real *s); -extern int srotm_(integer *n, real *sx, integer *incx, real *sy, integer *incy, - real *sparam); -extern int srotmg_(real *sd1, real *sd2, real *sx1, real *sy1, real *sparam); -extern int ssbmv_(char *uplo, integer *n, integer *k, real *alpha, real *a, - integer *lda, real *x, integer *incx, real *beta, real *y, - integer *incy, ftnlen uplo_len); -extern int sscal_(integer *n, real *sa, real *sx, integer *incx); -extern int sspmv_(char *uplo, integer *n, real *alpha, real *ap, real *x, - integer *incx, real *beta, real *y, integer *incy, - ftnlen uplo_len); -extern int sspr_(char *uplo, integer *n, real *alpha, real *x, integer *incx, - real *ap, ftnlen uplo_len); -extern int sspr2_(char *uplo, integer *n, real *alpha, real *x, integer *incx, - real *y, integer *incy, real *ap, ftnlen uplo_len); -extern int sswap_(integer *n, real *sx, integer *incx, real *sy, integer *incy); -extern int ssymm_(char *side, char *uplo, integer *m, integer *n, real *alpha, - real *a, integer *lda, real *b, integer *ldb, real *beta, - real *c__, integer *ldc, ftnlen side_len, ftnlen uplo_len); -extern int ssymv_(char *uplo, integer *n, real *alpha, real *a, integer *lda, - real *x, integer *incx, real *beta, real *y, integer *incy, - ftnlen uplo_len); -extern int ssyr_(char *uplo, integer *n, real *alpha, real *x, integer *incx, - real *a, integer *lda, ftnlen uplo_len); -extern int ssyr2_(char *uplo, integer *n, real *alpha, real *x, integer *incx, - real *y, integer *incy, real *a, integer *lda, - ftnlen uplo_len); -extern int ssyr2k_(char *uplo, char *trans, integer *n, integer *k, real *alpha, - real *a, integer *lda, real *b, integer *ldb, real *beta, - real *c__, integer *ldc, ftnlen uplo_len, ftnlen trans_len); -extern int ssyrk_(char *uplo, char *trans, integer *n, integer *k, real *alpha, - real *a, integer *lda, real *beta, real *c__, integer *ldc, - ftnlen uplo_len, ftnlen trans_len); -extern int stbmv_(char *uplo, char *trans, char *diag, integer *n, integer *k, - real *a, integer *lda, real *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int stbsv_(char *uplo, char *trans, char *diag, integer *n, integer *k, - real *a, integer *lda, real *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int stpmv_(char *uplo, char *trans, char *diag, integer *n, real *ap, - real *x, integer *incx, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int stpsv_(char *uplo, char *trans, char *diag, integer *n, real *ap, - real *x, integer *incx, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int strmm_(char *side, char *uplo, char *transa, char *diag, integer *m, - integer *n, real *alpha, real *a, integer *lda, real *b, - integer *ldb, ftnlen side_len, ftnlen uplo_len, - ftnlen transa_len, ftnlen diag_len); -extern int strmv_(char *uplo, char *trans, char *diag, integer *n, real *a, - integer *lda, real *x, integer *incx, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int strsm_(char *side, char *uplo, char *transa, char *diag, integer *m, - integer *n, real *alpha, real *a, integer *lda, real *b, - integer *ldb, ftnlen side_len, ftnlen uplo_len, - ftnlen transa_len, ftnlen diag_len); -extern int strsv_(char *uplo, char *trans, char *diag, integer *n, real *a, - integer *lda, real *x, integer *incx, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int xerbla_(char *srname, integer *info, ftnlen srname_len); -extern int zaxpy_(integer *n, doublecomplex *za, doublecomplex *zx, - integer *incx, doublecomplex *zy, integer *incy); -extern int zcopy_(integer *n, doublecomplex *zx, integer *incx, - doublecomplex *zy, integer *incy); -extern Z_f zdotc_(doublecomplex *ret_val, integer *n, doublecomplex *zx, - integer *incx, doublecomplex *zy, integer *incy); -extern Z_f zdotu_(doublecomplex *ret_val, integer *n, doublecomplex *zx, - integer *incx, doublecomplex *zy, integer *incy); -extern int zdrot_(integer *n, doublecomplex *zx, integer *incx, - doublecomplex *zy, integer *incy, doublereal *c__, - doublereal *s); -extern int zdscal_(integer *n, doublereal *da, doublecomplex *zx, - integer *incx); -extern int zgbmv_(char *trans, integer *m, integer *n, integer *kl, integer *ku, - doublecomplex *alpha, doublecomplex *a, integer *lda, - doublecomplex *x, integer *incx, doublecomplex *beta, - doublecomplex *y, integer *incy, ftnlen trans_len); -extern int zgemm_(char *transa, char *transb, integer *m, integer *n, - integer *k, doublecomplex *alpha, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublecomplex *beta, doublecomplex *c__, integer *ldc, - ftnlen transa_len, ftnlen transb_len); -extern int zgemv_(char *trans, integer *m, integer *n, doublecomplex *alpha, - doublecomplex *a, integer *lda, doublecomplex *x, - integer *incx, doublecomplex *beta, doublecomplex *y, - integer *incy, ftnlen trans_len); -extern int zgerc_(integer *m, integer *n, doublecomplex *alpha, - doublecomplex *x, integer *incx, doublecomplex *y, - integer *incy, doublecomplex *a, integer *lda); -extern int zgeru_(integer *m, integer *n, doublecomplex *alpha, - doublecomplex *x, integer *incx, doublecomplex *y, - integer *incy, doublecomplex *a, integer *lda); -extern int zhbmv_(char *uplo, integer *n, integer *k, doublecomplex *alpha, - doublecomplex *a, integer *lda, doublecomplex *x, - integer *incx, doublecomplex *beta, doublecomplex *y, - integer *incy, ftnlen uplo_len); -extern int zhemm_(char *side, char *uplo, integer *m, integer *n, - doublecomplex *alpha, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, doublecomplex *beta, - doublecomplex *c__, integer *ldc, ftnlen side_len, - ftnlen uplo_len); -extern int zhemv_(char *uplo, integer *n, doublecomplex *alpha, - doublecomplex *a, integer *lda, doublecomplex *x, - integer *incx, doublecomplex *beta, doublecomplex *y, - integer *incy, ftnlen uplo_len); -extern int zher_(char *uplo, integer *n, doublereal *alpha, doublecomplex *x, - integer *incx, doublecomplex *a, integer *lda, - ftnlen uplo_len); -extern int zher2_(char *uplo, integer *n, doublecomplex *alpha, - doublecomplex *x, integer *incx, doublecomplex *y, - integer *incy, doublecomplex *a, integer *lda, - ftnlen uplo_len); -extern int zher2k_(char *uplo, char *trans, integer *n, integer *k, - doublecomplex *alpha, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, doublereal *beta, - doublecomplex *c__, integer *ldc, ftnlen uplo_len, - ftnlen trans_len); -extern int zherk_(char *uplo, char *trans, integer *n, integer *k, - doublereal *alpha, doublecomplex *a, integer *lda, - doublereal *beta, doublecomplex *c__, integer *ldc, - ftnlen uplo_len, ftnlen trans_len); -extern int zhpmv_(char *uplo, integer *n, doublecomplex *alpha, - doublecomplex *ap, doublecomplex *x, integer *incx, - doublecomplex *beta, doublecomplex *y, integer *incy, - ftnlen uplo_len); -extern int zhpr_(char *uplo, integer *n, doublereal *alpha, doublecomplex *x, - integer *incx, doublecomplex *ap, ftnlen uplo_len); -extern int zhpr2_(char *uplo, integer *n, doublecomplex *alpha, - doublecomplex *x, integer *incx, doublecomplex *y, - integer *incy, doublecomplex *ap, ftnlen uplo_len); -extern int zrotg_(doublecomplex *ca, doublecomplex *cb, doublereal *c__, - doublecomplex *s); -extern int zscal_(integer *n, doublecomplex *za, doublecomplex *zx, - integer *incx); -extern int zswap_(integer *n, doublecomplex *zx, integer *incx, - doublecomplex *zy, integer *incy); -extern int zsymm_(char *side, char *uplo, integer *m, integer *n, - doublecomplex *alpha, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, doublecomplex *beta, - doublecomplex *c__, integer *ldc, ftnlen side_len, - ftnlen uplo_len); -extern int zsyr2k_(char *uplo, char *trans, integer *n, integer *k, - doublecomplex *alpha, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, doublecomplex *beta, - doublecomplex *c__, integer *ldc, ftnlen uplo_len, - ftnlen trans_len); -extern int zsyrk_(char *uplo, char *trans, integer *n, integer *k, - doublecomplex *alpha, doublecomplex *a, integer *lda, - doublecomplex *beta, doublecomplex *c__, integer *ldc, - ftnlen uplo_len, ftnlen trans_len); -extern int ztbmv_(char *uplo, char *trans, char *diag, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *x, - integer *incx, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int ztbsv_(char *uplo, char *trans, char *diag, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *x, - integer *incx, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int ztpmv_(char *uplo, char *trans, char *diag, integer *n, - doublecomplex *ap, doublecomplex *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ztpsv_(char *uplo, char *trans, char *diag, integer *n, - doublecomplex *ap, doublecomplex *x, integer *incx, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ztrmm_(char *side, char *uplo, char *transa, char *diag, integer *m, - integer *n, doublecomplex *alpha, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, ftnlen side_len, - ftnlen uplo_len, ftnlen transa_len, ftnlen diag_len); -extern int ztrmv_(char *uplo, char *trans, char *diag, integer *n, - doublecomplex *a, integer *lda, doublecomplex *x, - integer *incx, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int ztrsm_(char *side, char *uplo, char *transa, char *diag, integer *m, - integer *n, doublecomplex *alpha, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, ftnlen side_len, - ftnlen uplo_len, ftnlen transa_len, ftnlen diag_len); -extern int ztrsv_(char *uplo, char *trans, char *diag, integer *n, - doublecomplex *a, integer *lda, doublecomplex *x, - integer *incx, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); - -#endif diff --git a/include/grass/config.h.in b/include/grass/config.h.in index f070b4ccc0d..2451d8cc2b8 100644 --- a/include/grass/config.h.in +++ b/include/grass/config.h.in @@ -14,21 +14,18 @@ /* Define to 1 if you have the `asprintf' function. */ #undef HAVE_ASPRINTF -/* Define to 1 if you have the `strlcpy' function. */ -#undef HAVE_STRLCPY - /* Define to 1 if you have the header file. */ #undef HAVE_BZLIB_H /* Define to 1 if you have the header file. */ #undef HAVE_CAIRO_H +/* Define to 1 if you have the header file. */ +#undef HAVE_CBLAS_ATLAS_H + /* Define to 1 if you have the header file. */ #undef HAVE_CBLAS_H -/* Define to 1 if you have the header file. */ -#undef HAVE_CLAPACK_H - /* Define to 1 if you have the header file. */ #undef HAVE_CL_CL_H @@ -38,9 +35,6 @@ /* Define to 1 if you have the `drand48' function. */ #undef HAVE_DRAND48 -/* Define to 1 if you have the header file. */ -#undef HAVE_F2C_H - /* Define to 1 if you have the header file. */ #undef HAVE_FFTW3_H @@ -56,9 +50,6 @@ /* Define to 1 if you have the `ftime' function. */ #undef HAVE_FTIME -/* Define to 1 if you have the header file. */ -#undef HAVE_G2C_H - /* Define to 1 if GDAL is to be used. */ #undef HAVE_GDAL @@ -92,8 +83,8 @@ /* Define to 1 if you have the header file. */ #undef HAVE_LANGINFO_H -/* Define to 1 if ATLAS exists. */ -#undef HAVE_LIBATLAS +/* Define to 1 if you have the header file. */ +#undef HAVE_LAPACKE_H /* Define to 1 if BLAS exists. */ #undef HAVE_LIBBLAS @@ -239,6 +230,12 @@ /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H +/* Define to 1 if you have the `strlcat' function. */ +#undef HAVE_STRLCAT + +/* Define to 1 if you have the `strlcpy' function. */ +#undef HAVE_STRLCPY + /* Define to 1 if you have the header file. */ #undef HAVE_SVM_H diff --git a/include/grass/defs/gis.h b/include/grass/defs/gis.h index 4125a3aeed3..dc5ad2499f0 100644 --- a/include/grass/defs/gis.h +++ b/include/grass/defs/gis.h @@ -152,6 +152,9 @@ int G_vfaprintf(FILE *, const char *, va_list); int G_vsaprintf(char *, const char *, va_list); int G_vsnaprintf(char *, size_t, const char *, va_list); +/* strlcat.c */ +size_t G_strlcat(char *, const char *, size_t); + /* strlcpy.c */ size_t G_strlcpy(char *, const char *, size_t); diff --git a/include/grass/defs/raster.h b/include/grass/defs/raster.h index 7244da2a354..7f358562c72 100644 --- a/include/grass/defs/raster.h +++ b/include/grass/defs/raster.h @@ -392,7 +392,9 @@ int Rast_option_to_interp_type(const struct Option *); /* mask_info.c */ char *Rast_mask_info(void); +bool Rast_mask_status(char *, char *, bool *, char *, char *); int Rast__mask_info(char *, char *); +bool Rast_mask_is_present(void); /* maskfd.c */ int Rast_maskfd(void); diff --git a/include/grass/la.h b/include/grass/la.h index 2981dc3401e..edec847c8e1 100644 --- a/include/grass/la.h +++ b/include/grass/la.h @@ -23,93 +23,9 @@ #ifndef GRASS_LA_H #define GRASS_LA_H -/* QUESTION: On some systems there appears to be no default link - to this. Do we create a symlink to - /usr/lib/gcc-lib///include/g2c.h - - or link to any old f2c.h that happens to hanging around? - - A job for autoconf - - [Also a consideration for -lg2c] - */ - #include #include -#ifdef HAVE_G2C_H -typedef int __g77_integer; -typedef unsigned int __g77_uinteger; -typedef long int __g77_longint; -typedef unsigned long int __g77_ulongint; - -#include -#else /* for gcc4+ */ -typedef int integer; -typedef unsigned int uinteger; -typedef char *address; -typedef short shortint; -typedef float real; -typedef double doublereal; -typedef struct { - real r, i; -} complex; -typedef struct { - doublereal r, i; -} doublecomplex; -typedef int logical; -typedef short shortlogical; -typedef char logical1; -typedef char integer1; -typedef long longint; -typedef unsigned long ulongint; - -/* IO stuff */ -typedef int ftnlen; - -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wstrict-prototypes" -#elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wstrict-prototypes" -#endif - -/* procedure parameter types for -A */ -typedef int (*U_fp)(); -typedef shortint (*J_fp)(); -typedef integer (*I_fp)(); -typedef real (*R_fp)(); -typedef doublereal (*D_fp)(), (*E_fp)(); -typedef void (*C_fp)(); -typedef void (*Z_fp)(); -typedef logical (*L_fp)(); -typedef shortlogical (*K_fp)(); -typedef void (*H_fp)(); -typedef int (*S_fp)(); - -#if defined(__clang__) -#pragma clang diagnostic pop -#elif defined(__GNUC__) -#pragma GCC diagnostic pop -#endif - -/* E_fp is for real functions when -R is not specified */ -typedef void C_f; /* complex function */ -typedef void H_f; /* character function */ -typedef void Z_f; /* double complex function */ -typedef doublereal E_f; /* real function with -R not specified */ -#endif /* HAVE_G2C_H */ - -/* The following may have to be selectively installed according - to platform, at least partly - */ - -#if defined(HAVE_LIBBLAS) && defined(HAVE_LIBLAPACK) -#include -#include -#endif - /* Useful defines */ #define MAX_POS 1 /* Indicates maximum value */ @@ -117,17 +33,7 @@ typedef doublereal E_f; /* real function with -R not specified */ #define MAX_ABS 0 /* Indicates absolute value */ #define DO_COMPACT 0 /* Eliminate unnecessary rows (cols) in matrix */ -#define NO_COMPACT 1 /* ... or not */ - -/* define macros for fortran symbols (called directly). Needed because - of platform invariance on fortran->C symbol translations - */ - -#if defined(HAVE_LIBBLAS) && defined(HAVE_LIBLAPACK) -#define f77_dgesv dgesv_ -#define f77_dgemm dgemm_ -#define f77_dnrm2 dnrm2_ -#endif +#define NO_COMPACT 1 /* ... or not */ /* Operations should know type of coefficient matrix, so that they can call the right driver @@ -146,16 +52,16 @@ typedef enum { RVEC, CVEC } vtype; typedef struct matrix_ { - mat_spec type; /* matrix, row vector or column vector? */ - int v_indx; /* If a vector, which row(column) is active? - * If a matrix this is ignored. If value is < 0, - * the first row(column) is assumed, ie. index 0. */ - int rows, cols; /* Rows and columns of matrix */ - int ldim; /* Lead dimension of matrix. How many `rows' are - * alloc'ed? May exceed real number of rows `rows' */ - doublereal *vals; /* The values (should be dimensioned to lda * cols */ - int is_init; /* Is matrix initialised: values array - * is allocated and parameters set ? */ + mat_spec type; /* matrix, row vector or column vector? */ + int v_indx; /* If a vector, which row(column) is active? + * If a matrix this is ignored. If value is < 0, + * the first row(column) is assumed, ie. index 0. */ + int rows, cols; /* Rows and columns of matrix */ + int ldim; /* Lead dimension of matrix. How many `rows' are + * alloc'ed? May exceed real number of rows `rows' */ + double *vals; /* The values (should be dimensioned to lda * cols */ + int is_init; /* Is matrix initialised: values array + * is allocated and parameters set ? */ } mat_struct; typedef mat_struct vec_struct; diff --git a/include/grass/lapack.h b/include/grass/lapack.h deleted file mode 100644 index 2763404ae8c..00000000000 --- a/include/grass/lapack.h +++ /dev/null @@ -1,4748 +0,0 @@ -#ifndef LAPACK_WRAP_ -#define LAPACK_WRAP_ - -extern int cbdsqr_(char *uplo, integer *n, integer *ncvt, integer *nru, - integer *ncc, real *d__, real *e, complex *vt, integer *ldvt, - complex *u, integer *ldu, complex *c__, integer *ldc, - real *rwork, integer *info, ftnlen uplo_len); -extern int cgbbrd_(char *vect, integer *m, integer *n, integer *ncc, - integer *kl, integer *ku, complex *ab, integer *ldab, - real *d__, real *e, complex *q, integer *ldq, complex *pt, - integer *ldpt, complex *c__, integer *ldc, complex *work, - real *rwork, integer *info, ftnlen vect_len); -extern int cgbcon_(char *norm, integer *n, integer *kl, integer *ku, - complex *ab, integer *ldab, integer *ipiv, real *anorm, - real *rcond, complex *work, real *rwork, integer *info, - ftnlen norm_len); -extern int cgbequ_(integer *m, integer *n, integer *kl, integer *ku, - complex *ab, integer *ldab, real *r__, real *c__, - real *rowcnd, real *colcnd, real *amax, integer *info); -extern int cgbrfs_(char *trans, integer *n, integer *kl, integer *ku, - integer *nrhs, complex *ab, integer *ldab, complex *afb, - integer *ldafb, integer *ipiv, complex *b, integer *ldb, - complex *x, integer *ldx, real *ferr, real *berr, - complex *work, real *rwork, integer *info, ftnlen trans_len); -extern int cgbsv_(integer *n, integer *kl, integer *ku, integer *nrhs, - complex *ab, integer *ldab, integer *ipiv, complex *b, - integer *ldb, integer *info); -extern int cgbsvx_(char *fact, char *trans, integer *n, integer *kl, - integer *ku, integer *nrhs, complex *ab, integer *ldab, - complex *afb, integer *ldafb, integer *ipiv, char *equed, - real *r__, real *c__, complex *b, integer *ldb, complex *x, - integer *ldx, real *rcond, real *ferr, real *berr, - complex *work, real *rwork, integer *info, ftnlen fact_len, - ftnlen trans_len, ftnlen equed_len); -extern int cgbtf2_(integer *m, integer *n, integer *kl, integer *ku, - complex *ab, integer *ldab, integer *ipiv, integer *info); -extern int cgbtrf_(integer *m, integer *n, integer *kl, integer *ku, - complex *ab, integer *ldab, integer *ipiv, integer *info); -extern int cgbtrs_(char *trans, integer *n, integer *kl, integer *ku, - integer *nrhs, complex *ab, integer *ldab, integer *ipiv, - complex *b, integer *ldb, integer *info, ftnlen trans_len); -extern int cgebak_(char *job, char *side, integer *n, integer *ilo, - integer *ihi, real *scale, integer *m, complex *v, - integer *ldv, integer *info, ftnlen job_len, - ftnlen side_len); -extern int cgebal_(char *job, integer *n, complex *a, integer *lda, - integer *ilo, integer *ihi, real *scale, integer *info, - ftnlen job_len); -extern int cgebd2_(integer *m, integer *n, complex *a, integer *lda, real *d__, - real *e, complex *tauq, complex *taup, complex *work, - integer *info); -extern int cgebrd_(integer *m, integer *n, complex *a, integer *lda, real *d__, - real *e, complex *tauq, complex *taup, complex *work, - integer *lwork, integer *info); -extern int cgecon_(char *norm, integer *n, complex *a, integer *lda, - real *anorm, real *rcond, complex *work, real *rwork, - integer *info, ftnlen norm_len); -extern int cgeequ_(integer *m, integer *n, complex *a, integer *lda, real *r__, - real *c__, real *rowcnd, real *colcnd, real *amax, - integer *info); -extern int cgees_(char *jobvs, char *sort, L_fp select, integer *n, complex *a, - integer *lda, integer *sdim, complex *w, complex *vs, - integer *ldvs, complex *work, integer *lwork, real *rwork, - logical *bwork, integer *info, ftnlen jobvs_len, - ftnlen sort_len); -extern int cgeesx_(char *jobvs, char *sort, L_fp select, char *sense, - integer *n, complex *a, integer *lda, integer *sdim, - complex *w, complex *vs, integer *ldvs, real *rconde, - real *rcondv, complex *work, integer *lwork, real *rwork, - logical *bwork, integer *info, ftnlen jobvs_len, - ftnlen sort_len, ftnlen sense_len); -extern int cgeev_(char *jobvl, char *jobvr, integer *n, complex *a, - integer *lda, complex *w, complex *vl, integer *ldvl, - complex *vr, integer *ldvr, complex *work, integer *lwork, - real *rwork, integer *info, ftnlen jobvl_len, - ftnlen jobvr_len); -extern int cgeevx_(char *balanc, char *jobvl, char *jobvr, char *sense, - integer *n, complex *a, integer *lda, complex *w, - complex *vl, integer *ldvl, complex *vr, integer *ldvr, - integer *ilo, integer *ihi, real *scale, real *abnrm, - real *rconde, real *rcondv, complex *work, integer *lwork, - real *rwork, integer *info, ftnlen balanc_len, - ftnlen jobvl_len, ftnlen jobvr_len, ftnlen sense_len); -extern int cgegs_(char *jobvsl, char *jobvsr, integer *n, complex *a, - integer *lda, complex *b, integer *ldb, complex *alpha, - complex *beta, complex *vsl, integer *ldvsl, complex *vsr, - integer *ldvsr, complex *work, integer *lwork, real *rwork, - integer *info, ftnlen jobvsl_len, ftnlen jobvsr_len); -extern int cgegv_(char *jobvl, char *jobvr, integer *n, complex *a, - integer *lda, complex *b, integer *ldb, complex *alpha, - complex *beta, complex *vl, integer *ldvl, complex *vr, - integer *ldvr, complex *work, integer *lwork, real *rwork, - integer *info, ftnlen jobvl_len, ftnlen jobvr_len); -extern int cgehd2_(integer *n, integer *ilo, integer *ihi, complex *a, - integer *lda, complex *tau, complex *work, integer *info); -extern int cgehrd_(integer *n, integer *ilo, integer *ihi, complex *a, - integer *lda, complex *tau, complex *work, integer *lwork, - integer *info); -extern int cgelq2_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *info); -extern int cgelqf_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info); -extern int cgels_(char *trans, integer *m, integer *n, integer *nrhs, - complex *a, integer *lda, complex *b, integer *ldb, - complex *work, integer *lwork, integer *info, - ftnlen trans_len); -extern int cgelsd_(integer *m, integer *n, integer *nrhs, complex *a, - integer *lda, complex *b, integer *ldb, real *s, real *rcond, - integer *rank, complex *work, integer *lwork, real *rwork, - integer *iwork, integer *info); -extern int cgelss_(integer *m, integer *n, integer *nrhs, complex *a, - integer *lda, complex *b, integer *ldb, real *s, real *rcond, - integer *rank, complex *work, integer *lwork, real *rwork, - integer *info); -extern int cgelsx_(integer *m, integer *n, integer *nrhs, complex *a, - integer *lda, complex *b, integer *ldb, integer *jpvt, - real *rcond, integer *rank, complex *work, real *rwork, - integer *info); -extern int cgelsy_(integer *m, integer *n, integer *nrhs, complex *a, - integer *lda, complex *b, integer *ldb, integer *jpvt, - real *rcond, integer *rank, complex *work, integer *lwork, - real *rwork, integer *info); -extern int cgeql2_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *info); -extern int cgeqlf_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info); -extern int cgeqp3_(integer *m, integer *n, complex *a, integer *lda, - integer *jpvt, complex *tau, complex *work, integer *lwork, - real *rwork, integer *info); -extern int cgeqpf_(integer *m, integer *n, complex *a, integer *lda, - integer *jpvt, complex *tau, complex *work, real *rwork, - integer *info); -extern int cgeqr2_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *info); -extern int cgeqrf_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info); -extern int cgerfs_(char *trans, integer *n, integer *nrhs, complex *a, - integer *lda, complex *af, integer *ldaf, integer *ipiv, - complex *b, integer *ldb, complex *x, integer *ldx, - real *ferr, real *berr, complex *work, real *rwork, - integer *info, ftnlen trans_len); -extern int cgerq2_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *info); -extern int cgerqf_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info); -extern int cgesc2_(integer *n, complex *a, integer *lda, complex *rhs, - integer *ipiv, integer *jpiv, real *scale); -extern int cgesdd_(char *jobz, integer *m, integer *n, complex *a, integer *lda, - real *s, complex *u, integer *ldu, complex *vt, - integer *ldvt, complex *work, integer *lwork, real *rwork, - integer *iwork, integer *info, ftnlen jobz_len); -extern int cgesv_(integer *n, integer *nrhs, complex *a, integer *lda, - integer *ipiv, complex *b, integer *ldb, integer *info); -extern int cgesvd_(char *jobu, char *jobvt, integer *m, integer *n, complex *a, - integer *lda, real *s, complex *u, integer *ldu, complex *vt, - integer *ldvt, complex *work, integer *lwork, real *rwork, - integer *info, ftnlen jobu_len, ftnlen jobvt_len); -extern int cgesvx_(char *fact, char *trans, integer *n, integer *nrhs, - complex *a, integer *lda, complex *af, integer *ldaf, - integer *ipiv, char *equed, real *r__, real *c__, complex *b, - integer *ldb, complex *x, integer *ldx, real *rcond, - real *ferr, real *berr, complex *work, real *rwork, - integer *info, ftnlen fact_len, ftnlen trans_len, - ftnlen equed_len); -extern int cgetc2_(integer *n, complex *a, integer *lda, integer *ipiv, - integer *jpiv, integer *info); -extern int cgetf2_(integer *m, integer *n, complex *a, integer *lda, - integer *ipiv, integer *info); -extern int cgetrf_(integer *m, integer *n, complex *a, integer *lda, - integer *ipiv, integer *info); -extern int cgetri_(integer *n, complex *a, integer *lda, integer *ipiv, - complex *work, integer *lwork, integer *info); -extern int cgetrs_(char *trans, integer *n, integer *nrhs, complex *a, - integer *lda, integer *ipiv, complex *b, integer *ldb, - integer *info, ftnlen trans_len); -extern int cggbak_(char *job, char *side, integer *n, integer *ilo, - integer *ihi, real *lscale, real *rscale, integer *m, - complex *v, integer *ldv, integer *info, ftnlen job_len, - ftnlen side_len); -extern int cggbal_(char *job, integer *n, complex *a, integer *lda, complex *b, - integer *ldb, integer *ilo, integer *ihi, real *lscale, - real *rscale, real *work, integer *info, ftnlen job_len); -extern int cgges_(char *jobvsl, char *jobvsr, char *sort, L_fp selctg, - integer *n, complex *a, integer *lda, complex *b, - integer *ldb, integer *sdim, complex *alpha, complex *beta, - complex *vsl, integer *ldvsl, complex *vsr, integer *ldvsr, - complex *work, integer *lwork, real *rwork, logical *bwork, - integer *info, ftnlen jobvsl_len, ftnlen jobvsr_len, - ftnlen sort_len); -extern int cggesx_(char *jobvsl, char *jobvsr, char *sort, L_fp selctg, - char *sense, integer *n, complex *a, integer *lda, - complex *b, integer *ldb, integer *sdim, complex *alpha, - complex *beta, complex *vsl, integer *ldvsl, complex *vsr, - integer *ldvsr, real *rconde, real *rcondv, complex *work, - integer *lwork, real *rwork, integer *iwork, integer *liwork, - logical *bwork, integer *info, ftnlen jobvsl_len, - ftnlen jobvsr_len, ftnlen sort_len, ftnlen sense_len); -extern int cggev_(char *jobvl, char *jobvr, integer *n, complex *a, - integer *lda, complex *b, integer *ldb, complex *alpha, - complex *beta, complex *vl, integer *ldvl, complex *vr, - integer *ldvr, complex *work, integer *lwork, real *rwork, - integer *info, ftnlen jobvl_len, ftnlen jobvr_len); -extern int cggevx_(char *balanc, char *jobvl, char *jobvr, char *sense, - integer *n, complex *a, integer *lda, complex *b, - integer *ldb, complex *alpha, complex *beta, complex *vl, - integer *ldvl, complex *vr, integer *ldvr, integer *ilo, - integer *ihi, real *lscale, real *rscale, real *abnrm, - real *bbnrm, real *rconde, real *rcondv, complex *work, - integer *lwork, real *rwork, integer *iwork, logical *bwork, - integer *info, ftnlen balanc_len, ftnlen jobvl_len, - ftnlen jobvr_len, ftnlen sense_len); -extern int cggglm_(integer *n, integer *m, integer *p, complex *a, integer *lda, - complex *b, integer *ldb, complex *d__, complex *x, - complex *y, complex *work, integer *lwork, integer *info); -extern int cgghrd_(char *compq, char *compz, integer *n, integer *ilo, - integer *ihi, complex *a, integer *lda, complex *b, - integer *ldb, complex *q, integer *ldq, complex *z__, - integer *ldz, integer *info, ftnlen compq_len, - ftnlen compz_len); -extern int cgglse_(integer *m, integer *n, integer *p, complex *a, integer *lda, - complex *b, integer *ldb, complex *c__, complex *d__, - complex *x, complex *work, integer *lwork, integer *info); -extern int cggqrf_(integer *n, integer *m, integer *p, complex *a, integer *lda, - complex *taua, complex *b, integer *ldb, complex *taub, - complex *work, integer *lwork, integer *info); -extern int cggrqf_(integer *m, integer *p, integer *n, complex *a, integer *lda, - complex *taua, complex *b, integer *ldb, complex *taub, - complex *work, integer *lwork, integer *info); -extern int cggsvd_(char *jobu, char *jobv, char *jobq, integer *m, integer *n, - integer *p, integer *k, integer *l, complex *a, integer *lda, - complex *b, integer *ldb, real *alpha, real *beta, - complex *u, integer *ldu, complex *v, integer *ldv, - complex *q, integer *ldq, complex *work, real *rwork, - integer *iwork, integer *info, ftnlen jobu_len, - ftnlen jobv_len, ftnlen jobq_len); -extern int cggsvp_(char *jobu, char *jobv, char *jobq, integer *m, integer *p, - integer *n, complex *a, integer *lda, complex *b, - integer *ldb, real *tola, real *tolb, integer *k, integer *l, - complex *u, integer *ldu, complex *v, integer *ldv, - complex *q, integer *ldq, integer *iwork, real *rwork, - complex *tau, complex *work, integer *info, ftnlen jobu_len, - ftnlen jobv_len, ftnlen jobq_len); -extern int cgtcon_(char *norm, integer *n, complex *dl, complex *d__, - complex *du, complex *du2, integer *ipiv, real *anorm, - real *rcond, complex *work, integer *info, ftnlen norm_len); -extern int cgtrfs_(char *trans, integer *n, integer *nrhs, complex *dl, - complex *d__, complex *du, complex *dlf, complex *df, - complex *duf, complex *du2, integer *ipiv, complex *b, - integer *ldb, complex *x, integer *ldx, real *ferr, - real *berr, complex *work, real *rwork, integer *info, - ftnlen trans_len); -extern int cgtsv_(integer *n, integer *nrhs, complex *dl, complex *d__, - complex *du, complex *b, integer *ldb, integer *info); -extern int cgtsvx_(char *fact, char *trans, integer *n, integer *nrhs, - complex *dl, complex *d__, complex *du, complex *dlf, - complex *df, complex *duf, complex *du2, integer *ipiv, - complex *b, integer *ldb, complex *x, integer *ldx, - real *rcond, real *ferr, real *berr, complex *work, - real *rwork, integer *info, ftnlen fact_len, - ftnlen trans_len); -extern int cgttrf_(integer *n, complex *dl, complex *d__, complex *du, - complex *du2, integer *ipiv, integer *info); -extern int cgttrs_(char *trans, integer *n, integer *nrhs, complex *dl, - complex *d__, complex *du, complex *du2, integer *ipiv, - complex *b, integer *ldb, integer *info, ftnlen trans_len); -extern int cgtts2_(integer *itrans, integer *n, integer *nrhs, complex *dl, - complex *d__, complex *du, complex *du2, integer *ipiv, - complex *b, integer *ldb); -extern int chbev_(char *jobz, char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, real *w, complex *z__, integer *ldz, - complex *work, real *rwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int chbevd_(char *jobz, char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, real *w, complex *z__, integer *ldz, - complex *work, integer *lwork, real *rwork, integer *lrwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int chbevx_(char *jobz, char *range, char *uplo, integer *n, integer *kd, - complex *ab, integer *ldab, complex *q, integer *ldq, - real *vl, real *vu, integer *il, integer *iu, real *abstol, - integer *m, real *w, complex *z__, integer *ldz, - complex *work, real *rwork, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int chbgst_(char *vect, char *uplo, integer *n, integer *ka, integer *kb, - complex *ab, integer *ldab, complex *bb, integer *ldbb, - complex *x, integer *ldx, complex *work, real *rwork, - integer *info, ftnlen vect_len, ftnlen uplo_len); -extern int chbgv_(char *jobz, char *uplo, integer *n, integer *ka, integer *kb, - complex *ab, integer *ldab, complex *bb, integer *ldbb, - real *w, complex *z__, integer *ldz, complex *work, - real *rwork, integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int chbgvd_(char *jobz, char *uplo, integer *n, integer *ka, integer *kb, - complex *ab, integer *ldab, complex *bb, integer *ldbb, - real *w, complex *z__, integer *ldz, complex *work, - integer *lwork, real *rwork, integer *lrwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int chbgvx_(char *jobz, char *range, char *uplo, integer *n, integer *ka, - integer *kb, complex *ab, integer *ldab, complex *bb, - integer *ldbb, complex *q, integer *ldq, real *vl, real *vu, - integer *il, integer *iu, real *abstol, integer *m, real *w, - complex *z__, integer *ldz, complex *work, real *rwork, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len, ftnlen uplo_len); -extern int chbtrd_(char *vect, char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, real *d__, real *e, complex *q, integer *ldq, - complex *work, integer *info, ftnlen vect_len, - ftnlen uplo_len); -extern int checon_(char *uplo, integer *n, complex *a, integer *lda, - integer *ipiv, real *anorm, real *rcond, complex *work, - integer *info, ftnlen uplo_len); -extern int cheev_(char *jobz, char *uplo, integer *n, complex *a, integer *lda, - real *w, complex *work, integer *lwork, real *rwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int cheevd_(char *jobz, char *uplo, integer *n, complex *a, integer *lda, - real *w, complex *work, integer *lwork, real *rwork, - integer *lrwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int cheevr_(char *jobz, char *range, char *uplo, integer *n, complex *a, - integer *lda, real *vl, real *vu, integer *il, integer *iu, - real *abstol, integer *m, real *w, complex *z__, - integer *ldz, integer *isuppz, complex *work, integer *lwork, - real *rwork, integer *lrwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen range_len, ftnlen uplo_len); -extern int cheevx_(char *jobz, char *range, char *uplo, integer *n, complex *a, - integer *lda, real *vl, real *vu, integer *il, integer *iu, - real *abstol, integer *m, real *w, complex *z__, - integer *ldz, complex *work, integer *lwork, real *rwork, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len, ftnlen uplo_len); -extern int chegs2_(integer *itype, char *uplo, integer *n, complex *a, - integer *lda, complex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int chegst_(integer *itype, char *uplo, integer *n, complex *a, - integer *lda, complex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int chegv_(integer *itype, char *jobz, char *uplo, integer *n, - complex *a, integer *lda, complex *b, integer *ldb, real *w, - complex *work, integer *lwork, real *rwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int chegvd_(integer *itype, char *jobz, char *uplo, integer *n, - complex *a, integer *lda, complex *b, integer *ldb, real *w, - complex *work, integer *lwork, real *rwork, integer *lrwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int chegvx_(integer *itype, char *jobz, char *range, char *uplo, - integer *n, complex *a, integer *lda, complex *b, - integer *ldb, real *vl, real *vu, integer *il, integer *iu, - real *abstol, integer *m, real *w, complex *z__, - integer *ldz, complex *work, integer *lwork, real *rwork, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len, ftnlen uplo_len); -extern int cherfs_(char *uplo, integer *n, integer *nrhs, complex *a, - integer *lda, complex *af, integer *ldaf, integer *ipiv, - complex *b, integer *ldb, complex *x, integer *ldx, - real *ferr, real *berr, complex *work, real *rwork, - integer *info, ftnlen uplo_len); -extern int chesv_(char *uplo, integer *n, integer *nrhs, complex *a, - integer *lda, integer *ipiv, complex *b, integer *ldb, - complex *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int chesvx_(char *fact, char *uplo, integer *n, integer *nrhs, - complex *a, integer *lda, complex *af, integer *ldaf, - integer *ipiv, complex *b, integer *ldb, complex *x, - integer *ldx, real *rcond, real *ferr, real *berr, - complex *work, integer *lwork, real *rwork, integer *info, - ftnlen fact_len, ftnlen uplo_len); -extern int chetd2_(char *uplo, integer *n, complex *a, integer *lda, real *d__, - real *e, complex *tau, integer *info, ftnlen uplo_len); -extern int chetf2_(char *uplo, integer *n, complex *a, integer *lda, - integer *ipiv, integer *info, ftnlen uplo_len); -extern int chetrd_(char *uplo, integer *n, complex *a, integer *lda, real *d__, - real *e, complex *tau, complex *work, integer *lwork, - integer *info, ftnlen uplo_len); -extern int chetrf_(char *uplo, integer *n, complex *a, integer *lda, - integer *ipiv, complex *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int chetri_(char *uplo, integer *n, complex *a, integer *lda, - integer *ipiv, complex *work, integer *info, - ftnlen uplo_len); -extern int chetrs_(char *uplo, integer *n, integer *nrhs, complex *a, - integer *lda, integer *ipiv, complex *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int chgeqz_(char *job, char *compq, char *compz, integer *n, - integer *ilo, integer *ihi, complex *a, integer *lda, - complex *b, integer *ldb, complex *alpha, complex *beta, - complex *q, integer *ldq, complex *z__, integer *ldz, - complex *work, integer *lwork, real *rwork, integer *info, - ftnlen job_len, ftnlen compq_len, ftnlen compz_len); -extern int chpcon_(char *uplo, integer *n, complex *ap, integer *ipiv, - real *anorm, real *rcond, complex *work, integer *info, - ftnlen uplo_len); -extern int chpev_(char *jobz, char *uplo, integer *n, complex *ap, real *w, - complex *z__, integer *ldz, complex *work, real *rwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int chpevd_(char *jobz, char *uplo, integer *n, complex *ap, real *w, - complex *z__, integer *ldz, complex *work, integer *lwork, - real *rwork, integer *lrwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int chpevx_(char *jobz, char *range, char *uplo, integer *n, complex *ap, - real *vl, real *vu, integer *il, integer *iu, real *abstol, - integer *m, real *w, complex *z__, integer *ldz, - complex *work, real *rwork, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int chpgst_(integer *itype, char *uplo, integer *n, complex *ap, - complex *bp, integer *info, ftnlen uplo_len); -extern int chpgv_(integer *itype, char *jobz, char *uplo, integer *n, - complex *ap, complex *bp, real *w, complex *z__, integer *ldz, - complex *work, real *rwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int chpgvd_(integer *itype, char *jobz, char *uplo, integer *n, - complex *ap, complex *bp, real *w, complex *z__, - integer *ldz, complex *work, integer *lwork, real *rwork, - integer *lrwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int chpgvx_(integer *itype, char *jobz, char *range, char *uplo, - integer *n, complex *ap, complex *bp, real *vl, real *vu, - integer *il, integer *iu, real *abstol, integer *m, real *w, - complex *z__, integer *ldz, complex *work, real *rwork, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len, ftnlen uplo_len); -extern int chprfs_(char *uplo, integer *n, integer *nrhs, complex *ap, - complex *afp, integer *ipiv, complex *b, integer *ldb, - complex *x, integer *ldx, real *ferr, real *berr, - complex *work, real *rwork, integer *info, ftnlen uplo_len); -extern int chpsv_(char *uplo, integer *n, integer *nrhs, complex *ap, - integer *ipiv, complex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int chpsvx_(char *fact, char *uplo, integer *n, integer *nrhs, - complex *ap, complex *afp, integer *ipiv, complex *b, - integer *ldb, complex *x, integer *ldx, real *rcond, - real *ferr, real *berr, complex *work, real *rwork, - integer *info, ftnlen fact_len, ftnlen uplo_len); -extern int chptrd_(char *uplo, integer *n, complex *ap, real *d__, real *e, - complex *tau, integer *info, ftnlen uplo_len); -extern int chptrf_(char *uplo, integer *n, complex *ap, integer *ipiv, - integer *info, ftnlen uplo_len); -extern int chptri_(char *uplo, integer *n, complex *ap, integer *ipiv, - complex *work, integer *info, ftnlen uplo_len); -extern int chptrs_(char *uplo, integer *n, integer *nrhs, complex *ap, - integer *ipiv, complex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int chsein_(char *side, char *eigsrc, char *initv, logical *select, - integer *n, complex *h__, integer *ldh, complex *w, - complex *vl, integer *ldvl, complex *vr, integer *ldvr, - integer *mm, integer *m, complex *work, real *rwork, - integer *ifaill, integer *ifailr, integer *info, - ftnlen side_len, ftnlen eigsrc_len, ftnlen initv_len); -extern int chseqr_(char *job, char *compz, integer *n, integer *ilo, - integer *ihi, complex *h__, integer *ldh, complex *w, - complex *z__, integer *ldz, complex *work, integer *lwork, - integer *info, ftnlen job_len, ftnlen compz_len); -extern int clabrd_(integer *m, integer *n, integer *nb, complex *a, - integer *lda, real *d__, real *e, complex *tauq, - complex *taup, complex *x, integer *ldx, complex *y, - integer *ldy); -extern int clacgv_(integer *n, complex *x, integer *incx); -extern int clacon_(integer *n, complex *v, complex *x, real *est, - integer *kase); -extern int clacp2_(char *uplo, integer *m, integer *n, real *a, integer *lda, - complex *b, integer *ldb, ftnlen uplo_len); -extern int clacpy_(char *uplo, integer *m, integer *n, complex *a, integer *lda, - complex *b, integer *ldb, ftnlen uplo_len); -extern int clacrm_(integer *m, integer *n, complex *a, integer *lda, real *b, - integer *ldb, complex *c__, integer *ldc, real *rwork); -extern int clacrt_(integer *n, complex *cx, integer *incx, complex *cy, - integer *incy, complex *c__, complex *s); -extern C_f cladiv_(complex *ret_val, complex *x, complex *y); -extern int claed0_(integer *qsiz, integer *n, real *d__, real *e, complex *q, - integer *ldq, complex *qstore, integer *ldqs, real *rwork, - integer *iwork, integer *info); -extern int claed7_(integer *n, integer *cutpnt, integer *qsiz, integer *tlvls, - integer *curlvl, integer *curpbm, real *d__, complex *q, - integer *ldq, real *rho, integer *indxq, real *qstore, - integer *qptr, integer *prmptr, integer *perm, - integer *givptr, integer *givcol, real *givnum, - complex *work, real *rwork, integer *iwork, integer *info); -extern int claed8_(integer *k, integer *n, integer *qsiz, complex *q, - integer *ldq, real *d__, real *rho, integer *cutpnt, - real *z__, real *dlamda, complex *q2, integer *ldq2, real *w, - integer *indxp, integer *indx, integer *indxq, integer *perm, - integer *givptr, integer *givcol, real *givnum, - integer *info); -extern int claein_(logical *rightv, logical *noinit, integer *n, complex *h__, - integer *ldh, complex *w, complex *v, complex *b, - integer *ldb, real *rwork, real *eps3, real *smlnum, - integer *info); -extern int claesy_(complex *a, complex *b, complex *c__, complex *rt1, - complex *rt2, complex *evscal, complex *cs1, complex *sn1); -extern int claev2_(complex *a, complex *b, complex *c__, real *rt1, real *rt2, - real *cs1, complex *sn1); -extern int clags2_(logical *upper, real *a1, complex *a2, real *a3, real *b1, - complex *b2, real *b3, real *csu, complex *snu, real *csv, - complex *snv, real *csq, complex *snq); -extern int clagtm_(char *trans, integer *n, integer *nrhs, real *alpha, - complex *dl, complex *d__, complex *du, complex *x, - integer *ldx, real *beta, complex *b, integer *ldb, - ftnlen trans_len); -extern int clahef_(char *uplo, integer *n, integer *nb, integer *kb, complex *a, - integer *lda, integer *ipiv, complex *w, integer *ldw, - integer *info, ftnlen uplo_len); -extern int clahqr_(logical *wantt, logical *wantz, integer *n, integer *ilo, - integer *ihi, complex *h__, integer *ldh, complex *w, - integer *iloz, integer *ihiz, complex *z__, integer *ldz, - integer *info); -extern int clahrd_(integer *n, integer *k, integer *nb, complex *a, - integer *lda, complex *tau, complex *t, integer *ldt, - complex *y, integer *ldy); -extern int claic1_(integer *job, integer *j, complex *x, real *sest, complex *w, - complex *gamma, real *sestpr, complex *s, complex *c__); -extern int clals0_(integer *icompq, integer *nl, integer *nr, integer *sqre, - integer *nrhs, complex *b, integer *ldb, complex *bx, - integer *ldbx, integer *perm, integer *givptr, - integer *givcol, integer *ldgcol, real *givnum, - integer *ldgnum, real *poles, real *difl, real *difr, - real *z__, integer *k, real *c__, real *s, real *rwork, - integer *info); -extern int clalsa_(integer *icompq, integer *smlsiz, integer *n, integer *nrhs, - complex *b, integer *ldb, complex *bx, integer *ldbx, - real *u, integer *ldu, real *vt, integer *k, real *difl, - real *difr, real *z__, real *poles, integer *givptr, - integer *givcol, integer *ldgcol, integer *perm, - real *givnum, real *c__, real *s, real *rwork, - integer *iwork, integer *info); -extern int clalsd_(char *uplo, integer *smlsiz, integer *n, integer *nrhs, - real *d__, real *e, complex *b, integer *ldb, real *rcond, - integer *rank, complex *work, real *rwork, integer *iwork, - integer *info, ftnlen uplo_len); -extern E_f clangb_(char *norm, integer *n, integer *kl, integer *ku, - complex *ab, integer *ldab, real *work, ftnlen norm_len); -extern E_f clange_(char *norm, integer *m, integer *n, complex *a, integer *lda, - real *work, ftnlen norm_len); -extern E_f clangt_(char *norm, integer *n, complex *dl, complex *d__, - complex *du, ftnlen norm_len); -extern E_f clanhb_(char *norm, char *uplo, integer *n, integer *k, complex *ab, - integer *ldab, real *work, ftnlen norm_len, ftnlen uplo_len); -extern E_f clanhe_(char *norm, char *uplo, integer *n, complex *a, integer *lda, - real *work, ftnlen norm_len, ftnlen uplo_len); -extern E_f clanhp_(char *norm, char *uplo, integer *n, complex *ap, real *work, - ftnlen norm_len, ftnlen uplo_len); -extern E_f clanhs_(char *norm, integer *n, complex *a, integer *lda, real *work, - ftnlen norm_len); -extern E_f clanht_(char *norm, integer *n, real *d__, complex *e, - ftnlen norm_len); -extern E_f clansb_(char *norm, char *uplo, integer *n, integer *k, complex *ab, - integer *ldab, real *work, ftnlen norm_len, ftnlen uplo_len); -extern E_f clansp_(char *norm, char *uplo, integer *n, complex *ap, real *work, - ftnlen norm_len, ftnlen uplo_len); -extern E_f clansy_(char *norm, char *uplo, integer *n, complex *a, integer *lda, - real *work, ftnlen norm_len, ftnlen uplo_len); -extern E_f clantb_(char *norm, char *uplo, char *diag, integer *n, integer *k, - complex *ab, integer *ldab, real *work, ftnlen norm_len, - ftnlen uplo_len, ftnlen diag_len); -extern E_f clantp_(char *norm, char *uplo, char *diag, integer *n, complex *ap, - real *work, ftnlen norm_len, ftnlen uplo_len, - ftnlen diag_len); -extern E_f clantr_(char *norm, char *uplo, char *diag, integer *m, integer *n, - complex *a, integer *lda, real *work, ftnlen norm_len, - ftnlen uplo_len, ftnlen diag_len); -extern int clapll_(integer *n, complex *x, integer *incx, complex *y, - integer *incy, real *ssmin); -extern int clapmt_(logical *forwrd, integer *m, integer *n, complex *x, - integer *ldx, integer *k); -extern int claqgb_(integer *m, integer *n, integer *kl, integer *ku, - complex *ab, integer *ldab, real *r__, real *c__, - real *rowcnd, real *colcnd, real *amax, char *equed, - ftnlen equed_len); -extern int claqge_(integer *m, integer *n, complex *a, integer *lda, real *r__, - real *c__, real *rowcnd, real *colcnd, real *amax, - char *equed, ftnlen equed_len); -extern int claqhb_(char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, real *s, real *scond, real *amax, char *equed, - ftnlen uplo_len, ftnlen equed_len); -extern int claqhe_(char *uplo, integer *n, complex *a, integer *lda, real *s, - real *scond, real *amax, char *equed, ftnlen uplo_len, - ftnlen equed_len); -extern int claqhp_(char *uplo, integer *n, complex *ap, real *s, real *scond, - real *amax, char *equed, ftnlen uplo_len, ftnlen equed_len); -extern int claqp2_(integer *m, integer *n, integer *offset, complex *a, - integer *lda, integer *jpvt, complex *tau, real *vn1, - real *vn2, complex *work); -extern int claqps_(integer *m, integer *n, integer *offset, integer *nb, - integer *kb, complex *a, integer *lda, integer *jpvt, - complex *tau, real *vn1, real *vn2, complex *auxv, - complex *f, integer *ldf); -extern int claqsb_(char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, real *s, real *scond, real *amax, char *equed, - ftnlen uplo_len, ftnlen equed_len); -extern int claqsp_(char *uplo, integer *n, complex *ap, real *s, real *scond, - real *amax, char *equed, ftnlen uplo_len, ftnlen equed_len); -extern int claqsy_(char *uplo, integer *n, complex *a, integer *lda, real *s, - real *scond, real *amax, char *equed, ftnlen uplo_len, - ftnlen equed_len); -extern int clar1v_(integer *n, integer *b1, integer *bn, real *sigma, real *d__, - real *l, real *ld, real *lld, real *gersch, complex *z__, - real *ztz, real *mingma, integer *r__, integer *isuppz, - real *work); -extern int clar2v_(integer *n, complex *x, complex *y, complex *z__, - integer *incx, real *c__, complex *s, integer *incc); -extern int clarcm_(integer *m, integer *n, real *a, integer *lda, complex *b, - integer *ldb, complex *c__, integer *ldc, real *rwork); -extern int clarf_(char *side, integer *m, integer *n, complex *v, integer *incv, - complex *tau, complex *c__, integer *ldc, complex *work, - ftnlen side_len); -extern int clarfb_(char *side, char *trans, char *direct, char *storev, - integer *m, integer *n, integer *k, complex *v, integer *ldv, - complex *t, integer *ldt, complex *c__, integer *ldc, - complex *work, integer *ldwork, ftnlen side_len, - ftnlen trans_len, ftnlen direct_len, ftnlen storev_len); -extern int clarfg_(integer *n, complex *alpha, complex *x, integer *incx, - complex *tau); -extern int clarft_(char *direct, char *storev, integer *n, integer *k, - complex *v, integer *ldv, complex *tau, complex *t, - integer *ldt, ftnlen direct_len, ftnlen storev_len); -extern int clarfx_(char *side, integer *m, integer *n, complex *v, complex *tau, - complex *c__, integer *ldc, complex *work, ftnlen side_len); -extern int clargv_(integer *n, complex *x, integer *incx, complex *y, - integer *incy, real *c__, integer *incc); -extern int clarnv_(integer *idist, integer *iseed, integer *n, complex *x); -extern int clarrv_(integer *n, real *d__, real *l, integer *isplit, integer *m, - real *w, integer *iblock, real *gersch, real *tol, - complex *z__, integer *ldz, integer *isuppz, real *work, - integer *iwork, integer *info); -extern int clartg_(complex *f, complex *g, real *cs, complex *sn, complex *r__); -extern int clartv_(integer *n, complex *x, integer *incx, complex *y, - integer *incy, real *c__, complex *s, integer *incc); -extern int clarz_(char *side, integer *m, integer *n, integer *l, complex *v, - integer *incv, complex *tau, complex *c__, integer *ldc, - complex *work, ftnlen side_len); -extern int clarzb_(char *side, char *trans, char *direct, char *storev, - integer *m, integer *n, integer *k, integer *l, complex *v, - integer *ldv, complex *t, integer *ldt, complex *c__, - integer *ldc, complex *work, integer *ldwork, - ftnlen side_len, ftnlen trans_len, ftnlen direct_len, - ftnlen storev_len); -extern int clarzt_(char *direct, char *storev, integer *n, integer *k, - complex *v, integer *ldv, complex *tau, complex *t, - integer *ldt, ftnlen direct_len, ftnlen storev_len); -extern int clascl_(char *type__, integer *kl, integer *ku, real *cfrom, - real *cto, integer *m, integer *n, complex *a, integer *lda, - integer *info, ftnlen type_len); -extern int claset_(char *uplo, integer *m, integer *n, complex *alpha, - complex *beta, complex *a, integer *lda, ftnlen uplo_len); -extern int clasr_(char *side, char *pivot, char *direct, integer *m, integer *n, - real *c__, real *s, complex *a, integer *lda, ftnlen side_len, - ftnlen pivot_len, ftnlen direct_len); -extern int classq_(integer *n, complex *x, integer *incx, real *scale, - real *sumsq); -extern int claswp_(integer *n, complex *a, integer *lda, integer *k1, - integer *k2, integer *ipiv, integer *incx); -extern int clasyf_(char *uplo, integer *n, integer *nb, integer *kb, complex *a, - integer *lda, integer *ipiv, complex *w, integer *ldw, - integer *info, ftnlen uplo_len); -extern int clatbs_(char *uplo, char *trans, char *diag, char *normin, - integer *n, integer *kd, complex *ab, integer *ldab, - complex *x, real *scale, real *cnorm, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len, - ftnlen normin_len); -extern int clatdf_(integer *ijob, integer *n, complex *z__, integer *ldz, - complex *rhs, real *rdsum, real *rdscal, integer *ipiv, - integer *jpiv); -extern int clatps_(char *uplo, char *trans, char *diag, char *normin, - integer *n, complex *ap, complex *x, real *scale, - real *cnorm, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len, ftnlen normin_len); -extern int clatrd_(char *uplo, integer *n, integer *nb, complex *a, - integer *lda, real *e, complex *tau, complex *w, - integer *ldw, ftnlen uplo_len); -extern int clatrs_(char *uplo, char *trans, char *diag, char *normin, - integer *n, complex *a, integer *lda, complex *x, - real *scale, real *cnorm, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len, ftnlen normin_len); -extern int clatrz_(integer *m, integer *n, integer *l, complex *a, integer *lda, - complex *tau, complex *work); -extern int clatzm_(char *side, integer *m, integer *n, complex *v, - integer *incv, complex *tau, complex *c1, complex *c2, - integer *ldc, complex *work, ftnlen side_len); -extern int clauu2_(char *uplo, integer *n, complex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int clauum_(char *uplo, integer *n, complex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int cpbcon_(char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, real *anorm, real *rcond, complex *work, - real *rwork, integer *info, ftnlen uplo_len); -extern int cpbequ_(char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, real *s, real *scond, real *amax, - integer *info, ftnlen uplo_len); -extern int cpbrfs_(char *uplo, integer *n, integer *kd, integer *nrhs, - complex *ab, integer *ldab, complex *afb, integer *ldafb, - complex *b, integer *ldb, complex *x, integer *ldx, - real *ferr, real *berr, complex *work, real *rwork, - integer *info, ftnlen uplo_len); -extern int cpbstf_(char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, integer *info, ftnlen uplo_len); -extern int cpbsv_(char *uplo, integer *n, integer *kd, integer *nrhs, - complex *ab, integer *ldab, complex *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int cpbsvx_(char *fact, char *uplo, integer *n, integer *kd, - integer *nrhs, complex *ab, integer *ldab, complex *afb, - integer *ldafb, char *equed, real *s, complex *b, - integer *ldb, complex *x, integer *ldx, real *rcond, - real *ferr, real *berr, complex *work, real *rwork, - integer *info, ftnlen fact_len, ftnlen uplo_len, - ftnlen equed_len); -extern int cpbtf2_(char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, integer *info, ftnlen uplo_len); -extern int cpbtrf_(char *uplo, integer *n, integer *kd, complex *ab, - integer *ldab, integer *info, ftnlen uplo_len); -extern int cpbtrs_(char *uplo, integer *n, integer *kd, integer *nrhs, - complex *ab, integer *ldab, complex *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int cpocon_(char *uplo, integer *n, complex *a, integer *lda, - real *anorm, real *rcond, complex *work, real *rwork, - integer *info, ftnlen uplo_len); -extern int cpoequ_(integer *n, complex *a, integer *lda, real *s, real *scond, - real *amax, integer *info); -extern int cporfs_(char *uplo, integer *n, integer *nrhs, complex *a, - integer *lda, complex *af, integer *ldaf, complex *b, - integer *ldb, complex *x, integer *ldx, real *ferr, - real *berr, complex *work, real *rwork, integer *info, - ftnlen uplo_len); -extern int cposv_(char *uplo, integer *n, integer *nrhs, complex *a, - integer *lda, complex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int cposvx_(char *fact, char *uplo, integer *n, integer *nrhs, - complex *a, integer *lda, complex *af, integer *ldaf, - char *equed, real *s, complex *b, integer *ldb, complex *x, - integer *ldx, real *rcond, real *ferr, real *berr, - complex *work, real *rwork, integer *info, ftnlen fact_len, - ftnlen uplo_len, ftnlen equed_len); -extern int cpotf2_(char *uplo, integer *n, complex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int cpotrf_(char *uplo, integer *n, complex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int cpotri_(char *uplo, integer *n, complex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int cpotrs_(char *uplo, integer *n, integer *nrhs, complex *a, - integer *lda, complex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int cppcon_(char *uplo, integer *n, complex *ap, real *anorm, - real *rcond, complex *work, real *rwork, integer *info, - ftnlen uplo_len); -extern int cppequ_(char *uplo, integer *n, complex *ap, real *s, real *scond, - real *amax, integer *info, ftnlen uplo_len); -extern int cpprfs_(char *uplo, integer *n, integer *nrhs, complex *ap, - complex *afp, complex *b, integer *ldb, complex *x, - integer *ldx, real *ferr, real *berr, complex *work, - real *rwork, integer *info, ftnlen uplo_len); -extern int cppsv_(char *uplo, integer *n, integer *nrhs, complex *ap, - complex *b, integer *ldb, integer *info, ftnlen uplo_len); -extern int cppsvx_(char *fact, char *uplo, integer *n, integer *nrhs, - complex *ap, complex *afp, char *equed, real *s, complex *b, - integer *ldb, complex *x, integer *ldx, real *rcond, - real *ferr, real *berr, complex *work, real *rwork, - integer *info, ftnlen fact_len, ftnlen uplo_len, - ftnlen equed_len); -extern int cpptrf_(char *uplo, integer *n, complex *ap, integer *info, - ftnlen uplo_len); -extern int cpptri_(char *uplo, integer *n, complex *ap, integer *info, - ftnlen uplo_len); -extern int cpptrs_(char *uplo, integer *n, integer *nrhs, complex *ap, - complex *b, integer *ldb, integer *info, ftnlen uplo_len); -extern int cptcon_(integer *n, real *d__, complex *e, real *anorm, real *rcond, - real *rwork, integer *info); -extern int cpteqr_(char *compz, integer *n, real *d__, real *e, complex *z__, - integer *ldz, real *work, integer *info, ftnlen compz_len); -extern int cptrfs_(char *uplo, integer *n, integer *nrhs, real *d__, complex *e, - real *df, complex *ef, complex *b, integer *ldb, complex *x, - integer *ldx, real *ferr, real *berr, complex *work, - real *rwork, integer *info, ftnlen uplo_len); -extern int cptsv_(integer *n, integer *nrhs, real *d__, complex *e, complex *b, - integer *ldb, integer *info); -extern int cptsvx_(char *fact, integer *n, integer *nrhs, real *d__, complex *e, - real *df, complex *ef, complex *b, integer *ldb, complex *x, - integer *ldx, real *rcond, real *ferr, real *berr, - complex *work, real *rwork, integer *info, ftnlen fact_len); -extern int cpttrf_(integer *n, real *d__, complex *e, integer *info); -extern int cpttrs_(char *uplo, integer *n, integer *nrhs, real *d__, complex *e, - complex *b, integer *ldb, integer *info, ftnlen uplo_len); -extern int cptts2_(integer *iuplo, integer *n, integer *nrhs, real *d__, - complex *e, complex *b, integer *ldb); -extern int crot_(integer *n, complex *cx, integer *incx, complex *cy, - integer *incy, real *c__, complex *s); -extern int cspcon_(char *uplo, integer *n, complex *ap, integer *ipiv, - real *anorm, real *rcond, complex *work, integer *info, - ftnlen uplo_len); -extern int cspmv_(char *uplo, integer *n, complex *alpha, complex *ap, - complex *x, integer *incx, complex *beta, complex *y, - integer *incy, ftnlen uplo_len); -extern int cspr_(char *uplo, integer *n, complex *alpha, complex *x, - integer *incx, complex *ap, ftnlen uplo_len); -extern int csprfs_(char *uplo, integer *n, integer *nrhs, complex *ap, - complex *afp, integer *ipiv, complex *b, integer *ldb, - complex *x, integer *ldx, real *ferr, real *berr, - complex *work, real *rwork, integer *info, ftnlen uplo_len); -extern int cspsv_(char *uplo, integer *n, integer *nrhs, complex *ap, - integer *ipiv, complex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int cspsvx_(char *fact, char *uplo, integer *n, integer *nrhs, - complex *ap, complex *afp, integer *ipiv, complex *b, - integer *ldb, complex *x, integer *ldx, real *rcond, - real *ferr, real *berr, complex *work, real *rwork, - integer *info, ftnlen fact_len, ftnlen uplo_len); -extern int csptrf_(char *uplo, integer *n, complex *ap, integer *ipiv, - integer *info, ftnlen uplo_len); -extern int csptri_(char *uplo, integer *n, complex *ap, integer *ipiv, - complex *work, integer *info, ftnlen uplo_len); -extern int csptrs_(char *uplo, integer *n, integer *nrhs, complex *ap, - integer *ipiv, complex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int csrot_(integer *n, complex *cx, integer *incx, complex *cy, - integer *incy, real *c__, real *s); -extern int csrscl_(integer *n, real *sa, complex *sx, integer *incx); -extern int cstedc_(char *compz, integer *n, real *d__, real *e, complex *z__, - integer *ldz, complex *work, integer *lwork, real *rwork, - integer *lrwork, integer *iwork, integer *liwork, - integer *info, ftnlen compz_len); -extern int cstegr_(char *jobz, char *range, integer *n, real *d__, real *e, - real *vl, real *vu, integer *il, integer *iu, real *abstol, - integer *m, real *w, complex *z__, integer *ldz, - integer *isuppz, real *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen range_len); -extern int cstein_(integer *n, real *d__, real *e, integer *m, real *w, - integer *iblock, integer *isplit, complex *z__, integer *ldz, - real *work, integer *iwork, integer *ifail, integer *info); -extern int csteqr_(char *compz, integer *n, real *d__, real *e, complex *z__, - integer *ldz, real *work, integer *info, ftnlen compz_len); -extern int csycon_(char *uplo, integer *n, complex *a, integer *lda, - integer *ipiv, real *anorm, real *rcond, complex *work, - integer *info, ftnlen uplo_len); -extern int csymv_(char *uplo, integer *n, complex *alpha, complex *a, - integer *lda, complex *x, integer *incx, complex *beta, - complex *y, integer *incy, ftnlen uplo_len); -extern int csyr_(char *uplo, integer *n, complex *alpha, complex *x, - integer *incx, complex *a, integer *lda, ftnlen uplo_len); -extern int csyrfs_(char *uplo, integer *n, integer *nrhs, complex *a, - integer *lda, complex *af, integer *ldaf, integer *ipiv, - complex *b, integer *ldb, complex *x, integer *ldx, - real *ferr, real *berr, complex *work, real *rwork, - integer *info, ftnlen uplo_len); -extern int csysv_(char *uplo, integer *n, integer *nrhs, complex *a, - integer *lda, integer *ipiv, complex *b, integer *ldb, - complex *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int csysvx_(char *fact, char *uplo, integer *n, integer *nrhs, - complex *a, integer *lda, complex *af, integer *ldaf, - integer *ipiv, complex *b, integer *ldb, complex *x, - integer *ldx, real *rcond, real *ferr, real *berr, - complex *work, integer *lwork, real *rwork, integer *info, - ftnlen fact_len, ftnlen uplo_len); -extern int csytf2_(char *uplo, integer *n, complex *a, integer *lda, - integer *ipiv, integer *info, ftnlen uplo_len); -extern int csytrf_(char *uplo, integer *n, complex *a, integer *lda, - integer *ipiv, complex *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int csytri_(char *uplo, integer *n, complex *a, integer *lda, - integer *ipiv, complex *work, integer *info, - ftnlen uplo_len); -extern int csytrs_(char *uplo, integer *n, integer *nrhs, complex *a, - integer *lda, integer *ipiv, complex *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int ctbcon_(char *norm, char *uplo, char *diag, integer *n, integer *kd, - complex *ab, integer *ldab, real *rcond, complex *work, - real *rwork, integer *info, ftnlen norm_len, ftnlen uplo_len, - ftnlen diag_len); -extern int ctbrfs_(char *uplo, char *trans, char *diag, integer *n, integer *kd, - integer *nrhs, complex *ab, integer *ldab, complex *b, - integer *ldb, complex *x, integer *ldx, real *ferr, - real *berr, complex *work, real *rwork, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ctbtrs_(char *uplo, char *trans, char *diag, integer *n, integer *kd, - integer *nrhs, complex *ab, integer *ldab, complex *b, - integer *ldb, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int ctgevc_(char *side, char *howmny, logical *select, integer *n, - complex *a, integer *lda, complex *b, integer *ldb, - complex *vl, integer *ldvl, complex *vr, integer *ldvr, - integer *mm, integer *m, complex *work, real *rwork, - integer *info, ftnlen side_len, ftnlen howmny_len); -extern int ctgex2_(logical *wantq, logical *wantz, integer *n, complex *a, - integer *lda, complex *b, integer *ldb, complex *q, - integer *ldq, complex *z__, integer *ldz, integer *j1, - integer *info); -extern int ctgexc_(logical *wantq, logical *wantz, integer *n, complex *a, - integer *lda, complex *b, integer *ldb, complex *q, - integer *ldq, complex *z__, integer *ldz, integer *ifst, - integer *ilst, integer *info); -extern int ctgsen_(integer *ijob, logical *wantq, logical *wantz, - logical *select, integer *n, complex *a, integer *lda, - complex *b, integer *ldb, complex *alpha, complex *beta, - complex *q, integer *ldq, complex *z__, integer *ldz, - integer *m, real *pl, real *pr, real *dif, complex *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info); -extern int ctgsja_(char *jobu, char *jobv, char *jobq, integer *m, integer *p, - integer *n, integer *k, integer *l, complex *a, integer *lda, - complex *b, integer *ldb, real *tola, real *tolb, - real *alpha, real *beta, complex *u, integer *ldu, - complex *v, integer *ldv, complex *q, integer *ldq, - complex *work, integer *ncycle, integer *info, - ftnlen jobu_len, ftnlen jobv_len, ftnlen jobq_len); -extern int ctgsna_(char *job, char *howmny, logical *select, integer *n, - complex *a, integer *lda, complex *b, integer *ldb, - complex *vl, integer *ldvl, complex *vr, integer *ldvr, - real *s, real *dif, integer *mm, integer *m, complex *work, - integer *lwork, integer *iwork, integer *info, - ftnlen job_len, ftnlen howmny_len); -extern int ctgsy2_(char *trans, integer *ijob, integer *m, integer *n, - complex *a, integer *lda, complex *b, integer *ldb, - complex *c__, integer *ldc, complex *d__, integer *ldd, - complex *e, integer *lde, complex *f, integer *ldf, - real *scale, real *rdsum, real *rdscal, integer *info, - ftnlen trans_len); -extern int ctgsyl_(char *trans, integer *ijob, integer *m, integer *n, - complex *a, integer *lda, complex *b, integer *ldb, - complex *c__, integer *ldc, complex *d__, integer *ldd, - complex *e, integer *lde, complex *f, integer *ldf, - real *scale, real *dif, complex *work, integer *lwork, - integer *iwork, integer *info, ftnlen trans_len); -extern int ctpcon_(char *norm, char *uplo, char *diag, integer *n, complex *ap, - real *rcond, complex *work, real *rwork, integer *info, - ftnlen norm_len, ftnlen uplo_len, ftnlen diag_len); -extern int ctprfs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, complex *ap, complex *b, integer *ldb, - complex *x, integer *ldx, real *ferr, real *berr, - complex *work, real *rwork, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int ctptri_(char *uplo, char *diag, integer *n, complex *ap, - integer *info, ftnlen uplo_len, ftnlen diag_len); -extern int ctptrs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, complex *ap, complex *b, integer *ldb, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int ctrcon_(char *norm, char *uplo, char *diag, integer *n, complex *a, - integer *lda, real *rcond, complex *work, real *rwork, - integer *info, ftnlen norm_len, ftnlen uplo_len, - ftnlen diag_len); -extern int ctrevc_(char *side, char *howmny, logical *select, integer *n, - complex *t, integer *ldt, complex *vl, integer *ldvl, - complex *vr, integer *ldvr, integer *mm, integer *m, - complex *work, real *rwork, integer *info, ftnlen side_len, - ftnlen howmny_len); -extern int ctrexc_(char *compq, integer *n, complex *t, integer *ldt, - complex *q, integer *ldq, integer *ifst, integer *ilst, - integer *info, ftnlen compq_len); -extern int ctrrfs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, complex *a, integer *lda, complex *b, - integer *ldb, complex *x, integer *ldx, real *ferr, - real *berr, complex *work, real *rwork, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ctrsen_(char *job, char *compq, logical *select, integer *n, - complex *t, integer *ldt, complex *q, integer *ldq, - complex *w, integer *m, real *s, real *sep, complex *work, - integer *lwork, integer *info, ftnlen job_len, - ftnlen compq_len); -extern int ctrsna_(char *job, char *howmny, logical *select, integer *n, - complex *t, integer *ldt, complex *vl, integer *ldvl, - complex *vr, integer *ldvr, real *s, real *sep, integer *mm, - integer *m, complex *work, integer *ldwork, real *rwork, - integer *info, ftnlen job_len, ftnlen howmny_len); -extern int ctrsyl_(char *trana, char *tranb, integer *isgn, integer *m, - integer *n, complex *a, integer *lda, complex *b, - integer *ldb, complex *c__, integer *ldc, real *scale, - integer *info, ftnlen trana_len, ftnlen tranb_len); -extern int ctrti2_(char *uplo, char *diag, integer *n, complex *a, integer *lda, - integer *info, ftnlen uplo_len, ftnlen diag_len); -extern int ctrtri_(char *uplo, char *diag, integer *n, complex *a, integer *lda, - integer *info, ftnlen uplo_len, ftnlen diag_len); -extern int ctrtrs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, complex *a, integer *lda, complex *b, - integer *ldb, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int ctzrqf_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, integer *info); -extern int ctzrzf_(integer *m, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info); -extern int cung2l_(integer *m, integer *n, integer *k, complex *a, integer *lda, - complex *tau, complex *work, integer *info); -extern int cung2r_(integer *m, integer *n, integer *k, complex *a, integer *lda, - complex *tau, complex *work, integer *info); -extern int cungbr_(char *vect, integer *m, integer *n, integer *k, complex *a, - integer *lda, complex *tau, complex *work, integer *lwork, - integer *info, ftnlen vect_len); -extern int cunghr_(integer *n, integer *ilo, integer *ihi, complex *a, - integer *lda, complex *tau, complex *work, integer *lwork, - integer *info); -extern int cungl2_(integer *m, integer *n, integer *k, complex *a, integer *lda, - complex *tau, complex *work, integer *info); -extern int cunglq_(integer *m, integer *n, integer *k, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info); -extern int cungql_(integer *m, integer *n, integer *k, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info); -extern int cungqr_(integer *m, integer *n, integer *k, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info); -extern int cungr2_(integer *m, integer *n, integer *k, complex *a, integer *lda, - complex *tau, complex *work, integer *info); -extern int cungrq_(integer *m, integer *n, integer *k, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info); -extern int cungtr_(char *uplo, integer *n, complex *a, integer *lda, - complex *tau, complex *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int cunm2l_(char *side, char *trans, integer *m, integer *n, integer *k, - complex *a, integer *lda, complex *tau, complex *c__, - integer *ldc, complex *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int cunm2r_(char *side, char *trans, integer *m, integer *n, integer *k, - complex *a, integer *lda, complex *tau, complex *c__, - integer *ldc, complex *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int cunmbr_(char *vect, char *side, char *trans, integer *m, integer *n, - integer *k, complex *a, integer *lda, complex *tau, - complex *c__, integer *ldc, complex *work, integer *lwork, - integer *info, ftnlen vect_len, ftnlen side_len, - ftnlen trans_len); -extern int cunmhr_(char *side, char *trans, integer *m, integer *n, - integer *ilo, integer *ihi, complex *a, integer *lda, - complex *tau, complex *c__, integer *ldc, complex *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int cunml2_(char *side, char *trans, integer *m, integer *n, integer *k, - complex *a, integer *lda, complex *tau, complex *c__, - integer *ldc, complex *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int cunmlq_(char *side, char *trans, integer *m, integer *n, integer *k, - complex *a, integer *lda, complex *tau, complex *c__, - integer *ldc, complex *work, integer *lwork, integer *info, - ftnlen side_len, ftnlen trans_len); -extern int cunmql_(char *side, char *trans, integer *m, integer *n, integer *k, - complex *a, integer *lda, complex *tau, complex *c__, - integer *ldc, complex *work, integer *lwork, integer *info, - ftnlen side_len, ftnlen trans_len); -extern int cunmqr_(char *side, char *trans, integer *m, integer *n, integer *k, - complex *a, integer *lda, complex *tau, complex *c__, - integer *ldc, complex *work, integer *lwork, integer *info, - ftnlen side_len, ftnlen trans_len); -extern int cunmr2_(char *side, char *trans, integer *m, integer *n, integer *k, - complex *a, integer *lda, complex *tau, complex *c__, - integer *ldc, complex *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int cunmr3_(char *side, char *trans, integer *m, integer *n, integer *k, - integer *l, complex *a, integer *lda, complex *tau, - complex *c__, integer *ldc, complex *work, integer *info, - ftnlen side_len, ftnlen trans_len); -extern int cunmrq_(char *side, char *trans, integer *m, integer *n, integer *k, - complex *a, integer *lda, complex *tau, complex *c__, - integer *ldc, complex *work, integer *lwork, integer *info, - ftnlen side_len, ftnlen trans_len); -extern int cunmrz_(char *side, char *trans, integer *m, integer *n, integer *k, - integer *l, complex *a, integer *lda, complex *tau, - complex *c__, integer *ldc, complex *work, integer *lwork, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int cunmtr_(char *side, char *uplo, char *trans, integer *m, integer *n, - complex *a, integer *lda, complex *tau, complex *c__, - integer *ldc, complex *work, integer *lwork, integer *info, - ftnlen side_len, ftnlen uplo_len, ftnlen trans_len); -extern int cupgtr_(char *uplo, integer *n, complex *ap, complex *tau, - complex *q, integer *ldq, complex *work, integer *info, - ftnlen uplo_len); -extern int cupmtr_(char *side, char *uplo, char *trans, integer *m, integer *n, - complex *ap, complex *tau, complex *c__, integer *ldc, - complex *work, integer *info, ftnlen side_len, - ftnlen uplo_len, ftnlen trans_len); -extern int dbdsdc_(char *uplo, char *compq, integer *n, doublereal *d__, - doublereal *e, doublereal *u, integer *ldu, doublereal *vt, - integer *ldvt, doublereal *q, integer *iq, doublereal *work, - integer *iwork, integer *info, ftnlen uplo_len, - ftnlen compq_len); -extern int dbdsqr_(char *uplo, integer *n, integer *ncvt, integer *nru, - integer *ncc, doublereal *d__, doublereal *e, doublereal *vt, - integer *ldvt, doublereal *u, integer *ldu, doublereal *c__, - integer *ldc, doublereal *work, integer *info, - ftnlen uplo_len); -extern int ddisna_(char *job, integer *m, integer *n, doublereal *d__, - doublereal *sep, integer *info, ftnlen job_len); -extern int dgbbrd_(char *vect, integer *m, integer *n, integer *ncc, - integer *kl, integer *ku, doublereal *ab, integer *ldab, - doublereal *d__, doublereal *e, doublereal *q, integer *ldq, - doublereal *pt, integer *ldpt, doublereal *c__, integer *ldc, - doublereal *work, integer *info, ftnlen vect_len); -extern int dgbcon_(char *norm, integer *n, integer *kl, integer *ku, - doublereal *ab, integer *ldab, integer *ipiv, - doublereal *anorm, doublereal *rcond, doublereal *work, - integer *iwork, integer *info, ftnlen norm_len); -extern int dgbequ_(integer *m, integer *n, integer *kl, integer *ku, - doublereal *ab, integer *ldab, doublereal *r__, - doublereal *c__, doublereal *rowcnd, doublereal *colcnd, - doublereal *amax, integer *info); -extern int dgbrfs_(char *trans, integer *n, integer *kl, integer *ku, - integer *nrhs, doublereal *ab, integer *ldab, - doublereal *afb, integer *ldafb, integer *ipiv, - doublereal *b, integer *ldb, doublereal *x, integer *ldx, - doublereal *ferr, doublereal *berr, doublereal *work, - integer *iwork, integer *info, ftnlen trans_len); -extern int dgbsv_(integer *n, integer *kl, integer *ku, integer *nrhs, - doublereal *ab, integer *ldab, integer *ipiv, doublereal *b, - integer *ldb, integer *info); -extern int dgbsvx_(char *fact, char *trans, integer *n, integer *kl, - integer *ku, integer *nrhs, doublereal *ab, integer *ldab, - doublereal *afb, integer *ldafb, integer *ipiv, char *equed, - doublereal *r__, doublereal *c__, doublereal *b, - integer *ldb, doublereal *x, integer *ldx, doublereal *rcond, - doublereal *ferr, doublereal *berr, doublereal *work, - integer *iwork, integer *info, ftnlen fact_len, - ftnlen trans_len, ftnlen equed_len); -extern int dgbtf2_(integer *m, integer *n, integer *kl, integer *ku, - doublereal *ab, integer *ldab, integer *ipiv, integer *info); -extern int dgbtrf_(integer *m, integer *n, integer *kl, integer *ku, - doublereal *ab, integer *ldab, integer *ipiv, integer *info); -extern int dgbtrs_(char *trans, integer *n, integer *kl, integer *ku, - integer *nrhs, doublereal *ab, integer *ldab, integer *ipiv, - doublereal *b, integer *ldb, integer *info, - ftnlen trans_len); -extern int dgebak_(char *job, char *side, integer *n, integer *ilo, - integer *ihi, doublereal *scale, integer *m, doublereal *v, - integer *ldv, integer *info, ftnlen job_len, - ftnlen side_len); -extern int dgebal_(char *job, integer *n, doublereal *a, integer *lda, - integer *ilo, integer *ihi, doublereal *scale, integer *info, - ftnlen job_len); -extern int dgebd2_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *d__, doublereal *e, doublereal *tauq, - doublereal *taup, doublereal *work, integer *info); -extern int dgebrd_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *d__, doublereal *e, doublereal *tauq, - doublereal *taup, doublereal *work, integer *lwork, - integer *info); -extern int dgecon_(char *norm, integer *n, doublereal *a, integer *lda, - doublereal *anorm, doublereal *rcond, doublereal *work, - integer *iwork, integer *info, ftnlen norm_len); -extern int dgeequ_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *r__, doublereal *c__, doublereal *rowcnd, - doublereal *colcnd, doublereal *amax, integer *info); -extern int dgees_(char *jobvs, char *sort, L_fp select, integer *n, - doublereal *a, integer *lda, integer *sdim, doublereal *wr, - doublereal *wi, doublereal *vs, integer *ldvs, - doublereal *work, integer *lwork, logical *bwork, - integer *info, ftnlen jobvs_len, ftnlen sort_len); -extern int dgeesx_(char *jobvs, char *sort, L_fp select, char *sense, - integer *n, doublereal *a, integer *lda, integer *sdim, - doublereal *wr, doublereal *wi, doublereal *vs, - integer *ldvs, doublereal *rconde, doublereal *rcondv, - doublereal *work, integer *lwork, integer *iwork, - integer *liwork, logical *bwork, integer *info, - ftnlen jobvs_len, ftnlen sort_len, ftnlen sense_len); -extern int dgeev_(char *jobvl, char *jobvr, integer *n, doublereal *a, - integer *lda, doublereal *wr, doublereal *wi, doublereal *vl, - integer *ldvl, doublereal *vr, integer *ldvr, - doublereal *work, integer *lwork, integer *info, - ftnlen jobvl_len, ftnlen jobvr_len); -extern int dgeevx_(char *balanc, char *jobvl, char *jobvr, char *sense, - integer *n, doublereal *a, integer *lda, doublereal *wr, - doublereal *wi, doublereal *vl, integer *ldvl, - doublereal *vr, integer *ldvr, integer *ilo, integer *ihi, - doublereal *scale, doublereal *abnrm, doublereal *rconde, - doublereal *rcondv, doublereal *work, integer *lwork, - integer *iwork, integer *info, ftnlen balanc_len, - ftnlen jobvl_len, ftnlen jobvr_len, ftnlen sense_len); -extern int dgegs_(char *jobvsl, char *jobvsr, integer *n, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *alphar, - doublereal *alphai, doublereal *beta, doublereal *vsl, - integer *ldvsl, doublereal *vsr, integer *ldvsr, - doublereal *work, integer *lwork, integer *info, - ftnlen jobvsl_len, ftnlen jobvsr_len); -extern int dgegv_(char *jobvl, char *jobvr, integer *n, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *alphar, - doublereal *alphai, doublereal *beta, doublereal *vl, - integer *ldvl, doublereal *vr, integer *ldvr, - doublereal *work, integer *lwork, integer *info, - ftnlen jobvl_len, ftnlen jobvr_len); -extern int dgehd2_(integer *n, integer *ilo, integer *ihi, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *info); -extern int dgehrd_(integer *n, integer *ilo, integer *ihi, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *lwork, integer *info); -extern int dgelq2_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *info); -extern int dgelqf_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *lwork, - integer *info); -extern int dgels_(char *trans, integer *m, integer *n, integer *nrhs, - doublereal *a, integer *lda, doublereal *b, integer *ldb, - doublereal *work, integer *lwork, integer *info, - ftnlen trans_len); -extern int dgelsd_(integer *m, integer *n, integer *nrhs, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *s, - doublereal *rcond, integer *rank, doublereal *work, - integer *lwork, integer *iwork, integer *info); -extern int dgelss_(integer *m, integer *n, integer *nrhs, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *s, - doublereal *rcond, integer *rank, doublereal *work, - integer *lwork, integer *info); -extern int dgelsx_(integer *m, integer *n, integer *nrhs, doublereal *a, - integer *lda, doublereal *b, integer *ldb, integer *jpvt, - doublereal *rcond, integer *rank, doublereal *work, - integer *info); -extern int dgelsy_(integer *m, integer *n, integer *nrhs, doublereal *a, - integer *lda, doublereal *b, integer *ldb, integer *jpvt, - doublereal *rcond, integer *rank, doublereal *work, - integer *lwork, integer *info); -extern int dgeql2_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *info); -extern int dgeqlf_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *lwork, - integer *info); -extern int dgeqp3_(integer *m, integer *n, doublereal *a, integer *lda, - integer *jpvt, doublereal *tau, doublereal *work, - integer *lwork, integer *info); -extern int dgeqpf_(integer *m, integer *n, doublereal *a, integer *lda, - integer *jpvt, doublereal *tau, doublereal *work, - integer *info); -extern int dgeqr2_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *info); -extern int dgeqrf_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *lwork, - integer *info); -extern int dgerfs_(char *trans, integer *n, integer *nrhs, doublereal *a, - integer *lda, doublereal *af, integer *ldaf, integer *ipiv, - doublereal *b, integer *ldb, doublereal *x, integer *ldx, - doublereal *ferr, doublereal *berr, doublereal *work, - integer *iwork, integer *info, ftnlen trans_len); -extern int dgerq2_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *info); -extern int dgerqf_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *lwork, - integer *info); -extern int dgesc2_(integer *n, doublereal *a, integer *lda, doublereal *rhs, - integer *ipiv, integer *jpiv, doublereal *scale); -extern int dgesdd_(char *jobz, integer *m, integer *n, doublereal *a, - integer *lda, doublereal *s, doublereal *u, integer *ldu, - doublereal *vt, integer *ldvt, doublereal *work, - integer *lwork, integer *iwork, integer *info, - ftnlen jobz_len); -extern int dgesv_(integer *n, integer *nrhs, doublereal *a, integer *lda, - integer *ipiv, doublereal *b, integer *ldb, integer *info); -extern int dgesvd_(char *jobu, char *jobvt, integer *m, integer *n, - doublereal *a, integer *lda, doublereal *s, doublereal *u, - integer *ldu, doublereal *vt, integer *ldvt, - doublereal *work, integer *lwork, integer *info, - ftnlen jobu_len, ftnlen jobvt_len); -extern int dgesvx_(char *fact, char *trans, integer *n, integer *nrhs, - doublereal *a, integer *lda, doublereal *af, integer *ldaf, - integer *ipiv, char *equed, doublereal *r__, doublereal *c__, - doublereal *b, integer *ldb, doublereal *x, integer *ldx, - doublereal *rcond, doublereal *ferr, doublereal *berr, - doublereal *work, integer *iwork, integer *info, - ftnlen fact_len, ftnlen trans_len, ftnlen equed_len); -extern int dgetc2_(integer *n, doublereal *a, integer *lda, integer *ipiv, - integer *jpiv, integer *info); -extern int dgetf2_(integer *m, integer *n, doublereal *a, integer *lda, - integer *ipiv, integer *info); -extern int dgetrf_(integer *m, integer *n, doublereal *a, integer *lda, - integer *ipiv, integer *info); -extern int dgetri_(integer *n, doublereal *a, integer *lda, integer *ipiv, - doublereal *work, integer *lwork, integer *info); -extern int dgetrs_(char *trans, integer *n, integer *nrhs, doublereal *a, - integer *lda, integer *ipiv, doublereal *b, integer *ldb, - integer *info, ftnlen trans_len); -extern int dggbak_(char *job, char *side, integer *n, integer *ilo, - integer *ihi, doublereal *lscale, doublereal *rscale, - integer *m, doublereal *v, integer *ldv, integer *info, - ftnlen job_len, ftnlen side_len); -extern int dggbal_(char *job, integer *n, doublereal *a, integer *lda, - doublereal *b, integer *ldb, integer *ilo, integer *ihi, - doublereal *lscale, doublereal *rscale, doublereal *work, - integer *info, ftnlen job_len); -extern int dgges_(char *jobvsl, char *jobvsr, char *sort, L_fp delctg, - integer *n, doublereal *a, integer *lda, doublereal *b, - integer *ldb, integer *sdim, doublereal *alphar, - doublereal *alphai, doublereal *beta, doublereal *vsl, - integer *ldvsl, doublereal *vsr, integer *ldvsr, - doublereal *work, integer *lwork, logical *bwork, - integer *info, ftnlen jobvsl_len, ftnlen jobvsr_len, - ftnlen sort_len); -extern int dggesx_(char *jobvsl, char *jobvsr, char *sort, L_fp delctg, - char *sense, integer *n, doublereal *a, integer *lda, - doublereal *b, integer *ldb, integer *sdim, - doublereal *alphar, doublereal *alphai, doublereal *beta, - doublereal *vsl, integer *ldvsl, doublereal *vsr, - integer *ldvsr, doublereal *rconde, doublereal *rcondv, - doublereal *work, integer *lwork, integer *iwork, - integer *liwork, logical *bwork, integer *info, - ftnlen jobvsl_len, ftnlen jobvsr_len, ftnlen sort_len, - ftnlen sense_len); -extern int dggev_(char *jobvl, char *jobvr, integer *n, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *alphar, - doublereal *alphai, doublereal *beta, doublereal *vl, - integer *ldvl, doublereal *vr, integer *ldvr, - doublereal *work, integer *lwork, integer *info, - ftnlen jobvl_len, ftnlen jobvr_len); -extern int dggevx_(char *balanc, char *jobvl, char *jobvr, char *sense, - integer *n, doublereal *a, integer *lda, doublereal *b, - integer *ldb, doublereal *alphar, doublereal *alphai, - doublereal *beta, doublereal *vl, integer *ldvl, - doublereal *vr, integer *ldvr, integer *ilo, integer *ihi, - doublereal *lscale, doublereal *rscale, doublereal *abnrm, - doublereal *bbnrm, doublereal *rconde, doublereal *rcondv, - doublereal *work, integer *lwork, integer *iwork, - logical *bwork, integer *info, ftnlen balanc_len, - ftnlen jobvl_len, ftnlen jobvr_len, ftnlen sense_len); -extern int dggglm_(integer *n, integer *m, integer *p, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *d__, - doublereal *x, doublereal *y, doublereal *work, - integer *lwork, integer *info); -extern int dgghrd_(char *compq, char *compz, integer *n, integer *ilo, - integer *ihi, doublereal *a, integer *lda, doublereal *b, - integer *ldb, doublereal *q, integer *ldq, doublereal *z__, - integer *ldz, integer *info, ftnlen compq_len, - ftnlen compz_len); -extern int dgglse_(integer *m, integer *n, integer *p, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *c__, - doublereal *d__, doublereal *x, doublereal *work, - integer *lwork, integer *info); -extern int dggqrf_(integer *n, integer *m, integer *p, doublereal *a, - integer *lda, doublereal *taua, doublereal *b, integer *ldb, - doublereal *taub, doublereal *work, integer *lwork, - integer *info); -extern int dggrqf_(integer *m, integer *p, integer *n, doublereal *a, - integer *lda, doublereal *taua, doublereal *b, integer *ldb, - doublereal *taub, doublereal *work, integer *lwork, - integer *info); -extern int dggsvd_(char *jobu, char *jobv, char *jobq, integer *m, integer *n, - integer *p, integer *k, integer *l, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *alpha, - doublereal *beta, doublereal *u, integer *ldu, doublereal *v, - integer *ldv, doublereal *q, integer *ldq, doublereal *work, - integer *iwork, integer *info, ftnlen jobu_len, - ftnlen jobv_len, ftnlen jobq_len); -extern int dggsvp_(char *jobu, char *jobv, char *jobq, integer *m, integer *p, - integer *n, doublereal *a, integer *lda, doublereal *b, - integer *ldb, doublereal *tola, doublereal *tolb, integer *k, - integer *l, doublereal *u, integer *ldu, doublereal *v, - integer *ldv, doublereal *q, integer *ldq, integer *iwork, - doublereal *tau, doublereal *work, integer *info, - ftnlen jobu_len, ftnlen jobv_len, ftnlen jobq_len); -extern int dgtcon_(char *norm, integer *n, doublereal *dl, doublereal *d__, - doublereal *du, doublereal *du2, integer *ipiv, - doublereal *anorm, doublereal *rcond, doublereal *work, - integer *iwork, integer *info, ftnlen norm_len); -extern int dgtrfs_(char *trans, integer *n, integer *nrhs, doublereal *dl, - doublereal *d__, doublereal *du, doublereal *dlf, - doublereal *df, doublereal *duf, doublereal *du2, - integer *ipiv, doublereal *b, integer *ldb, doublereal *x, - integer *ldx, doublereal *ferr, doublereal *berr, - doublereal *work, integer *iwork, integer *info, - ftnlen trans_len); -extern int dgtsv_(integer *n, integer *nrhs, doublereal *dl, doublereal *d__, - doublereal *du, doublereal *b, integer *ldb, integer *info); -extern int dgtsvx_(char *fact, char *trans, integer *n, integer *nrhs, - doublereal *dl, doublereal *d__, doublereal *du, - doublereal *dlf, doublereal *df, doublereal *duf, - doublereal *du2, integer *ipiv, doublereal *b, integer *ldb, - doublereal *x, integer *ldx, doublereal *rcond, - doublereal *ferr, doublereal *berr, doublereal *work, - integer *iwork, integer *info, ftnlen fact_len, - ftnlen trans_len); -extern int dgttrf_(integer *n, doublereal *dl, doublereal *d__, doublereal *du, - doublereal *du2, integer *ipiv, integer *info); -extern int dgttrs_(char *trans, integer *n, integer *nrhs, doublereal *dl, - doublereal *d__, doublereal *du, doublereal *du2, - integer *ipiv, doublereal *b, integer *ldb, integer *info, - ftnlen trans_len); -extern int dgtts2_(integer *itrans, integer *n, integer *nrhs, doublereal *dl, - doublereal *d__, doublereal *du, doublereal *du2, - integer *ipiv, doublereal *b, integer *ldb); -extern int dhgeqz_(char *job, char *compq, char *compz, integer *n, - integer *ilo, integer *ihi, doublereal *a, integer *lda, - doublereal *b, integer *ldb, doublereal *alphar, - doublereal *alphai, doublereal *beta, doublereal *q, - integer *ldq, doublereal *z__, integer *ldz, - doublereal *work, integer *lwork, integer *info, - ftnlen job_len, ftnlen compq_len, ftnlen compz_len); -extern int dhsein_(char *side, char *eigsrc, char *initv, logical *select, - integer *n, doublereal *h__, integer *ldh, doublereal *wr, - doublereal *wi, doublereal *vl, integer *ldvl, - doublereal *vr, integer *ldvr, integer *mm, integer *m, - doublereal *work, integer *ifaill, integer *ifailr, - integer *info, ftnlen side_len, ftnlen eigsrc_len, - ftnlen initv_len); -extern int dhseqr_(char *job, char *compz, integer *n, integer *ilo, - integer *ihi, doublereal *h__, integer *ldh, doublereal *wr, - doublereal *wi, doublereal *z__, integer *ldz, - doublereal *work, integer *lwork, integer *info, - ftnlen job_len, ftnlen compz_len); -extern int dlabad_(doublereal *small, doublereal *large); -extern int dlabrd_(integer *m, integer *n, integer *nb, doublereal *a, - integer *lda, doublereal *d__, doublereal *e, - doublereal *tauq, doublereal *taup, doublereal *x, - integer *ldx, doublereal *y, integer *ldy); -extern int dlacon_(integer *n, doublereal *v, doublereal *x, integer *isgn, - doublereal *est, integer *kase); -extern int dlacpy_(char *uplo, integer *m, integer *n, doublereal *a, - integer *lda, doublereal *b, integer *ldb, ftnlen uplo_len); -extern int dladiv_(doublereal *a, doublereal *b, doublereal *c__, - doublereal *d__, doublereal *p, doublereal *q); -extern int dlae2_(doublereal *a, doublereal *b, doublereal *c__, - doublereal *rt1, doublereal *rt2); -extern int dlaebz_(integer *ijob, integer *nitmax, integer *n, integer *mmax, - integer *minp, integer *nbmin, doublereal *abstol, - doublereal *reltol, doublereal *pivmin, doublereal *d__, - doublereal *e, doublereal *e2, integer *nval, doublereal *ab, - doublereal *c__, integer *mout, integer *nab, - doublereal *work, integer *iwork, integer *info); -extern int dlaed0_(integer *icompq, integer *qsiz, integer *n, doublereal *d__, - doublereal *e, doublereal *q, integer *ldq, - doublereal *qstore, integer *ldqs, doublereal *work, - integer *iwork, integer *info); -extern int dlaed1_(integer *n, doublereal *d__, doublereal *q, integer *ldq, - integer *indxq, doublereal *rho, integer *cutpnt, - doublereal *work, integer *iwork, integer *info); -extern int dlaed2_(integer *k, integer *n, integer *n1, doublereal *d__, - doublereal *q, integer *ldq, integer *indxq, doublereal *rho, - doublereal *z__, doublereal *dlamda, doublereal *w, - doublereal *q2, integer *indx, integer *indxc, - integer *indxp, integer *coltyp, integer *info); -extern int dlaed3_(integer *k, integer *n, integer *n1, doublereal *d__, - doublereal *q, integer *ldq, doublereal *rho, - doublereal *dlamda, doublereal *q2, integer *indx, - integer *ctot, doublereal *w, doublereal *s, integer *info); -extern int dlaed4_(integer *n, integer *i__, doublereal *d__, doublereal *z__, - doublereal *delta, doublereal *rho, doublereal *dlam, - integer *info); -extern int dlaed5_(integer *i__, doublereal *d__, doublereal *z__, - doublereal *delta, doublereal *rho, doublereal *dlam); -extern int dlaed6_(integer *kniter, logical *orgati, doublereal *rho, - doublereal *d__, doublereal *z__, doublereal *finit, - doublereal *tau, integer *info); -extern int dlaed7_(integer *icompq, integer *n, integer *qsiz, integer *tlvls, - integer *curlvl, integer *curpbm, doublereal *d__, - doublereal *q, integer *ldq, integer *indxq, doublereal *rho, - integer *cutpnt, doublereal *qstore, integer *qptr, - integer *prmptr, integer *perm, integer *givptr, - integer *givcol, doublereal *givnum, doublereal *work, - integer *iwork, integer *info); -extern int dlaed8_(integer *icompq, integer *k, integer *n, integer *qsiz, - doublereal *d__, doublereal *q, integer *ldq, integer *indxq, - doublereal *rho, integer *cutpnt, doublereal *z__, - doublereal *dlamda, doublereal *q2, integer *ldq2, - doublereal *w, integer *perm, integer *givptr, - integer *givcol, doublereal *givnum, integer *indxp, - integer *indx, integer *info); -extern int dlaed9_(integer *k, integer *kstart, integer *kstop, integer *n, - doublereal *d__, doublereal *q, integer *ldq, - doublereal *rho, doublereal *dlamda, doublereal *w, - doublereal *s, integer *lds, integer *info); -extern int dlaeda_(integer *n, integer *tlvls, integer *curlvl, integer *curpbm, - integer *prmptr, integer *perm, integer *givptr, - integer *givcol, doublereal *givnum, doublereal *q, - integer *qptr, doublereal *z__, doublereal *ztemp, - integer *info); -extern int dlaein_(logical *rightv, logical *noinit, integer *n, - doublereal *h__, integer *ldh, doublereal *wr, - doublereal *wi, doublereal *vr, doublereal *vi, - doublereal *b, integer *ldb, doublereal *work, - doublereal *eps3, doublereal *smlnum, doublereal *bignum, - integer *info); -extern int dlaev2_(doublereal *a, doublereal *b, doublereal *c__, - doublereal *rt1, doublereal *rt2, doublereal *cs1, - doublereal *sn1); -extern int dlaexc_(logical *wantq, integer *n, doublereal *t, integer *ldt, - doublereal *q, integer *ldq, integer *j1, integer *n1, - integer *n2, doublereal *work, integer *info); -extern int dlag2_(doublereal *a, integer *lda, doublereal *b, integer *ldb, - doublereal *safmin, doublereal *scale1, doublereal *scale2, - doublereal *wr1, doublereal *wr2, doublereal *wi); -extern int dlags2_(logical *upper, doublereal *a1, doublereal *a2, - doublereal *a3, doublereal *b1, doublereal *b2, - doublereal *b3, doublereal *csu, doublereal *snu, - doublereal *csv, doublereal *snv, doublereal *csq, - doublereal *snq); -extern int dlagtf_(integer *n, doublereal *a, doublereal *lambda, doublereal *b, - doublereal *c__, doublereal *tol, doublereal *d__, - integer *in, integer *info); -extern int dlagtm_(char *trans, integer *n, integer *nrhs, doublereal *alpha, - doublereal *dl, doublereal *d__, doublereal *du, - doublereal *x, integer *ldx, doublereal *beta, doublereal *b, - integer *ldb, ftnlen trans_len); -extern int dlagts_(integer *job, integer *n, doublereal *a, doublereal *b, - doublereal *c__, doublereal *d__, integer *in, doublereal *y, - doublereal *tol, integer *info); -extern int dlagv2_(doublereal *a, integer *lda, doublereal *b, integer *ldb, - doublereal *alphar, doublereal *alphai, doublereal *beta, - doublereal *csl, doublereal *snl, doublereal *csr, - doublereal *snr); -extern int dlahqr_(logical *wantt, logical *wantz, integer *n, integer *ilo, - integer *ihi, doublereal *h__, integer *ldh, doublereal *wr, - doublereal *wi, integer *iloz, integer *ihiz, - doublereal *z__, integer *ldz, integer *info); -extern int dlahrd_(integer *n, integer *k, integer *nb, doublereal *a, - integer *lda, doublereal *tau, doublereal *t, integer *ldt, - doublereal *y, integer *ldy); -extern int dlaic1_(integer *job, integer *j, doublereal *x, doublereal *sest, - doublereal *w, doublereal *gamma, doublereal *sestpr, - doublereal *s, doublereal *c__); -extern int dlaln2_(logical *ltrans, integer *na, integer *nw, doublereal *smin, - doublereal *ca, doublereal *a, integer *lda, doublereal *d1, - doublereal *d2, doublereal *b, integer *ldb, doublereal *wr, - doublereal *wi, doublereal *x, integer *ldx, - doublereal *scale, doublereal *xnorm, integer *info); -extern int dlals0_(integer *icompq, integer *nl, integer *nr, integer *sqre, - integer *nrhs, doublereal *b, integer *ldb, doublereal *bx, - integer *ldbx, integer *perm, integer *givptr, - integer *givcol, integer *ldgcol, doublereal *givnum, - integer *ldgnum, doublereal *poles, doublereal *difl, - doublereal *difr, doublereal *z__, integer *k, - doublereal *c__, doublereal *s, doublereal *work, - integer *info); -extern int dlalsa_(integer *icompq, integer *smlsiz, integer *n, integer *nrhs, - doublereal *b, integer *ldb, doublereal *bx, integer *ldbx, - doublereal *u, integer *ldu, doublereal *vt, integer *k, - doublereal *difl, doublereal *difr, doublereal *z__, - doublereal *poles, integer *givptr, integer *givcol, - integer *ldgcol, integer *perm, doublereal *givnum, - doublereal *c__, doublereal *s, doublereal *work, - integer *iwork, integer *info); -extern int dlalsd_(char *uplo, integer *smlsiz, integer *n, integer *nrhs, - doublereal *d__, doublereal *e, doublereal *b, integer *ldb, - doublereal *rcond, integer *rank, doublereal *work, - integer *iwork, integer *info, ftnlen uplo_len); -extern doublereal dlamch_(char *cmach, ftnlen cmach_len); -extern int dlamc1_(integer *beta, integer *t, logical *rnd, logical *ieee1); -extern int dlamc2_(integer *beta, integer *t, logical *rnd, doublereal *eps, - integer *emin, doublereal *rmin, integer *emax, - doublereal *rmax); -extern doublereal dlamc3_(doublereal *a, doublereal *b); -extern int dlamc4_(integer *emin, doublereal *start, integer *base); -extern int dlamc5_(integer *beta, integer *p, integer *emin, logical *ieee, - integer *emax, doublereal *rmax); -extern int dlamrg_(integer *n1, integer *n2, doublereal *a, integer *dtrd1, - integer *dtrd2, integer *index); -extern doublereal dlangb_(char *norm, integer *n, integer *kl, integer *ku, - doublereal *ab, integer *ldab, doublereal *work, - ftnlen norm_len); -extern doublereal dlange_(char *norm, integer *m, integer *n, doublereal *a, - integer *lda, doublereal *work, ftnlen norm_len); -extern doublereal dlangt_(char *norm, integer *n, doublereal *dl, - doublereal *d__, doublereal *du, ftnlen norm_len); -extern doublereal dlanhs_(char *norm, integer *n, doublereal *a, integer *lda, - doublereal *work, ftnlen norm_len); -extern doublereal dlansb_(char *norm, char *uplo, integer *n, integer *k, - doublereal *ab, integer *ldab, doublereal *work, - ftnlen norm_len, ftnlen uplo_len); -extern doublereal dlansp_(char *norm, char *uplo, integer *n, doublereal *ap, - doublereal *work, ftnlen norm_len, ftnlen uplo_len); -extern doublereal dlanst_(char *norm, integer *n, doublereal *d__, - doublereal *e, ftnlen norm_len); -extern doublereal dlansy_(char *norm, char *uplo, integer *n, doublereal *a, - integer *lda, doublereal *work, ftnlen norm_len, - ftnlen uplo_len); -extern doublereal dlantb_(char *norm, char *uplo, char *diag, integer *n, - integer *k, doublereal *ab, integer *ldab, - doublereal *work, ftnlen norm_len, ftnlen uplo_len, - ftnlen diag_len); -extern doublereal dlantp_(char *norm, char *uplo, char *diag, integer *n, - doublereal *ap, doublereal *work, ftnlen norm_len, - ftnlen uplo_len, ftnlen diag_len); -extern doublereal dlantr_(char *norm, char *uplo, char *diag, integer *m, - integer *n, doublereal *a, integer *lda, - doublereal *work, ftnlen norm_len, ftnlen uplo_len, - ftnlen diag_len); -extern int dlanv2_(doublereal *a, doublereal *b, doublereal *c__, - doublereal *d__, doublereal *rt1r, doublereal *rt1i, - doublereal *rt2r, doublereal *rt2i, doublereal *cs, - doublereal *sn); -extern int dlapll_(integer *n, doublereal *x, integer *incx, doublereal *y, - integer *incy, doublereal *ssmin); -extern int dlapmt_(logical *forwrd, integer *m, integer *n, doublereal *x, - integer *ldx, integer *k); -extern doublereal dlapy2_(doublereal *x, doublereal *y); -extern doublereal dlapy3_(doublereal *x, doublereal *y, doublereal *z__); -extern int dlaqgb_(integer *m, integer *n, integer *kl, integer *ku, - doublereal *ab, integer *ldab, doublereal *r__, - doublereal *c__, doublereal *rowcnd, doublereal *colcnd, - doublereal *amax, char *equed, ftnlen equed_len); -extern int dlaqge_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *r__, doublereal *c__, doublereal *rowcnd, - doublereal *colcnd, doublereal *amax, char *equed, - ftnlen equed_len); -extern int dlaqp2_(integer *m, integer *n, integer *offset, doublereal *a, - integer *lda, integer *jpvt, doublereal *tau, - doublereal *vn1, doublereal *vn2, doublereal *work); -extern int dlaqps_(integer *m, integer *n, integer *offset, integer *nb, - integer *kb, doublereal *a, integer *lda, integer *jpvt, - doublereal *tau, doublereal *vn1, doublereal *vn2, - doublereal *auxv, doublereal *f, integer *ldf); -extern int dlaqsb_(char *uplo, integer *n, integer *kd, doublereal *ab, - integer *ldab, doublereal *s, doublereal *scond, - doublereal *amax, char *equed, ftnlen uplo_len, - ftnlen equed_len); -extern int dlaqsp_(char *uplo, integer *n, doublereal *ap, doublereal *s, - doublereal *scond, doublereal *amax, char *equed, - ftnlen uplo_len, ftnlen equed_len); -extern int dlaqsy_(char *uplo, integer *n, doublereal *a, integer *lda, - doublereal *s, doublereal *scond, doublereal *amax, - char *equed, ftnlen uplo_len, ftnlen equed_len); -extern int dlaqtr_(logical *ltran, logical *lreal, integer *n, doublereal *t, - integer *ldt, doublereal *b, doublereal *w, - doublereal *scale, doublereal *x, doublereal *work, - integer *info); -extern int dlar1v_(integer *n, integer *b1, integer *bn, doublereal *sigma, - doublereal *d__, doublereal *l, doublereal *ld, - doublereal *lld, doublereal *gersch, doublereal *z__, - doublereal *ztz, doublereal *mingma, integer *r__, - integer *isuppz, doublereal *work); -extern int dlar2v_(integer *n, doublereal *x, doublereal *y, doublereal *z__, - integer *incx, doublereal *c__, doublereal *s, - integer *incc); -extern int dlarf_(char *side, integer *m, integer *n, doublereal *v, - integer *incv, doublereal *tau, doublereal *c__, integer *ldc, - doublereal *work, ftnlen side_len); -extern int dlarfb_(char *side, char *trans, char *direct, char *storev, - integer *m, integer *n, integer *k, doublereal *v, - integer *ldv, doublereal *t, integer *ldt, doublereal *c__, - integer *ldc, doublereal *work, integer *ldwork, - ftnlen side_len, ftnlen trans_len, ftnlen direct_len, - ftnlen storev_len); -extern int dlarfg_(integer *n, doublereal *alpha, doublereal *x, integer *incx, - doublereal *tau); -extern int dlarft_(char *direct, char *storev, integer *n, integer *k, - doublereal *v, integer *ldv, doublereal *tau, doublereal *t, - integer *ldt, ftnlen direct_len, ftnlen storev_len); -extern int dlarfx_(char *side, integer *m, integer *n, doublereal *v, - doublereal *tau, doublereal *c__, integer *ldc, - doublereal *work, ftnlen side_len); -extern int dlargv_(integer *n, doublereal *x, integer *incx, doublereal *y, - integer *incy, doublereal *c__, integer *incc); -extern int dlarnv_(integer *idist, integer *iseed, integer *n, doublereal *x); -extern int dlarrb_(integer *n, doublereal *d__, doublereal *l, doublereal *ld, - doublereal *lld, integer *ifirst, integer *ilast, - doublereal *sigma, doublereal *reltol, doublereal *w, - doublereal *wgap, doublereal *werr, doublereal *work, - integer *iwork, integer *info); -extern int dlarre_(integer *n, doublereal *d__, doublereal *e, doublereal *tol, - integer *nsplit, integer *isplit, integer *m, doublereal *w, - doublereal *woff, doublereal *gersch, doublereal *work, - integer *info); -extern int dlarrf_(integer *n, doublereal *d__, doublereal *l, doublereal *ld, - doublereal *lld, integer *ifirst, integer *ilast, - doublereal *w, doublereal *dplus, doublereal *lplus, - doublereal *work, integer *iwork, integer *info); -extern int dlarrv_(integer *n, doublereal *d__, doublereal *l, integer *isplit, - integer *m, doublereal *w, integer *iblock, - doublereal *gersch, doublereal *tol, doublereal *z__, - integer *ldz, integer *isuppz, doublereal *work, - integer *iwork, integer *info); -extern int dlartg_(doublereal *f, doublereal *g, doublereal *cs, doublereal *sn, - doublereal *r__); -extern int dlartv_(integer *n, doublereal *x, integer *incx, doublereal *y, - integer *incy, doublereal *c__, doublereal *s, - integer *incc); -extern int dlaruv_(integer *iseed, integer *n, doublereal *x); -extern int dlarz_(char *side, integer *m, integer *n, integer *l, doublereal *v, - integer *incv, doublereal *tau, doublereal *c__, integer *ldc, - doublereal *work, ftnlen side_len); -extern int dlarzb_(char *side, char *trans, char *direct, char *storev, - integer *m, integer *n, integer *k, integer *l, - doublereal *v, integer *ldv, doublereal *t, integer *ldt, - doublereal *c__, integer *ldc, doublereal *work, - integer *ldwork, ftnlen side_len, ftnlen trans_len, - ftnlen direct_len, ftnlen storev_len); -extern int dlarzt_(char *direct, char *storev, integer *n, integer *k, - doublereal *v, integer *ldv, doublereal *tau, doublereal *t, - integer *ldt, ftnlen direct_len, ftnlen storev_len); -extern int dlas2_(doublereal *f, doublereal *g, doublereal *h__, - doublereal *ssmin, doublereal *ssmax); -extern int dlascl_(char *type__, integer *kl, integer *ku, doublereal *cfrom, - doublereal *cto, integer *m, integer *n, doublereal *a, - integer *lda, integer *info, ftnlen type_len); -extern int dlasd0_(integer *n, integer *sqre, doublereal *d__, doublereal *e, - doublereal *u, integer *ldu, doublereal *vt, integer *ldvt, - integer *smlsiz, integer *iwork, doublereal *work, - integer *info); -extern int dlasd1_(integer *nl, integer *nr, integer *sqre, doublereal *d__, - doublereal *alpha, doublereal *beta, doublereal *u, - integer *ldu, doublereal *vt, integer *ldvt, integer *idxq, - integer *iwork, doublereal *work, integer *info); -extern int dlasd2_(integer *nl, integer *nr, integer *sqre, integer *k, - doublereal *d__, doublereal *z__, doublereal *alpha, - doublereal *beta, doublereal *u, integer *ldu, - doublereal *vt, integer *ldvt, doublereal *dsigma, - doublereal *u2, integer *ldu2, doublereal *vt2, - integer *ldvt2, integer *idxp, integer *idx, integer *idxc, - integer *idxq, integer *coltyp, integer *info); -extern int dlasd3_(integer *nl, integer *nr, integer *sqre, integer *k, - doublereal *d__, doublereal *q, integer *ldq, - doublereal *dsigma, doublereal *u, integer *ldu, - doublereal *u2, integer *ldu2, doublereal *vt, integer *ldvt, - doublereal *vt2, integer *ldvt2, integer *idxc, - integer *ctot, doublereal *z__, integer *info); -extern int dlasd4_(integer *n, integer *i__, doublereal *d__, doublereal *z__, - doublereal *delta, doublereal *rho, doublereal *sigma, - doublereal *work, integer *info); -extern int dlasd5_(integer *i__, doublereal *d__, doublereal *z__, - doublereal *delta, doublereal *rho, doublereal *dsigma, - doublereal *work); -extern int dlasd6_(integer *icompq, integer *nl, integer *nr, integer *sqre, - doublereal *d__, doublereal *vf, doublereal *vl, - doublereal *alpha, doublereal *beta, integer *idxq, - integer *perm, integer *givptr, integer *givcol, - integer *ldgcol, doublereal *givnum, integer *ldgnum, - doublereal *poles, doublereal *difl, doublereal *difr, - doublereal *z__, integer *k, doublereal *c__, doublereal *s, - doublereal *work, integer *iwork, integer *info); -extern int dlasd7_(integer *icompq, integer *nl, integer *nr, integer *sqre, - integer *k, doublereal *d__, doublereal *z__, doublereal *zw, - doublereal *vf, doublereal *vfw, doublereal *vl, - doublereal *vlw, doublereal *alpha, doublereal *beta, - doublereal *dsigma, integer *idx, integer *idxp, - integer *idxq, integer *perm, integer *givptr, - integer *givcol, integer *ldgcol, doublereal *givnum, - integer *ldgnum, doublereal *c__, doublereal *s, - integer *info); -extern int dlasd8_(integer *icompq, integer *k, doublereal *d__, - doublereal *z__, doublereal *vf, doublereal *vl, - doublereal *difl, doublereal *difr, integer *lddifr, - doublereal *dsigma, doublereal *work, integer *info); -extern int dlasd9_(integer *icompq, integer *ldu, integer *k, doublereal *d__, - doublereal *z__, doublereal *vf, doublereal *vl, - doublereal *difl, doublereal *difr, doublereal *dsigma, - doublereal *work, integer *info); -extern int dlasda_(integer *icompq, integer *smlsiz, integer *n, integer *sqre, - doublereal *d__, doublereal *e, doublereal *u, integer *ldu, - doublereal *vt, integer *k, doublereal *difl, - doublereal *difr, doublereal *z__, doublereal *poles, - integer *givptr, integer *givcol, integer *ldgcol, - integer *perm, doublereal *givnum, doublereal *c__, - doublereal *s, doublereal *work, integer *iwork, - integer *info); -extern int dlasdq_(char *uplo, integer *sqre, integer *n, integer *ncvt, - integer *nru, integer *ncc, doublereal *d__, doublereal *e, - doublereal *vt, integer *ldvt, doublereal *u, integer *ldu, - doublereal *c__, integer *ldc, doublereal *work, - integer *info, ftnlen uplo_len); -extern int dlasdt_(integer *n, integer *lvl, integer *nd, integer *inode, - integer *ndiml, integer *ndimr, integer *msub); -extern int dlaset_(char *uplo, integer *m, integer *n, doublereal *alpha, - doublereal *beta, doublereal *a, integer *lda, - ftnlen uplo_len); -extern int dlasq1_(integer *n, doublereal *d__, doublereal *e, doublereal *work, - integer *info); -extern int dlasq2_(integer *n, doublereal *z__, integer *info); -extern int dlasq3_(integer *i0, integer *n0, doublereal *z__, integer *pp, - doublereal *dmin__, doublereal *sigma, doublereal *desig, - doublereal *qmax, integer *nfail, integer *iter, - integer *ndiv); -extern int dlasq4_(integer *i0, integer *n0, doublereal *z__, integer *pp, - integer *n0in, doublereal *dmin__, doublereal *dmin1, - doublereal *dmin2, doublereal *dn, doublereal *dn1, - doublereal *dn2, doublereal *tau, integer *ttype); -extern int dlasq5_(integer *i0, integer *n0, doublereal *z__, integer *pp, - doublereal *tau, doublereal *dmin__, doublereal *dmin1, - doublereal *dmin2, doublereal *dn, doublereal *dnm1, - doublereal *dnm2); -extern int dlasq6_(integer *i0, integer *n0, doublereal *z__, integer *pp, - doublereal *dmin__, doublereal *dmin1, doublereal *dmin2, - doublereal *dn, doublereal *dnm1, doublereal *dnm2); -extern int dlasr_(char *side, char *pivot, char *direct, integer *m, integer *n, - doublereal *c__, doublereal *s, doublereal *a, integer *lda, - ftnlen side_len, ftnlen pivot_len, ftnlen direct_len); -extern int dlasrt_(char *id, integer *n, doublereal *d__, integer *info, - ftnlen id_len); -extern int dlassq_(integer *n, doublereal *x, integer *incx, doublereal *scale, - doublereal *sumsq); -extern int dlasv2_(doublereal *f, doublereal *g, doublereal *h__, - doublereal *ssmin, doublereal *ssmax, doublereal *snr, - doublereal *csr, doublereal *snl, doublereal *csl); -extern int dlaswp_(integer *n, doublereal *a, integer *lda, integer *k1, - integer *k2, integer *ipiv, integer *incx); -extern int dlasy2_(logical *ltranl, logical *ltranr, integer *isgn, integer *n1, - integer *n2, doublereal *tl, integer *ldtl, doublereal *tr, - integer *ldtr, doublereal *b, integer *ldb, - doublereal *scale, doublereal *x, integer *ldx, - doublereal *xnorm, integer *info); -extern int dlasyf_(char *uplo, integer *n, integer *nb, integer *kb, - doublereal *a, integer *lda, integer *ipiv, doublereal *w, - integer *ldw, integer *info, ftnlen uplo_len); -extern int dlatbs_(char *uplo, char *trans, char *diag, char *normin, - integer *n, integer *kd, doublereal *ab, integer *ldab, - doublereal *x, doublereal *scale, doublereal *cnorm, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len, ftnlen normin_len); -extern int dlatdf_(integer *ijob, integer *n, doublereal *z__, integer *ldz, - doublereal *rhs, doublereal *rdsum, doublereal *rdscal, - integer *ipiv, integer *jpiv); -extern int dlatps_(char *uplo, char *trans, char *diag, char *normin, - integer *n, doublereal *ap, doublereal *x, doublereal *scale, - doublereal *cnorm, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len, ftnlen normin_len); -extern int dlatrd_(char *uplo, integer *n, integer *nb, doublereal *a, - integer *lda, doublereal *e, doublereal *tau, doublereal *w, - integer *ldw, ftnlen uplo_len); -extern int dlatrs_(char *uplo, char *trans, char *diag, char *normin, - integer *n, doublereal *a, integer *lda, doublereal *x, - doublereal *scale, doublereal *cnorm, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len, - ftnlen normin_len); -extern int dlatrz_(integer *m, integer *n, integer *l, doublereal *a, - integer *lda, doublereal *tau, doublereal *work); -extern int dlatzm_(char *side, integer *m, integer *n, doublereal *v, - integer *incv, doublereal *tau, doublereal *c1, - doublereal *c2, integer *ldc, doublereal *work, - ftnlen side_len); -extern int dlauu2_(char *uplo, integer *n, doublereal *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int dlauum_(char *uplo, integer *n, doublereal *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int dopgtr_(char *uplo, integer *n, doublereal *ap, doublereal *tau, - doublereal *q, integer *ldq, doublereal *work, integer *info, - ftnlen uplo_len); -extern int dopmtr_(char *side, char *uplo, char *trans, integer *m, integer *n, - doublereal *ap, doublereal *tau, doublereal *c__, - integer *ldc, doublereal *work, integer *info, - ftnlen side_len, ftnlen uplo_len, ftnlen trans_len); -extern int dorg2l_(integer *m, integer *n, integer *k, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *info); -extern int dorg2r_(integer *m, integer *n, integer *k, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *info); -extern int dorgbr_(char *vect, integer *m, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *tau, - doublereal *work, integer *lwork, integer *info, - ftnlen vect_len); -extern int dorghr_(integer *n, integer *ilo, integer *ihi, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *lwork, integer *info); -extern int dorgl2_(integer *m, integer *n, integer *k, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *info); -extern int dorglq_(integer *m, integer *n, integer *k, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *lwork, integer *info); -extern int dorgql_(integer *m, integer *n, integer *k, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *lwork, integer *info); -extern int dorgqr_(integer *m, integer *n, integer *k, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *lwork, integer *info); -extern int dorgr2_(integer *m, integer *n, integer *k, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *info); -extern int dorgrq_(integer *m, integer *n, integer *k, doublereal *a, - integer *lda, doublereal *tau, doublereal *work, - integer *lwork, integer *info); -extern int dorgtr_(char *uplo, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *lwork, - integer *info, ftnlen uplo_len); -extern int dorm2l_(char *side, char *trans, integer *m, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int dorm2r_(char *side, char *trans, integer *m, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int dormbr_(char *vect, char *side, char *trans, integer *m, integer *n, - integer *k, doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *lwork, integer *info, ftnlen vect_len, - ftnlen side_len, ftnlen trans_len); -extern int dormhr_(char *side, char *trans, integer *m, integer *n, - integer *ilo, integer *ihi, doublereal *a, integer *lda, - doublereal *tau, doublereal *c__, integer *ldc, - doublereal *work, integer *lwork, integer *info, - ftnlen side_len, ftnlen trans_len); -extern int dorml2_(char *side, char *trans, integer *m, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int dormlq_(char *side, char *trans, integer *m, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int dormql_(char *side, char *trans, integer *m, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int dormqr_(char *side, char *trans, integer *m, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int dormr2_(char *side, char *trans, integer *m, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int dormr3_(char *side, char *trans, integer *m, integer *n, integer *k, - integer *l, doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int dormrq_(char *side, char *trans, integer *m, integer *n, integer *k, - doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int dormrz_(char *side, char *trans, integer *m, integer *n, integer *k, - integer *l, doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int dormtr_(char *side, char *uplo, char *trans, integer *m, integer *n, - doublereal *a, integer *lda, doublereal *tau, - doublereal *c__, integer *ldc, doublereal *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen uplo_len, ftnlen trans_len); -extern int dpbcon_(char *uplo, integer *n, integer *kd, doublereal *ab, - integer *ldab, doublereal *anorm, doublereal *rcond, - doublereal *work, integer *iwork, integer *info, - ftnlen uplo_len); -extern int dpbequ_(char *uplo, integer *n, integer *kd, doublereal *ab, - integer *ldab, doublereal *s, doublereal *scond, - doublereal *amax, integer *info, ftnlen uplo_len); -extern int dpbrfs_(char *uplo, integer *n, integer *kd, integer *nrhs, - doublereal *ab, integer *ldab, doublereal *afb, - integer *ldafb, doublereal *b, integer *ldb, doublereal *x, - integer *ldx, doublereal *ferr, doublereal *berr, - doublereal *work, integer *iwork, integer *info, - ftnlen uplo_len); -extern int dpbstf_(char *uplo, integer *n, integer *kd, doublereal *ab, - integer *ldab, integer *info, ftnlen uplo_len); -extern int dpbsv_(char *uplo, integer *n, integer *kd, integer *nrhs, - doublereal *ab, integer *ldab, doublereal *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int dpbsvx_(char *fact, char *uplo, integer *n, integer *kd, - integer *nrhs, doublereal *ab, integer *ldab, - doublereal *afb, integer *ldafb, char *equed, doublereal *s, - doublereal *b, integer *ldb, doublereal *x, integer *ldx, - doublereal *rcond, doublereal *ferr, doublereal *berr, - doublereal *work, integer *iwork, integer *info, - ftnlen fact_len, ftnlen uplo_len, ftnlen equed_len); -extern int dpbtf2_(char *uplo, integer *n, integer *kd, doublereal *ab, - integer *ldab, integer *info, ftnlen uplo_len); -extern int dpbtrf_(char *uplo, integer *n, integer *kd, doublereal *ab, - integer *ldab, integer *info, ftnlen uplo_len); -extern int dpbtrs_(char *uplo, integer *n, integer *kd, integer *nrhs, - doublereal *ab, integer *ldab, doublereal *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int dpocon_(char *uplo, integer *n, doublereal *a, integer *lda, - doublereal *anorm, doublereal *rcond, doublereal *work, - integer *iwork, integer *info, ftnlen uplo_len); -extern int dpoequ_(integer *n, doublereal *a, integer *lda, doublereal *s, - doublereal *scond, doublereal *amax, integer *info); -extern int dporfs_(char *uplo, integer *n, integer *nrhs, doublereal *a, - integer *lda, doublereal *af, integer *ldaf, doublereal *b, - integer *ldb, doublereal *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublereal *work, integer *iwork, - integer *info, ftnlen uplo_len); -extern int dposv_(char *uplo, integer *n, integer *nrhs, doublereal *a, - integer *lda, doublereal *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int dposvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublereal *a, integer *lda, doublereal *af, integer *ldaf, - char *equed, doublereal *s, doublereal *b, integer *ldb, - doublereal *x, integer *ldx, doublereal *rcond, - doublereal *ferr, doublereal *berr, doublereal *work, - integer *iwork, integer *info, ftnlen fact_len, - ftnlen uplo_len, ftnlen equed_len); -extern int dpotf2_(char *uplo, integer *n, doublereal *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int dpotrf_(char *uplo, integer *n, doublereal *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int dpotri_(char *uplo, integer *n, doublereal *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int dpotrs_(char *uplo, integer *n, integer *nrhs, doublereal *a, - integer *lda, doublereal *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int dppcon_(char *uplo, integer *n, doublereal *ap, doublereal *anorm, - doublereal *rcond, doublereal *work, integer *iwork, - integer *info, ftnlen uplo_len); -extern int dppequ_(char *uplo, integer *n, doublereal *ap, doublereal *s, - doublereal *scond, doublereal *amax, integer *info, - ftnlen uplo_len); -extern int dpprfs_(char *uplo, integer *n, integer *nrhs, doublereal *ap, - doublereal *afp, doublereal *b, integer *ldb, doublereal *x, - integer *ldx, doublereal *ferr, doublereal *berr, - doublereal *work, integer *iwork, integer *info, - ftnlen uplo_len); -extern int dppsv_(char *uplo, integer *n, integer *nrhs, doublereal *ap, - doublereal *b, integer *ldb, integer *info, ftnlen uplo_len); -extern int dppsvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublereal *ap, doublereal *afp, char *equed, doublereal *s, - doublereal *b, integer *ldb, doublereal *x, integer *ldx, - doublereal *rcond, doublereal *ferr, doublereal *berr, - doublereal *work, integer *iwork, integer *info, - ftnlen fact_len, ftnlen uplo_len, ftnlen equed_len); -extern int dpptrf_(char *uplo, integer *n, doublereal *ap, integer *info, - ftnlen uplo_len); -extern int dpptri_(char *uplo, integer *n, doublereal *ap, integer *info, - ftnlen uplo_len); -extern int dpptrs_(char *uplo, integer *n, integer *nrhs, doublereal *ap, - doublereal *b, integer *ldb, integer *info, ftnlen uplo_len); -extern int dptcon_(integer *n, doublereal *d__, doublereal *e, - doublereal *anorm, doublereal *rcond, doublereal *work, - integer *info); -extern int dpteqr_(char *compz, integer *n, doublereal *d__, doublereal *e, - doublereal *z__, integer *ldz, doublereal *work, - integer *info, ftnlen compz_len); -extern int dptrfs_(integer *n, integer *nrhs, doublereal *d__, doublereal *e, - doublereal *df, doublereal *ef, doublereal *b, integer *ldb, - doublereal *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublereal *work, integer *info); -extern int dptsv_(integer *n, integer *nrhs, doublereal *d__, doublereal *e, - doublereal *b, integer *ldb, integer *info); -extern int dptsvx_(char *fact, integer *n, integer *nrhs, doublereal *d__, - doublereal *e, doublereal *df, doublereal *ef, doublereal *b, - integer *ldb, doublereal *x, integer *ldx, doublereal *rcond, - doublereal *ferr, doublereal *berr, doublereal *work, - integer *info, ftnlen fact_len); -extern int dpttrf_(integer *n, doublereal *d__, doublereal *e, integer *info); -extern int dpttrs_(integer *n, integer *nrhs, doublereal *d__, doublereal *e, - doublereal *b, integer *ldb, integer *info); -extern int dptts2_(integer *n, integer *nrhs, doublereal *d__, doublereal *e, - doublereal *b, integer *ldb); -extern int drscl_(integer *n, doublereal *sa, doublereal *sx, integer *incx); -extern int dsbev_(char *jobz, char *uplo, integer *n, integer *kd, - doublereal *ab, integer *ldab, doublereal *w, doublereal *z__, - integer *ldz, doublereal *work, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int dsbevd_(char *jobz, char *uplo, integer *n, integer *kd, - doublereal *ab, integer *ldab, doublereal *w, - doublereal *z__, integer *ldz, doublereal *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int dsbevx_(char *jobz, char *range, char *uplo, integer *n, integer *kd, - doublereal *ab, integer *ldab, doublereal *q, integer *ldq, - doublereal *vl, doublereal *vu, integer *il, integer *iu, - doublereal *abstol, integer *m, doublereal *w, - doublereal *z__, integer *ldz, doublereal *work, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len, ftnlen uplo_len); -extern int dsbgst_(char *vect, char *uplo, integer *n, integer *ka, integer *kb, - doublereal *ab, integer *ldab, doublereal *bb, integer *ldbb, - doublereal *x, integer *ldx, doublereal *work, integer *info, - ftnlen vect_len, ftnlen uplo_len); -extern int dsbgv_(char *jobz, char *uplo, integer *n, integer *ka, integer *kb, - doublereal *ab, integer *ldab, doublereal *bb, integer *ldbb, - doublereal *w, doublereal *z__, integer *ldz, - doublereal *work, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int dsbgvd_(char *jobz, char *uplo, integer *n, integer *ka, integer *kb, - doublereal *ab, integer *ldab, doublereal *bb, integer *ldbb, - doublereal *w, doublereal *z__, integer *ldz, - doublereal *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int dsbgvx_(char *jobz, char *range, char *uplo, integer *n, integer *ka, - integer *kb, doublereal *ab, integer *ldab, doublereal *bb, - integer *ldbb, doublereal *q, integer *ldq, doublereal *vl, - doublereal *vu, integer *il, integer *iu, doublereal *abstol, - integer *m, doublereal *w, doublereal *z__, integer *ldz, - doublereal *work, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int dsbtrd_(char *vect, char *uplo, integer *n, integer *kd, - doublereal *ab, integer *ldab, doublereal *d__, - doublereal *e, doublereal *q, integer *ldq, doublereal *work, - integer *info, ftnlen vect_len, ftnlen uplo_len); -extern doublereal dsecnd_(void); -extern int dspcon_(char *uplo, integer *n, doublereal *ap, integer *ipiv, - doublereal *anorm, doublereal *rcond, doublereal *work, - integer *iwork, integer *info, ftnlen uplo_len); -extern int dspev_(char *jobz, char *uplo, integer *n, doublereal *ap, - doublereal *w, doublereal *z__, integer *ldz, - doublereal *work, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int dspevd_(char *jobz, char *uplo, integer *n, doublereal *ap, - doublereal *w, doublereal *z__, integer *ldz, - doublereal *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int dspevx_(char *jobz, char *range, char *uplo, integer *n, - doublereal *ap, doublereal *vl, doublereal *vu, integer *il, - integer *iu, doublereal *abstol, integer *m, doublereal *w, - doublereal *z__, integer *ldz, doublereal *work, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len, ftnlen uplo_len); -extern int dspgst_(integer *itype, char *uplo, integer *n, doublereal *ap, - doublereal *bp, integer *info, ftnlen uplo_len); -extern int dspgv_(integer *itype, char *jobz, char *uplo, integer *n, - doublereal *ap, doublereal *bp, doublereal *w, - doublereal *z__, integer *ldz, doublereal *work, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int dspgvd_(integer *itype, char *jobz, char *uplo, integer *n, - doublereal *ap, doublereal *bp, doublereal *w, - doublereal *z__, integer *ldz, doublereal *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int dspgvx_(integer *itype, char *jobz, char *range, char *uplo, - integer *n, doublereal *ap, doublereal *bp, doublereal *vl, - doublereal *vu, integer *il, integer *iu, doublereal *abstol, - integer *m, doublereal *w, doublereal *z__, integer *ldz, - doublereal *work, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int dsprfs_(char *uplo, integer *n, integer *nrhs, doublereal *ap, - doublereal *afp, integer *ipiv, doublereal *b, integer *ldb, - doublereal *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublereal *work, integer *iwork, - integer *info, ftnlen uplo_len); -extern int dspsv_(char *uplo, integer *n, integer *nrhs, doublereal *ap, - integer *ipiv, doublereal *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int dspsvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublereal *ap, doublereal *afp, integer *ipiv, - doublereal *b, integer *ldb, doublereal *x, integer *ldx, - doublereal *rcond, doublereal *ferr, doublereal *berr, - doublereal *work, integer *iwork, integer *info, - ftnlen fact_len, ftnlen uplo_len); -extern int dsptrd_(char *uplo, integer *n, doublereal *ap, doublereal *d__, - doublereal *e, doublereal *tau, integer *info, - ftnlen uplo_len); -extern int dsptrf_(char *uplo, integer *n, doublereal *ap, integer *ipiv, - integer *info, ftnlen uplo_len); -extern int dsptri_(char *uplo, integer *n, doublereal *ap, integer *ipiv, - doublereal *work, integer *info, ftnlen uplo_len); -extern int dsptrs_(char *uplo, integer *n, integer *nrhs, doublereal *ap, - integer *ipiv, doublereal *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int dstebz_(char *range, char *order, integer *n, doublereal *vl, - doublereal *vu, integer *il, integer *iu, doublereal *abstol, - doublereal *d__, doublereal *e, integer *m, integer *nsplit, - doublereal *w, integer *iblock, integer *isplit, - doublereal *work, integer *iwork, integer *info, - ftnlen range_len, ftnlen order_len); -extern int dstedc_(char *compz, integer *n, doublereal *d__, doublereal *e, - doublereal *z__, integer *ldz, doublereal *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info, ftnlen compz_len); -extern int dstegr_(char *jobz, char *range, integer *n, doublereal *d__, - doublereal *e, doublereal *vl, doublereal *vu, integer *il, - integer *iu, doublereal *abstol, integer *m, doublereal *w, - doublereal *z__, integer *ldz, integer *isuppz, - doublereal *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen range_len); -extern int dstein_(integer *n, doublereal *d__, doublereal *e, integer *m, - doublereal *w, integer *iblock, integer *isplit, - doublereal *z__, integer *ldz, doublereal *work, - integer *iwork, integer *ifail, integer *info); -extern int dsteqr_(char *compz, integer *n, doublereal *d__, doublereal *e, - doublereal *z__, integer *ldz, doublereal *work, - integer *info, ftnlen compz_len); -extern int dsterf_(integer *n, doublereal *d__, doublereal *e, integer *info); -extern int dstev_(char *jobz, integer *n, doublereal *d__, doublereal *e, - doublereal *z__, integer *ldz, doublereal *work, - integer *info, ftnlen jobz_len); -extern int dstevd_(char *jobz, integer *n, doublereal *d__, doublereal *e, - doublereal *z__, integer *ldz, doublereal *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len); -extern int dstevr_(char *jobz, char *range, integer *n, doublereal *d__, - doublereal *e, doublereal *vl, doublereal *vu, integer *il, - integer *iu, doublereal *abstol, integer *m, doublereal *w, - doublereal *z__, integer *ldz, integer *isuppz, - doublereal *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen range_len); -extern int dstevx_(char *jobz, char *range, integer *n, doublereal *d__, - doublereal *e, doublereal *vl, doublereal *vu, integer *il, - integer *iu, doublereal *abstol, integer *m, doublereal *w, - doublereal *z__, integer *ldz, doublereal *work, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len); -extern int dsycon_(char *uplo, integer *n, doublereal *a, integer *lda, - integer *ipiv, doublereal *anorm, doublereal *rcond, - doublereal *work, integer *iwork, integer *info, - ftnlen uplo_len); -extern int dsyev_(char *jobz, char *uplo, integer *n, doublereal *a, - integer *lda, doublereal *w, doublereal *work, integer *lwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int dsyevd_(char *jobz, char *uplo, integer *n, doublereal *a, - integer *lda, doublereal *w, doublereal *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int dsyevr_(char *jobz, char *range, char *uplo, integer *n, - doublereal *a, integer *lda, doublereal *vl, doublereal *vu, - integer *il, integer *iu, doublereal *abstol, integer *m, - doublereal *w, doublereal *z__, integer *ldz, - integer *isuppz, doublereal *work, integer *lwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen range_len, ftnlen uplo_len); -extern int dsyevx_(char *jobz, char *range, char *uplo, integer *n, - doublereal *a, integer *lda, doublereal *vl, doublereal *vu, - integer *il, integer *iu, doublereal *abstol, integer *m, - doublereal *w, doublereal *z__, integer *ldz, - doublereal *work, integer *lwork, integer *iwork, - integer *ifail, integer *info, ftnlen jobz_len, - ftnlen range_len, ftnlen uplo_len); -extern int dsygs2_(integer *itype, char *uplo, integer *n, doublereal *a, - integer *lda, doublereal *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int dsygst_(integer *itype, char *uplo, integer *n, doublereal *a, - integer *lda, doublereal *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int dsygv_(integer *itype, char *jobz, char *uplo, integer *n, - doublereal *a, integer *lda, doublereal *b, integer *ldb, - doublereal *w, doublereal *work, integer *lwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int dsygvd_(integer *itype, char *jobz, char *uplo, integer *n, - doublereal *a, integer *lda, doublereal *b, integer *ldb, - doublereal *w, doublereal *work, integer *lwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int dsygvx_(integer *itype, char *jobz, char *range, char *uplo, - integer *n, doublereal *a, integer *lda, doublereal *b, - integer *ldb, doublereal *vl, doublereal *vu, integer *il, - integer *iu, doublereal *abstol, integer *m, doublereal *w, - doublereal *z__, integer *ldz, doublereal *work, - integer *lwork, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int dsyrfs_(char *uplo, integer *n, integer *nrhs, doublereal *a, - integer *lda, doublereal *af, integer *ldaf, integer *ipiv, - doublereal *b, integer *ldb, doublereal *x, integer *ldx, - doublereal *ferr, doublereal *berr, doublereal *work, - integer *iwork, integer *info, ftnlen uplo_len); -extern int dsysv_(char *uplo, integer *n, integer *nrhs, doublereal *a, - integer *lda, integer *ipiv, doublereal *b, integer *ldb, - doublereal *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int dsysvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublereal *a, integer *lda, doublereal *af, integer *ldaf, - integer *ipiv, doublereal *b, integer *ldb, doublereal *x, - integer *ldx, doublereal *rcond, doublereal *ferr, - doublereal *berr, doublereal *work, integer *lwork, - integer *iwork, integer *info, ftnlen fact_len, - ftnlen uplo_len); -extern int dsytd2_(char *uplo, integer *n, doublereal *a, integer *lda, - doublereal *d__, doublereal *e, doublereal *tau, - integer *info, ftnlen uplo_len); -extern int dsytf2_(char *uplo, integer *n, doublereal *a, integer *lda, - integer *ipiv, integer *info, ftnlen uplo_len); -extern int dsytrd_(char *uplo, integer *n, doublereal *a, integer *lda, - doublereal *d__, doublereal *e, doublereal *tau, - doublereal *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int dsytrf_(char *uplo, integer *n, doublereal *a, integer *lda, - integer *ipiv, doublereal *work, integer *lwork, - integer *info, ftnlen uplo_len); -extern int dsytri_(char *uplo, integer *n, doublereal *a, integer *lda, - integer *ipiv, doublereal *work, integer *info, - ftnlen uplo_len); -extern int dsytrs_(char *uplo, integer *n, integer *nrhs, doublereal *a, - integer *lda, integer *ipiv, doublereal *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int dtbcon_(char *norm, char *uplo, char *diag, integer *n, integer *kd, - doublereal *ab, integer *ldab, doublereal *rcond, - doublereal *work, integer *iwork, integer *info, - ftnlen norm_len, ftnlen uplo_len, ftnlen diag_len); -extern int dtbrfs_(char *uplo, char *trans, char *diag, integer *n, integer *kd, - integer *nrhs, doublereal *ab, integer *ldab, doublereal *b, - integer *ldb, doublereal *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublereal *work, integer *iwork, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int dtbtrs_(char *uplo, char *trans, char *diag, integer *n, integer *kd, - integer *nrhs, doublereal *ab, integer *ldab, doublereal *b, - integer *ldb, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int dtgevc_(char *side, char *howmny, logical *select, integer *n, - doublereal *a, integer *lda, doublereal *b, integer *ldb, - doublereal *vl, integer *ldvl, doublereal *vr, integer *ldvr, - integer *mm, integer *m, doublereal *work, integer *info, - ftnlen side_len, ftnlen howmny_len); -extern int dtgex2_(logical *wantq, logical *wantz, integer *n, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *q, - integer *ldq, doublereal *z__, integer *ldz, integer *j1, - integer *n1, integer *n2, doublereal *work, integer *lwork, - integer *info); -extern int dtgexc_(logical *wantq, logical *wantz, integer *n, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *q, - integer *ldq, doublereal *z__, integer *ldz, integer *ifst, - integer *ilst, doublereal *work, integer *lwork, - integer *info); -extern int dtgsen_(integer *ijob, logical *wantq, logical *wantz, - logical *select, integer *n, doublereal *a, integer *lda, - doublereal *b, integer *ldb, doublereal *alphar, - doublereal *alphai, doublereal *beta, doublereal *q, - integer *ldq, doublereal *z__, integer *ldz, integer *m, - doublereal *pl, doublereal *pr, doublereal *dif, - doublereal *work, integer *lwork, integer *iwork, - integer *liwork, integer *info); -extern int dtgsja_(char *jobu, char *jobv, char *jobq, integer *m, integer *p, - integer *n, integer *k, integer *l, doublereal *a, - integer *lda, doublereal *b, integer *ldb, doublereal *tola, - doublereal *tolb, doublereal *alpha, doublereal *beta, - doublereal *u, integer *ldu, doublereal *v, integer *ldv, - doublereal *q, integer *ldq, doublereal *work, - integer *ncycle, integer *info, ftnlen jobu_len, - ftnlen jobv_len, ftnlen jobq_len); -extern int dtgsna_(char *job, char *howmny, logical *select, integer *n, - doublereal *a, integer *lda, doublereal *b, integer *ldb, - doublereal *vl, integer *ldvl, doublereal *vr, integer *ldvr, - doublereal *s, doublereal *dif, integer *mm, integer *m, - doublereal *work, integer *lwork, integer *iwork, - integer *info, ftnlen job_len, ftnlen howmny_len); -extern int dtgsy2_(char *trans, integer *ijob, integer *m, integer *n, - doublereal *a, integer *lda, doublereal *b, integer *ldb, - doublereal *c__, integer *ldc, doublereal *d__, integer *ldd, - doublereal *e, integer *lde, doublereal *f, integer *ldf, - doublereal *scale, doublereal *rdsum, doublereal *rdscal, - integer *iwork, integer *pq, integer *info, - ftnlen trans_len); -extern int dtgsyl_(char *trans, integer *ijob, integer *m, integer *n, - doublereal *a, integer *lda, doublereal *b, integer *ldb, - doublereal *c__, integer *ldc, doublereal *d__, integer *ldd, - doublereal *e, integer *lde, doublereal *f, integer *ldf, - doublereal *scale, doublereal *dif, doublereal *work, - integer *lwork, integer *iwork, integer *info, - ftnlen trans_len); -extern int dtpcon_(char *norm, char *uplo, char *diag, integer *n, - doublereal *ap, doublereal *rcond, doublereal *work, - integer *iwork, integer *info, ftnlen norm_len, - ftnlen uplo_len, ftnlen diag_len); -extern int dtprfs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, doublereal *ap, doublereal *b, integer *ldb, - doublereal *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublereal *work, integer *iwork, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int dtptri_(char *uplo, char *diag, integer *n, doublereal *ap, - integer *info, ftnlen uplo_len, ftnlen diag_len); -extern int dtptrs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, doublereal *ap, doublereal *b, integer *ldb, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int dtrcon_(char *norm, char *uplo, char *diag, integer *n, - doublereal *a, integer *lda, doublereal *rcond, - doublereal *work, integer *iwork, integer *info, - ftnlen norm_len, ftnlen uplo_len, ftnlen diag_len); -extern int dtrevc_(char *side, char *howmny, logical *select, integer *n, - doublereal *t, integer *ldt, doublereal *vl, integer *ldvl, - doublereal *vr, integer *ldvr, integer *mm, integer *m, - doublereal *work, integer *info, ftnlen side_len, - ftnlen howmny_len); -extern int dtrexc_(char *compq, integer *n, doublereal *t, integer *ldt, - doublereal *q, integer *ldq, integer *ifst, integer *ilst, - doublereal *work, integer *info, ftnlen compq_len); -extern int dtrrfs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, doublereal *a, integer *lda, doublereal *b, - integer *ldb, doublereal *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublereal *work, integer *iwork, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int dtrsen_(char *job, char *compq, logical *select, integer *n, - doublereal *t, integer *ldt, doublereal *q, integer *ldq, - doublereal *wr, doublereal *wi, integer *m, doublereal *s, - doublereal *sep, doublereal *work, integer *lwork, - integer *iwork, integer *liwork, integer *info, - ftnlen job_len, ftnlen compq_len); -extern int dtrsna_(char *job, char *howmny, logical *select, integer *n, - doublereal *t, integer *ldt, doublereal *vl, integer *ldvl, - doublereal *vr, integer *ldvr, doublereal *s, - doublereal *sep, integer *mm, integer *m, doublereal *work, - integer *ldwork, integer *iwork, integer *info, - ftnlen job_len, ftnlen howmny_len); -extern int dtrsyl_(char *trana, char *tranb, integer *isgn, integer *m, - integer *n, doublereal *a, integer *lda, doublereal *b, - integer *ldb, doublereal *c__, integer *ldc, - doublereal *scale, integer *info, ftnlen trana_len, - ftnlen tranb_len); -extern int dtrti2_(char *uplo, char *diag, integer *n, doublereal *a, - integer *lda, integer *info, ftnlen uplo_len, - ftnlen diag_len); -extern int dtrtri_(char *uplo, char *diag, integer *n, doublereal *a, - integer *lda, integer *info, ftnlen uplo_len, - ftnlen diag_len); -extern int dtrtrs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, doublereal *a, integer *lda, doublereal *b, - integer *ldb, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int dtzrqf_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, integer *info); -extern int dtzrzf_(integer *m, integer *n, doublereal *a, integer *lda, - doublereal *tau, doublereal *work, integer *lwork, - integer *info); -extern doublereal dzsum1_(integer *n, doublecomplex *cx, integer *incx); -extern integer icmax1_(integer *n, complex *cx, integer *incx); -extern integer ieeeck_(integer *ispec, real *zero, real *one); -extern integer ilaenv_(integer *ispec, char *name__, char *opts, integer *n1, - integer *n2, integer *n3, integer *n4, ftnlen name_len, - ftnlen opts_len); -extern integer izmax1_(integer *n, doublecomplex *cx, integer *incx); -extern logical lsame_(char *ca, char *cb, ftnlen ca_len, ftnlen cb_len); -extern logical lsamen_(integer *n, char *ca, char *cb, ftnlen ca_len, - ftnlen cb_len); -extern int sbdsdc_(char *uplo, char *compq, integer *n, real *d__, real *e, - real *u, integer *ldu, real *vt, integer *ldvt, real *q, - integer *iq, real *work, integer *iwork, integer *info, - ftnlen uplo_len, ftnlen compq_len); -extern int sbdsqr_(char *uplo, integer *n, integer *ncvt, integer *nru, - integer *ncc, real *d__, real *e, real *vt, integer *ldvt, - real *u, integer *ldu, real *c__, integer *ldc, real *work, - integer *info, ftnlen uplo_len); -extern E_f scsum1_(integer *n, complex *cx, integer *incx); -extern int sdisna_(char *job, integer *m, integer *n, real *d__, real *sep, - integer *info, ftnlen job_len); -extern E_f second_(void); -extern int sgbbrd_(char *vect, integer *m, integer *n, integer *ncc, - integer *kl, integer *ku, real *ab, integer *ldab, real *d__, - real *e, real *q, integer *ldq, real *pt, integer *ldpt, - real *c__, integer *ldc, real *work, integer *info, - ftnlen vect_len); -extern int sgbcon_(char *norm, integer *n, integer *kl, integer *ku, real *ab, - integer *ldab, integer *ipiv, real *anorm, real *rcond, - real *work, integer *iwork, integer *info, ftnlen norm_len); -extern int sgbequ_(integer *m, integer *n, integer *kl, integer *ku, real *ab, - integer *ldab, real *r__, real *c__, real *rowcnd, - real *colcnd, real *amax, integer *info); -extern int sgbrfs_(char *trans, integer *n, integer *kl, integer *ku, - integer *nrhs, real *ab, integer *ldab, real *afb, - integer *ldafb, integer *ipiv, real *b, integer *ldb, - real *x, integer *ldx, real *ferr, real *berr, real *work, - integer *iwork, integer *info, ftnlen trans_len); -extern int sgbsv_(integer *n, integer *kl, integer *ku, integer *nrhs, real *ab, - integer *ldab, integer *ipiv, real *b, integer *ldb, - integer *info); -extern int sgbsvx_(char *fact, char *trans, integer *n, integer *kl, - integer *ku, integer *nrhs, real *ab, integer *ldab, - real *afb, integer *ldafb, integer *ipiv, char *equed, - real *r__, real *c__, real *b, integer *ldb, real *x, - integer *ldx, real *rcond, real *ferr, real *berr, - real *work, integer *iwork, integer *info, ftnlen fact_len, - ftnlen trans_len, ftnlen equed_len); -extern int sgbtf2_(integer *m, integer *n, integer *kl, integer *ku, real *ab, - integer *ldab, integer *ipiv, integer *info); -extern int sgbtrf_(integer *m, integer *n, integer *kl, integer *ku, real *ab, - integer *ldab, integer *ipiv, integer *info); -extern int sgbtrs_(char *trans, integer *n, integer *kl, integer *ku, - integer *nrhs, real *ab, integer *ldab, integer *ipiv, - real *b, integer *ldb, integer *info, ftnlen trans_len); -extern int sgebak_(char *job, char *side, integer *n, integer *ilo, - integer *ihi, real *scale, integer *m, real *v, integer *ldv, - integer *info, ftnlen job_len, ftnlen side_len); -extern int sgebal_(char *job, integer *n, real *a, integer *lda, integer *ilo, - integer *ihi, real *scale, integer *info, ftnlen job_len); -extern int sgebd2_(integer *m, integer *n, real *a, integer *lda, real *d__, - real *e, real *tauq, real *taup, real *work, integer *info); -extern int sgebrd_(integer *m, integer *n, real *a, integer *lda, real *d__, - real *e, real *tauq, real *taup, real *work, integer *lwork, - integer *info); -extern int sgecon_(char *norm, integer *n, real *a, integer *lda, real *anorm, - real *rcond, real *work, integer *iwork, integer *info, - ftnlen norm_len); -extern int sgeequ_(integer *m, integer *n, real *a, integer *lda, real *r__, - real *c__, real *rowcnd, real *colcnd, real *amax, - integer *info); -extern int sgees_(char *jobvs, char *sort, L_fp select, integer *n, real *a, - integer *lda, integer *sdim, real *wr, real *wi, real *vs, - integer *ldvs, real *work, integer *lwork, logical *bwork, - integer *info, ftnlen jobvs_len, ftnlen sort_len); -extern int sgeesx_(char *jobvs, char *sort, L_fp select, char *sense, - integer *n, real *a, integer *lda, integer *sdim, real *wr, - real *wi, real *vs, integer *ldvs, real *rconde, - real *rcondv, real *work, integer *lwork, integer *iwork, - integer *liwork, logical *bwork, integer *info, - ftnlen jobvs_len, ftnlen sort_len, ftnlen sense_len); -extern int sgeev_(char *jobvl, char *jobvr, integer *n, real *a, integer *lda, - real *wr, real *wi, real *vl, integer *ldvl, real *vr, - integer *ldvr, real *work, integer *lwork, integer *info, - ftnlen jobvl_len, ftnlen jobvr_len); -extern int sgeevx_(char *balanc, char *jobvl, char *jobvr, char *sense, - integer *n, real *a, integer *lda, real *wr, real *wi, - real *vl, integer *ldvl, real *vr, integer *ldvr, - integer *ilo, integer *ihi, real *scale, real *abnrm, - real *rconde, real *rcondv, real *work, integer *lwork, - integer *iwork, integer *info, ftnlen balanc_len, - ftnlen jobvl_len, ftnlen jobvr_len, ftnlen sense_len); -extern int sgegs_(char *jobvsl, char *jobvsr, integer *n, real *a, integer *lda, - real *b, integer *ldb, real *alphar, real *alphai, real *beta, - real *vsl, integer *ldvsl, real *vsr, integer *ldvsr, - real *work, integer *lwork, integer *info, ftnlen jobvsl_len, - ftnlen jobvsr_len); -extern int sgegv_(char *jobvl, char *jobvr, integer *n, real *a, integer *lda, - real *b, integer *ldb, real *alphar, real *alphai, real *beta, - real *vl, integer *ldvl, real *vr, integer *ldvr, real *work, - integer *lwork, integer *info, ftnlen jobvl_len, - ftnlen jobvr_len); -extern int sgehd2_(integer *n, integer *ilo, integer *ihi, real *a, - integer *lda, real *tau, real *work, integer *info); -extern int sgehrd_(integer *n, integer *ilo, integer *ihi, real *a, - integer *lda, real *tau, real *work, integer *lwork, - integer *info); -extern int sgelq2_(integer *m, integer *n, real *a, integer *lda, real *tau, - real *work, integer *info); -extern int sgelqf_(integer *m, integer *n, real *a, integer *lda, real *tau, - real *work, integer *lwork, integer *info); -extern int sgels_(char *trans, integer *m, integer *n, integer *nrhs, real *a, - integer *lda, real *b, integer *ldb, real *work, - integer *lwork, integer *info, ftnlen trans_len); -extern int sgelsd_(integer *m, integer *n, integer *nrhs, real *a, integer *lda, - real *b, integer *ldb, real *s, real *rcond, integer *rank, - real *work, integer *lwork, integer *iwork, integer *info); -extern int sgelss_(integer *m, integer *n, integer *nrhs, real *a, integer *lda, - real *b, integer *ldb, real *s, real *rcond, integer *rank, - real *work, integer *lwork, integer *info); -extern int sgelsx_(integer *m, integer *n, integer *nrhs, real *a, integer *lda, - real *b, integer *ldb, integer *jpvt, real *rcond, - integer *rank, real *work, integer *info); -extern int sgelsy_(integer *m, integer *n, integer *nrhs, real *a, integer *lda, - real *b, integer *ldb, integer *jpvt, real *rcond, - integer *rank, real *work, integer *lwork, integer *info); -extern int sgeql2_(integer *m, integer *n, real *a, integer *lda, real *tau, - real *work, integer *info); -extern int sgeqlf_(integer *m, integer *n, real *a, integer *lda, real *tau, - real *work, integer *lwork, integer *info); -extern int sgeqp3_(integer *m, integer *n, real *a, integer *lda, integer *jpvt, - real *tau, real *work, integer *lwork, integer *info); -extern int sgeqpf_(integer *m, integer *n, real *a, integer *lda, integer *jpvt, - real *tau, real *work, integer *info); -extern int sgeqr2_(integer *m, integer *n, real *a, integer *lda, real *tau, - real *work, integer *info); -extern int sgeqrf_(integer *m, integer *n, real *a, integer *lda, real *tau, - real *work, integer *lwork, integer *info); -extern int sgerfs_(char *trans, integer *n, integer *nrhs, real *a, - integer *lda, real *af, integer *ldaf, integer *ipiv, - real *b, integer *ldb, real *x, integer *ldx, real *ferr, - real *berr, real *work, integer *iwork, integer *info, - ftnlen trans_len); -extern int sgerq2_(integer *m, integer *n, real *a, integer *lda, real *tau, - real *work, integer *info); -extern int sgerqf_(integer *m, integer *n, real *a, integer *lda, real *tau, - real *work, integer *lwork, integer *info); -extern int sgesc2_(integer *n, real *a, integer *lda, real *rhs, integer *ipiv, - integer *jpiv, real *scale); -extern int sgesdd_(char *jobz, integer *m, integer *n, real *a, integer *lda, - real *s, real *u, integer *ldu, real *vt, integer *ldvt, - real *work, integer *lwork, integer *iwork, integer *info, - ftnlen jobz_len); -extern int sgesv_(integer *n, integer *nrhs, real *a, integer *lda, - integer *ipiv, real *b, integer *ldb, integer *info); -extern int sgesvd_(char *jobu, char *jobvt, integer *m, integer *n, real *a, - integer *lda, real *s, real *u, integer *ldu, real *vt, - integer *ldvt, real *work, integer *lwork, integer *info, - ftnlen jobu_len, ftnlen jobvt_len); -extern int sgesvx_(char *fact, char *trans, integer *n, integer *nrhs, real *a, - integer *lda, real *af, integer *ldaf, integer *ipiv, - char *equed, real *r__, real *c__, real *b, integer *ldb, - real *x, integer *ldx, real *rcond, real *ferr, real *berr, - real *work, integer *iwork, integer *info, ftnlen fact_len, - ftnlen trans_len, ftnlen equed_len); -extern int sgetc2_(integer *n, real *a, integer *lda, integer *ipiv, - integer *jpiv, integer *info); -extern int sgetf2_(integer *m, integer *n, real *a, integer *lda, integer *ipiv, - integer *info); -extern int sgetrf_(integer *m, integer *n, real *a, integer *lda, integer *ipiv, - integer *info); -extern int sgetri_(integer *n, real *a, integer *lda, integer *ipiv, real *work, - integer *lwork, integer *info); -extern int sgetrs_(char *trans, integer *n, integer *nrhs, real *a, - integer *lda, integer *ipiv, real *b, integer *ldb, - integer *info, ftnlen trans_len); -extern int sggbak_(char *job, char *side, integer *n, integer *ilo, - integer *ihi, real *lscale, real *rscale, integer *m, - real *v, integer *ldv, integer *info, ftnlen job_len, - ftnlen side_len); -extern int sggbal_(char *job, integer *n, real *a, integer *lda, real *b, - integer *ldb, integer *ilo, integer *ihi, real *lscale, - real *rscale, real *work, integer *info, ftnlen job_len); -extern int sgges_(char *jobvsl, char *jobvsr, char *sort, L_fp selctg, - integer *n, real *a, integer *lda, real *b, integer *ldb, - integer *sdim, real *alphar, real *alphai, real *beta, - real *vsl, integer *ldvsl, real *vsr, integer *ldvsr, - real *work, integer *lwork, logical *bwork, integer *info, - ftnlen jobvsl_len, ftnlen jobvsr_len, ftnlen sort_len); -extern int sggesx_(char *jobvsl, char *jobvsr, char *sort, L_fp selctg, - char *sense, integer *n, real *a, integer *lda, real *b, - integer *ldb, integer *sdim, real *alphar, real *alphai, - real *beta, real *vsl, integer *ldvsl, real *vsr, - integer *ldvsr, real *rconde, real *rcondv, real *work, - integer *lwork, integer *iwork, integer *liwork, - logical *bwork, integer *info, ftnlen jobvsl_len, - ftnlen jobvsr_len, ftnlen sort_len, ftnlen sense_len); -extern int sggev_(char *jobvl, char *jobvr, integer *n, real *a, integer *lda, - real *b, integer *ldb, real *alphar, real *alphai, real *beta, - real *vl, integer *ldvl, real *vr, integer *ldvr, real *work, - integer *lwork, integer *info, ftnlen jobvl_len, - ftnlen jobvr_len); -extern int sggevx_(char *balanc, char *jobvl, char *jobvr, char *sense, - integer *n, real *a, integer *lda, real *b, integer *ldb, - real *alphar, real *alphai, real *beta, real *vl, - integer *ldvl, real *vr, integer *ldvr, integer *ilo, - integer *ihi, real *lscale, real *rscale, real *abnrm, - real *bbnrm, real *rconde, real *rcondv, real *work, - integer *lwork, integer *iwork, logical *bwork, - integer *info, ftnlen balanc_len, ftnlen jobvl_len, - ftnlen jobvr_len, ftnlen sense_len); -extern int sggglm_(integer *n, integer *m, integer *p, real *a, integer *lda, - real *b, integer *ldb, real *d__, real *x, real *y, - real *work, integer *lwork, integer *info); -extern int sgghrd_(char *compq, char *compz, integer *n, integer *ilo, - integer *ihi, real *a, integer *lda, real *b, integer *ldb, - real *q, integer *ldq, real *z__, integer *ldz, - integer *info, ftnlen compq_len, ftnlen compz_len); -extern int sgglse_(integer *m, integer *n, integer *p, real *a, integer *lda, - real *b, integer *ldb, real *c__, real *d__, real *x, - real *work, integer *lwork, integer *info); -extern int sggqrf_(integer *n, integer *m, integer *p, real *a, integer *lda, - real *taua, real *b, integer *ldb, real *taub, real *work, - integer *lwork, integer *info); -extern int sggrqf_(integer *m, integer *p, integer *n, real *a, integer *lda, - real *taua, real *b, integer *ldb, real *taub, real *work, - integer *lwork, integer *info); -extern int sggsvd_(char *jobu, char *jobv, char *jobq, integer *m, integer *n, - integer *p, integer *k, integer *l, real *a, integer *lda, - real *b, integer *ldb, real *alpha, real *beta, real *u, - integer *ldu, real *v, integer *ldv, real *q, integer *ldq, - real *work, integer *iwork, integer *info, ftnlen jobu_len, - ftnlen jobv_len, ftnlen jobq_len); -extern int sggsvp_(char *jobu, char *jobv, char *jobq, integer *m, integer *p, - integer *n, real *a, integer *lda, real *b, integer *ldb, - real *tola, real *tolb, integer *k, integer *l, real *u, - integer *ldu, real *v, integer *ldv, real *q, integer *ldq, - integer *iwork, real *tau, real *work, integer *info, - ftnlen jobu_len, ftnlen jobv_len, ftnlen jobq_len); -extern int sgtcon_(char *norm, integer *n, real *dl, real *d__, real *du, - real *du2, integer *ipiv, real *anorm, real *rcond, - real *work, integer *iwork, integer *info, ftnlen norm_len); -extern int sgtrfs_(char *trans, integer *n, integer *nrhs, real *dl, real *d__, - real *du, real *dlf, real *df, real *duf, real *du2, - integer *ipiv, real *b, integer *ldb, real *x, integer *ldx, - real *ferr, real *berr, real *work, integer *iwork, - integer *info, ftnlen trans_len); -extern int sgtsv_(integer *n, integer *nrhs, real *dl, real *d__, real *du, - real *b, integer *ldb, integer *info); -extern int sgtsvx_(char *fact, char *trans, integer *n, integer *nrhs, real *dl, - real *d__, real *du, real *dlf, real *df, real *duf, - real *du2, integer *ipiv, real *b, integer *ldb, real *x, - integer *ldx, real *rcond, real *ferr, real *berr, - real *work, integer *iwork, integer *info, ftnlen fact_len, - ftnlen trans_len); -extern int sgttrf_(integer *n, real *dl, real *d__, real *du, real *du2, - integer *ipiv, integer *info); -extern int sgttrs_(char *trans, integer *n, integer *nrhs, real *dl, real *d__, - real *du, real *du2, integer *ipiv, real *b, integer *ldb, - integer *info, ftnlen trans_len); -extern int sgtts2_(integer *itrans, integer *n, integer *nrhs, real *dl, - real *d__, real *du, real *du2, integer *ipiv, real *b, - integer *ldb); -extern int shgeqz_(char *job, char *compq, char *compz, integer *n, - integer *ilo, integer *ihi, real *a, integer *lda, real *b, - integer *ldb, real *alphar, real *alphai, real *beta, - real *q, integer *ldq, real *z__, integer *ldz, real *work, - integer *lwork, integer *info, ftnlen job_len, - ftnlen compq_len, ftnlen compz_len); -extern int shsein_(char *side, char *eigsrc, char *initv, logical *select, - integer *n, real *h__, integer *ldh, real *wr, real *wi, - real *vl, integer *ldvl, real *vr, integer *ldvr, - integer *mm, integer *m, real *work, integer *ifaill, - integer *ifailr, integer *info, ftnlen side_len, - ftnlen eigsrc_len, ftnlen initv_len); -extern int shseqr_(char *job, char *compz, integer *n, integer *ilo, - integer *ihi, real *h__, integer *ldh, real *wr, real *wi, - real *z__, integer *ldz, real *work, integer *lwork, - integer *info, ftnlen job_len, ftnlen compz_len); -extern int slabad_(real *small, real *large); -extern int slabrd_(integer *m, integer *n, integer *nb, real *a, integer *lda, - real *d__, real *e, real *tauq, real *taup, real *x, - integer *ldx, real *y, integer *ldy); -extern int slacon_(integer *n, real *v, real *x, integer *isgn, real *est, - integer *kase); -extern int slacpy_(char *uplo, integer *m, integer *n, real *a, integer *lda, - real *b, integer *ldb, ftnlen uplo_len); -extern int sladiv_(real *a, real *b, real *c__, real *d__, real *p, real *q); -extern int slae2_(real *a, real *b, real *c__, real *rt1, real *rt2); -extern int slaebz_(integer *ijob, integer *nitmax, integer *n, integer *mmax, - integer *minp, integer *nbmin, real *abstol, real *reltol, - real *pivmin, real *d__, real *e, real *e2, integer *nval, - real *ab, real *c__, integer *mout, integer *nab, real *work, - integer *iwork, integer *info); -extern int slaed0_(integer *icompq, integer *qsiz, integer *n, real *d__, - real *e, real *q, integer *ldq, real *qstore, integer *ldqs, - real *work, integer *iwork, integer *info); -extern int slaed1_(integer *n, real *d__, real *q, integer *ldq, integer *indxq, - real *rho, integer *cutpnt, real *work, integer *iwork, - integer *info); -extern int slaed2_(integer *k, integer *n, integer *n1, real *d__, real *q, - integer *ldq, integer *indxq, real *rho, real *z__, - real *dlamda, real *w, real *q2, integer *indx, - integer *indxc, integer *indxp, integer *coltyp, - integer *info); -extern int slaed3_(integer *k, integer *n, integer *n1, real *d__, real *q, - integer *ldq, real *rho, real *dlamda, real *q2, - integer *indx, integer *ctot, real *w, real *s, - integer *info); -extern int slaed4_(integer *n, integer *i__, real *d__, real *z__, real *delta, - real *rho, real *dlam, integer *info); -extern int slaed5_(integer *i__, real *d__, real *z__, real *delta, real *rho, - real *dlam); -extern int slaed6_(integer *kniter, logical *orgati, real *rho, real *d__, - real *z__, real *finit, real *tau, integer *info); -extern int slaed7_(integer *icompq, integer *n, integer *qsiz, integer *tlvls, - integer *curlvl, integer *curpbm, real *d__, real *q, - integer *ldq, integer *indxq, real *rho, integer *cutpnt, - real *qstore, integer *qptr, integer *prmptr, integer *perm, - integer *givptr, integer *givcol, real *givnum, real *work, - integer *iwork, integer *info); -extern int slaed8_(integer *icompq, integer *k, integer *n, integer *qsiz, - real *d__, real *q, integer *ldq, integer *indxq, real *rho, - integer *cutpnt, real *z__, real *dlamda, real *q2, - integer *ldq2, real *w, integer *perm, integer *givptr, - integer *givcol, real *givnum, integer *indxp, integer *indx, - integer *info); -extern int slaed9_(integer *k, integer *kstart, integer *kstop, integer *n, - real *d__, real *q, integer *ldq, real *rho, real *dlamda, - real *w, real *s, integer *lds, integer *info); -extern int slaeda_(integer *n, integer *tlvls, integer *curlvl, integer *curpbm, - integer *prmptr, integer *perm, integer *givptr, - integer *givcol, real *givnum, real *q, integer *qptr, - real *z__, real *ztemp, integer *info); -extern int slaein_(logical *rightv, logical *noinit, integer *n, real *h__, - integer *ldh, real *wr, real *wi, real *vr, real *vi, - real *b, integer *ldb, real *work, real *eps3, real *smlnum, - real *bignum, integer *info); -extern int slaev2_(real *a, real *b, real *c__, real *rt1, real *rt2, real *cs1, - real *sn1); -extern int slaexc_(logical *wantq, integer *n, real *t, integer *ldt, real *q, - integer *ldq, integer *j1, integer *n1, integer *n2, - real *work, integer *info); -extern int slag2_(real *a, integer *lda, real *b, integer *ldb, real *safmin, - real *scale1, real *scale2, real *wr1, real *wr2, real *wi); -extern int slags2_(logical *upper, real *a1, real *a2, real *a3, real *b1, - real *b2, real *b3, real *csu, real *snu, real *csv, - real *snv, real *csq, real *snq); -extern int slagtf_(integer *n, real *a, real *lambda, real *b, real *c__, - real *tol, real *d__, integer *in, integer *info); -extern int slagtm_(char *trans, integer *n, integer *nrhs, real *alpha, - real *dl, real *d__, real *du, real *x, integer *ldx, - real *beta, real *b, integer *ldb, ftnlen trans_len); -extern int slagts_(integer *job, integer *n, real *a, real *b, real *c__, - real *d__, integer *in, real *y, real *tol, integer *info); -extern int slagv2_(real *a, integer *lda, real *b, integer *ldb, real *alphar, - real *alphai, real *beta, real *csl, real *snl, real *csr, - real *snr); -extern int slahqr_(logical *wantt, logical *wantz, integer *n, integer *ilo, - integer *ihi, real *h__, integer *ldh, real *wr, real *wi, - integer *iloz, integer *ihiz, real *z__, integer *ldz, - integer *info); -extern int slahrd_(integer *n, integer *k, integer *nb, real *a, integer *lda, - real *tau, real *t, integer *ldt, real *y, integer *ldy); -extern int slaic1_(integer *job, integer *j, real *x, real *sest, real *w, - real *gamma, real *sestpr, real *s, real *c__); -extern int slaln2_(logical *ltrans, integer *na, integer *nw, real *smin, - real *ca, real *a, integer *lda, real *d1, real *d2, real *b, - integer *ldb, real *wr, real *wi, real *x, integer *ldx, - real *scale, real *xnorm, integer *info); -extern int slals0_(integer *icompq, integer *nl, integer *nr, integer *sqre, - integer *nrhs, real *b, integer *ldb, real *bx, - integer *ldbx, integer *perm, integer *givptr, - integer *givcol, integer *ldgcol, real *givnum, - integer *ldgnum, real *poles, real *difl, real *difr, - real *z__, integer *k, real *c__, real *s, real *work, - integer *info); -extern int slalsa_(integer *icompq, integer *smlsiz, integer *n, integer *nrhs, - real *b, integer *ldb, real *bx, integer *ldbx, real *u, - integer *ldu, real *vt, integer *k, real *difl, real *difr, - real *z__, real *poles, integer *givptr, integer *givcol, - integer *ldgcol, integer *perm, real *givnum, real *c__, - real *s, real *work, integer *iwork, integer *info); -extern int slalsd_(char *uplo, integer *smlsiz, integer *n, integer *nrhs, - real *d__, real *e, real *b, integer *ldb, real *rcond, - integer *rank, real *work, integer *iwork, integer *info, - ftnlen uplo_len); -extern E_f slamch_(char *cmach, ftnlen cmach_len); -extern int slamc1_(integer *beta, integer *t, logical *rnd, logical *ieee1); -extern int slamc2_(integer *beta, integer *t, logical *rnd, real *eps, - integer *emin, real *rmin, integer *emax, real *rmax); -extern E_f slamc3_(real *a, real *b); -extern int slamc4_(integer *emin, real *start, integer *base); -extern int slamc5_(integer *beta, integer *p, integer *emin, logical *ieee, - integer *emax, real *rmax); -extern int slamrg_(integer *n1, integer *n2, real *a, integer *strd1, - integer *strd2, integer *index); -extern E_f slangb_(char *norm, integer *n, integer *kl, integer *ku, real *ab, - integer *ldab, real *work, ftnlen norm_len); -extern E_f slange_(char *norm, integer *m, integer *n, real *a, integer *lda, - real *work, ftnlen norm_len); -extern E_f slangt_(char *norm, integer *n, real *dl, real *d__, real *du, - ftnlen norm_len); -extern E_f slanhs_(char *norm, integer *n, real *a, integer *lda, real *work, - ftnlen norm_len); -extern E_f slansb_(char *norm, char *uplo, integer *n, integer *k, real *ab, - integer *ldab, real *work, ftnlen norm_len, ftnlen uplo_len); -extern E_f slansp_(char *norm, char *uplo, integer *n, real *ap, real *work, - ftnlen norm_len, ftnlen uplo_len); -extern E_f slanst_(char *norm, integer *n, real *d__, real *e, ftnlen norm_len); -extern E_f slansy_(char *norm, char *uplo, integer *n, real *a, integer *lda, - real *work, ftnlen norm_len, ftnlen uplo_len); -extern E_f slantb_(char *norm, char *uplo, char *diag, integer *n, integer *k, - real *ab, integer *ldab, real *work, ftnlen norm_len, - ftnlen uplo_len, ftnlen diag_len); -extern E_f slantp_(char *norm, char *uplo, char *diag, integer *n, real *ap, - real *work, ftnlen norm_len, ftnlen uplo_len, - ftnlen diag_len); -extern E_f slantr_(char *norm, char *uplo, char *diag, integer *m, integer *n, - real *a, integer *lda, real *work, ftnlen norm_len, - ftnlen uplo_len, ftnlen diag_len); -extern int slanv2_(real *a, real *b, real *c__, real *d__, real *rt1r, - real *rt1i, real *rt2r, real *rt2i, real *cs, real *sn); -extern int slapll_(integer *n, real *x, integer *incx, real *y, integer *incy, - real *ssmin); -extern int slapmt_(logical *forwrd, integer *m, integer *n, real *x, - integer *ldx, integer *k); -extern E_f slapy2_(real *x, real *y); -extern E_f slapy3_(real *x, real *y, real *z__); -extern int slaqgb_(integer *m, integer *n, integer *kl, integer *ku, real *ab, - integer *ldab, real *r__, real *c__, real *rowcnd, - real *colcnd, real *amax, char *equed, ftnlen equed_len); -extern int slaqge_(integer *m, integer *n, real *a, integer *lda, real *r__, - real *c__, real *rowcnd, real *colcnd, real *amax, - char *equed, ftnlen equed_len); -extern int slaqp2_(integer *m, integer *n, integer *offset, real *a, - integer *lda, integer *jpvt, real *tau, real *vn1, real *vn2, - real *work); -extern int slaqps_(integer *m, integer *n, integer *offset, integer *nb, - integer *kb, real *a, integer *lda, integer *jpvt, real *tau, - real *vn1, real *vn2, real *auxv, real *f, integer *ldf); -extern int slaqsb_(char *uplo, integer *n, integer *kd, real *ab, integer *ldab, - real *s, real *scond, real *amax, char *equed, - ftnlen uplo_len, ftnlen equed_len); -extern int slaqsp_(char *uplo, integer *n, real *ap, real *s, real *scond, - real *amax, char *equed, ftnlen uplo_len, ftnlen equed_len); -extern int slaqsy_(char *uplo, integer *n, real *a, integer *lda, real *s, - real *scond, real *amax, char *equed, ftnlen uplo_len, - ftnlen equed_len); -extern int slaqtr_(logical *ltran, logical *lreal, integer *n, real *t, - integer *ldt, real *b, real *w, real *scale, real *x, - real *work, integer *info); -extern int slar1v_(integer *n, integer *b1, integer *bn, real *sigma, real *d__, - real *l, real *ld, real *lld, real *gersch, real *z__, - real *ztz, real *mingma, integer *r__, integer *isuppz, - real *work); -extern int slar2v_(integer *n, real *x, real *y, real *z__, integer *incx, - real *c__, real *s, integer *incc); -extern int slarf_(char *side, integer *m, integer *n, real *v, integer *incv, - real *tau, real *c__, integer *ldc, real *work, - ftnlen side_len); -extern int slarfb_(char *side, char *trans, char *direct, char *storev, - integer *m, integer *n, integer *k, real *v, integer *ldv, - real *t, integer *ldt, real *c__, integer *ldc, real *work, - integer *ldwork, ftnlen side_len, ftnlen trans_len, - ftnlen direct_len, ftnlen storev_len); -extern int slarfg_(integer *n, real *alpha, real *x, integer *incx, real *tau); -extern int slarft_(char *direct, char *storev, integer *n, integer *k, real *v, - integer *ldv, real *tau, real *t, integer *ldt, - ftnlen direct_len, ftnlen storev_len); -extern int slarfx_(char *side, integer *m, integer *n, real *v, real *tau, - real *c__, integer *ldc, real *work, ftnlen side_len); -extern int slargv_(integer *n, real *x, integer *incx, real *y, integer *incy, - real *c__, integer *incc); -extern int slarnv_(integer *idist, integer *iseed, integer *n, real *x); -extern int slarrb_(integer *n, real *d__, real *l, real *ld, real *lld, - integer *ifirst, integer *ilast, real *sigma, real *reltol, - real *w, real *wgap, real *werr, real *work, integer *iwork, - integer *info); -extern int slarre_(integer *n, real *d__, real *e, real *tol, integer *nsplit, - integer *isplit, integer *m, real *w, real *woff, - real *gersch, real *work, integer *info); -extern int slarrf_(integer *n, real *d__, real *l, real *ld, real *lld, - integer *ifirst, integer *ilast, real *w, real *dplus, - real *lplus, real *work, integer *iwork, integer *info); -extern int slarrv_(integer *n, real *d__, real *l, integer *isplit, integer *m, - real *w, integer *iblock, real *gersch, real *tol, real *z__, - integer *ldz, integer *isuppz, real *work, integer *iwork, - integer *info); -extern int slartg_(real *f, real *g, real *cs, real *sn, real *r__); -extern int slartv_(integer *n, real *x, integer *incx, real *y, integer *incy, - real *c__, real *s, integer *incc); -extern int slaruv_(integer *iseed, integer *n, real *x); -extern int slarz_(char *side, integer *m, integer *n, integer *l, real *v, - integer *incv, real *tau, real *c__, integer *ldc, real *work, - ftnlen side_len); -extern int slarzb_(char *side, char *trans, char *direct, char *storev, - integer *m, integer *n, integer *k, integer *l, real *v, - integer *ldv, real *t, integer *ldt, real *c__, integer *ldc, - real *work, integer *ldwork, ftnlen side_len, - ftnlen trans_len, ftnlen direct_len, ftnlen storev_len); -extern int slarzt_(char *direct, char *storev, integer *n, integer *k, real *v, - integer *ldv, real *tau, real *t, integer *ldt, - ftnlen direct_len, ftnlen storev_len); -extern int slas2_(real *f, real *g, real *h__, real *ssmin, real *ssmax); -extern int slascl_(char *type__, integer *kl, integer *ku, real *cfrom, - real *cto, integer *m, integer *n, real *a, integer *lda, - integer *info, ftnlen type_len); -extern int slasd0_(integer *n, integer *sqre, real *d__, real *e, real *u, - integer *ldu, real *vt, integer *ldvt, integer *smlsiz, - integer *iwork, real *work, integer *info); -extern int slasd1_(integer *nl, integer *nr, integer *sqre, real *d__, - real *alpha, real *beta, real *u, integer *ldu, real *vt, - integer *ldvt, integer *idxq, integer *iwork, real *work, - integer *info); -extern int slasd2_(integer *nl, integer *nr, integer *sqre, integer *k, - real *d__, real *z__, real *alpha, real *beta, real *u, - integer *ldu, real *vt, integer *ldvt, real *dsigma, - real *u2, integer *ldu2, real *vt2, integer *ldvt2, - integer *idxp, integer *idx, integer *idxc, integer *idxq, - integer *coltyp, integer *info); -extern int slasd3_(integer *nl, integer *nr, integer *sqre, integer *k, - real *d__, real *q, integer *ldq, real *dsigma, real *u, - integer *ldu, real *u2, integer *ldu2, real *vt, - integer *ldvt, real *vt2, integer *ldvt2, integer *idxc, - integer *ctot, real *z__, integer *info); -extern int slasd4_(integer *n, integer *i__, real *d__, real *z__, real *delta, - real *rho, real *sigma, real *work, integer *info); -extern int slasd5_(integer *i__, real *d__, real *z__, real *delta, real *rho, - real *dsigma, real *work); -extern int slasd6_(integer *icompq, integer *nl, integer *nr, integer *sqre, - real *d__, real *vf, real *vl, real *alpha, real *beta, - integer *idxq, integer *perm, integer *givptr, - integer *givcol, integer *ldgcol, real *givnum, - integer *ldgnum, real *poles, real *difl, real *difr, - real *z__, integer *k, real *c__, real *s, real *work, - integer *iwork, integer *info); -extern int slasd7_(integer *icompq, integer *nl, integer *nr, integer *sqre, - integer *k, real *d__, real *z__, real *zw, real *vf, - real *vfw, real *vl, real *vlw, real *alpha, real *beta, - real *dsigma, integer *idx, integer *idxp, integer *idxq, - integer *perm, integer *givptr, integer *givcol, - integer *ldgcol, real *givnum, integer *ldgnum, real *c__, - real *s, integer *info); -extern int slasd8_(integer *icompq, integer *k, real *d__, real *z__, real *vf, - real *vl, real *difl, real *difr, integer *lddifr, - real *dsigma, real *work, integer *info); -extern int slasd9_(integer *icompq, integer *ldu, integer *k, real *d__, - real *z__, real *vf, real *vl, real *difl, real *difr, - real *dsigma, real *work, integer *info); -extern int slasda_(integer *icompq, integer *smlsiz, integer *n, integer *sqre, - real *d__, real *e, real *u, integer *ldu, real *vt, - integer *k, real *difl, real *difr, real *z__, real *poles, - integer *givptr, integer *givcol, integer *ldgcol, - integer *perm, real *givnum, real *c__, real *s, real *work, - integer *iwork, integer *info); -extern int slasdq_(char *uplo, integer *sqre, integer *n, integer *ncvt, - integer *nru, integer *ncc, real *d__, real *e, real *vt, - integer *ldvt, real *u, integer *ldu, real *c__, - integer *ldc, real *work, integer *info, ftnlen uplo_len); -extern int slasdt_(integer *n, integer *lvl, integer *nd, integer *inode, - integer *ndiml, integer *ndimr, integer *msub); -extern int slaset_(char *uplo, integer *m, integer *n, real *alpha, real *beta, - real *a, integer *lda, ftnlen uplo_len); -extern int slasq1_(integer *n, real *d__, real *e, real *work, integer *info); -extern int slasq2_(integer *n, real *z__, integer *info); -extern int slasq3_(integer *i0, integer *n0, real *z__, integer *pp, - real *dmin__, real *sigma, real *desig, real *qmax, - integer *nfail, integer *iter, integer *ndiv); -extern int slasq4_(integer *i0, integer *n0, real *z__, integer *pp, - integer *n0in, real *dmin__, real *dmin1, real *dmin2, - real *dn, real *dn1, real *dn2, real *tau, integer *ttype); -extern int slasq5_(integer *i0, integer *n0, real *z__, integer *pp, real *tau, - real *dmin__, real *dmin1, real *dmin2, real *dn, real *dnm1, - real *dnm2); -extern int slasq6_(integer *i0, integer *n0, real *z__, integer *pp, - real *dmin__, real *dmin1, real *dmin2, real *dn, real *dnm1, - real *dnm2); -extern int slasr_(char *side, char *pivot, char *direct, integer *m, integer *n, - real *c__, real *s, real *a, integer *lda, ftnlen side_len, - ftnlen pivot_len, ftnlen direct_len); -extern int slasrt_(char *id, integer *n, real *d__, integer *info, - ftnlen id_len); -extern int slassq_(integer *n, real *x, integer *incx, real *scale, - real *sumsq); -extern int slasv2_(real *f, real *g, real *h__, real *ssmin, real *ssmax, - real *snr, real *csr, real *snl, real *csl); -extern int slaswp_(integer *n, real *a, integer *lda, integer *k1, integer *k2, - integer *ipiv, integer *incx); -extern int slasy2_(logical *ltranl, logical *ltranr, integer *isgn, integer *n1, - integer *n2, real *tl, integer *ldtl, real *tr, - integer *ldtr, real *b, integer *ldb, real *scale, real *x, - integer *ldx, real *xnorm, integer *info); -extern int slasyf_(char *uplo, integer *n, integer *nb, integer *kb, real *a, - integer *lda, integer *ipiv, real *w, integer *ldw, - integer *info, ftnlen uplo_len); -extern int slatbs_(char *uplo, char *trans, char *diag, char *normin, - integer *n, integer *kd, real *ab, integer *ldab, real *x, - real *scale, real *cnorm, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len, ftnlen normin_len); -extern int slatdf_(integer *ijob, integer *n, real *z__, integer *ldz, - real *rhs, real *rdsum, real *rdscal, integer *ipiv, - integer *jpiv); -extern int slatps_(char *uplo, char *trans, char *diag, char *normin, - integer *n, real *ap, real *x, real *scale, real *cnorm, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len, ftnlen normin_len); -extern int slatrd_(char *uplo, integer *n, integer *nb, real *a, integer *lda, - real *e, real *tau, real *w, integer *ldw, ftnlen uplo_len); -extern int slatrs_(char *uplo, char *trans, char *diag, char *normin, - integer *n, real *a, integer *lda, real *x, real *scale, - real *cnorm, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len, ftnlen normin_len); -extern int slatrz_(integer *m, integer *n, integer *l, real *a, integer *lda, - real *tau, real *work); -extern int slatzm_(char *side, integer *m, integer *n, real *v, integer *incv, - real *tau, real *c1, real *c2, integer *ldc, real *work, - ftnlen side_len); -extern int slauu2_(char *uplo, integer *n, real *a, integer *lda, integer *info, - ftnlen uplo_len); -extern int slauum_(char *uplo, integer *n, real *a, integer *lda, integer *info, - ftnlen uplo_len); -extern int sopgtr_(char *uplo, integer *n, real *ap, real *tau, real *q, - integer *ldq, real *work, integer *info, ftnlen uplo_len); -extern int sopmtr_(char *side, char *uplo, char *trans, integer *m, integer *n, - real *ap, real *tau, real *c__, integer *ldc, real *work, - integer *info, ftnlen side_len, ftnlen uplo_len, - ftnlen trans_len); -extern int sorg2l_(integer *m, integer *n, integer *k, real *a, integer *lda, - real *tau, real *work, integer *info); -extern int sorg2r_(integer *m, integer *n, integer *k, real *a, integer *lda, - real *tau, real *work, integer *info); -extern int sorgbr_(char *vect, integer *m, integer *n, integer *k, real *a, - integer *lda, real *tau, real *work, integer *lwork, - integer *info, ftnlen vect_len); -extern int sorghr_(integer *n, integer *ilo, integer *ihi, real *a, - integer *lda, real *tau, real *work, integer *lwork, - integer *info); -extern int sorgl2_(integer *m, integer *n, integer *k, real *a, integer *lda, - real *tau, real *work, integer *info); -extern int sorglq_(integer *m, integer *n, integer *k, real *a, integer *lda, - real *tau, real *work, integer *lwork, integer *info); -extern int sorgql_(integer *m, integer *n, integer *k, real *a, integer *lda, - real *tau, real *work, integer *lwork, integer *info); -extern int sorgqr_(integer *m, integer *n, integer *k, real *a, integer *lda, - real *tau, real *work, integer *lwork, integer *info); -extern int sorgr2_(integer *m, integer *n, integer *k, real *a, integer *lda, - real *tau, real *work, integer *info); -extern int sorgrq_(integer *m, integer *n, integer *k, real *a, integer *lda, - real *tau, real *work, integer *lwork, integer *info); -extern int sorgtr_(char *uplo, integer *n, real *a, integer *lda, real *tau, - real *work, integer *lwork, integer *info, ftnlen uplo_len); -extern int sorm2l_(char *side, char *trans, integer *m, integer *n, integer *k, - real *a, integer *lda, real *tau, real *c__, integer *ldc, - real *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int sorm2r_(char *side, char *trans, integer *m, integer *n, integer *k, - real *a, integer *lda, real *tau, real *c__, integer *ldc, - real *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int sormbr_(char *vect, char *side, char *trans, integer *m, integer *n, - integer *k, real *a, integer *lda, real *tau, real *c__, - integer *ldc, real *work, integer *lwork, integer *info, - ftnlen vect_len, ftnlen side_len, ftnlen trans_len); -extern int sormhr_(char *side, char *trans, integer *m, integer *n, - integer *ilo, integer *ihi, real *a, integer *lda, real *tau, - real *c__, integer *ldc, real *work, integer *lwork, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int sorml2_(char *side, char *trans, integer *m, integer *n, integer *k, - real *a, integer *lda, real *tau, real *c__, integer *ldc, - real *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int sormlq_(char *side, char *trans, integer *m, integer *n, integer *k, - real *a, integer *lda, real *tau, real *c__, integer *ldc, - real *work, integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int sormql_(char *side, char *trans, integer *m, integer *n, integer *k, - real *a, integer *lda, real *tau, real *c__, integer *ldc, - real *work, integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int sormqr_(char *side, char *trans, integer *m, integer *n, integer *k, - real *a, integer *lda, real *tau, real *c__, integer *ldc, - real *work, integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int sormr2_(char *side, char *trans, integer *m, integer *n, integer *k, - real *a, integer *lda, real *tau, real *c__, integer *ldc, - real *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int sormr3_(char *side, char *trans, integer *m, integer *n, integer *k, - integer *l, real *a, integer *lda, real *tau, real *c__, - integer *ldc, real *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int sormrq_(char *side, char *trans, integer *m, integer *n, integer *k, - real *a, integer *lda, real *tau, real *c__, integer *ldc, - real *work, integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int sormrz_(char *side, char *trans, integer *m, integer *n, integer *k, - integer *l, real *a, integer *lda, real *tau, real *c__, - integer *ldc, real *work, integer *lwork, integer *info, - ftnlen side_len, ftnlen trans_len); -extern int sormtr_(char *side, char *uplo, char *trans, integer *m, integer *n, - real *a, integer *lda, real *tau, real *c__, integer *ldc, - real *work, integer *lwork, integer *info, ftnlen side_len, - ftnlen uplo_len, ftnlen trans_len); -extern int spbcon_(char *uplo, integer *n, integer *kd, real *ab, integer *ldab, - real *anorm, real *rcond, real *work, integer *iwork, - integer *info, ftnlen uplo_len); -extern int spbequ_(char *uplo, integer *n, integer *kd, real *ab, integer *ldab, - real *s, real *scond, real *amax, integer *info, - ftnlen uplo_len); -extern int spbrfs_(char *uplo, integer *n, integer *kd, integer *nrhs, real *ab, - integer *ldab, real *afb, integer *ldafb, real *b, - integer *ldb, real *x, integer *ldx, real *ferr, real *berr, - real *work, integer *iwork, integer *info, ftnlen uplo_len); -extern int spbstf_(char *uplo, integer *n, integer *kd, real *ab, integer *ldab, - integer *info, ftnlen uplo_len); -extern int spbsv_(char *uplo, integer *n, integer *kd, integer *nrhs, real *ab, - integer *ldab, real *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int spbsvx_(char *fact, char *uplo, integer *n, integer *kd, - integer *nrhs, real *ab, integer *ldab, real *afb, - integer *ldafb, char *equed, real *s, real *b, integer *ldb, - real *x, integer *ldx, real *rcond, real *ferr, real *berr, - real *work, integer *iwork, integer *info, ftnlen fact_len, - ftnlen uplo_len, ftnlen equed_len); -extern int spbtf2_(char *uplo, integer *n, integer *kd, real *ab, integer *ldab, - integer *info, ftnlen uplo_len); -extern int spbtrf_(char *uplo, integer *n, integer *kd, real *ab, integer *ldab, - integer *info, ftnlen uplo_len); -extern int spbtrs_(char *uplo, integer *n, integer *kd, integer *nrhs, real *ab, - integer *ldab, real *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int spocon_(char *uplo, integer *n, real *a, integer *lda, real *anorm, - real *rcond, real *work, integer *iwork, integer *info, - ftnlen uplo_len); -extern int spoequ_(integer *n, real *a, integer *lda, real *s, real *scond, - real *amax, integer *info); -extern int sporfs_(char *uplo, integer *n, integer *nrhs, real *a, integer *lda, - real *af, integer *ldaf, real *b, integer *ldb, real *x, - integer *ldx, real *ferr, real *berr, real *work, - integer *iwork, integer *info, ftnlen uplo_len); -extern int sposv_(char *uplo, integer *n, integer *nrhs, real *a, integer *lda, - real *b, integer *ldb, integer *info, ftnlen uplo_len); -extern int sposvx_(char *fact, char *uplo, integer *n, integer *nrhs, real *a, - integer *lda, real *af, integer *ldaf, char *equed, real *s, - real *b, integer *ldb, real *x, integer *ldx, real *rcond, - real *ferr, real *berr, real *work, integer *iwork, - integer *info, ftnlen fact_len, ftnlen uplo_len, - ftnlen equed_len); -extern int spotf2_(char *uplo, integer *n, real *a, integer *lda, integer *info, - ftnlen uplo_len); -extern int spotrf_(char *uplo, integer *n, real *a, integer *lda, integer *info, - ftnlen uplo_len); -extern int spotri_(char *uplo, integer *n, real *a, integer *lda, integer *info, - ftnlen uplo_len); -extern int spotrs_(char *uplo, integer *n, integer *nrhs, real *a, integer *lda, - real *b, integer *ldb, integer *info, ftnlen uplo_len); -extern int sppcon_(char *uplo, integer *n, real *ap, real *anorm, real *rcond, - real *work, integer *iwork, integer *info, ftnlen uplo_len); -extern int sppequ_(char *uplo, integer *n, real *ap, real *s, real *scond, - real *amax, integer *info, ftnlen uplo_len); -extern int spprfs_(char *uplo, integer *n, integer *nrhs, real *ap, real *afp, - real *b, integer *ldb, real *x, integer *ldx, real *ferr, - real *berr, real *work, integer *iwork, integer *info, - ftnlen uplo_len); -extern int sppsv_(char *uplo, integer *n, integer *nrhs, real *ap, real *b, - integer *ldb, integer *info, ftnlen uplo_len); -extern int sppsvx_(char *fact, char *uplo, integer *n, integer *nrhs, real *ap, - real *afp, char *equed, real *s, real *b, integer *ldb, - real *x, integer *ldx, real *rcond, real *ferr, real *berr, - real *work, integer *iwork, integer *info, ftnlen fact_len, - ftnlen uplo_len, ftnlen equed_len); -extern int spptrf_(char *uplo, integer *n, real *ap, integer *info, - ftnlen uplo_len); -extern int spptri_(char *uplo, integer *n, real *ap, integer *info, - ftnlen uplo_len); -extern int spptrs_(char *uplo, integer *n, integer *nrhs, real *ap, real *b, - integer *ldb, integer *info, ftnlen uplo_len); -extern int sptcon_(integer *n, real *d__, real *e, real *anorm, real *rcond, - real *work, integer *info); -extern int spteqr_(char *compz, integer *n, real *d__, real *e, real *z__, - integer *ldz, real *work, integer *info, ftnlen compz_len); -extern int sptrfs_(integer *n, integer *nrhs, real *d__, real *e, real *df, - real *ef, real *b, integer *ldb, real *x, integer *ldx, - real *ferr, real *berr, real *work, integer *info); -extern int sptsv_(integer *n, integer *nrhs, real *d__, real *e, real *b, - integer *ldb, integer *info); -extern int sptsvx_(char *fact, integer *n, integer *nrhs, real *d__, real *e, - real *df, real *ef, real *b, integer *ldb, real *x, - integer *ldx, real *rcond, real *ferr, real *berr, - real *work, integer *info, ftnlen fact_len); -extern int spttrf_(integer *n, real *d__, real *e, integer *info); -extern int spttrs_(integer *n, integer *nrhs, real *d__, real *e, real *b, - integer *ldb, integer *info); -extern int sptts2_(integer *n, integer *nrhs, real *d__, real *e, real *b, - integer *ldb); -extern int srscl_(integer *n, real *sa, real *sx, integer *incx); -extern int ssbev_(char *jobz, char *uplo, integer *n, integer *kd, real *ab, - integer *ldab, real *w, real *z__, integer *ldz, real *work, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int ssbevd_(char *jobz, char *uplo, integer *n, integer *kd, real *ab, - integer *ldab, real *w, real *z__, integer *ldz, real *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int ssbevx_(char *jobz, char *range, char *uplo, integer *n, integer *kd, - real *ab, integer *ldab, real *q, integer *ldq, real *vl, - real *vu, integer *il, integer *iu, real *abstol, integer *m, - real *w, real *z__, integer *ldz, real *work, integer *iwork, - integer *ifail, integer *info, ftnlen jobz_len, - ftnlen range_len, ftnlen uplo_len); -extern int ssbgst_(char *vect, char *uplo, integer *n, integer *ka, integer *kb, - real *ab, integer *ldab, real *bb, integer *ldbb, real *x, - integer *ldx, real *work, integer *info, ftnlen vect_len, - ftnlen uplo_len); -extern int ssbgv_(char *jobz, char *uplo, integer *n, integer *ka, integer *kb, - real *ab, integer *ldab, real *bb, integer *ldbb, real *w, - real *z__, integer *ldz, real *work, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int ssbgvd_(char *jobz, char *uplo, integer *n, integer *ka, integer *kb, - real *ab, integer *ldab, real *bb, integer *ldbb, real *w, - real *z__, integer *ldz, real *work, integer *lwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int ssbgvx_(char *jobz, char *range, char *uplo, integer *n, integer *ka, - integer *kb, real *ab, integer *ldab, real *bb, - integer *ldbb, real *q, integer *ldq, real *vl, real *vu, - integer *il, integer *iu, real *abstol, integer *m, real *w, - real *z__, integer *ldz, real *work, integer *iwork, - integer *ifail, integer *info, ftnlen jobz_len, - ftnlen range_len, ftnlen uplo_len); -extern int ssbtrd_(char *vect, char *uplo, integer *n, integer *kd, real *ab, - integer *ldab, real *d__, real *e, real *q, integer *ldq, - real *work, integer *info, ftnlen vect_len, ftnlen uplo_len); -extern int sspcon_(char *uplo, integer *n, real *ap, integer *ipiv, real *anorm, - real *rcond, real *work, integer *iwork, integer *info, - ftnlen uplo_len); -extern int sspev_(char *jobz, char *uplo, integer *n, real *ap, real *w, - real *z__, integer *ldz, real *work, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int sspevd_(char *jobz, char *uplo, integer *n, real *ap, real *w, - real *z__, integer *ldz, real *work, integer *lwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int sspevx_(char *jobz, char *range, char *uplo, integer *n, real *ap, - real *vl, real *vu, integer *il, integer *iu, real *abstol, - integer *m, real *w, real *z__, integer *ldz, real *work, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len, ftnlen uplo_len); -extern int sspgst_(integer *itype, char *uplo, integer *n, real *ap, real *bp, - integer *info, ftnlen uplo_len); -extern int sspgv_(integer *itype, char *jobz, char *uplo, integer *n, real *ap, - real *bp, real *w, real *z__, integer *ldz, real *work, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int sspgvd_(integer *itype, char *jobz, char *uplo, integer *n, real *ap, - real *bp, real *w, real *z__, integer *ldz, real *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int sspgvx_(integer *itype, char *jobz, char *range, char *uplo, - integer *n, real *ap, real *bp, real *vl, real *vu, - integer *il, integer *iu, real *abstol, integer *m, real *w, - real *z__, integer *ldz, real *work, integer *iwork, - integer *ifail, integer *info, ftnlen jobz_len, - ftnlen range_len, ftnlen uplo_len); -extern int ssprfs_(char *uplo, integer *n, integer *nrhs, real *ap, real *afp, - integer *ipiv, real *b, integer *ldb, real *x, integer *ldx, - real *ferr, real *berr, real *work, integer *iwork, - integer *info, ftnlen uplo_len); -extern int sspsv_(char *uplo, integer *n, integer *nrhs, real *ap, - integer *ipiv, real *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int sspsvx_(char *fact, char *uplo, integer *n, integer *nrhs, real *ap, - real *afp, integer *ipiv, real *b, integer *ldb, real *x, - integer *ldx, real *rcond, real *ferr, real *berr, - real *work, integer *iwork, integer *info, ftnlen fact_len, - ftnlen uplo_len); -extern int ssptrd_(char *uplo, integer *n, real *ap, real *d__, real *e, - real *tau, integer *info, ftnlen uplo_len); -extern int ssptrf_(char *uplo, integer *n, real *ap, integer *ipiv, - integer *info, ftnlen uplo_len); -extern int ssptri_(char *uplo, integer *n, real *ap, integer *ipiv, real *work, - integer *info, ftnlen uplo_len); -extern int ssptrs_(char *uplo, integer *n, integer *nrhs, real *ap, - integer *ipiv, real *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int sstebz_(char *range, char *order, integer *n, real *vl, real *vu, - integer *il, integer *iu, real *abstol, real *d__, real *e, - integer *m, integer *nsplit, real *w, integer *iblock, - integer *isplit, real *work, integer *iwork, integer *info, - ftnlen range_len, ftnlen order_len); -extern int sstedc_(char *compz, integer *n, real *d__, real *e, real *z__, - integer *ldz, real *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen compz_len); -extern int sstegr_(char *jobz, char *range, integer *n, real *d__, real *e, - real *vl, real *vu, integer *il, integer *iu, real *abstol, - integer *m, real *w, real *z__, integer *ldz, - integer *isuppz, real *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen range_len); -extern int sstein_(integer *n, real *d__, real *e, integer *m, real *w, - integer *iblock, integer *isplit, real *z__, integer *ldz, - real *work, integer *iwork, integer *ifail, integer *info); -extern int ssteqr_(char *compz, integer *n, real *d__, real *e, real *z__, - integer *ldz, real *work, integer *info, ftnlen compz_len); -extern int ssterf_(integer *n, real *d__, real *e, integer *info); -extern int sstev_(char *jobz, integer *n, real *d__, real *e, real *z__, - integer *ldz, real *work, integer *info, ftnlen jobz_len); -extern int sstevd_(char *jobz, integer *n, real *d__, real *e, real *z__, - integer *ldz, real *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len); -extern int sstevr_(char *jobz, char *range, integer *n, real *d__, real *e, - real *vl, real *vu, integer *il, integer *iu, real *abstol, - integer *m, real *w, real *z__, integer *ldz, - integer *isuppz, real *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen range_len); -extern int sstevx_(char *jobz, char *range, integer *n, real *d__, real *e, - real *vl, real *vu, integer *il, integer *iu, real *abstol, - integer *m, real *w, real *z__, integer *ldz, real *work, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len); -extern int ssycon_(char *uplo, integer *n, real *a, integer *lda, integer *ipiv, - real *anorm, real *rcond, real *work, integer *iwork, - integer *info, ftnlen uplo_len); -extern int ssyev_(char *jobz, char *uplo, integer *n, real *a, integer *lda, - real *w, real *work, integer *lwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int ssyevd_(char *jobz, char *uplo, integer *n, real *a, integer *lda, - real *w, real *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int ssyevr_(char *jobz, char *range, char *uplo, integer *n, real *a, - integer *lda, real *vl, real *vu, integer *il, integer *iu, - real *abstol, integer *m, real *w, real *z__, integer *ldz, - integer *isuppz, real *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen range_len, ftnlen uplo_len); -extern int ssyevx_(char *jobz, char *range, char *uplo, integer *n, real *a, - integer *lda, real *vl, real *vu, integer *il, integer *iu, - real *abstol, integer *m, real *w, real *z__, integer *ldz, - real *work, integer *lwork, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int ssygs2_(integer *itype, char *uplo, integer *n, real *a, - integer *lda, real *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int ssygst_(integer *itype, char *uplo, integer *n, real *a, - integer *lda, real *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int ssygv_(integer *itype, char *jobz, char *uplo, integer *n, real *a, - integer *lda, real *b, integer *ldb, real *w, real *work, - integer *lwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int ssygvd_(integer *itype, char *jobz, char *uplo, integer *n, real *a, - integer *lda, real *b, integer *ldb, real *w, real *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int ssygvx_(integer *itype, char *jobz, char *range, char *uplo, - integer *n, real *a, integer *lda, real *b, integer *ldb, - real *vl, real *vu, integer *il, integer *iu, real *abstol, - integer *m, real *w, real *z__, integer *ldz, real *work, - integer *lwork, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int ssyrfs_(char *uplo, integer *n, integer *nrhs, real *a, integer *lda, - real *af, integer *ldaf, integer *ipiv, real *b, - integer *ldb, real *x, integer *ldx, real *ferr, real *berr, - real *work, integer *iwork, integer *info, ftnlen uplo_len); -extern int ssysv_(char *uplo, integer *n, integer *nrhs, real *a, integer *lda, - integer *ipiv, real *b, integer *ldb, real *work, - integer *lwork, integer *info, ftnlen uplo_len); -extern int ssysvx_(char *fact, char *uplo, integer *n, integer *nrhs, real *a, - integer *lda, real *af, integer *ldaf, integer *ipiv, - real *b, integer *ldb, real *x, integer *ldx, real *rcond, - real *ferr, real *berr, real *work, integer *lwork, - integer *iwork, integer *info, ftnlen fact_len, - ftnlen uplo_len); -extern int ssytd2_(char *uplo, integer *n, real *a, integer *lda, real *d__, - real *e, real *tau, integer *info, ftnlen uplo_len); -extern int ssytf2_(char *uplo, integer *n, real *a, integer *lda, integer *ipiv, - integer *info, ftnlen uplo_len); -extern int ssytrd_(char *uplo, integer *n, real *a, integer *lda, real *d__, - real *e, real *tau, real *work, integer *lwork, - integer *info, ftnlen uplo_len); -extern int ssytrf_(char *uplo, integer *n, real *a, integer *lda, integer *ipiv, - real *work, integer *lwork, integer *info, ftnlen uplo_len); -extern int ssytri_(char *uplo, integer *n, real *a, integer *lda, integer *ipiv, - real *work, integer *info, ftnlen uplo_len); -extern int ssytrs_(char *uplo, integer *n, integer *nrhs, real *a, integer *lda, - integer *ipiv, real *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int stbcon_(char *norm, char *uplo, char *diag, integer *n, integer *kd, - real *ab, integer *ldab, real *rcond, real *work, - integer *iwork, integer *info, ftnlen norm_len, - ftnlen uplo_len, ftnlen diag_len); -extern int stbrfs_(char *uplo, char *trans, char *diag, integer *n, integer *kd, - integer *nrhs, real *ab, integer *ldab, real *b, - integer *ldb, real *x, integer *ldx, real *ferr, real *berr, - real *work, integer *iwork, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int stbtrs_(char *uplo, char *trans, char *diag, integer *n, integer *kd, - integer *nrhs, real *ab, integer *ldab, real *b, - integer *ldb, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int stgevc_(char *side, char *howmny, logical *select, integer *n, - real *a, integer *lda, real *b, integer *ldb, real *vl, - integer *ldvl, real *vr, integer *ldvr, integer *mm, - integer *m, real *work, integer *info, ftnlen side_len, - ftnlen howmny_len); -extern int stgex2_(logical *wantq, logical *wantz, integer *n, real *a, - integer *lda, real *b, integer *ldb, real *q, integer *ldq, - real *z__, integer *ldz, integer *j1, integer *n1, - integer *n2, real *work, integer *lwork, integer *info); -extern int stgexc_(logical *wantq, logical *wantz, integer *n, real *a, - integer *lda, real *b, integer *ldb, real *q, integer *ldq, - real *z__, integer *ldz, integer *ifst, integer *ilst, - real *work, integer *lwork, integer *info); -extern int stgsen_(integer *ijob, logical *wantq, logical *wantz, - logical *select, integer *n, real *a, integer *lda, real *b, - integer *ldb, real *alphar, real *alphai, real *beta, - real *q, integer *ldq, real *z__, integer *ldz, integer *m, - real *pl, real *pr, real *dif, real *work, integer *lwork, - integer *iwork, integer *liwork, integer *info); -extern int stgsja_(char *jobu, char *jobv, char *jobq, integer *m, integer *p, - integer *n, integer *k, integer *l, real *a, integer *lda, - real *b, integer *ldb, real *tola, real *tolb, real *alpha, - real *beta, real *u, integer *ldu, real *v, integer *ldv, - real *q, integer *ldq, real *work, integer *ncycle, - integer *info, ftnlen jobu_len, ftnlen jobv_len, - ftnlen jobq_len); -extern int stgsna_(char *job, char *howmny, logical *select, integer *n, - real *a, integer *lda, real *b, integer *ldb, real *vl, - integer *ldvl, real *vr, integer *ldvr, real *s, real *dif, - integer *mm, integer *m, real *work, integer *lwork, - integer *iwork, integer *info, ftnlen job_len, - ftnlen howmny_len); -extern int stgsy2_(char *trans, integer *ijob, integer *m, integer *n, real *a, - integer *lda, real *b, integer *ldb, real *c__, integer *ldc, - real *d__, integer *ldd, real *e, integer *lde, real *f, - integer *ldf, real *scale, real *rdsum, real *rdscal, - integer *iwork, integer *pq, integer *info, - ftnlen trans_len); -extern int stgsyl_(char *trans, integer *ijob, integer *m, integer *n, real *a, - integer *lda, real *b, integer *ldb, real *c__, integer *ldc, - real *d__, integer *ldd, real *e, integer *lde, real *f, - integer *ldf, real *scale, real *dif, real *work, - integer *lwork, integer *iwork, integer *info, - ftnlen trans_len); -extern int stpcon_(char *norm, char *uplo, char *diag, integer *n, real *ap, - real *rcond, real *work, integer *iwork, integer *info, - ftnlen norm_len, ftnlen uplo_len, ftnlen diag_len); -extern int stprfs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, real *ap, real *b, integer *ldb, real *x, - integer *ldx, real *ferr, real *berr, real *work, - integer *iwork, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int stptri_(char *uplo, char *diag, integer *n, real *ap, integer *info, - ftnlen uplo_len, ftnlen diag_len); -extern int stptrs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, real *ap, real *b, integer *ldb, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int strcon_(char *norm, char *uplo, char *diag, integer *n, real *a, - integer *lda, real *rcond, real *work, integer *iwork, - integer *info, ftnlen norm_len, ftnlen uplo_len, - ftnlen diag_len); -extern int strevc_(char *side, char *howmny, logical *select, integer *n, - real *t, integer *ldt, real *vl, integer *ldvl, real *vr, - integer *ldvr, integer *mm, integer *m, real *work, - integer *info, ftnlen side_len, ftnlen howmny_len); -extern int strexc_(char *compq, integer *n, real *t, integer *ldt, real *q, - integer *ldq, integer *ifst, integer *ilst, real *work, - integer *info, ftnlen compq_len); -extern int strrfs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, real *a, integer *lda, real *b, integer *ldb, - real *x, integer *ldx, real *ferr, real *berr, real *work, - integer *iwork, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int strsen_(char *job, char *compq, logical *select, integer *n, real *t, - integer *ldt, real *q, integer *ldq, real *wr, real *wi, - integer *m, real *s, real *sep, real *work, integer *lwork, - integer *iwork, integer *liwork, integer *info, - ftnlen job_len, ftnlen compq_len); -extern int strsna_(char *job, char *howmny, logical *select, integer *n, - real *t, integer *ldt, real *vl, integer *ldvl, real *vr, - integer *ldvr, real *s, real *sep, integer *mm, integer *m, - real *work, integer *ldwork, integer *iwork, integer *info, - ftnlen job_len, ftnlen howmny_len); -extern int strsyl_(char *trana, char *tranb, integer *isgn, integer *m, - integer *n, real *a, integer *lda, real *b, integer *ldb, - real *c__, integer *ldc, real *scale, integer *info, - ftnlen trana_len, ftnlen tranb_len); -extern int strti2_(char *uplo, char *diag, integer *n, real *a, integer *lda, - integer *info, ftnlen uplo_len, ftnlen diag_len); -extern int strtri_(char *uplo, char *diag, integer *n, real *a, integer *lda, - integer *info, ftnlen uplo_len, ftnlen diag_len); -extern int strtrs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, real *a, integer *lda, real *b, integer *ldb, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len); -extern int stzrqf_(integer *m, integer *n, real *a, integer *lda, real *tau, - integer *info); -extern int stzrzf_(integer *m, integer *n, real *a, integer *lda, real *tau, - real *work, integer *lwork, integer *info); -extern int xerbla_(char *srname, integer *info, ftnlen srname_len); -extern int zbdsqr_(char *uplo, integer *n, integer *ncvt, integer *nru, - integer *ncc, doublereal *d__, doublereal *e, - doublecomplex *vt, integer *ldvt, doublecomplex *u, - integer *ldu, doublecomplex *c__, integer *ldc, - doublereal *rwork, integer *info, ftnlen uplo_len); -extern int zdrot_(integer *n, doublecomplex *cx, integer *incx, - doublecomplex *cy, integer *incy, doublereal *c__, - doublereal *s); -extern int zdrscl_(integer *n, doublereal *sa, doublecomplex *sx, - integer *incx); -extern int zgbbrd_(char *vect, integer *m, integer *n, integer *ncc, - integer *kl, integer *ku, doublecomplex *ab, integer *ldab, - doublereal *d__, doublereal *e, doublecomplex *q, - integer *ldq, doublecomplex *pt, integer *ldpt, - doublecomplex *c__, integer *ldc, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen vect_len); -extern int zgbcon_(char *norm, integer *n, integer *kl, integer *ku, - doublecomplex *ab, integer *ldab, integer *ipiv, - doublereal *anorm, doublereal *rcond, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen norm_len); -extern int zgbequ_(integer *m, integer *n, integer *kl, integer *ku, - doublecomplex *ab, integer *ldab, doublereal *r__, - doublereal *c__, doublereal *rowcnd, doublereal *colcnd, - doublereal *amax, integer *info); -extern int zgbrfs_(char *trans, integer *n, integer *kl, integer *ku, - integer *nrhs, doublecomplex *ab, integer *ldab, - doublecomplex *afb, integer *ldafb, integer *ipiv, - doublecomplex *b, integer *ldb, doublecomplex *x, - integer *ldx, doublereal *ferr, doublereal *berr, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen trans_len); -extern int zgbsv_(integer *n, integer *kl, integer *ku, integer *nrhs, - doublecomplex *ab, integer *ldab, integer *ipiv, - doublecomplex *b, integer *ldb, integer *info); -extern int zgbsvx_(char *fact, char *trans, integer *n, integer *kl, - integer *ku, integer *nrhs, doublecomplex *ab, integer *ldab, - doublecomplex *afb, integer *ldafb, integer *ipiv, - char *equed, doublereal *r__, doublereal *c__, - doublecomplex *b, integer *ldb, doublecomplex *x, - integer *ldx, doublereal *rcond, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen fact_len, ftnlen trans_len, - ftnlen equed_len); -extern int zgbtf2_(integer *m, integer *n, integer *kl, integer *ku, - doublecomplex *ab, integer *ldab, integer *ipiv, - integer *info); -extern int zgbtrf_(integer *m, integer *n, integer *kl, integer *ku, - doublecomplex *ab, integer *ldab, integer *ipiv, - integer *info); -extern int zgbtrs_(char *trans, integer *n, integer *kl, integer *ku, - integer *nrhs, doublecomplex *ab, integer *ldab, - integer *ipiv, doublecomplex *b, integer *ldb, integer *info, - ftnlen trans_len); -extern int zgebak_(char *job, char *side, integer *n, integer *ilo, - integer *ihi, doublereal *scale, integer *m, - doublecomplex *v, integer *ldv, integer *info, - ftnlen job_len, ftnlen side_len); -extern int zgebal_(char *job, integer *n, doublecomplex *a, integer *lda, - integer *ilo, integer *ihi, doublereal *scale, integer *info, - ftnlen job_len); -extern int zgebd2_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublereal *d__, doublereal *e, doublecomplex *tauq, - doublecomplex *taup, doublecomplex *work, integer *info); -extern int zgebrd_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublereal *d__, doublereal *e, doublecomplex *tauq, - doublecomplex *taup, doublecomplex *work, integer *lwork, - integer *info); -extern int zgecon_(char *norm, integer *n, doublecomplex *a, integer *lda, - doublereal *anorm, doublereal *rcond, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen norm_len); -extern int zgeequ_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublereal *r__, doublereal *c__, doublereal *rowcnd, - doublereal *colcnd, doublereal *amax, integer *info); -extern int zgees_(char *jobvs, char *sort, L_fp select, integer *n, - doublecomplex *a, integer *lda, integer *sdim, - doublecomplex *w, doublecomplex *vs, integer *ldvs, - doublecomplex *work, integer *lwork, doublereal *rwork, - logical *bwork, integer *info, ftnlen jobvs_len, - ftnlen sort_len); -extern int zgeesx_(char *jobvs, char *sort, L_fp select, char *sense, - integer *n, doublecomplex *a, integer *lda, integer *sdim, - doublecomplex *w, doublecomplex *vs, integer *ldvs, - doublereal *rconde, doublereal *rcondv, doublecomplex *work, - integer *lwork, doublereal *rwork, logical *bwork, - integer *info, ftnlen jobvs_len, ftnlen sort_len, - ftnlen sense_len); -extern int zgeev_(char *jobvl, char *jobvr, integer *n, doublecomplex *a, - integer *lda, doublecomplex *w, doublecomplex *vl, - integer *ldvl, doublecomplex *vr, integer *ldvr, - doublecomplex *work, integer *lwork, doublereal *rwork, - integer *info, ftnlen jobvl_len, ftnlen jobvr_len); -extern int zgeevx_(char *balanc, char *jobvl, char *jobvr, char *sense, - integer *n, doublecomplex *a, integer *lda, doublecomplex *w, - doublecomplex *vl, integer *ldvl, doublecomplex *vr, - integer *ldvr, integer *ilo, integer *ihi, doublereal *scale, - doublereal *abnrm, doublereal *rconde, doublereal *rcondv, - doublecomplex *work, integer *lwork, doublereal *rwork, - integer *info, ftnlen balanc_len, ftnlen jobvl_len, - ftnlen jobvr_len, ftnlen sense_len); -extern int zgegs_(char *jobvsl, char *jobvsr, integer *n, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublecomplex *alpha, doublecomplex *beta, doublecomplex *vsl, - integer *ldvsl, doublecomplex *vsr, integer *ldvsr, - doublecomplex *work, integer *lwork, doublereal *rwork, - integer *info, ftnlen jobvsl_len, ftnlen jobvsr_len); -extern int zgegv_(char *jobvl, char *jobvr, integer *n, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublecomplex *alpha, doublecomplex *beta, doublecomplex *vl, - integer *ldvl, doublecomplex *vr, integer *ldvr, - doublecomplex *work, integer *lwork, doublereal *rwork, - integer *info, ftnlen jobvl_len, ftnlen jobvr_len); -extern int zgehd2_(integer *n, integer *ilo, integer *ihi, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *info); -extern int zgehrd_(integer *n, integer *ilo, integer *ihi, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *lwork, integer *info); -extern int zgelq2_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *info); -extern int zgelqf_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *lwork, - integer *info); -extern int zgels_(char *trans, integer *m, integer *n, integer *nrhs, - doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublecomplex *work, integer *lwork, - integer *info, ftnlen trans_len); -extern int zgelsd_(integer *m, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, doublereal *s, - doublereal *rcond, integer *rank, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *iwork, - integer *info); -extern int zgelss_(integer *m, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, doublereal *s, - doublereal *rcond, integer *rank, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *info); -extern int zgelsx_(integer *m, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, integer *jpvt, - doublereal *rcond, integer *rank, doublecomplex *work, - doublereal *rwork, integer *info); -extern int zgelsy_(integer *m, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, integer *jpvt, - doublereal *rcond, integer *rank, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *info); -extern int zgeql2_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *info); -extern int zgeqlf_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *lwork, - integer *info); -extern int zgeqp3_(integer *m, integer *n, doublecomplex *a, integer *lda, - integer *jpvt, doublecomplex *tau, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *info); -extern int zgeqpf_(integer *m, integer *n, doublecomplex *a, integer *lda, - integer *jpvt, doublecomplex *tau, doublecomplex *work, - doublereal *rwork, integer *info); -extern int zgeqr2_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *info); -extern int zgeqrf_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *lwork, - integer *info); -extern int zgerfs_(char *trans, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *af, integer *ldaf, - integer *ipiv, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen trans_len); -extern int zgerq2_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *info); -extern int zgerqf_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *lwork, - integer *info); -extern int zgesc2_(integer *n, doublecomplex *a, integer *lda, - doublecomplex *rhs, integer *ipiv, integer *jpiv, - doublereal *scale); -extern int zgesdd_(char *jobz, integer *m, integer *n, doublecomplex *a, - integer *lda, doublereal *s, doublecomplex *u, integer *ldu, - doublecomplex *vt, integer *ldvt, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *iwork, - integer *info, ftnlen jobz_len); -extern int zgesv_(integer *n, integer *nrhs, doublecomplex *a, integer *lda, - integer *ipiv, doublecomplex *b, integer *ldb, integer *info); -extern int zgesvd_(char *jobu, char *jobvt, integer *m, integer *n, - doublecomplex *a, integer *lda, doublereal *s, - doublecomplex *u, integer *ldu, doublecomplex *vt, - integer *ldvt, doublecomplex *work, integer *lwork, - doublereal *rwork, integer *info, ftnlen jobu_len, - ftnlen jobvt_len); -extern int zgesvx_(char *fact, char *trans, integer *n, integer *nrhs, - doublecomplex *a, integer *lda, doublecomplex *af, - integer *ldaf, integer *ipiv, char *equed, doublereal *r__, - doublereal *c__, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *rcond, - doublereal *ferr, doublereal *berr, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen fact_len, - ftnlen trans_len, ftnlen equed_len); -extern int zgetc2_(integer *n, doublecomplex *a, integer *lda, integer *ipiv, - integer *jpiv, integer *info); -extern int zgetf2_(integer *m, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, integer *info); -extern int zgetrf_(integer *m, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, integer *info); -extern int zgetri_(integer *n, doublecomplex *a, integer *lda, integer *ipiv, - doublecomplex *work, integer *lwork, integer *info); -extern int zgetrs_(char *trans, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, integer *ipiv, doublecomplex *b, integer *ldb, - integer *info, ftnlen trans_len); -extern int zggbak_(char *job, char *side, integer *n, integer *ilo, - integer *ihi, doublereal *lscale, doublereal *rscale, - integer *m, doublecomplex *v, integer *ldv, integer *info, - ftnlen job_len, ftnlen side_len); -extern int zggbal_(char *job, integer *n, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, integer *ilo, integer *ihi, - doublereal *lscale, doublereal *rscale, doublereal *work, - integer *info, ftnlen job_len); -extern int zgges_(char *jobvsl, char *jobvsr, char *sort, L_fp delctg, - integer *n, doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, integer *sdim, doublecomplex *alpha, - doublecomplex *beta, doublecomplex *vsl, integer *ldvsl, - doublecomplex *vsr, integer *ldvsr, doublecomplex *work, - integer *lwork, doublereal *rwork, logical *bwork, - integer *info, ftnlen jobvsl_len, ftnlen jobvsr_len, - ftnlen sort_len); -extern int zggesx_(char *jobvsl, char *jobvsr, char *sort, L_fp delctg, - char *sense, integer *n, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, integer *sdim, - doublecomplex *alpha, doublecomplex *beta, - doublecomplex *vsl, integer *ldvsl, doublecomplex *vsr, - integer *ldvsr, doublereal *rconde, doublereal *rcondv, - doublecomplex *work, integer *lwork, doublereal *rwork, - integer *iwork, integer *liwork, logical *bwork, - integer *info, ftnlen jobvsl_len, ftnlen jobvsr_len, - ftnlen sort_len, ftnlen sense_len); -extern int zggev_(char *jobvl, char *jobvr, integer *n, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublecomplex *alpha, doublecomplex *beta, doublecomplex *vl, - integer *ldvl, doublecomplex *vr, integer *ldvr, - doublecomplex *work, integer *lwork, doublereal *rwork, - integer *info, ftnlen jobvl_len, ftnlen jobvr_len); -extern int zggevx_(char *balanc, char *jobvl, char *jobvr, char *sense, - integer *n, doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublecomplex *alpha, doublecomplex *beta, - doublecomplex *vl, integer *ldvl, doublecomplex *vr, - integer *ldvr, integer *ilo, integer *ihi, - doublereal *lscale, doublereal *rscale, doublereal *abnrm, - doublereal *bbnrm, doublereal *rconde, doublereal *rcondv, - doublecomplex *work, integer *lwork, doublereal *rwork, - integer *iwork, logical *bwork, integer *info, - ftnlen balanc_len, ftnlen jobvl_len, ftnlen jobvr_len, - ftnlen sense_len); -extern int zggglm_(integer *n, integer *m, integer *p, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublecomplex *d__, doublecomplex *x, doublecomplex *y, - doublecomplex *work, integer *lwork, integer *info); -extern int zgghrd_(char *compq, char *compz, integer *n, integer *ilo, - integer *ihi, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, doublecomplex *q, - integer *ldq, doublecomplex *z__, integer *ldz, - integer *info, ftnlen compq_len, ftnlen compz_len); -extern int zgglse_(integer *m, integer *n, integer *p, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublecomplex *c__, doublecomplex *d__, doublecomplex *x, - doublecomplex *work, integer *lwork, integer *info); -extern int zggqrf_(integer *n, integer *m, integer *p, doublecomplex *a, - integer *lda, doublecomplex *taua, doublecomplex *b, - integer *ldb, doublecomplex *taub, doublecomplex *work, - integer *lwork, integer *info); -extern int zggrqf_(integer *m, integer *p, integer *n, doublecomplex *a, - integer *lda, doublecomplex *taua, doublecomplex *b, - integer *ldb, doublecomplex *taub, doublecomplex *work, - integer *lwork, integer *info); -extern int zggsvd_(char *jobu, char *jobv, char *jobq, integer *m, integer *n, - integer *p, integer *k, integer *l, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublereal *alpha, doublereal *beta, doublecomplex *u, - integer *ldu, doublecomplex *v, integer *ldv, - doublecomplex *q, integer *ldq, doublecomplex *work, - doublereal *rwork, integer *iwork, integer *info, - ftnlen jobu_len, ftnlen jobv_len, ftnlen jobq_len); -extern int zggsvp_(char *jobu, char *jobv, char *jobq, integer *m, integer *p, - integer *n, doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublereal *tola, doublereal *tolb, integer *k, - integer *l, doublecomplex *u, integer *ldu, doublecomplex *v, - integer *ldv, doublecomplex *q, integer *ldq, integer *iwork, - doublereal *rwork, doublecomplex *tau, doublecomplex *work, - integer *info, ftnlen jobu_len, ftnlen jobv_len, - ftnlen jobq_len); -extern int zgtcon_(char *norm, integer *n, doublecomplex *dl, - doublecomplex *d__, doublecomplex *du, doublecomplex *du2, - integer *ipiv, doublereal *anorm, doublereal *rcond, - doublecomplex *work, integer *info, ftnlen norm_len); -extern int zgtrfs_(char *trans, integer *n, integer *nrhs, doublecomplex *dl, - doublecomplex *d__, doublecomplex *du, doublecomplex *dlf, - doublecomplex *df, doublecomplex *duf, doublecomplex *du2, - integer *ipiv, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen trans_len); -extern int zgtsv_(integer *n, integer *nrhs, doublecomplex *dl, - doublecomplex *d__, doublecomplex *du, doublecomplex *b, - integer *ldb, integer *info); -extern int zgtsvx_(char *fact, char *trans, integer *n, integer *nrhs, - doublecomplex *dl, doublecomplex *d__, doublecomplex *du, - doublecomplex *dlf, doublecomplex *df, doublecomplex *duf, - doublecomplex *du2, integer *ipiv, doublecomplex *b, - integer *ldb, doublecomplex *x, integer *ldx, - doublereal *rcond, doublereal *ferr, doublereal *berr, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen fact_len, ftnlen trans_len); -extern int zgttrf_(integer *n, doublecomplex *dl, doublecomplex *d__, - doublecomplex *du, doublecomplex *du2, integer *ipiv, - integer *info); -extern int zgttrs_(char *trans, integer *n, integer *nrhs, doublecomplex *dl, - doublecomplex *d__, doublecomplex *du, doublecomplex *du2, - integer *ipiv, doublecomplex *b, integer *ldb, integer *info, - ftnlen trans_len); -extern int zgtts2_(integer *itrans, integer *n, integer *nrhs, - doublecomplex *dl, doublecomplex *d__, doublecomplex *du, - doublecomplex *du2, integer *ipiv, doublecomplex *b, - integer *ldb); -extern int zhbev_(char *jobz, char *uplo, integer *n, integer *kd, - doublecomplex *ab, integer *ldab, doublereal *w, - doublecomplex *z__, integer *ldz, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int zhbevd_(char *jobz, char *uplo, integer *n, integer *kd, - doublecomplex *ab, integer *ldab, doublereal *w, - doublecomplex *z__, integer *ldz, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *lrwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int zhbevx_(char *jobz, char *range, char *uplo, integer *n, integer *kd, - doublecomplex *ab, integer *ldab, doublecomplex *q, - integer *ldq, doublereal *vl, doublereal *vu, integer *il, - integer *iu, doublereal *abstol, integer *m, doublereal *w, - doublecomplex *z__, integer *ldz, doublecomplex *work, - doublereal *rwork, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int zhbgst_(char *vect, char *uplo, integer *n, integer *ka, integer *kb, - doublecomplex *ab, integer *ldab, doublecomplex *bb, - integer *ldbb, doublecomplex *x, integer *ldx, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen vect_len, ftnlen uplo_len); -extern int zhbgv_(char *jobz, char *uplo, integer *n, integer *ka, integer *kb, - doublecomplex *ab, integer *ldab, doublecomplex *bb, - integer *ldbb, doublereal *w, doublecomplex *z__, - integer *ldz, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int zhbgvd_(char *jobz, char *uplo, integer *n, integer *ka, integer *kb, - doublecomplex *ab, integer *ldab, doublecomplex *bb, - integer *ldbb, doublereal *w, doublecomplex *z__, - integer *ldz, doublecomplex *work, integer *lwork, - doublereal *rwork, integer *lrwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int zhbgvx_(char *jobz, char *range, char *uplo, integer *n, integer *ka, - integer *kb, doublecomplex *ab, integer *ldab, - doublecomplex *bb, integer *ldbb, doublecomplex *q, - integer *ldq, doublereal *vl, doublereal *vu, integer *il, - integer *iu, doublereal *abstol, integer *m, doublereal *w, - doublecomplex *z__, integer *ldz, doublecomplex *work, - doublereal *rwork, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int zhbtrd_(char *vect, char *uplo, integer *n, integer *kd, - doublecomplex *ab, integer *ldab, doublereal *d__, - doublereal *e, doublecomplex *q, integer *ldq, - doublecomplex *work, integer *info, ftnlen vect_len, - ftnlen uplo_len); -extern int zhecon_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, doublereal *anorm, doublereal *rcond, - doublecomplex *work, integer *info, ftnlen uplo_len); -extern int zheev_(char *jobz, char *uplo, integer *n, doublecomplex *a, - integer *lda, doublereal *w, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int zheevd_(char *jobz, char *uplo, integer *n, doublecomplex *a, - integer *lda, doublereal *w, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *lrwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int zheevr_(char *jobz, char *range, char *uplo, integer *n, - doublecomplex *a, integer *lda, doublereal *vl, - doublereal *vu, integer *il, integer *iu, doublereal *abstol, - integer *m, doublereal *w, doublecomplex *z__, integer *ldz, - integer *isuppz, doublecomplex *work, integer *lwork, - doublereal *rwork, integer *lrwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen range_len, ftnlen uplo_len); -extern int zheevx_(char *jobz, char *range, char *uplo, integer *n, - doublecomplex *a, integer *lda, doublereal *vl, - doublereal *vu, integer *il, integer *iu, doublereal *abstol, - integer *m, doublereal *w, doublecomplex *z__, integer *ldz, - doublecomplex *work, integer *lwork, doublereal *rwork, - integer *iwork, integer *ifail, integer *info, - ftnlen jobz_len, ftnlen range_len, ftnlen uplo_len); -extern int zhegs2_(integer *itype, char *uplo, integer *n, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zhegst_(integer *itype, char *uplo, integer *n, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zhegv_(integer *itype, char *jobz, char *uplo, integer *n, - doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublereal *w, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int zhegvd_(integer *itype, char *jobz, char *uplo, integer *n, - doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublereal *w, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *lrwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int zhegvx_(integer *itype, char *jobz, char *range, char *uplo, - integer *n, doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublereal *vl, doublereal *vu, integer *il, - integer *iu, doublereal *abstol, integer *m, doublereal *w, - doublecomplex *z__, integer *ldz, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *iwork, - integer *ifail, integer *info, ftnlen jobz_len, - ftnlen range_len, ftnlen uplo_len); -extern int zherfs_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *af, integer *ldaf, - integer *ipiv, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen uplo_len); -extern int zhesv_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, integer *ipiv, doublecomplex *b, integer *ldb, - doublecomplex *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int zhesvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublecomplex *a, integer *lda, doublecomplex *af, - integer *ldaf, integer *ipiv, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *rcond, - doublereal *ferr, doublereal *berr, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *info, - ftnlen fact_len, ftnlen uplo_len); -extern int zhetd2_(char *uplo, integer *n, doublecomplex *a, integer *lda, - doublereal *d__, doublereal *e, doublecomplex *tau, - integer *info, ftnlen uplo_len); -extern int zhetf2_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, integer *info, ftnlen uplo_len); -extern int zhetrd_(char *uplo, integer *n, doublecomplex *a, integer *lda, - doublereal *d__, doublereal *e, doublecomplex *tau, - doublecomplex *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int zhetrf_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, doublecomplex *work, integer *lwork, - integer *info, ftnlen uplo_len); -extern int zhetri_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, doublecomplex *work, integer *info, - ftnlen uplo_len); -extern int zhetrs_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, integer *ipiv, doublecomplex *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int zhgeqz_(char *job, char *compq, char *compz, integer *n, - integer *ilo, integer *ihi, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, doublecomplex *alpha, - doublecomplex *beta, doublecomplex *q, integer *ldq, - doublecomplex *z__, integer *ldz, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *info, - ftnlen job_len, ftnlen compq_len, ftnlen compz_len); -extern int zhpcon_(char *uplo, integer *n, doublecomplex *ap, integer *ipiv, - doublereal *anorm, doublereal *rcond, doublecomplex *work, - integer *info, ftnlen uplo_len); -extern int zhpev_(char *jobz, char *uplo, integer *n, doublecomplex *ap, - doublereal *w, doublecomplex *z__, integer *ldz, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int zhpevd_(char *jobz, char *uplo, integer *n, doublecomplex *ap, - doublereal *w, doublecomplex *z__, integer *ldz, - doublecomplex *work, integer *lwork, doublereal *rwork, - integer *lrwork, integer *iwork, integer *liwork, - integer *info, ftnlen jobz_len, ftnlen uplo_len); -extern int zhpevx_(char *jobz, char *range, char *uplo, integer *n, - doublecomplex *ap, doublereal *vl, doublereal *vu, - integer *il, integer *iu, doublereal *abstol, integer *m, - doublereal *w, doublecomplex *z__, integer *ldz, - doublecomplex *work, doublereal *rwork, integer *iwork, - integer *ifail, integer *info, ftnlen jobz_len, - ftnlen range_len, ftnlen uplo_len); -extern int zhpgst_(integer *itype, char *uplo, integer *n, doublecomplex *ap, - doublecomplex *bp, integer *info, ftnlen uplo_len); -extern int zhpgv_(integer *itype, char *jobz, char *uplo, integer *n, - doublecomplex *ap, doublecomplex *bp, doublereal *w, - doublecomplex *z__, integer *ldz, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen jobz_len, - ftnlen uplo_len); -extern int zhpgvd_(integer *itype, char *jobz, char *uplo, integer *n, - doublecomplex *ap, doublecomplex *bp, doublereal *w, - doublecomplex *z__, integer *ldz, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *lrwork, - integer *iwork, integer *liwork, integer *info, - ftnlen jobz_len, ftnlen uplo_len); -extern int zhpgvx_(integer *itype, char *jobz, char *range, char *uplo, - integer *n, doublecomplex *ap, doublecomplex *bp, - doublereal *vl, doublereal *vu, integer *il, integer *iu, - doublereal *abstol, integer *m, doublereal *w, - doublecomplex *z__, integer *ldz, doublecomplex *work, - doublereal *rwork, integer *iwork, integer *ifail, - integer *info, ftnlen jobz_len, ftnlen range_len, - ftnlen uplo_len); -extern int zhprfs_(char *uplo, integer *n, integer *nrhs, doublecomplex *ap, - doublecomplex *afp, integer *ipiv, doublecomplex *b, - integer *ldb, doublecomplex *x, integer *ldx, - doublereal *ferr, doublereal *berr, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen uplo_len); -extern int zhpsv_(char *uplo, integer *n, integer *nrhs, doublecomplex *ap, - integer *ipiv, doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zhpsvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublecomplex *ap, doublecomplex *afp, integer *ipiv, - doublecomplex *b, integer *ldb, doublecomplex *x, - integer *ldx, doublereal *rcond, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen fact_len, ftnlen uplo_len); -extern int zhptrd_(char *uplo, integer *n, doublecomplex *ap, doublereal *d__, - doublereal *e, doublecomplex *tau, integer *info, - ftnlen uplo_len); -extern int zhptrf_(char *uplo, integer *n, doublecomplex *ap, integer *ipiv, - integer *info, ftnlen uplo_len); -extern int zhptri_(char *uplo, integer *n, doublecomplex *ap, integer *ipiv, - doublecomplex *work, integer *info, ftnlen uplo_len); -extern int zhptrs_(char *uplo, integer *n, integer *nrhs, doublecomplex *ap, - integer *ipiv, doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zhsein_(char *side, char *eigsrc, char *initv, logical *select, - integer *n, doublecomplex *h__, integer *ldh, - doublecomplex *w, doublecomplex *vl, integer *ldvl, - doublecomplex *vr, integer *ldvr, integer *mm, integer *m, - doublecomplex *work, doublereal *rwork, integer *ifaill, - integer *ifailr, integer *info, ftnlen side_len, - ftnlen eigsrc_len, ftnlen initv_len); -extern int zhseqr_(char *job, char *compz, integer *n, integer *ilo, - integer *ihi, doublecomplex *h__, integer *ldh, - doublecomplex *w, doublecomplex *z__, integer *ldz, - doublecomplex *work, integer *lwork, integer *info, - ftnlen job_len, ftnlen compz_len); -extern int zlabrd_(integer *m, integer *n, integer *nb, doublecomplex *a, - integer *lda, doublereal *d__, doublereal *e, - doublecomplex *tauq, doublecomplex *taup, doublecomplex *x, - integer *ldx, doublecomplex *y, integer *ldy); -extern int zlacgv_(integer *n, doublecomplex *x, integer *incx); -extern int zlacon_(integer *n, doublecomplex *v, doublecomplex *x, - doublereal *est, integer *kase); -extern int zlacp2_(char *uplo, integer *m, integer *n, doublereal *a, - integer *lda, doublecomplex *b, integer *ldb, - ftnlen uplo_len); -extern int zlacpy_(char *uplo, integer *m, integer *n, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - ftnlen uplo_len); -extern int zlacrm_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublereal *b, integer *ldb, doublecomplex *c__, - integer *ldc, doublereal *rwork); -extern int zlacrt_(integer *n, doublecomplex *cx, integer *incx, - doublecomplex *cy, integer *incy, doublecomplex *c__, - doublecomplex *s); -extern Z_f zladiv_(doublecomplex *ret_val, doublecomplex *x, doublecomplex *y); -extern int zlaed0_(integer *qsiz, integer *n, doublereal *d__, doublereal *e, - doublecomplex *q, integer *ldq, doublecomplex *qstore, - integer *ldqs, doublereal *rwork, integer *iwork, - integer *info); -extern int zlaed7_(integer *n, integer *cutpnt, integer *qsiz, integer *tlvls, - integer *curlvl, integer *curpbm, doublereal *d__, - doublecomplex *q, integer *ldq, doublereal *rho, - integer *indxq, doublereal *qstore, integer *qptr, - integer *prmptr, integer *perm, integer *givptr, - integer *givcol, doublereal *givnum, doublecomplex *work, - doublereal *rwork, integer *iwork, integer *info); -extern int zlaed8_(integer *k, integer *n, integer *qsiz, doublecomplex *q, - integer *ldq, doublereal *d__, doublereal *rho, - integer *cutpnt, doublereal *z__, doublereal *dlamda, - doublecomplex *q2, integer *ldq2, doublereal *w, - integer *indxp, integer *indx, integer *indxq, integer *perm, - integer *givptr, integer *givcol, doublereal *givnum, - integer *info); -extern int zlaein_(logical *rightv, logical *noinit, integer *n, - doublecomplex *h__, integer *ldh, doublecomplex *w, - doublecomplex *v, doublecomplex *b, integer *ldb, - doublereal *rwork, doublereal *eps3, doublereal *smlnum, - integer *info); -extern int zlaesy_(doublecomplex *a, doublecomplex *b, doublecomplex *c__, - doublecomplex *rt1, doublecomplex *rt2, - doublecomplex *evscal, doublecomplex *cs1, - doublecomplex *sn1); -extern int zlaev2_(doublecomplex *a, doublecomplex *b, doublecomplex *c__, - doublereal *rt1, doublereal *rt2, doublereal *cs1, - doublecomplex *sn1); -extern int zlags2_(logical *upper, doublereal *a1, doublecomplex *a2, - doublereal *a3, doublereal *b1, doublecomplex *b2, - doublereal *b3, doublereal *csu, doublecomplex *snu, - doublereal *csv, doublecomplex *snv, doublereal *csq, - doublecomplex *snq); -extern int zlagtm_(char *trans, integer *n, integer *nrhs, doublereal *alpha, - doublecomplex *dl, doublecomplex *d__, doublecomplex *du, - doublecomplex *x, integer *ldx, doublereal *beta, - doublecomplex *b, integer *ldb, ftnlen trans_len); -extern int zlahef_(char *uplo, integer *n, integer *nb, integer *kb, - doublecomplex *a, integer *lda, integer *ipiv, - doublecomplex *w, integer *ldw, integer *info, - ftnlen uplo_len); -extern int zlahqr_(logical *wantt, logical *wantz, integer *n, integer *ilo, - integer *ihi, doublecomplex *h__, integer *ldh, - doublecomplex *w, integer *iloz, integer *ihiz, - doublecomplex *z__, integer *ldz, integer *info); -extern int zlahrd_(integer *n, integer *k, integer *nb, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *t, - integer *ldt, doublecomplex *y, integer *ldy); -extern int zlaic1_(integer *job, integer *j, doublecomplex *x, doublereal *sest, - doublecomplex *w, doublecomplex *gamma, doublereal *sestpr, - doublecomplex *s, doublecomplex *c__); -extern int zlals0_(integer *icompq, integer *nl, integer *nr, integer *sqre, - integer *nrhs, doublecomplex *b, integer *ldb, - doublecomplex *bx, integer *ldbx, integer *perm, - integer *givptr, integer *givcol, integer *ldgcol, - doublereal *givnum, integer *ldgnum, doublereal *poles, - doublereal *difl, doublereal *difr, doublereal *z__, - integer *k, doublereal *c__, doublereal *s, - doublereal *rwork, integer *info); -extern int zlalsa_(integer *icompq, integer *smlsiz, integer *n, integer *nrhs, - doublecomplex *b, integer *ldb, doublecomplex *bx, - integer *ldbx, doublereal *u, integer *ldu, doublereal *vt, - integer *k, doublereal *difl, doublereal *difr, - doublereal *z__, doublereal *poles, integer *givptr, - integer *givcol, integer *ldgcol, integer *perm, - doublereal *givnum, doublereal *c__, doublereal *s, - doublereal *rwork, integer *iwork, integer *info); -extern int zlalsd_(char *uplo, integer *smlsiz, integer *n, integer *nrhs, - doublereal *d__, doublereal *e, doublecomplex *b, - integer *ldb, doublereal *rcond, integer *rank, - doublecomplex *work, doublereal *rwork, integer *iwork, - integer *info, ftnlen uplo_len); -extern doublereal zlangb_(char *norm, integer *n, integer *kl, integer *ku, - doublecomplex *ab, integer *ldab, doublereal *work, - ftnlen norm_len); -extern doublereal zlange_(char *norm, integer *m, integer *n, doublecomplex *a, - integer *lda, doublereal *work, ftnlen norm_len); -extern doublereal zlangt_(char *norm, integer *n, doublecomplex *dl, - doublecomplex *d__, doublecomplex *du, - ftnlen norm_len); -extern doublereal zlanhb_(char *norm, char *uplo, integer *n, integer *k, - doublecomplex *ab, integer *ldab, doublereal *work, - ftnlen norm_len, ftnlen uplo_len); -extern doublereal zlanhe_(char *norm, char *uplo, integer *n, doublecomplex *a, - integer *lda, doublereal *work, ftnlen norm_len, - ftnlen uplo_len); -extern doublereal zlanhp_(char *norm, char *uplo, integer *n, doublecomplex *ap, - doublereal *work, ftnlen norm_len, ftnlen uplo_len); -extern doublereal zlanhs_(char *norm, integer *n, doublecomplex *a, - integer *lda, doublereal *work, ftnlen norm_len); -extern doublereal zlanht_(char *norm, integer *n, doublereal *d__, - doublecomplex *e, ftnlen norm_len); -extern doublereal zlansb_(char *norm, char *uplo, integer *n, integer *k, - doublecomplex *ab, integer *ldab, doublereal *work, - ftnlen norm_len, ftnlen uplo_len); -extern doublereal zlansp_(char *norm, char *uplo, integer *n, doublecomplex *ap, - doublereal *work, ftnlen norm_len, ftnlen uplo_len); -extern doublereal zlansy_(char *norm, char *uplo, integer *n, doublecomplex *a, - integer *lda, doublereal *work, ftnlen norm_len, - ftnlen uplo_len); -extern doublereal zlantb_(char *norm, char *uplo, char *diag, integer *n, - integer *k, doublecomplex *ab, integer *ldab, - doublereal *work, ftnlen norm_len, ftnlen uplo_len, - ftnlen diag_len); -extern doublereal zlantp_(char *norm, char *uplo, char *diag, integer *n, - doublecomplex *ap, doublereal *work, ftnlen norm_len, - ftnlen uplo_len, ftnlen diag_len); -extern doublereal zlantr_(char *norm, char *uplo, char *diag, integer *m, - integer *n, doublecomplex *a, integer *lda, - doublereal *work, ftnlen norm_len, ftnlen uplo_len, - ftnlen diag_len); -extern int zlapll_(integer *n, doublecomplex *x, integer *incx, - doublecomplex *y, integer *incy, doublereal *ssmin); -extern int zlapmt_(logical *forwrd, integer *m, integer *n, doublecomplex *x, - integer *ldx, integer *k); -extern int zlaqgb_(integer *m, integer *n, integer *kl, integer *ku, - doublecomplex *ab, integer *ldab, doublereal *r__, - doublereal *c__, doublereal *rowcnd, doublereal *colcnd, - doublereal *amax, char *equed, ftnlen equed_len); -extern int zlaqge_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublereal *r__, doublereal *c__, doublereal *rowcnd, - doublereal *colcnd, doublereal *amax, char *equed, - ftnlen equed_len); -extern int zlaqhb_(char *uplo, integer *n, integer *kd, doublecomplex *ab, - integer *ldab, doublereal *s, doublereal *scond, - doublereal *amax, char *equed, ftnlen uplo_len, - ftnlen equed_len); -extern int zlaqhe_(char *uplo, integer *n, doublecomplex *a, integer *lda, - doublereal *s, doublereal *scond, doublereal *amax, - char *equed, ftnlen uplo_len, ftnlen equed_len); -extern int zlaqhp_(char *uplo, integer *n, doublecomplex *ap, doublereal *s, - doublereal *scond, doublereal *amax, char *equed, - ftnlen uplo_len, ftnlen equed_len); -extern int zlaqp2_(integer *m, integer *n, integer *offset, doublecomplex *a, - integer *lda, integer *jpvt, doublecomplex *tau, - doublereal *vn1, doublereal *vn2, doublecomplex *work); -extern int zlaqps_(integer *m, integer *n, integer *offset, integer *nb, - integer *kb, doublecomplex *a, integer *lda, integer *jpvt, - doublecomplex *tau, doublereal *vn1, doublereal *vn2, - doublecomplex *auxv, doublecomplex *f, integer *ldf); -extern int zlaqsb_(char *uplo, integer *n, integer *kd, doublecomplex *ab, - integer *ldab, doublereal *s, doublereal *scond, - doublereal *amax, char *equed, ftnlen uplo_len, - ftnlen equed_len); -extern int zlaqsp_(char *uplo, integer *n, doublecomplex *ap, doublereal *s, - doublereal *scond, doublereal *amax, char *equed, - ftnlen uplo_len, ftnlen equed_len); -extern int zlaqsy_(char *uplo, integer *n, doublecomplex *a, integer *lda, - doublereal *s, doublereal *scond, doublereal *amax, - char *equed, ftnlen uplo_len, ftnlen equed_len); -extern int zlar1v_(integer *n, integer *b1, integer *bn, doublereal *sigma, - doublereal *d__, doublereal *l, doublereal *ld, - doublereal *lld, doublereal *gersch, doublecomplex *z__, - doublereal *ztz, doublereal *mingma, integer *r__, - integer *isuppz, doublereal *work); -extern int zlar2v_(integer *n, doublecomplex *x, doublecomplex *y, - doublecomplex *z__, integer *incx, doublereal *c__, - doublecomplex *s, integer *incc); -extern int zlarcm_(integer *m, integer *n, doublereal *a, integer *lda, - doublecomplex *b, integer *ldb, doublecomplex *c__, - integer *ldc, doublereal *rwork); -extern int zlarf_(char *side, integer *m, integer *n, doublecomplex *v, - integer *incv, doublecomplex *tau, doublecomplex *c__, - integer *ldc, doublecomplex *work, ftnlen side_len); -extern int zlarfb_(char *side, char *trans, char *direct, char *storev, - integer *m, integer *n, integer *k, doublecomplex *v, - integer *ldv, doublecomplex *t, integer *ldt, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *ldwork, ftnlen side_len, ftnlen trans_len, - ftnlen direct_len, ftnlen storev_len); -extern int zlarfg_(integer *n, doublecomplex *alpha, doublecomplex *x, - integer *incx, doublecomplex *tau); -extern int zlarft_(char *direct, char *storev, integer *n, integer *k, - doublecomplex *v, integer *ldv, doublecomplex *tau, - doublecomplex *t, integer *ldt, ftnlen direct_len, - ftnlen storev_len); -extern int zlarfx_(char *side, integer *m, integer *n, doublecomplex *v, - doublecomplex *tau, doublecomplex *c__, integer *ldc, - doublecomplex *work, ftnlen side_len); -extern int zlargv_(integer *n, doublecomplex *x, integer *incx, - doublecomplex *y, integer *incy, doublereal *c__, - integer *incc); -extern int zlarnv_(integer *idist, integer *iseed, integer *n, - doublecomplex *x); -extern int zlarrv_(integer *n, doublereal *d__, doublereal *l, integer *isplit, - integer *m, doublereal *w, integer *iblock, - doublereal *gersch, doublereal *tol, doublecomplex *z__, - integer *ldz, integer *isuppz, doublereal *work, - integer *iwork, integer *info); -extern int zlartg_(doublecomplex *f, doublecomplex *g, doublereal *cs, - doublecomplex *sn, doublecomplex *r__); -extern int zlartv_(integer *n, doublecomplex *x, integer *incx, - doublecomplex *y, integer *incy, doublereal *c__, - doublecomplex *s, integer *incc); -extern int zlarz_(char *side, integer *m, integer *n, integer *l, - doublecomplex *v, integer *incv, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - ftnlen side_len); -extern int zlarzb_(char *side, char *trans, char *direct, char *storev, - integer *m, integer *n, integer *k, integer *l, - doublecomplex *v, integer *ldv, doublecomplex *t, - integer *ldt, doublecomplex *c__, integer *ldc, - doublecomplex *work, integer *ldwork, ftnlen side_len, - ftnlen trans_len, ftnlen direct_len, ftnlen storev_len); -extern int zlarzt_(char *direct, char *storev, integer *n, integer *k, - doublecomplex *v, integer *ldv, doublecomplex *tau, - doublecomplex *t, integer *ldt, ftnlen direct_len, - ftnlen storev_len); -extern int zlascl_(char *type__, integer *kl, integer *ku, doublereal *cfrom, - doublereal *cto, integer *m, integer *n, doublecomplex *a, - integer *lda, integer *info, ftnlen type_len); -extern int zlaset_(char *uplo, integer *m, integer *n, doublecomplex *alpha, - doublecomplex *beta, doublecomplex *a, integer *lda, - ftnlen uplo_len); -extern int zlasr_(char *side, char *pivot, char *direct, integer *m, integer *n, - doublereal *c__, doublereal *s, doublecomplex *a, - integer *lda, ftnlen side_len, ftnlen pivot_len, - ftnlen direct_len); -extern int zlassq_(integer *n, doublecomplex *x, integer *incx, - doublereal *scale, doublereal *sumsq); -extern int zlaswp_(integer *n, doublecomplex *a, integer *lda, integer *k1, - integer *k2, integer *ipiv, integer *incx); -extern int zlasyf_(char *uplo, integer *n, integer *nb, integer *kb, - doublecomplex *a, integer *lda, integer *ipiv, - doublecomplex *w, integer *ldw, integer *info, - ftnlen uplo_len); -extern int zlatbs_(char *uplo, char *trans, char *diag, char *normin, - integer *n, integer *kd, doublecomplex *ab, integer *ldab, - doublecomplex *x, doublereal *scale, doublereal *cnorm, - integer *info, ftnlen uplo_len, ftnlen trans_len, - ftnlen diag_len, ftnlen normin_len); -extern int zlatdf_(integer *ijob, integer *n, doublecomplex *z__, integer *ldz, - doublecomplex *rhs, doublereal *rdsum, doublereal *rdscal, - integer *ipiv, integer *jpiv); -extern int zlatps_(char *uplo, char *trans, char *diag, char *normin, - integer *n, doublecomplex *ap, doublecomplex *x, - doublereal *scale, doublereal *cnorm, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len, - ftnlen normin_len); -extern int zlatrd_(char *uplo, integer *n, integer *nb, doublecomplex *a, - integer *lda, doublereal *e, doublecomplex *tau, - doublecomplex *w, integer *ldw, ftnlen uplo_len); -extern int zlatrs_(char *uplo, char *trans, char *diag, char *normin, - integer *n, doublecomplex *a, integer *lda, doublecomplex *x, - doublereal *scale, doublereal *cnorm, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len, - ftnlen normin_len); -extern int zlatrz_(integer *m, integer *n, integer *l, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work); -extern int zlatzm_(char *side, integer *m, integer *n, doublecomplex *v, - integer *incv, doublecomplex *tau, doublecomplex *c1, - doublecomplex *c2, integer *ldc, doublecomplex *work, - ftnlen side_len); -extern int zlauu2_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int zlauum_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int zpbcon_(char *uplo, integer *n, integer *kd, doublecomplex *ab, - integer *ldab, doublereal *anorm, doublereal *rcond, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen uplo_len); -extern int zpbequ_(char *uplo, integer *n, integer *kd, doublecomplex *ab, - integer *ldab, doublereal *s, doublereal *scond, - doublereal *amax, integer *info, ftnlen uplo_len); -extern int zpbrfs_(char *uplo, integer *n, integer *kd, integer *nrhs, - doublecomplex *ab, integer *ldab, doublecomplex *afb, - integer *ldafb, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen uplo_len); -extern int zpbstf_(char *uplo, integer *n, integer *kd, doublecomplex *ab, - integer *ldab, integer *info, ftnlen uplo_len); -extern int zpbsv_(char *uplo, integer *n, integer *kd, integer *nrhs, - doublecomplex *ab, integer *ldab, doublecomplex *b, - integer *ldb, integer *info, ftnlen uplo_len); -extern int zpbsvx_(char *fact, char *uplo, integer *n, integer *kd, - integer *nrhs, doublecomplex *ab, integer *ldab, - doublecomplex *afb, integer *ldafb, char *equed, - doublereal *s, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *rcond, - doublereal *ferr, doublereal *berr, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen fact_len, - ftnlen uplo_len, ftnlen equed_len); -extern int zpbtf2_(char *uplo, integer *n, integer *kd, doublecomplex *ab, - integer *ldab, integer *info, ftnlen uplo_len); -extern int zpbtrf_(char *uplo, integer *n, integer *kd, doublecomplex *ab, - integer *ldab, integer *info, ftnlen uplo_len); -extern int zpbtrs_(char *uplo, integer *n, integer *kd, integer *nrhs, - doublecomplex *ab, integer *ldab, doublecomplex *b, - integer *ldb, integer *info, ftnlen uplo_len); -extern int zpocon_(char *uplo, integer *n, doublecomplex *a, integer *lda, - doublereal *anorm, doublereal *rcond, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen uplo_len); -extern int zpoequ_(integer *n, doublecomplex *a, integer *lda, doublereal *s, - doublereal *scond, doublereal *amax, integer *info); -extern int zporfs_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *af, integer *ldaf, - doublecomplex *b, integer *ldb, doublecomplex *x, - integer *ldx, doublereal *ferr, doublereal *berr, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen uplo_len); -extern int zposv_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zposvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublecomplex *a, integer *lda, doublecomplex *af, - integer *ldaf, char *equed, doublereal *s, doublecomplex *b, - integer *ldb, doublecomplex *x, integer *ldx, - doublereal *rcond, doublereal *ferr, doublereal *berr, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen fact_len, ftnlen uplo_len, ftnlen equed_len); -extern int zpotf2_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int zpotrf_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int zpotri_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *info, ftnlen uplo_len); -extern int zpotrs_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zppcon_(char *uplo, integer *n, doublecomplex *ap, doublereal *anorm, - doublereal *rcond, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen uplo_len); -extern int zppequ_(char *uplo, integer *n, doublecomplex *ap, doublereal *s, - doublereal *scond, doublereal *amax, integer *info, - ftnlen uplo_len); -extern int zpprfs_(char *uplo, integer *n, integer *nrhs, doublecomplex *ap, - doublecomplex *afp, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen uplo_len); -extern int zppsv_(char *uplo, integer *n, integer *nrhs, doublecomplex *ap, - doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zppsvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublecomplex *ap, doublecomplex *afp, char *equed, - doublereal *s, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *rcond, - doublereal *ferr, doublereal *berr, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen fact_len, - ftnlen uplo_len, ftnlen equed_len); -extern int zpptrf_(char *uplo, integer *n, doublecomplex *ap, integer *info, - ftnlen uplo_len); -extern int zpptri_(char *uplo, integer *n, doublecomplex *ap, integer *info, - ftnlen uplo_len); -extern int zpptrs_(char *uplo, integer *n, integer *nrhs, doublecomplex *ap, - doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zptcon_(integer *n, doublereal *d__, doublecomplex *e, - doublereal *anorm, doublereal *rcond, doublereal *rwork, - integer *info); -extern int zpteqr_(char *compz, integer *n, doublereal *d__, doublereal *e, - doublecomplex *z__, integer *ldz, doublereal *work, - integer *info, ftnlen compz_len); -extern int zptrfs_(char *uplo, integer *n, integer *nrhs, doublereal *d__, - doublecomplex *e, doublereal *df, doublecomplex *ef, - doublecomplex *b, integer *ldb, doublecomplex *x, - integer *ldx, doublereal *ferr, doublereal *berr, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen uplo_len); -extern int zptsv_(integer *n, integer *nrhs, doublereal *d__, doublecomplex *e, - doublecomplex *b, integer *ldb, integer *info); -extern int zptsvx_(char *fact, integer *n, integer *nrhs, doublereal *d__, - doublecomplex *e, doublereal *df, doublecomplex *ef, - doublecomplex *b, integer *ldb, doublecomplex *x, - integer *ldx, doublereal *rcond, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen fact_len); -extern int zpttrf_(integer *n, doublereal *d__, doublecomplex *e, - integer *info); -extern int zpttrs_(char *uplo, integer *n, integer *nrhs, doublereal *d__, - doublecomplex *e, doublecomplex *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int zptts2_(integer *iuplo, integer *n, integer *nrhs, doublereal *d__, - doublecomplex *e, doublecomplex *b, integer *ldb); -extern int zrot_(integer *n, doublecomplex *cx, integer *incx, - doublecomplex *cy, integer *incy, doublereal *c__, - doublecomplex *s); -extern int zspcon_(char *uplo, integer *n, doublecomplex *ap, integer *ipiv, - doublereal *anorm, doublereal *rcond, doublecomplex *work, - integer *info, ftnlen uplo_len); -extern int zspmv_(char *uplo, integer *n, doublecomplex *alpha, - doublecomplex *ap, doublecomplex *x, integer *incx, - doublecomplex *beta, doublecomplex *y, integer *incy, - ftnlen uplo_len); -extern int zspr_(char *uplo, integer *n, doublecomplex *alpha, doublecomplex *x, - integer *incx, doublecomplex *ap, ftnlen uplo_len); -extern int zsprfs_(char *uplo, integer *n, integer *nrhs, doublecomplex *ap, - doublecomplex *afp, integer *ipiv, doublecomplex *b, - integer *ldb, doublecomplex *x, integer *ldx, - doublereal *ferr, doublereal *berr, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen uplo_len); -extern int zspsv_(char *uplo, integer *n, integer *nrhs, doublecomplex *ap, - integer *ipiv, doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zspsvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublecomplex *ap, doublecomplex *afp, integer *ipiv, - doublecomplex *b, integer *ldb, doublecomplex *x, - integer *ldx, doublereal *rcond, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen fact_len, ftnlen uplo_len); -extern int zsptrf_(char *uplo, integer *n, doublecomplex *ap, integer *ipiv, - integer *info, ftnlen uplo_len); -extern int zsptri_(char *uplo, integer *n, doublecomplex *ap, integer *ipiv, - doublecomplex *work, integer *info, ftnlen uplo_len); -extern int zsptrs_(char *uplo, integer *n, integer *nrhs, doublecomplex *ap, - integer *ipiv, doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len); -extern int zstedc_(char *compz, integer *n, doublereal *d__, doublereal *e, - doublecomplex *z__, integer *ldz, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *lrwork, - integer *iwork, integer *liwork, integer *info, - ftnlen compz_len); -extern int zstegr_(char *jobz, char *range, integer *n, doublereal *d__, - doublereal *e, doublereal *vl, doublereal *vu, integer *il, - integer *iu, doublereal *abstol, integer *m, doublereal *w, - doublecomplex *z__, integer *ldz, integer *isuppz, - doublereal *work, integer *lwork, integer *iwork, - integer *liwork, integer *info, ftnlen jobz_len, - ftnlen range_len); -extern int zstein_(integer *n, doublereal *d__, doublereal *e, integer *m, - doublereal *w, integer *iblock, integer *isplit, - doublecomplex *z__, integer *ldz, doublereal *work, - integer *iwork, integer *ifail, integer *info); -extern int zsteqr_(char *compz, integer *n, doublereal *d__, doublereal *e, - doublecomplex *z__, integer *ldz, doublereal *work, - integer *info, ftnlen compz_len); -extern int zsycon_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, doublereal *anorm, doublereal *rcond, - doublecomplex *work, integer *info, ftnlen uplo_len); -extern int zsymv_(char *uplo, integer *n, doublecomplex *alpha, - doublecomplex *a, integer *lda, doublecomplex *x, - integer *incx, doublecomplex *beta, doublecomplex *y, - integer *incy, ftnlen uplo_len); -extern int zsyr_(char *uplo, integer *n, doublecomplex *alpha, doublecomplex *x, - integer *incx, doublecomplex *a, integer *lda, - ftnlen uplo_len); -extern int zsyrfs_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, doublecomplex *af, integer *ldaf, - integer *ipiv, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *ferr, - doublereal *berr, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen uplo_len); -extern int zsysv_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, integer *ipiv, doublecomplex *b, integer *ldb, - doublecomplex *work, integer *lwork, integer *info, - ftnlen uplo_len); -extern int zsysvx_(char *fact, char *uplo, integer *n, integer *nrhs, - doublecomplex *a, integer *lda, doublecomplex *af, - integer *ldaf, integer *ipiv, doublecomplex *b, integer *ldb, - doublecomplex *x, integer *ldx, doublereal *rcond, - doublereal *ferr, doublereal *berr, doublecomplex *work, - integer *lwork, doublereal *rwork, integer *info, - ftnlen fact_len, ftnlen uplo_len); -extern int zsytf2_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, integer *info, ftnlen uplo_len); -extern int zsytrf_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, doublecomplex *work, integer *lwork, - integer *info, ftnlen uplo_len); -extern int zsytri_(char *uplo, integer *n, doublecomplex *a, integer *lda, - integer *ipiv, doublecomplex *work, integer *info, - ftnlen uplo_len); -extern int zsytrs_(char *uplo, integer *n, integer *nrhs, doublecomplex *a, - integer *lda, integer *ipiv, doublecomplex *b, integer *ldb, - integer *info, ftnlen uplo_len); -extern int ztbcon_(char *norm, char *uplo, char *diag, integer *n, integer *kd, - doublecomplex *ab, integer *ldab, doublereal *rcond, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen norm_len, ftnlen uplo_len, ftnlen diag_len); -extern int ztbrfs_(char *uplo, char *trans, char *diag, integer *n, integer *kd, - integer *nrhs, doublecomplex *ab, integer *ldab, - doublecomplex *b, integer *ldb, doublecomplex *x, - integer *ldx, doublereal *ferr, doublereal *berr, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ztbtrs_(char *uplo, char *trans, char *diag, integer *n, integer *kd, - integer *nrhs, doublecomplex *ab, integer *ldab, - doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ztgevc_(char *side, char *howmny, logical *select, integer *n, - doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublecomplex *vl, integer *ldvl, - doublecomplex *vr, integer *ldvr, integer *mm, integer *m, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen side_len, ftnlen howmny_len); -extern int ztgex2_(logical *wantq, logical *wantz, integer *n, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublecomplex *q, integer *ldq, doublecomplex *z__, - integer *ldz, integer *j1, integer *info); -extern int ztgexc_(logical *wantq, logical *wantz, integer *n, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublecomplex *q, integer *ldq, doublecomplex *z__, - integer *ldz, integer *ifst, integer *ilst, integer *info); -extern int ztgsen_(integer *ijob, logical *wantq, logical *wantz, - logical *select, integer *n, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, doublecomplex *alpha, - doublecomplex *beta, doublecomplex *q, integer *ldq, - doublecomplex *z__, integer *ldz, integer *m, doublereal *pl, - doublereal *pr, doublereal *dif, doublecomplex *work, - integer *lwork, integer *iwork, integer *liwork, - integer *info); -extern int ztgsja_(char *jobu, char *jobv, char *jobq, integer *m, integer *p, - integer *n, integer *k, integer *l, doublecomplex *a, - integer *lda, doublecomplex *b, integer *ldb, - doublereal *tola, doublereal *tolb, doublereal *alpha, - doublereal *beta, doublecomplex *u, integer *ldu, - doublecomplex *v, integer *ldv, doublecomplex *q, - integer *ldq, doublecomplex *work, integer *ncycle, - integer *info, ftnlen jobu_len, ftnlen jobv_len, - ftnlen jobq_len); -extern int ztgsna_(char *job, char *howmny, logical *select, integer *n, - doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublecomplex *vl, integer *ldvl, - doublecomplex *vr, integer *ldvr, doublereal *s, - doublereal *dif, integer *mm, integer *m, - doublecomplex *work, integer *lwork, integer *iwork, - integer *info, ftnlen job_len, ftnlen howmny_len); -extern int ztgsy2_(char *trans, integer *ijob, integer *m, integer *n, - doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublecomplex *c__, integer *ldc, - doublecomplex *d__, integer *ldd, doublecomplex *e, - integer *lde, doublecomplex *f, integer *ldf, - doublereal *scale, doublereal *rdsum, doublereal *rdscal, - integer *info, ftnlen trans_len); -extern int ztgsyl_(char *trans, integer *ijob, integer *m, integer *n, - doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublecomplex *c__, integer *ldc, - doublecomplex *d__, integer *ldd, doublecomplex *e, - integer *lde, doublecomplex *f, integer *ldf, - doublereal *scale, doublereal *dif, doublecomplex *work, - integer *lwork, integer *iwork, integer *info, - ftnlen trans_len); -extern int ztpcon_(char *norm, char *uplo, char *diag, integer *n, - doublecomplex *ap, doublereal *rcond, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen norm_len, - ftnlen uplo_len, ftnlen diag_len); -extern int ztprfs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, doublecomplex *ap, doublecomplex *b, - integer *ldb, doublecomplex *x, integer *ldx, - doublereal *ferr, doublereal *berr, doublecomplex *work, - doublereal *rwork, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int ztptri_(char *uplo, char *diag, integer *n, doublecomplex *ap, - integer *info, ftnlen uplo_len, ftnlen diag_len); -extern int ztptrs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, doublecomplex *ap, doublecomplex *b, - integer *ldb, integer *info, ftnlen uplo_len, - ftnlen trans_len, ftnlen diag_len); -extern int ztrcon_(char *norm, char *uplo, char *diag, integer *n, - doublecomplex *a, integer *lda, doublereal *rcond, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen norm_len, ftnlen uplo_len, ftnlen diag_len); -extern int ztrevc_(char *side, char *howmny, logical *select, integer *n, - doublecomplex *t, integer *ldt, doublecomplex *vl, - integer *ldvl, doublecomplex *vr, integer *ldvr, integer *mm, - integer *m, doublecomplex *work, doublereal *rwork, - integer *info, ftnlen side_len, ftnlen howmny_len); -extern int ztrexc_(char *compq, integer *n, doublecomplex *t, integer *ldt, - doublecomplex *q, integer *ldq, integer *ifst, integer *ilst, - integer *info, ftnlen compq_len); -extern int ztrrfs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, doublecomplex *x, - integer *ldx, doublereal *ferr, doublereal *berr, - doublecomplex *work, doublereal *rwork, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ztrsen_(char *job, char *compq, logical *select, integer *n, - doublecomplex *t, integer *ldt, doublecomplex *q, - integer *ldq, doublecomplex *w, integer *m, doublereal *s, - doublereal *sep, doublecomplex *work, integer *lwork, - integer *info, ftnlen job_len, ftnlen compq_len); -extern int ztrsna_(char *job, char *howmny, logical *select, integer *n, - doublecomplex *t, integer *ldt, doublecomplex *vl, - integer *ldvl, doublecomplex *vr, integer *ldvr, - doublereal *s, doublereal *sep, integer *mm, integer *m, - doublecomplex *work, integer *ldwork, doublereal *rwork, - integer *info, ftnlen job_len, ftnlen howmny_len); -extern int ztrsyl_(char *trana, char *tranb, integer *isgn, integer *m, - integer *n, doublecomplex *a, integer *lda, doublecomplex *b, - integer *ldb, doublecomplex *c__, integer *ldc, - doublereal *scale, integer *info, ftnlen trana_len, - ftnlen tranb_len); -extern int ztrti2_(char *uplo, char *diag, integer *n, doublecomplex *a, - integer *lda, integer *info, ftnlen uplo_len, - ftnlen diag_len); -extern int ztrtri_(char *uplo, char *diag, integer *n, doublecomplex *a, - integer *lda, integer *info, ftnlen uplo_len, - ftnlen diag_len); -extern int ztrtrs_(char *uplo, char *trans, char *diag, integer *n, - integer *nrhs, doublecomplex *a, integer *lda, - doublecomplex *b, integer *ldb, integer *info, - ftnlen uplo_len, ftnlen trans_len, ftnlen diag_len); -extern int ztzrqf_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, integer *info); -extern int ztzrzf_(integer *m, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *lwork, - integer *info); -extern int zung2l_(integer *m, integer *n, integer *k, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *info); -extern int zung2r_(integer *m, integer *n, integer *k, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *info); -extern int zungbr_(char *vect, integer *m, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *work, integer *lwork, integer *info, - ftnlen vect_len); -extern int zunghr_(integer *n, integer *ilo, integer *ihi, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *lwork, integer *info); -extern int zungl2_(integer *m, integer *n, integer *k, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *info); -extern int zunglq_(integer *m, integer *n, integer *k, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *lwork, integer *info); -extern int zungql_(integer *m, integer *n, integer *k, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *lwork, integer *info); -extern int zungqr_(integer *m, integer *n, integer *k, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *lwork, integer *info); -extern int zungr2_(integer *m, integer *n, integer *k, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *info); -extern int zungrq_(integer *m, integer *n, integer *k, doublecomplex *a, - integer *lda, doublecomplex *tau, doublecomplex *work, - integer *lwork, integer *info); -extern int zungtr_(char *uplo, integer *n, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *work, integer *lwork, - integer *info, ftnlen uplo_len); -extern int zunm2l_(char *side, char *trans, integer *m, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int zunm2r_(char *side, char *trans, integer *m, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int zunmbr_(char *vect, char *side, char *trans, integer *m, integer *n, - integer *k, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *c__, integer *ldc, - doublecomplex *work, integer *lwork, integer *info, - ftnlen vect_len, ftnlen side_len, ftnlen trans_len); -extern int zunmhr_(char *side, char *trans, integer *m, integer *n, - integer *ilo, integer *ihi, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *c__, integer *ldc, - doublecomplex *work, integer *lwork, integer *info, - ftnlen side_len, ftnlen trans_len); -extern int zunml2_(char *side, char *trans, integer *m, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int zunmlq_(char *side, char *trans, integer *m, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int zunmql_(char *side, char *trans, integer *m, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int zunmqr_(char *side, char *trans, integer *m, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int zunmr2_(char *side, char *trans, integer *m, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *info, ftnlen side_len, ftnlen trans_len); -extern int zunmr3_(char *side, char *trans, integer *m, integer *n, integer *k, - integer *l, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *c__, integer *ldc, - doublecomplex *work, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int zunmrq_(char *side, char *trans, integer *m, integer *n, integer *k, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen trans_len); -extern int zunmrz_(char *side, char *trans, integer *m, integer *n, integer *k, - integer *l, doublecomplex *a, integer *lda, - doublecomplex *tau, doublecomplex *c__, integer *ldc, - doublecomplex *work, integer *lwork, integer *info, - ftnlen side_len, ftnlen trans_len); -extern int zunmtr_(char *side, char *uplo, char *trans, integer *m, integer *n, - doublecomplex *a, integer *lda, doublecomplex *tau, - doublecomplex *c__, integer *ldc, doublecomplex *work, - integer *lwork, integer *info, ftnlen side_len, - ftnlen uplo_len, ftnlen trans_len); -extern int zupgtr_(char *uplo, integer *n, doublecomplex *ap, - doublecomplex *tau, doublecomplex *q, integer *ldq, - doublecomplex *work, integer *info, ftnlen uplo_len); -extern int zupmtr_(char *side, char *uplo, char *trans, integer *m, integer *n, - doublecomplex *ap, doublecomplex *tau, doublecomplex *c__, - integer *ldc, doublecomplex *work, integer *info, - ftnlen side_len, ftnlen uplo_len, ftnlen trans_len); - -#endif diff --git a/lib/external/shapelib/README.md b/lib/external/shapelib/README.md index e004d2d0419..d446eccd014 100644 --- a/lib/external/shapelib/README.md +++ b/lib/external/shapelib/README.md @@ -1,12 +1,13 @@ # Update history of SHAPELIB copy -* files `shpopen.c`, `shapefil.h`, `dbfopen.c` +* files `shpopen.c`, `shapefil.h`, `dbfopen.c`, `shapefil_private.h` from GDAL [ogr/ogrsf_frmts/shape/](https://github.com/OSGeo/gdal/tree/master/ogr/ogrsf_frmts/shape) * file `safileio.c` from [SHAPELIB](http://download.osgeo.org/shapelib/) ## Last update +* taken from GDAL 3.9.2 and SHAPELIB 1.6.0 (Sep 2024) * taken from GDAL 3.5.3 and SHAPELIB 1.5.0 (Dec 2022) * taken from GDAL 2.1.2 and SHAPELIB 1.3.0 (Thu Nov 24 10:45:41 CET 2016) * taken from GDAL 1.5.1-SVN (Sun Mar 30 11:20:43 CEST 2008) @@ -15,44 +16,5 @@ ## Summary of fixes -* dbfopen.c - around line 1229: GDAL bug [ticket-#809](http://trac.osgeo.org/gdal/ticket/809) - * safileio.c - SHP_CVSID: ISO C does not allow extra ‘;’ outside of a function - -## Full fix - -```diff -diff --git a/lib/external/shapelib/dbfopen.c b/lib/external/shapelib/dbfopen.c -index 5380e3e20b..5151148d33 100644 ---- a/lib/external/shapelib/dbfopen.c -+++ b/lib/external/shapelib/dbfopen.c -@@ -1226,9 +1226,10 @@ DBFGetFieldInfo( DBFHandle psDBF, int iField, char * pszFieldName, - else if( psDBF->pachFieldType[iField] == 'N' - || psDBF->pachFieldType[iField] == 'F' ) - { -- if( psDBF->panFieldDecimals[iField] > 0 -- || psDBF->panFieldSize[iField] >= 10 ) -+ if( psDBF->panFieldDecimals[iField] > 0 ) { -+ /* || psDBF->panFieldSize[iField] >= 10 ) */ /* GDAL bug #809 */ - return( FTDouble ); -+ } - else - return( FTInteger ); - } -diff --git a/lib/external/shapelib/safileio.c b/lib/external/shapelib/safileio.c -index 289d347eaf..7a614a5806 100644 ---- a/lib/external/shapelib/safileio.c -+++ b/lib/external/shapelib/safileio.c -@@ -74,7 +74,7 @@ - #include - #include - --SHP_CVSID("$Id: safileio.c,v 1.6 2018-06-15 19:56:32 erouault Exp $"); -+SHP_CVSID("$Id: safileio.c,v 1.6 2018-06-15 19:56:32 erouault Exp $") - - #ifdef SHPAPI_UTF8_HOOKS - # ifdef SHPAPI_WINDOWS - -``` + [shapelib commit 316ff87](https://github.com/OSGeo/shapelib/commit/316ff872566ea0d91d6b62fe01bfe39931db39aa#diff-f068bc465ca1a32e1b9c214d4eb9504ef9e0f3c4cabc1aa4bab8aa41e2248cc6R153) diff --git a/lib/external/shapelib/dbfopen.c b/lib/external/shapelib/dbfopen.c index 2bbba339e21..9078a29ba95 100644 --- a/lib/external/shapelib/dbfopen.c +++ b/lib/external/shapelib/dbfopen.c @@ -1,5 +1,4 @@ /****************************************************************************** - * $Id$ * * Project: Shapelib * Purpose: Implementation of .dbf access API documented in dbf_api.html. @@ -9,32 +8,10 @@ * Copyright (c) 1999, Frank Warmerdam * Copyright (c) 2012-2019, Even Rouault * - * This software is available under the following "MIT Style" license, - * or at the option of the licensee under the LGPL (see COPYING). This - * option is discussed in more detail in shapelib.html. - * - * -- - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * SPDX-License-Identifier: MIT OR LGPL-2.0-or-later ******************************************************************************/ -#include "shapefil.h" +#include "shapefil_private.h" #include #include @@ -47,7 +24,9 @@ #include "cpl_string.h" #else -#if defined(WIN32) || defined(_WIN32) +#if defined(_MSC_VER) +#define STRCASECMP(a, b) (_stricmp(a, b)) +#elif defined(_WIN32) #define STRCASECMP(a, b) (stricmp(a, b)) #else #include @@ -58,7 +37,7 @@ #if _MSC_VER < 1900 #define snprintf _snprintf #endif -#elif defined(WIN32) || defined(_WIN32) +#elif defined(_WIN32) #ifndef snprintf #define snprintf _snprintf #endif @@ -68,8 +47,6 @@ #define CPLsnprintf snprintf #endif -SHP_CVSID("$Id$") - #ifndef FALSE #define FALSE 0 #define TRUE 1 @@ -91,33 +68,6 @@ CPL_INLINE static void CPL_IGNORE_RET_VAL_INT(CPL_UNUSED int unused) #define CPL_IGNORE_RET_VAL_INT(x) x #endif -#ifdef __cplusplus -#define STATIC_CAST(type, x) static_cast(x) -#define REINTERPRET_CAST(type, x) reinterpret_cast(x) -#define CONST_CAST(type, x) const_cast(x) -#define SHPLIB_NULLPTR nullptr -#else -#define STATIC_CAST(type, x) ((type)(x)) -#define REINTERPRET_CAST(type, x) ((type)(x)) -#define CONST_CAST(type, x) ((type)(x)) -#define SHPLIB_NULLPTR NULL -#endif - -/************************************************************************/ -/* SfRealloc() */ -/* */ -/* A realloc cover function that will access a NULL pointer as */ -/* a valid input. */ -/************************************************************************/ - -static void *SfRealloc(void *pMem, int nNewSize) -{ - if (pMem == SHPLIB_NULLPTR) - return malloc(nNewSize); - else - return realloc(pMem, nNewSize); -} - /************************************************************************/ /* DBFWriteHeader() */ /* */ @@ -137,9 +87,9 @@ static void DBFWriteHeader(DBFHandle psDBF) psDBF->bNoHeader = FALSE; /* -------------------------------------------------------------------- */ - /* Initialize the file header information. */ + /* Initialize the file header information. */ /* -------------------------------------------------------------------- */ - abyHeader[0] = 0x03; /* memo field? - just copying */ + abyHeader[0] = 0x03; /* memo field? - just copying */ /* write out update date */ abyHeader[1] = STATIC_CAST(unsigned char, psDBF->nUpdateYearSince1900); @@ -158,7 +108,7 @@ static void DBFWriteHeader(DBFHandle psDBF) /* -------------------------------------------------------------------- */ /* Write the initial 32 byte file header, and all the field */ - /* descriptions. */ + /* descriptions. */ /* -------------------------------------------------------------------- */ psDBF->sHooks.FSeek(psDBF->fp, 0, 0); psDBF->sHooks.FWrite(abyHeader, XBASE_FILEHDR_SZ, 1, psDBF->fp); @@ -344,7 +294,6 @@ void SHPAPI_CALL DBFSetLastModifiedDate(DBFHandle psDBF, int nYYSince1900, /************************************************************************/ DBFHandle SHPAPI_CALL DBFOpen(const char *pszFilename, const char *pszAccess) - { SAHooks sHooks; @@ -376,7 +325,7 @@ static int DBFGetLenWithoutExtension(const char *pszBasename) /************************************************************************/ DBFHandle SHPAPI_CALL DBFOpenLL(const char *pszFilename, const char *pszAccess, - SAHooks *psHooks) + const SAHooks *psHooks) { /* -------------------------------------------------------------------- */ /* We only allow the access strings "rb" and "r+". */ @@ -393,8 +342,8 @@ DBFHandle SHPAPI_CALL DBFOpenLL(const char *pszFilename, const char *pszAccess, pszAccess = "rb+"; /* -------------------------------------------------------------------- */ - /* Compute the base (layer) name. If there is any extension */ - /* on the passed in filename we will strip it off. */ + /* Compute the base (layer) name. If there is any extension */ + /* on the passed in filename we will strip it off. */ /* -------------------------------------------------------------------- */ const int nLenWithoutExtension = DBFGetLenWithoutExtension(pszFilename); char *pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5)); @@ -402,19 +351,20 @@ DBFHandle SHPAPI_CALL DBFOpenLL(const char *pszFilename, const char *pszAccess, memcpy(pszFullname + nLenWithoutExtension, ".dbf", 5); DBFHandle psDBF = STATIC_CAST(DBFHandle, calloc(1, sizeof(DBFInfo))); - psDBF->fp = psHooks->FOpen(pszFullname, pszAccess); + psDBF->fp = psHooks->FOpen(pszFullname, pszAccess, psHooks->pvUserData); memcpy(&(psDBF->sHooks), psHooks, sizeof(SAHooks)); if (psDBF->fp == SHPLIB_NULLPTR) { memcpy(pszFullname + nLenWithoutExtension, ".DBF", 5); - psDBF->fp = psDBF->sHooks.FOpen(pszFullname, pszAccess); + psDBF->fp = + psDBF->sHooks.FOpen(pszFullname, pszAccess, psHooks->pvUserData); } memcpy(pszFullname + nLenWithoutExtension, ".cpg", 5); - SAFile pfCPG = psHooks->FOpen(pszFullname, "r"); + SAFile pfCPG = psHooks->FOpen(pszFullname, "r", psHooks->pvUserData); if (pfCPG == SHPLIB_NULLPTR) { memcpy(pszFullname + nLenWithoutExtension, ".CPG", 5); - pfCPG = psHooks->FOpen(pszFullname, "r"); + pfCPG = psHooks->FOpen(pszFullname, "r", psHooks->pvUserData); } free(pszFullname); @@ -495,7 +445,7 @@ DBFHandle SHPAPI_CALL DBFOpenLL(const char *pszFilename, const char *pszAccess, /* -------------------------------------------------------------------- */ /* Read in Field Definitions */ /* -------------------------------------------------------------------- */ - pabyBuf = STATIC_CAST(unsigned char *, SfRealloc(pabyBuf, nHeadLen)); + pabyBuf = STATIC_CAST(unsigned char *, realloc(pabyBuf, nHeadLen)); psDBF->pszHeader = REINTERPRET_CAST(char *, pabyBuf); psDBF->sHooks.FSeek(psDBF->fp, XBASE_FILEHDR_SZ, 0); @@ -583,8 +533,8 @@ void SHPAPI_CALL DBFClose(DBFHandle psDBF) CPL_IGNORE_RET_VAL_INT(DBFFlushRecord(psDBF)); /* -------------------------------------------------------------------- */ - /* Update last access date, and number of records if we have */ - /* write access. */ + /* Update last access date, and number of records if we have */ + /* write access. */ /* -------------------------------------------------------------------- */ if (psDBF->bUpdated) DBFUpdateHeader(psDBF); @@ -645,11 +595,12 @@ DBFHandle SHPAPI_CALL DBFCreateEx(const char *pszFilename, /************************************************************************/ DBFHandle SHPAPI_CALL DBFCreateLL(const char *pszFilename, - const char *pszCodePage, SAHooks *psHooks) + const char *pszCodePage, + const SAHooks *psHooks) { /* -------------------------------------------------------------------- */ - /* Compute the base (layer) name. If there is any extension */ - /* on the passed in filename we will strip it off. */ + /* Compute the base (layer) name. If there is any extension */ + /* on the passed in filename we will strip it off. */ /* -------------------------------------------------------------------- */ const int nLenWithoutExtension = DBFGetLenWithoutExtension(pszFilename); char *pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5)); @@ -659,17 +610,7 @@ DBFHandle SHPAPI_CALL DBFCreateLL(const char *pszFilename, /* -------------------------------------------------------------------- */ /* Create the file. */ /* -------------------------------------------------------------------- */ - SAFile fp = psHooks->FOpen(pszFullname, "wb"); - if (fp == SHPLIB_NULLPTR) { - free(pszFullname); - return SHPLIB_NULLPTR; - } - - char chZero = '\0'; - psHooks->FWrite(&chZero, 1, 1, fp); - psHooks->FClose(fp); - - fp = psHooks->FOpen(pszFullname, "rb+"); + SAFile fp = psHooks->FOpen(pszFullname, "wb+", psHooks->pvUserData); if (fp == SHPLIB_NULLPTR) { free(pszFullname); return SHPLIB_NULLPTR; @@ -685,7 +626,8 @@ DBFHandle SHPAPI_CALL DBFCreateLL(const char *pszFilename, // a valid one } if (ldid < 0) { - SAFile fpCPG = psHooks->FOpen(pszFullname, "w"); + SAFile fpCPG = + psHooks->FOpen(pszFullname, "w", psHooks->pvUserData); psHooks->FWrite( CONST_CAST(void *, STATIC_CAST(const void *, pszCodePage)), strlen(pszCodePage), 1, fpCPG); @@ -693,13 +635,13 @@ DBFHandle SHPAPI_CALL DBFCreateLL(const char *pszFilename, } } if (pszCodePage == SHPLIB_NULLPTR || ldid >= 0) { - psHooks->Remove(pszFullname); + psHooks->Remove(pszFullname, psHooks->pvUserData); } free(pszFullname); /* -------------------------------------------------------------------- */ - /* Create the info structure. */ + /* Create the info structure. */ /* -------------------------------------------------------------------- */ DBFHandle psDBF = STATIC_CAST(DBFHandle, calloc(1, sizeof(DBFInfo))); @@ -829,23 +771,22 @@ int SHPAPI_CALL DBFAddNativeFieldType(DBFHandle psDBF, const char *pszFieldName, const int nOldHeaderLength = psDBF->nHeaderLength; /* -------------------------------------------------------------------- */ - /* SfRealloc all the arrays larger to hold the additional field */ + /* realloc all the arrays larger to hold the additional field */ /* information. */ /* -------------------------------------------------------------------- */ psDBF->nFields++; psDBF->panFieldOffset = STATIC_CAST( - int *, SfRealloc(psDBF->panFieldOffset, sizeof(int) * psDBF->nFields)); + int *, realloc(psDBF->panFieldOffset, sizeof(int) * psDBF->nFields)); psDBF->panFieldSize = STATIC_CAST( - int *, SfRealloc(psDBF->panFieldSize, sizeof(int) * psDBF->nFields)); + int *, realloc(psDBF->panFieldSize, sizeof(int) * psDBF->nFields)); - psDBF->panFieldDecimals = - STATIC_CAST(int *, SfRealloc(psDBF->panFieldDecimals, - sizeof(int) * psDBF->nFields)); + psDBF->panFieldDecimals = STATIC_CAST( + int *, realloc(psDBF->panFieldDecimals, sizeof(int) * psDBF->nFields)); psDBF->pachFieldType = STATIC_CAST( - char *, SfRealloc(psDBF->pachFieldType, sizeof(char) * psDBF->nFields)); + char *, realloc(psDBF->pachFieldType, sizeof(char) * psDBF->nFields)); /* -------------------------------------------------------------------- */ /* Assign the new field information fields. */ @@ -863,7 +804,7 @@ int SHPAPI_CALL DBFAddNativeFieldType(DBFHandle psDBF, const char *pszFieldName, psDBF->bUpdated = FALSE; psDBF->pszHeader = STATIC_CAST( - char *, SfRealloc(psDBF->pszHeader, psDBF->nFields * XBASE_FLDHDR_SZ)); + char *, realloc(psDBF->pszHeader, psDBF->nFields * XBASE_FLDHDR_SZ)); char *pszFInfo = psDBF->pszHeader + XBASE_FLDHDR_SZ * (psDBF->nFields - 1); @@ -887,7 +828,7 @@ int SHPAPI_CALL DBFAddNativeFieldType(DBFHandle psDBF, const char *pszFieldName, /* Make the current record buffer appropriately larger. */ /* -------------------------------------------------------------------- */ psDBF->pszCurrentRecord = STATIC_CAST( - char *, SfRealloc(psDBF->pszCurrentRecord, psDBF->nRecordLength)); + char *, realloc(psDBF->pszCurrentRecord, psDBF->nRecordLength)); /* we're done if dealing with new .dbf */ if (psDBF->bNoHeader) @@ -971,13 +912,13 @@ static void *DBFReadAttribute(DBFHandle psDBF, int hEntity, int iField, return SHPLIB_NULLPTR; /* -------------------------------------------------------------------- */ - /* Have we read the record? */ + /* Have we read the record? */ /* -------------------------------------------------------------------- */ if (!DBFLoadRecord(psDBF, hEntity)) return SHPLIB_NULLPTR; - unsigned char *pabyRec = - REINTERPRET_CAST(unsigned char *, psDBF->pszCurrentRecord); + const unsigned char *pabyRec = + REINTERPRET_CAST(const unsigned char *, psDBF->pszCurrentRecord); /* -------------------------------------------------------------------- */ /* Ensure we have room to extract the target field. */ @@ -993,7 +934,7 @@ static void *DBFReadAttribute(DBFHandle psDBF, int hEntity, int iField, } /* -------------------------------------------------------------------- */ - /* Extract the requested field. */ + /* Extract the requested field. */ /* -------------------------------------------------------------------- */ memcpy(psDBF->pszWorkField, REINTERPRET_CAST(const char *, pabyRec) + @@ -1085,7 +1026,6 @@ double SHPAPI_CALL DBFReadDoubleAttribute(DBFHandle psDBF, int iRecord, const char SHPAPI_CALL1(*) DBFReadStringAttribute(DBFHandle psDBF, int iRecord, int iField) - { return STATIC_CAST(const char *, DBFReadAttribute(psDBF, iRecord, iField, 'C')); @@ -1099,12 +1039,40 @@ const char SHPAPI_CALL1(*) const char SHPAPI_CALL1(*) DBFReadLogicalAttribute(DBFHandle psDBF, int iRecord, int iField) - { return STATIC_CAST(const char *, DBFReadAttribute(psDBF, iRecord, iField, 'L')); } +/************************************************************************/ +/* DBFReadDateAttribute() */ +/* */ +/* Read a date attribute. */ +/************************************************************************/ + +SHPDate SHPAPI_CALL DBFReadDateAttribute(DBFHandle psDBF, int iRecord, + int iField) +{ + const char *pdateValue = STATIC_CAST( + const char *, DBFReadAttribute(psDBF, iRecord, iField, 'D')); + + SHPDate date; + + if (pdateValue == SHPLIB_NULLPTR) { + date.year = 0; + date.month = 0; + date.day = 0; + } + else if (3 != sscanf(pdateValue, "%4d%2d%2d", &date.year, &date.month, + &date.day)) { + date.year = 0; + date.month = 0; + date.day = 0; + } + + return date; +} + /************************************************************************/ /* DBFIsValueNULL() */ /* */ @@ -1135,7 +1103,16 @@ static bool DBFIsValueNULL(char chType, const char *pszValue) case 'D': /* NULL date fields have value "00000000" */ - return strncmp(pszValue, "00000000", 8) == 0; + /* Some DBF files have fields filled with spaces */ + /* (trimmed by DBFReadStringAttribute) to indicate null */ + /* values for dates (#4265). */ + /* And others have ' 0': + * https://lists.osgeo.org/pipermail/gdal-dev/2023-November/058010.html + */ + /* And others just empty string: + * https://github.com/OSGeo/gdal/issues/10405 */ + return pszValue[0] == 0 || strncmp(pszValue, "00000000", 8) == 0 || + strcmp(pszValue, " ") == 0 || strcmp(pszValue, "0") == 0; case 'L': /* NULL boolean fields have value "?" */ @@ -1155,7 +1132,8 @@ static bool DBFIsValueNULL(char chType, const char *pszValue) /* Contributed by Jim Matthews. */ /************************************************************************/ -int SHPAPI_CALL DBFIsAttributeNULL(DBFHandle psDBF, int iRecord, int iField) +int SHPAPI_CALL DBFIsAttributeNULL(const DBFHandle psDBF, int iRecord, + int iField) { const char *pszValue = DBFReadStringAttribute(psDBF, iRecord, iField); @@ -1171,8 +1149,7 @@ int SHPAPI_CALL DBFIsAttributeNULL(DBFHandle psDBF, int iRecord, int iField) /* Return the number of fields in this table. */ /************************************************************************/ -int SHPAPI_CALL DBFGetFieldCount(DBFHandle psDBF) - +int SHPAPI_CALL DBFGetFieldCount(const DBFHandle psDBF) { return (psDBF->nFields); } @@ -1183,8 +1160,7 @@ int SHPAPI_CALL DBFGetFieldCount(DBFHandle psDBF) /* Return the number of records in this table. */ /************************************************************************/ -int SHPAPI_CALL DBFGetRecordCount(DBFHandle psDBF) - +int SHPAPI_CALL DBFGetRecordCount(const DBFHandle psDBF) { return (psDBF->nRecords); } @@ -1197,10 +1173,9 @@ int SHPAPI_CALL DBFGetRecordCount(DBFHandle psDBF) /* bytes long. */ /************************************************************************/ -DBFFieldType SHPAPI_CALL DBFGetFieldInfo(DBFHandle psDBF, int iField, +DBFFieldType SHPAPI_CALL DBFGetFieldInfo(const DBFHandle psDBF, int iField, char *pszFieldName, int *pnWidth, int *pnDecimals) - { if (iField < 0 || iField >= psDBF->nFields) return (FTInvalid); @@ -1230,10 +1205,9 @@ DBFFieldType SHPAPI_CALL DBFGetFieldInfo(DBFHandle psDBF, int iField, else if (psDBF->pachFieldType[iField] == 'N' || psDBF->pachFieldType[iField] == 'F') { - if (psDBF->panFieldDecimals[iField] > 0) { - /* || psDBF->panFieldSize[iField] >= 10 ) */ /* GDAL bug #809 */ + if (psDBF->panFieldDecimals[iField] > 0 || + psDBF->panFieldSize[iField] >= 10) return (FTDouble); - } else return (FTInteger); } @@ -1244,15 +1218,15 @@ DBFFieldType SHPAPI_CALL DBFGetFieldInfo(DBFHandle psDBF, int iField, /************************************************************************/ /* DBFWriteAttribute() */ -/* */ -/* Write an attribute record to the file. */ +/* */ +/* Write an attribute record to the file. */ /************************************************************************/ static bool DBFWriteAttribute(DBFHandle psDBF, int hEntity, int iField, void *pValue) { /* -------------------------------------------------------------------- */ - /* Is this a valid record? */ + /* Is this a valid record? */ /* -------------------------------------------------------------------- */ if (hEntity < 0 || hEntity > psDBF->nRecords) return false; @@ -1333,9 +1307,13 @@ static bool DBFWriteAttribute(DBFHandle psDBF, int hEntity, int iField, case 'L': if (psDBF->panFieldSize[iField] >= 1 && (*STATIC_CAST(char *, pValue) == 'F' || - *STATIC_CAST(char *, pValue) == 'T')) + *STATIC_CAST(char *, pValue) == 'T')) { *(pabyRec + psDBF->panFieldOffset[iField]) = *STATIC_CAST(char *, pValue); + } + else { + nRetResult = false; + } break; default: { @@ -1370,10 +1348,10 @@ static bool DBFWriteAttribute(DBFHandle psDBF, int hEntity, int iField, /************************************************************************/ int SHPAPI_CALL DBFWriteAttributeDirectly(DBFHandle psDBF, int hEntity, - int iField, void *pValue) + int iField, const void *pValue) { /* -------------------------------------------------------------------- */ - /* Is this a valid record? */ + /* Is this a valid record? */ /* -------------------------------------------------------------------- */ if (hEntity < 0 || hEntity > psDBF->nRecords) return (FALSE); @@ -1402,24 +1380,29 @@ int SHPAPI_CALL DBFWriteAttributeDirectly(DBFHandle psDBF, int hEntity, if (!DBFLoadRecord(psDBF, hEntity)) return FALSE; - unsigned char *pabyRec = - REINTERPRET_CAST(unsigned char *, psDBF->pszCurrentRecord); + if (iField >= 0) { + unsigned char *pabyRec = + REINTERPRET_CAST(unsigned char *, psDBF->pszCurrentRecord); - /* -------------------------------------------------------------------- */ - /* Assign all the record fields. */ - /* -------------------------------------------------------------------- */ - int j; - if (STATIC_CAST(int, strlen(STATIC_CAST(char *, pValue))) > - psDBF->panFieldSize[iField]) - j = psDBF->panFieldSize[iField]; - else { - memset(pabyRec + psDBF->panFieldOffset[iField], ' ', - psDBF->panFieldSize[iField]); - j = STATIC_CAST(int, strlen(STATIC_CAST(char *, pValue))); - } + /* -------------------------------------------------------------------- + */ + /* Assign all the record fields. */ + /* -------------------------------------------------------------------- + */ + int j; + if (STATIC_CAST(int, strlen(STATIC_CAST(const char *, pValue))) > + psDBF->panFieldSize[iField]) + j = psDBF->panFieldSize[iField]; + else { + memset(pabyRec + psDBF->panFieldOffset[iField], ' ', + psDBF->panFieldSize[iField]); + j = STATIC_CAST(int, strlen(STATIC_CAST(const char *, pValue))); + } - strncpy(REINTERPRET_CAST(char *, pabyRec + psDBF->panFieldOffset[iField]), + memcpy( + REINTERPRET_CAST(char *, pabyRec + psDBF->panFieldOffset[iField]), STATIC_CAST(const char *, pValue), j); + } psDBF->bCurrentRecordModified = TRUE; psDBF->bUpdated = TRUE; @@ -1443,7 +1426,7 @@ int SHPAPI_CALL DBFWriteDoubleAttribute(DBFHandle psDBF, int iRecord, /************************************************************************/ /* DBFWriteIntegerAttribute() */ /* */ -/* Write a integer attribute. */ +/* Write an integer attribute. */ /************************************************************************/ int SHPAPI_CALL DBFWriteIntegerAttribute(DBFHandle psDBF, int iRecord, @@ -1463,7 +1446,6 @@ int SHPAPI_CALL DBFWriteIntegerAttribute(DBFHandle psDBF, int iRecord, int SHPAPI_CALL DBFWriteStringAttribute(DBFHandle psDBF, int iRecord, int iField, const char *pszValue) - { return ( DBFWriteAttribute(psDBF, iRecord, iField, @@ -1473,11 +1455,10 @@ int SHPAPI_CALL DBFWriteStringAttribute(DBFHandle psDBF, int iRecord, /************************************************************************/ /* DBFWriteNULLAttribute() */ /* */ -/* Write a string attribute. */ +/* Write a NULL attribute. */ /************************************************************************/ int SHPAPI_CALL DBFWriteNULLAttribute(DBFHandle psDBF, int iRecord, int iField) - { return (DBFWriteAttribute(psDBF, iRecord, iField, SHPLIB_NULLPTR)); } @@ -1490,23 +1471,47 @@ int SHPAPI_CALL DBFWriteNULLAttribute(DBFHandle psDBF, int iRecord, int iField) int SHPAPI_CALL DBFWriteLogicalAttribute(DBFHandle psDBF, int iRecord, int iField, const char lValue) - { return ( DBFWriteAttribute(psDBF, iRecord, iField, STATIC_CAST(void *, CONST_CAST(char *, &lValue)))); } +/************************************************************************/ +/* DBFWriteDateAttribute() */ +/* */ +/* Write a date attribute. */ +/************************************************************************/ + +int SHPAPI_CALL DBFWriteDateAttribute(DBFHandle psDBF, int iRecord, int iField, + const SHPDate *lValue) +{ + if (SHPLIB_NULLPTR == lValue) + return false; + /* check for supported digit range, but do not check for valid date */ + if (lValue->year < 0 || lValue->year > 9999) + return false; + if (lValue->month < 0 || lValue->month > 99) + return false; + if (lValue->day < 0 || lValue->day > 99) + return false; + char dateValue[9]; /* "yyyyMMdd\0" */ + snprintf(dateValue, sizeof(dateValue), "%04d%02d%02d", lValue->year, + lValue->month, lValue->day); + return (DBFWriteAttributeDirectly(psDBF, iRecord, iField, dateValue)); +} + /************************************************************************/ /* DBFWriteTuple() */ -/* */ -/* Write an attribute record to the file. */ +/* */ +/* Write an attribute record to the file. */ /************************************************************************/ -int SHPAPI_CALL DBFWriteTuple(DBFHandle psDBF, int hEntity, void *pRawTuple) +int SHPAPI_CALL DBFWriteTuple(DBFHandle psDBF, int hEntity, + const void *pRawTuple) { /* -------------------------------------------------------------------- */ - /* Is this a valid record? */ + /* Is this a valid record? */ /* -------------------------------------------------------------------- */ if (hEntity < 0 || hEntity > psDBF->nRecords) return (FALSE); @@ -1554,7 +1559,6 @@ int SHPAPI_CALL DBFWriteTuple(DBFHandle psDBF, int hEntity, void *pRawTuple) /************************************************************************/ const char SHPAPI_CALL1(*) DBFReadTuple(DBFHandle psDBF, int hEntity) - { if (hEntity < 0 || hEntity >= psDBF->nRecords) return SHPLIB_NULLPTR; @@ -1566,14 +1570,17 @@ const char SHPAPI_CALL1(*) DBFReadTuple(DBFHandle psDBF, int hEntity) } /************************************************************************/ -/* DBFCloneEmpty() */ +/* DBFCloneEmpty() */ /* */ -/* Read one of the attribute fields of a record. */ +/* Create a new .dbf file with same code page and field */ +/* definitions as the given handle. */ /************************************************************************/ -DBFHandle SHPAPI_CALL DBFCloneEmpty(DBFHandle psDBF, const char *pszFilename) +DBFHandle SHPAPI_CALL DBFCloneEmpty(const DBFHandle psDBF, + const char *pszFilename) { - DBFHandle newDBF = DBFCreateEx(pszFilename, psDBF->pszCodePage); + DBFHandle newDBF = + DBFCreateLL(pszFilename, psDBF->pszCodePage, &psDBF->sHooks); if (newDBF == SHPLIB_NULLPTR) return SHPLIB_NULLPTR; @@ -1629,8 +1636,7 @@ DBFHandle SHPAPI_CALL DBFCloneEmpty(DBFHandle psDBF, const char *pszFilename) /* 'M' (Memo: 10 digits .DBT block ptr) */ /************************************************************************/ -char SHPAPI_CALL DBFGetNativeFieldType(DBFHandle psDBF, int iField) - +char SHPAPI_CALL DBFGetNativeFieldType(const DBFHandle psDBF, int iField) { if (iField >= 0 && iField < psDBF->nFields) return psDBF->pachFieldType[iField]; @@ -1646,7 +1652,8 @@ char SHPAPI_CALL DBFGetNativeFieldType(DBFHandle psDBF, int iField) /* Contributed by Jim Matthews. */ /************************************************************************/ -int SHPAPI_CALL DBFGetFieldIndex(DBFHandle psDBF, const char *pszFieldName) +int SHPAPI_CALL DBFGetFieldIndex(const DBFHandle psDBF, + const char *pszFieldName) { char name[XBASE_FLDNAME_LEN_READ + 1]; @@ -1665,7 +1672,7 @@ int SHPAPI_CALL DBFGetFieldIndex(DBFHandle psDBF, const char *pszFieldName) /* it returns FALSE. */ /************************************************************************/ -int SHPAPI_CALL DBFIsRecordDeleted(DBFHandle psDBF, int iShape) +int SHPAPI_CALL DBFIsRecordDeleted(const DBFHandle psDBF, int iShape) { /* -------------------------------------------------------------------- */ /* Verify selection. */ @@ -1674,7 +1681,7 @@ int SHPAPI_CALL DBFIsRecordDeleted(DBFHandle psDBF, int iShape) return TRUE; /* -------------------------------------------------------------------- */ - /* Have we read the record? */ + /* Have we read the record? */ /* -------------------------------------------------------------------- */ if (!DBFLoadRecord(psDBF, iShape)) return FALSE; @@ -1727,7 +1734,7 @@ int SHPAPI_CALL DBFMarkRecordDeleted(DBFHandle psDBF, int iShape, /* DBFGetCodePage */ /************************************************************************/ -const char SHPAPI_CALL1(*) DBFGetCodePage(DBFHandle psDBF) +const char SHPAPI_CALL1(*) DBFGetCodePage(const DBFHandle psDBF) { if (psDBF == SHPLIB_NULLPTR) return SHPLIB_NULLPTR; @@ -1768,17 +1775,16 @@ int SHPAPI_CALL DBFDeleteField(DBFHandle psDBF, int iField) psDBF->nFields--; psDBF->panFieldOffset = STATIC_CAST( - int *, SfRealloc(psDBF->panFieldOffset, sizeof(int) * psDBF->nFields)); + int *, realloc(psDBF->panFieldOffset, sizeof(int) * psDBF->nFields)); psDBF->panFieldSize = STATIC_CAST( - int *, SfRealloc(psDBF->panFieldSize, sizeof(int) * psDBF->nFields)); + int *, realloc(psDBF->panFieldSize, sizeof(int) * psDBF->nFields)); - psDBF->panFieldDecimals = - STATIC_CAST(int *, SfRealloc(psDBF->panFieldDecimals, - sizeof(int) * psDBF->nFields)); + psDBF->panFieldDecimals = STATIC_CAST( + int *, realloc(psDBF->panFieldDecimals, sizeof(int) * psDBF->nFields)); psDBF->pachFieldType = STATIC_CAST( - char *, SfRealloc(psDBF->pachFieldType, sizeof(char) * psDBF->nFields)); + char *, realloc(psDBF->pachFieldType, sizeof(char) * psDBF->nFields)); /* update header information */ psDBF->nHeaderLength -= XBASE_FLDHDR_SZ; @@ -1790,11 +1796,11 @@ int SHPAPI_CALL DBFDeleteField(DBFHandle psDBF, int iField) sizeof(char) * (psDBF->nFields - iField) * XBASE_FLDHDR_SZ); psDBF->pszHeader = STATIC_CAST( - char *, SfRealloc(psDBF->pszHeader, psDBF->nFields * XBASE_FLDHDR_SZ)); + char *, realloc(psDBF->pszHeader, psDBF->nFields * XBASE_FLDHDR_SZ)); /* update size of current record appropriately */ psDBF->pszCurrentRecord = STATIC_CAST( - char *, SfRealloc(psDBF->pszCurrentRecord, psDBF->nRecordLength)); + char *, realloc(psDBF->pszCurrentRecord, psDBF->nRecordLength)); /* we're done if we're dealing with not yet created .dbf */ if (psDBF->bNoHeader && psDBF->nRecords == 0) @@ -1866,7 +1872,7 @@ int SHPAPI_CALL DBFDeleteField(DBFHandle psDBF, int iField) /* code of DBFReorderFields. */ /************************************************************************/ -int SHPAPI_CALL DBFReorderFields(DBFHandle psDBF, int *panMap) +int SHPAPI_CALL DBFReorderFields(DBFHandle psDBF, const int *panMap) { if (psDBF->nFields == 0) return TRUE; @@ -1878,13 +1884,13 @@ int SHPAPI_CALL DBFReorderFields(DBFHandle psDBF, int *panMap) /* a simple malloc() would be enough, but calloc() helps clang static * analyzer */ int *panFieldOffsetNew = - STATIC_CAST(int *, calloc(sizeof(int), psDBF->nFields)); + STATIC_CAST(int *, calloc(psDBF->nFields, sizeof(int))); int *panFieldSizeNew = - STATIC_CAST(int *, calloc(sizeof(int), psDBF->nFields)); + STATIC_CAST(int *, calloc(psDBF->nFields, sizeof(int))); int *panFieldDecimalsNew = - STATIC_CAST(int *, calloc(sizeof(int), psDBF->nFields)); + STATIC_CAST(int *, calloc(psDBF->nFields, sizeof(int))); char *pachFieldTypeNew = - STATIC_CAST(char *, calloc(sizeof(char), psDBF->nFields)); + STATIC_CAST(char *, calloc(psDBF->nFields, sizeof(char))); char *pszHeaderNew = STATIC_CAST( char *, malloc(sizeof(char) * XBASE_FLDHDR_SZ * psDBF->nFields)); @@ -2050,7 +2056,7 @@ int SHPAPI_CALL DBFAlterFieldDefn(DBFHandle psDBF, int iField, psDBF->nRecordLength += nWidth - nOldWidth; psDBF->pszCurrentRecord = STATIC_CAST( - char *, SfRealloc(psDBF->pszCurrentRecord, psDBF->nRecordLength)); + char *, realloc(psDBF->pszCurrentRecord, psDBF->nRecordLength)); } /* we're done if we're dealing with not yet created .dbf */ @@ -2069,7 +2075,6 @@ int SHPAPI_CALL DBFAlterFieldDefn(DBFHandle psDBF, int iField, char *pszOldField = STATIC_CAST(char *, malloc(sizeof(char) * (nOldWidth + 1))); - /* cppcheck-suppress uninitdata */ pszOldField[nOldWidth] = 0; /* move records to their new positions */ @@ -2139,7 +2144,6 @@ int SHPAPI_CALL DBFAlterFieldDefn(DBFHandle psDBF, int iField, char *pszOldField = STATIC_CAST(char *, malloc(sizeof(char) * (nOldWidth + 1))); - /* cppcheck-suppress uninitdata */ pszOldField[nOldWidth] = 0; /* move records to their new positions */ diff --git a/lib/external/shapelib/safileio.c b/lib/external/shapelib/safileio.c index 3377642e4d4..e13f1f29acf 100644 --- a/lib/external/shapelib/safileio.c +++ b/lib/external/shapelib/safileio.c @@ -1,5 +1,4 @@ /****************************************************************************** - * $Id: safileio.c,v 1.6 2018-06-15 19:56:32 erouault Exp $ * * Project: Shapelib * Purpose: Default implementation of file io based on stdio. @@ -8,74 +7,19 @@ ****************************************************************************** * Copyright (c) 2007, Frank Warmerdam * - * This software is available under the following "MIT Style" license, - * or at the option of the licensee under the LGPL (see COPYING). This - * option is discussed in more detail in shapelib.html. - * - * -- - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * SPDX-License-Identifier: MIT OR LGPL-2.0-or-later ****************************************************************************** * - * $Log: safileio.c,v $ - * Revision 1.6 2018-06-15 19:56:32 erouault - * * safileio.c: remove duplicate test. Patch by Jaroslav Fojtik. - * Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2744 - * - * Revision 1.5 2016-12-05 12:44:05 erouault - * * Major overhaul of Makefile build system to use autoconf/automake. - * - * * Warning fixes in contrib/ - * - * Revision 1.4 2008-01-16 20:05:14 bram - * Add file hooks that accept UTF-8 encoded filenames on some platforms. Use - *SASetupUtf8Hooks tosetup the hooks and check SHPAPI_UTF8_HOOKS for its - *availability. Currently, this is only available on the Windows platform that - *decodes the UTF-8 filenames to wide character strings and feeds them to - *_wfopen and _wremove. - * - * Revision 1.3 2007/12/18 18:28:11 bram - * - create hook for client specific atof (bugzilla ticket 1615) - * - check for NULL handle before closing cpCPG file, and close after reading. - * - * Revision 1.2 2007/12/15 20:25:30 bram - * dbfopen.c now reads the Code Page information from the DBF file, and exports - * this information as a string through the DBFGetCodePage function. This is - * either the number from the LDID header field ("LDID/") or as the - * content of an accompanying .CPG file. When creating a DBF file, the code can - * be set using DBFCreateEx. - * - * Revision 1.1 2007/12/06 06:56:41 fwarmerdam - * new - * */ #include "shapefil.h" +#include #include #include -#include +#include #include #include -#include - -SHP_CVSID("$Id: safileio.c,v 1.6 2018-06-15 19:56:32 erouault Exp $") #ifdef SHPAPI_UTF8_HOOKS #ifdef SHPAPI_WINDOWS @@ -86,102 +30,64 @@ SHP_CVSID("$Id: safileio.c,v 1.6 2018-06-15 19:56:32 erouault Exp $") #endif #endif -/************************************************************************/ -/* SADFOpen() */ -/************************************************************************/ - -SAFile SADFOpen(const char *pszFilename, const char *pszAccess) - +static SAFile SADFOpen(const char *pszFilename, const char *pszAccess, + void *pvUserData) { + (void)pvUserData; return (SAFile)fopen(pszFilename, pszAccess); } -/************************************************************************/ -/* SADFRead() */ -/************************************************************************/ - -SAOffset SADFRead(void *p, SAOffset size, SAOffset nmemb, SAFile file) - +static SAOffset SADFRead(void *p, SAOffset size, SAOffset nmemb, SAFile file) { return (SAOffset)fread(p, (size_t)size, (size_t)nmemb, (FILE *)file); } -/************************************************************************/ -/* SADFWrite() */ -/************************************************************************/ - -SAOffset SADFWrite(void *p, SAOffset size, SAOffset nmemb, SAFile file) - +static SAOffset SADFWrite(const void *p, SAOffset size, SAOffset nmemb, + SAFile file) { return (SAOffset)fwrite(p, (size_t)size, (size_t)nmemb, (FILE *)file); } -/************************************************************************/ -/* SADFSeek() */ -/************************************************************************/ - -SAOffset SADFSeek(SAFile file, SAOffset offset, int whence) - +static SAOffset SADFSeek(SAFile file, SAOffset offset, int whence) { +#if defined(_MSC_VER) && _MSC_VER >= 1400 + return (SAOffset)_fseeki64((FILE *)file, (__int64)offset, whence); +#else return (SAOffset)fseek((FILE *)file, (long)offset, whence); +#endif } -/************************************************************************/ -/* SADFTell() */ -/************************************************************************/ - -SAOffset SADFTell(SAFile file) - +static SAOffset SADFTell(SAFile file) { +#if defined(_MSC_VER) && _MSC_VER >= 1400 + return (SAOffset)_ftelli64((FILE *)file); +#else return (SAOffset)ftell((FILE *)file); +#endif } -/************************************************************************/ -/* SADFFlush() */ -/************************************************************************/ - -int SADFFlush(SAFile file) - +static int SADFFlush(SAFile file) { return fflush((FILE *)file); } -/************************************************************************/ -/* SADFClose() */ -/************************************************************************/ - -int SADFClose(SAFile file) - +static int SADFClose(SAFile file) { return fclose((FILE *)file); } -/************************************************************************/ -/* SADFClose() */ -/************************************************************************/ - -int SADRemove(const char *filename) - +static int SADRemove(const char *filename, void *pvUserData) { + (void)pvUserData; return remove(filename); } -/************************************************************************/ -/* SADError() */ -/************************************************************************/ - -void SADError(const char *message) - +static void SADError(const char *message) { fprintf(stderr, "%s\n", message); } -/************************************************************************/ -/* SASetupDefaultHooks() */ -/************************************************************************/ - void SASetupDefaultHooks(SAHooks *psHooks) - { psHooks->FOpen = SADFOpen; psHooks->FRead = SADFRead; @@ -194,25 +100,20 @@ void SASetupDefaultHooks(SAHooks *psHooks) psHooks->Error = SADError; psHooks->Atof = atof; + psHooks->pvUserData = NULL; } #ifdef SHPAPI_WINDOWS -/************************************************************************/ -/* Utf8ToWideChar */ -/************************************************************************/ - -const wchar_t *Utf8ToWideChar(const char *pszFilename) +static wchar_t *Utf8ToWideChar(const char *pszFilename) { - int nMulti, nWide; - wchar_t *pwszFileName; - - nMulti = strlen(pszFilename) + 1; - nWide = MultiByteToWideChar(CP_UTF8, 0, pszFilename, nMulti, 0, 0); + const int nMulti = (int)strlen(pszFilename) + 1; + const int nWide = + MultiByteToWideChar(CP_UTF8, 0, pszFilename, nMulti, 0, 0); if (nWide == 0) { return NULL; } - pwszFileName = (wchar_t *)malloc(nWide * sizeof(wchar_t)); + wchar_t *pwszFileName = (wchar_t *)malloc(nWide * sizeof(wchar_t)); if (pwszFileName == NULL) { return NULL; } @@ -228,51 +129,44 @@ const wchar_t *Utf8ToWideChar(const char *pszFilename) /* SAUtf8WFOpen */ /************************************************************************/ -SAFile SAUtf8WFOpen(const char *pszFilename, const char *pszAccess) +static SAFile SAUtf8WFOpen(const char *pszFilename, const char *pszAccess, + void *pvUserData) { + (void)pvUserData; SAFile file = NULL; - const wchar_t *pwszFileName, *pwszAccess; - pwszFileName = Utf8ToWideChar(pszFilename); - pwszAccess = Utf8ToWideChar(pszAccess); + wchar_t *pwszFileName = Utf8ToWideChar(pszFilename); + wchar_t *pwszAccess = Utf8ToWideChar(pszAccess); if (pwszFileName != NULL && pwszAccess != NULL) { file = (SAFile)_wfopen(pwszFileName, pwszAccess); } - free((wchar_t *)pwszFileName); - free((wchar_t *)pwszAccess); + free(pwszFileName); + free(pwszAccess); return file; } -/************************************************************************/ -/* SAUtf8WRemove() */ -/************************************************************************/ - -int SAUtf8WRemove(const char *pszFilename) +static int SAUtf8WRemove(const char *pszFilename, void *pvUserData) { - const wchar_t *pwszFileName = Utf8ToWideChar(pszFilename); + (void)pvUserData; + wchar_t *pwszFileName = Utf8ToWideChar(pszFilename); int rc = -1; if (pwszFileName != NULL) { rc = _wremove(pwszFileName); } - free((wchar_t *)pwszFileName); + free(pwszFileName); return rc; } #endif #ifdef SHPAPI_UTF8_HOOKS - -/************************************************************************/ -/* SASetupUtf8Hooks() */ -/************************************************************************/ +#ifndef SHPAPI_WINDOWS +#error "no implementations of UTF-8 hooks available for this platform" +#endif void SASetupUtf8Hooks(SAHooks *psHooks) { -#ifdef SHPAPI_WINDOWS psHooks->FOpen = SAUtf8WFOpen; psHooks->Remove = SAUtf8WRemove; -#else -#error "no implementations of UTF-8 hooks available for this platform" -#endif psHooks->FRead = SADFRead; psHooks->FWrite = SADFWrite; psHooks->FSeek = SADFSeek; @@ -283,5 +177,4 @@ void SASetupUtf8Hooks(SAHooks *psHooks) psHooks->Error = SADError; psHooks->Atof = atof; } - #endif diff --git a/lib/external/shapelib/shapefil.h b/lib/external/shapelib/shapefil.h index cd4ef54aa56..c11632fa6ba 100644 --- a/lib/external/shapelib/shapefil.h +++ b/lib/external/shapelib/shapefil.h @@ -2,7 +2,6 @@ #define SHAPEFILE_H_INCLUDED /****************************************************************************** - * $Id$ * * Project: Shapelib * Purpose: Primary include file for Shapelib. @@ -12,29 +11,7 @@ * Copyright (c) 1999, Frank Warmerdam * Copyright (c) 2012-2016, Even Rouault * - * This software is available under the following "MIT Style" license, - * or at the option of the licensee under the LGPL (see COPYING). This - * option is discussed in more detail in shapelib.html. - * - * -- - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * SPDX-License-Identifier: MIT OR LGPL-2.0-or-later ****************************************************************************** * */ @@ -49,6 +26,26 @@ extern "C" { #endif +/************************************************************************/ +/* Version related macros (added in 1.6.0) */ +/************************************************************************/ + +#define SHAPELIB_VERSION_MAJOR 1 +#define SHAPELIB_VERSION_MINOR 6 +#define SHAPELIB_VERSION_MICRO 0 + +#define SHAPELIB_MAKE_VERSION_NUMBER(major, minor, micro) \ + ((major) * 10000 + (minor) * 100 + (micro)) + +#define SHAPELIB_VERSION_NUMBER \ + SHAPELIB_MAKE_VERSION_NUMBER(SHAPELIB_VERSION_MAJOR, \ + SHAPELIB_VERSION_MINOR, \ + SHAPELIB_VERSION_MICRO) + +#define SHAPELIB_AT_LEAST(major, minor, micro) \ + (SHAPELIB_VERSION_NUMBER >= \ + SHAPELIB_MAKE_VERSION_NUMBER(major, minor, micro)) + /************************************************************************/ /* Configuration options. */ /************************************************************************/ @@ -73,7 +70,7 @@ extern "C" { /* various calling conventions on the Shapelib API. */ /* */ /* To force __stdcall conventions (needed to call Shapelib */ -/* from Visual Basic and/or Dephi I believe) the makefile could */ +/* from Visual Basic and/or Delphi I believe) the makefile could */ /* be modified to define: */ /* */ /* /DSHPAPI_CALL=__stdcall */ @@ -113,31 +110,11 @@ extern "C" { #define SHPAPI_CALL1(x) x SHPAPI_CALL #endif -/* -------------------------------------------------------------------- */ -/* Macros for controlling CVSID and ensuring they don't appear */ -/* as unreferenced variables resulting in lots of warnings. */ -/* -------------------------------------------------------------------- */ -#ifndef DISABLE_CVSID -#if defined(__GNUC__) && __GNUC__ >= 4 -#define SHP_CVSID(string) \ - static const char cpl_cvsid[] __attribute__((used)) = string; -#else -#define SHP_CVSID(string) \ - static const char cpl_cvsid[] = string; \ - static const char *cvsid_aw() \ - { \ - return (cvsid_aw() ? NULL : cpl_cvsid); \ - } -#endif -#else -#define SHP_CVSID(string) -#endif - /* -------------------------------------------------------------------- */ /* On some platforms, additional file IO hooks are defined that */ /* UTF-8 encoded filenames Unicode filenames */ /* -------------------------------------------------------------------- */ -#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +#if defined(_WIN32) #define SHPAPI_WINDOWS #define SHPAPI_UTF8_HOOKS #endif @@ -148,21 +125,27 @@ extern "C" { typedef int *SAFile; #ifndef SAOffset +#if defined(_MSC_VER) && _MSC_VER >= 1400 +typedef unsigned __int64 SAOffset; +#else typedef unsigned long SAOffset; #endif +#endif typedef struct { - SAFile (*FOpen)(const char *filename, const char *access); + SAFile (*FOpen)(const char *filename, const char *access, void *pvUserData); SAOffset (*FRead)(void *p, SAOffset size, SAOffset nmemb, SAFile file); - SAOffset (*FWrite)(void *p, SAOffset size, SAOffset nmemb, SAFile file); + SAOffset (*FWrite)(const void *p, SAOffset size, SAOffset nmemb, + SAFile file); SAOffset (*FSeek)(SAFile file, SAOffset offset, int whence); SAOffset (*FTell)(SAFile file); int (*FFlush)(SAFile file); int (*FClose)(SAFile file); - int (*Remove)(const char *filename); + int (*Remove)(const char *filename, void *pvUserData); void (*Error)(const char *message); double (*Atof)(const char *str); + void *pvUserData; } SAHooks; void SHPAPI_CALL SASetupDefaultHooks(SAHooks *psHooks); @@ -206,6 +189,12 @@ typedef struct { typedef SHPInfo *SHPHandle; +typedef struct { + int year; + int month; + int day; +} SHPDate; + /* -------------------------------------------------------------------- */ /* Shape types (nSHPType) */ /* -------------------------------------------------------------------- */ @@ -277,13 +266,13 @@ struct tagSHPObject { /* will be NULL as it is not necessary to keep the SHX file open */ SHPHandle SHPAPI_CALL SHPOpen(const char *pszShapeFile, const char *pszAccess); SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszShapeFile, const char *pszAccess, - SAHooks *psHooks); + const SAHooks *psHooks); SHPHandle SHPAPI_CALL SHPOpenLLEx(const char *pszShapeFile, - const char *pszAccess, SAHooks *psHooks, + const char *pszAccess, const SAHooks *psHooks, int bRestoreSHX); int SHPAPI_CALL SHPRestoreSHX(const char *pszShapeFile, const char *pszAccess, - SAHooks *psHooks); + const SAHooks *psHooks); /* If setting bFastMode = TRUE, the content of SHPReadObject() is owned by the * SHPHandle. */ @@ -296,12 +285,14 @@ void SHPAPI_CALL SHPSetFastModeReadObject(SHPHandle hSHP, int bFastMode); SHPHandle SHPAPI_CALL SHPCreate(const char *pszShapeFile, int nShapeType); SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszShapeFile, int nShapeType, - SAHooks *psHooks); -void SHPAPI_CALL SHPGetInfo(SHPHandle hSHP, int *pnEntities, int *pnShapeType, - double *padfMinBound, double *padfMaxBound); + const SAHooks *psHooks); +void SHPAPI_CALL SHPGetInfo(const SHPHandle hSHP, int *pnEntities, + int *pnShapeType, double *padfMinBound, + double *padfMaxBound); -SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle hSHP, int iShape); -int SHPAPI_CALL SHPWriteObject(SHPHandle hSHP, int iShape, SHPObject *psObject); +SHPObject SHPAPI_CALL1(*) SHPReadObject(const SHPHandle hSHP, int iShape); +int SHPAPI_CALL SHPWriteObject(SHPHandle hSHP, int iShape, + const SHPObject *psObject); void SHPAPI_CALL SHPDestroyObject(SHPObject *psObject); void SHPAPI_CALL SHPComputeExtents(SHPObject *psObject); @@ -314,7 +305,7 @@ SHPObject SHPAPI_CALL1(*) SHPCreateSimpleObject(int nSHPType, int nVertices, const double *padfX, const double *padfY, const double *padfZ); -int SHPAPI_CALL SHPRewindObject(SHPHandle hSHP, SHPObject *psObject); +int SHPAPI_CALL SHPRewindObject(const SHPHandle hSHP, SHPObject *psObject); void SHPAPI_CALL SHPClose(SHPHandle hSHP); void SHPAPI_CALL SHPWriteHeader(SHPHandle hSHP); @@ -360,21 +351,20 @@ typedef struct { SHPTree SHPAPI_CALL1(*) SHPCreateTree(SHPHandle hSHP, int nDimension, int nMaxDepth, - double *padfBoundsMin, double *padfBoundsMax); + const double *padfBoundsMin, const double *padfBoundsMax); void SHPAPI_CALL SHPDestroyTree(SHPTree *hTree); int SHPAPI_CALL SHPWriteTree(SHPTree *hTree, const char *pszFilename); int SHPAPI_CALL SHPTreeAddShapeId(SHPTree *hTree, SHPObject *psObject); -int SHPAPI_CALL SHPTreeRemoveShapeId(SHPTree *hTree, int nShapeId); void SHPAPI_CALL SHPTreeTrimExtraNodes(SHPTree *hTree); int SHPAPI_CALL1(*) - SHPTreeFindLikelyShapes(SHPTree *hTree, double *padfBoundsMin, + SHPTreeFindLikelyShapes(const SHPTree *hTree, double *padfBoundsMin, double *padfBoundsMax, int *); -int SHPAPI_CALL SHPCheckBoundsOverlap(double *, double *, double *, double *, - int); +int SHPAPI_CALL SHPCheckBoundsOverlap(const double *, const double *, + const double *, const double *, int); int SHPAPI_CALL1(*) SHPSearchDiskTree(FILE *fp, double *padfBoundsMin, double *padfBoundsMax, int *pnShapeCount); @@ -382,16 +372,17 @@ int SHPAPI_CALL1(*) SHPSearchDiskTree(FILE *fp, double *padfBoundsMin, typedef struct SHPDiskTreeInfo *SHPTreeDiskHandle; SHPTreeDiskHandle SHPAPI_CALL SHPOpenDiskTree(const char *pszQIXFilename, - SAHooks *psHooks); + const SAHooks *psHooks); void SHPAPI_CALL SHPCloseDiskTree(SHPTreeDiskHandle hDiskTree); int SHPAPI_CALL1(*) - SHPSearchDiskTreeEx(SHPTreeDiskHandle hDiskTree, double *padfBoundsMin, - double *padfBoundsMax, int *pnShapeCount); + SHPSearchDiskTreeEx(const SHPTreeDiskHandle hDiskTree, + double *padfBoundsMin, double *padfBoundsMax, + int *pnShapeCount); int SHPAPI_CALL SHPWriteTreeLL(SHPTree *hTree, const char *pszFilename, - SAHooks *psHooks); + const SAHooks *psHooks); /* -------------------------------------------------------------------- */ /* SBN Search API */ @@ -400,16 +391,16 @@ int SHPAPI_CALL SHPWriteTreeLL(SHPTree *hTree, const char *pszFilename, typedef struct SBNSearchInfo *SBNSearchHandle; SBNSearchHandle SHPAPI_CALL SBNOpenDiskTree(const char *pszSBNFilename, - SAHooks *psHooks); + const SAHooks *psHooks); void SHPAPI_CALL SBNCloseDiskTree(SBNSearchHandle hSBN); int SHPAPI_CALL1(*) - SBNSearchDiskTree(SBNSearchHandle hSBN, double *padfBoundsMin, - double *padfBoundsMax, int *pnShapeCount); + SBNSearchDiskTree(const SBNSearchHandle hSBN, const double *padfBoundsMin, + const double *padfBoundsMax, int *pnShapeCount); int SHPAPI_CALL1(*) - SBNSearchDiskTreeInteger(SBNSearchHandle hSBN, int bMinX, int bMinY, + SBNSearchDiskTreeInteger(const SBNSearchHandle hSBN, int bMinX, int bMinY, int bMaxX, int bMaxY, int *pnShapeCount); void SHPAPI_CALL SBNSearchFreeIds(int *panShapeId); @@ -485,15 +476,16 @@ typedef enum { DBFHandle SHPAPI_CALL DBFOpen(const char *pszDBFFile, const char *pszAccess); DBFHandle SHPAPI_CALL DBFOpenLL(const char *pszDBFFile, const char *pszAccess, - SAHooks *psHooks); + const SAHooks *psHooks); DBFHandle SHPAPI_CALL DBFCreate(const char *pszDBFFile); DBFHandle SHPAPI_CALL DBFCreateEx(const char *pszDBFFile, const char *pszCodePage); DBFHandle SHPAPI_CALL DBFCreateLL(const char *pszDBFFile, - const char *pszCodePage, SAHooks *psHooks); + const char *pszCodePage, + const SAHooks *psHooks); -int SHPAPI_CALL DBFGetFieldCount(DBFHandle psDBF); -int SHPAPI_CALL DBFGetRecordCount(DBFHandle psDBF); +int SHPAPI_CALL DBFGetFieldCount(const DBFHandle psDBF); +int SHPAPI_CALL DBFGetRecordCount(const DBFHandle psDBF); int SHPAPI_CALL DBFAddField(DBFHandle hDBF, const char *pszFieldName, DBFFieldType eType, int nWidth, int nDecimals); @@ -502,17 +494,18 @@ int SHPAPI_CALL DBFAddNativeFieldType(DBFHandle hDBF, const char *pszFieldName, int SHPAPI_CALL DBFDeleteField(DBFHandle hDBF, int iField); -int SHPAPI_CALL DBFReorderFields(DBFHandle psDBF, int *panMap); +int SHPAPI_CALL DBFReorderFields(DBFHandle psDBF, const int *panMap); int SHPAPI_CALL DBFAlterFieldDefn(DBFHandle psDBF, int iField, const char *pszFieldName, char chType, int nWidth, int nDecimals); -DBFFieldType SHPAPI_CALL DBFGetFieldInfo(DBFHandle psDBF, int iField, +DBFFieldType SHPAPI_CALL DBFGetFieldInfo(const DBFHandle psDBF, int iField, char *pszFieldName, int *pnWidth, int *pnDecimals); -int SHPAPI_CALL DBFGetFieldIndex(DBFHandle psDBF, const char *pszFieldName); +int SHPAPI_CALL DBFGetFieldIndex(const DBFHandle psDBF, + const char *pszFieldName); int SHPAPI_CALL DBFReadIntegerAttribute(DBFHandle hDBF, int iShape, int iField); double SHPAPI_CALL DBFReadDoubleAttribute(DBFHandle hDBF, int iShape, @@ -521,7 +514,10 @@ const char SHPAPI_CALL1(*) DBFReadStringAttribute(DBFHandle hDBF, int iShape, int iField); const char SHPAPI_CALL1(*) DBFReadLogicalAttribute(DBFHandle hDBF, int iShape, int iField); -int SHPAPI_CALL DBFIsAttributeNULL(DBFHandle hDBF, int iShape, int iField); +SHPDate SHPAPI_CALL DBFReadDateAttribute(DBFHandle hDBF, int iShape, + int iField); +int SHPAPI_CALL DBFIsAttributeNULL(const DBFHandle hDBF, int iShape, + int iField); int SHPAPI_CALL DBFWriteIntegerAttribute(DBFHandle hDBF, int iShape, int iField, int nFieldValue); @@ -533,22 +529,26 @@ int SHPAPI_CALL DBFWriteNULLAttribute(DBFHandle hDBF, int iShape, int iField); int SHPAPI_CALL DBFWriteLogicalAttribute(DBFHandle hDBF, int iShape, int iField, const char lFieldValue); +int SHPAPI_CALL DBFWriteDateAttribute(DBFHandle hDBF, int iShape, int iField, + const SHPDate *dateFieldValue); int SHPAPI_CALL DBFWriteAttributeDirectly(DBFHandle psDBF, int hEntity, - int iField, void *pValue); + int iField, const void *pValue); const char SHPAPI_CALL1(*) DBFReadTuple(DBFHandle psDBF, int hEntity); -int SHPAPI_CALL DBFWriteTuple(DBFHandle psDBF, int hEntity, void *pRawTuple); +int SHPAPI_CALL DBFWriteTuple(DBFHandle psDBF, int hEntity, + const void *pRawTuple); -int SHPAPI_CALL DBFIsRecordDeleted(DBFHandle psDBF, int iShape); +int SHPAPI_CALL DBFIsRecordDeleted(const DBFHandle psDBF, int iShape); int SHPAPI_CALL DBFMarkRecordDeleted(DBFHandle psDBF, int iShape, int bIsDeleted); -DBFHandle SHPAPI_CALL DBFCloneEmpty(DBFHandle psDBF, const char *pszFilename); +DBFHandle SHPAPI_CALL DBFCloneEmpty(const DBFHandle psDBF, + const char *pszFilename); void SHPAPI_CALL DBFClose(DBFHandle hDBF); void SHPAPI_CALL DBFUpdateHeader(DBFHandle hDBF); -char SHPAPI_CALL DBFGetNativeFieldType(DBFHandle hDBF, int iField); +char SHPAPI_CALL DBFGetNativeFieldType(const DBFHandle hDBF, int iField); -const char SHPAPI_CALL1(*) DBFGetCodePage(DBFHandle psDBF); +const char SHPAPI_CALL1(*) DBFGetCodePage(const DBFHandle psDBF); void SHPAPI_CALL DBFSetLastModifiedDate(DBFHandle psDBF, int nYYSince1900, int nMM, int nDD); diff --git a/lib/external/shapelib/shapefil_private.h b/lib/external/shapelib/shapefil_private.h new file mode 100644 index 00000000000..1bed49e7cce --- /dev/null +++ b/lib/external/shapelib/shapefil_private.h @@ -0,0 +1,115 @@ +#ifndef SHAPEFILE_PRIVATE_H_INCLUDED +#define SHAPEFILE_PRIVATE_H_INCLUDED + +/****************************************************************************** + * + * Project: Shapelib + * Purpose: Private include file for Shapelib. + * Author: Frank Warmerdam, warmerdam@pobox.com + * + ****************************************************************************** + * Copyright (c) 1999, Frank Warmerdam + * Copyright (c) 2012-2016, Even Rouault + * + * SPDX-License-Identifier: MIT OR LGPL-2.0-or-later + ****************************************************************************** + * + */ + +#ifdef __cplusplus +#define STATIC_CAST(type, x) static_cast(x) +#define REINTERPRET_CAST(type, x) reinterpret_cast(x) +#define CONST_CAST(type, x) const_cast(x) +#define SHPLIB_NULLPTR nullptr +#else +#define STATIC_CAST(type, x) ((type)(x)) +#define REINTERPRET_CAST(type, x) ((type)(x)) +#define CONST_CAST(type, x) ((type)(x)) +#define SHPLIB_NULLPTR NULL +#endif + +#if !defined(SHP_BIG_ENDIAN) +#if defined(CPL_MSB) +#define SHP_BIG_ENDIAN 1 +#elif (defined(__GNUC__) && __GNUC__ >= 5) || \ + (defined(__GNUC__) && defined(__GNUC_MINOR__) && __GNUC__ == 4 && \ + __GNUC_MINOR__ >= 6) +#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define SHP_BIG_ENDIAN 1 +#endif +#elif defined(__GLIBC__) +#if __BYTE_ORDER == __BIG_ENDIAN +#define SHP_BIG_ENDIAN 1 +#endif +#elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN) +#define SHP_BIG_ENDIAN 1 +#elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN) +#elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || \ + defined(__powerpc__) || defined(__ppc__) || defined(__hpux) || \ + defined(_MIPSEB) || defined(_POWER) || defined(__s390__) +#define SHP_BIG_ENDIAN 1 +#endif +#endif + +#include "shapefil.h" +#include +#include + +/************************************************************************/ +/* Little endian <==> big endian byte swap macros. */ +/************************************************************************/ + +#if (defined(__GNUC__) && __GNUC__ >= 5) || \ + (defined(__GNUC__) && defined(__GNUC_MINOR__) && __GNUC__ == 4 && \ + __GNUC_MINOR__ >= 8) +#define _SHP_SWAP32(x) \ + STATIC_CAST(uint32_t, __builtin_bswap32(STATIC_CAST(uint32_t, x))) +#define _SHP_SWAP64(x) \ + STATIC_CAST(uint64_t, __builtin_bswap64(STATIC_CAST(uint64_t, x))) +#elif defined(_MSC_VER) +#define _SHP_SWAP32(x) \ + STATIC_CAST(uint32_t, _byteswap_ulong(STATIC_CAST(uint32_t, x))) +#define _SHP_SWAP64(x) \ + STATIC_CAST(uint64_t, _byteswap_uint64(STATIC_CAST(uint64_t, x))) +#else +#define _SHP_SWAP32(x) \ + STATIC_CAST(uint32_t, \ + ((STATIC_CAST(uint32_t, x) & 0x000000ffU) << 24) | \ + ((STATIC_CAST(uint32_t, x) & 0x0000ff00U) << 8) | \ + ((STATIC_CAST(uint32_t, x) & 0x00ff0000U) >> 8) | \ + ((STATIC_CAST(uint32_t, x) & 0xff000000U) >> 24)) +#define _SHP_SWAP64(x) \ + ((STATIC_CAST(uint64_t, _SHP_SWAP32(STATIC_CAST(uint32_t, x))) << 32) | \ + (STATIC_CAST(uint64_t, _SHP_SWAP32(STATIC_CAST( \ + uint32_t, STATIC_CAST(uint64_t, x) >> 32))))) + +#endif + +/* in-place uint32_t* swap */ +#define SHP_SWAP32(p) \ + *REINTERPRET_CAST(uint32_t *, p) = \ + _SHP_SWAP32(*REINTERPRET_CAST(uint32_t *, p)) +/* in-place uint64_t* swap */ +#define SHP_SWAP64(p) \ + *REINTERPRET_CAST(uint64_t *, p) = \ + _SHP_SWAP64(*REINTERPRET_CAST(uint64_t *, p)) +/* in-place double* swap */ +#define SHP_SWAPDOUBLE(x) \ + do { \ + uint64_t _n64; \ + void *_lx = x; \ + memcpy(&_n64, _lx, 8); \ + _n64 = _SHP_SWAP64(_n64); \ + memcpy(_lx, &_n64, 8); \ + } while (0) +/* copy double* swap*/ +#define SHP_SWAPDOUBLE_CPY(dst, src) \ + do { \ + uint64_t _n64; \ + const void *_ls = src; \ + void *_ld = dst; \ + memcpy(&_n64, _ls, 8); \ + _n64 = _SHP_SWAP64(_n64); \ + memcpy(_ld, &_n64, 8); \ + } while (0) +#endif /* ndef SHAPEFILE_PRIVATE_H_INCLUDED */ diff --git a/lib/external/shapelib/shpopen.c b/lib/external/shapelib/shpopen.c index e63cf768d25..b2eeb3614fb 100644 --- a/lib/external/shapelib/shpopen.c +++ b/lib/external/shapelib/shpopen.c @@ -8,52 +8,21 @@ * Copyright (c) 1999, 2001, Frank Warmerdam * Copyright (c) 2011-2019, Even Rouault * - * This software is available under the following "MIT Style" license, - * or at the option of the licensee under the LGPL (see COPYING). This - * option is discussed in more detail in shapelib.html. - * - * -- - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included - * in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. + * SPDX-License-Identifier: MIT OR LGPL-2.0-or-later ******************************************************************************/ -#include "shapefil.h" +#include "shapefil_private.h" #include #include #include #include #include +#include #include #include #include -SHP_CVSID("$Id$") - -typedef unsigned char uchar; - -#if UINT_MAX == 65535 -typedef unsigned long int32; -#else -typedef unsigned int int32; -#endif - #ifndef FALSE #define FALSE 0 #define TRUE 1 @@ -70,73 +39,18 @@ typedef unsigned int int32; #if _MSC_VER < 1900 #define snprintf _snprintf #endif -#elif defined(WIN32) || defined(_WIN32) +#elif defined(_WIN32) #ifndef snprintf #define snprintf _snprintf #endif #endif #endif -#ifndef CPL_UNUSED -#if defined(__GNUC__) && __GNUC__ >= 4 -#define CPL_UNUSED __attribute((__unused__)) -#else -#define CPL_UNUSED -#endif -#endif - -#if defined(CPL_LSB) -#define bBigEndian false -#elif defined(CPL_MSB) -#define bBigEndian true -#else -static bool bBigEndian; -#endif - -#ifdef __cplusplus -#define STATIC_CAST(type, x) static_cast(x) -#define SHPLIB_NULLPTR nullptr -#else -#define STATIC_CAST(type, x) ((type)(x)) -#define SHPLIB_NULLPTR NULL -#endif - -/************************************************************************/ -/* SwapWord() */ -/* */ -/* Swap a 2, 4 or 8 byte word. */ -/************************************************************************/ - -static void SwapWord(int length, void *wordP) -{ - for (int i = 0; i < length / 2; i++) { - const uchar temp = STATIC_CAST(uchar *, wordP)[i]; - STATIC_CAST(uchar *, wordP) - [i] = STATIC_CAST(uchar *, wordP)[length - i - 1]; - STATIC_CAST(uchar *, wordP)[length - i - 1] = temp; - } -} - -/************************************************************************/ -/* SfRealloc() */ -/* */ -/* A realloc cover function that will access a NULL pointer as */ -/* a valid input. */ -/************************************************************************/ - -static void *SfRealloc(void *pMem, int nNewSize) -{ - if (pMem == SHPLIB_NULLPTR) - return malloc(nNewSize); - else - return realloc(pMem, nNewSize); -} - /************************************************************************/ /* SHPWriteHeader() */ /* */ -/* Write out a header for the .shp and .shx files as well as the */ -/* contents of the index (.shx) file. */ +/* Write out a header for the .shp and .shx files as well as the */ +/* contents of the index (.shx) file. */ /************************************************************************/ void SHPAPI_CALL SHPWriteHeader(SHPHandle psSHP) @@ -150,64 +64,73 @@ void SHPAPI_CALL SHPWriteHeader(SHPHandle psSHP) /* Prepare header block for .shp file. */ /* -------------------------------------------------------------------- */ - uchar abyHeader[100] = {0}; + unsigned char abyHeader[100] = {0}; abyHeader[2] = 0x27; /* magic cookie */ abyHeader[3] = 0x0a; - int32 i32 = psSHP->nFileSize / 2; /* file size */ + uint32_t i32 = psSHP->nFileSize / 2; /* file size */ ByteCopy(&i32, abyHeader + 24, 4); - if (!bBigEndian) - SwapWord(4, abyHeader + 24); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(abyHeader + 24); +#endif i32 = 1000; /* version */ ByteCopy(&i32, abyHeader + 28, 4); - if (bBigEndian) - SwapWord(4, abyHeader + 28); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(abyHeader + 28); +#endif i32 = psSHP->nShapeType; /* shape type */ ByteCopy(&i32, abyHeader + 32, 4); - if (bBigEndian) - SwapWord(4, abyHeader + 32); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(abyHeader + 32); +#endif double dValue = psSHP->adBoundsMin[0]; /* set bounds */ ByteCopy(&dValue, abyHeader + 36, 8); - if (bBigEndian) - SwapWord(8, abyHeader + 36); - +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(abyHeader + 36); +#endif dValue = psSHP->adBoundsMin[1]; ByteCopy(&dValue, abyHeader + 44, 8); - if (bBigEndian) - SwapWord(8, abyHeader + 44); - +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(abyHeader + 44); +#endif dValue = psSHP->adBoundsMax[0]; ByteCopy(&dValue, abyHeader + 52, 8); - if (bBigEndian) - SwapWord(8, abyHeader + 52); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(abyHeader + 52); +#endif dValue = psSHP->adBoundsMax[1]; ByteCopy(&dValue, abyHeader + 60, 8); - if (bBigEndian) - SwapWord(8, abyHeader + 60); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(abyHeader + 60); +#endif dValue = psSHP->adBoundsMin[2]; /* z */ ByteCopy(&dValue, abyHeader + 68, 8); - if (bBigEndian) - SwapWord(8, abyHeader + 68); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(abyHeader + 68); +#endif dValue = psSHP->adBoundsMax[2]; ByteCopy(&dValue, abyHeader + 76, 8); - if (bBigEndian) - SwapWord(8, abyHeader + 76); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(abyHeader + 76); +#endif dValue = psSHP->adBoundsMin[3]; /* m */ ByteCopy(&dValue, abyHeader + 84, 8); - if (bBigEndian) - SwapWord(8, abyHeader + 84); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(abyHeader + 84); +#endif dValue = psSHP->adBoundsMax[3]; ByteCopy(&dValue, abyHeader + 92, 8); - if (bBigEndian) - SwapWord(8, abyHeader + 92); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(abyHeader + 92); +#endif /* -------------------------------------------------------------------- */ /* Write .shp file header. */ @@ -226,10 +149,11 @@ void SHPAPI_CALL SHPWriteHeader(SHPHandle psSHP) /* -------------------------------------------------------------------- */ /* Prepare, and write .shx file header. */ /* -------------------------------------------------------------------- */ - i32 = (psSHP->nRecords * 2 * sizeof(int32) + 100) / 2; /* file size */ + i32 = (psSHP->nRecords * 2 * sizeof(uint32_t) + 100) / 2; /* file size */ ByteCopy(&i32, abyHeader + 24, 4); - if (!bBigEndian) - SwapWord(4, abyHeader + 24); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(abyHeader + 24); +#endif if (psSHP->sHooks.FSeek(psSHP->fpSHX, 0, 0) != 0 || psSHP->sHooks.FWrite(abyHeader, 100, 1, psSHP->fpSHX) != 1) { @@ -246,8 +170,8 @@ void SHPAPI_CALL SHPWriteHeader(SHPHandle psSHP) /* -------------------------------------------------------------------- */ /* Write out the .shx contents. */ /* -------------------------------------------------------------------- */ - int32 *panSHX = - STATIC_CAST(int32 *, malloc(sizeof(int32) * 2 * psSHP->nRecords)); + uint32_t *panSHX = + STATIC_CAST(uint32_t *, malloc(sizeof(uint32_t) * 2 * psSHP->nRecords)); if (panSHX == SHPLIB_NULLPTR) { psSHP->sHooks.Error("Failure allocatin panSHX"); return; @@ -256,13 +180,13 @@ void SHPAPI_CALL SHPWriteHeader(SHPHandle psSHP) for (int i = 0; i < psSHP->nRecords; i++) { panSHX[i * 2] = psSHP->panRecOffset[i] / 2; panSHX[i * 2 + 1] = psSHP->panRecSize[i] / 2; - if (!bBigEndian) - SwapWord(4, panSHX + i * 2); - if (!bBigEndian) - SwapWord(4, panSHX + i * 2 + 1); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(panSHX + i * 2); + SHP_SWAP32(panSHX + i * 2 + 1); +#endif } - if (STATIC_CAST(int, psSHP->sHooks.FWrite(panSHX, sizeof(int32) * 2, + if (STATIC_CAST(int, psSHP->sHooks.FWrite(panSHX, sizeof(uint32_t) * 2, psSHP->nRecords, psSHP->fpSHX)) != psSHP->nRecords) { char szErrorMsg[200]; @@ -319,7 +243,7 @@ static int SHPGetLenWithoutExtension(const char *pszBasename) /************************************************************************/ SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszLayer, const char *pszAccess, - SAHooks *psHooks) + const SAHooks *psHooks) { /* -------------------------------------------------------------------- */ /* Ensure the access string is one of the legal ones. We */ @@ -336,23 +260,10 @@ SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszLayer, const char *pszAccess, pszAccess = "rb"; } -/* -------------------------------------------------------------------- */ -/* Establish the byte order on this machine. */ -/* -------------------------------------------------------------------- */ -#if !defined(bBigEndian) - { - int i = 1; - if (*((uchar *)&i) == 1) - bBigEndian = false; - else - bBigEndian = true; - } -#endif - /* -------------------------------------------------------------------- */ /* Initialize the info structure. */ /* -------------------------------------------------------------------- */ - SHPHandle psSHP = STATIC_CAST(SHPHandle, calloc(sizeof(SHPInfo), 1)); + SHPHandle psSHP = STATIC_CAST(SHPHandle, calloc(1, sizeof(SHPInfo))); psSHP->bUpdated = FALSE; memcpy(&(psSHP->sHooks), psHooks, sizeof(SAHooks)); @@ -365,18 +276,21 @@ SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszLayer, const char *pszAccess, char *pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5)); memcpy(pszFullname, pszLayer, nLenWithoutExtension); memcpy(pszFullname + nLenWithoutExtension, ".shp", 5); - psSHP->fpSHP = psSHP->sHooks.FOpen(pszFullname, pszAccess); + psSHP->fpSHP = + psSHP->sHooks.FOpen(pszFullname, pszAccess, psSHP->sHooks.pvUserData); if (psSHP->fpSHP == SHPLIB_NULLPTR) { memcpy(pszFullname + nLenWithoutExtension, ".SHP", 5); - psSHP->fpSHP = psSHP->sHooks.FOpen(pszFullname, pszAccess); + psSHP->fpSHP = psSHP->sHooks.FOpen(pszFullname, pszAccess, + psSHP->sHooks.pvUserData); } if (psSHP->fpSHP == SHPLIB_NULLPTR) { const size_t nMessageLen = strlen(pszFullname) * 2 + 256; char *pszMessage = STATIC_CAST(char *, malloc(nMessageLen)); pszFullname[nLenWithoutExtension] = 0; - snprintf(pszMessage, nMessageLen, "Unable to open %s.shp or %s.SHP.", - pszFullname, pszFullname); + snprintf(pszMessage, nMessageLen, + "Unable to open %s.shp or %s.SHP in %s mode.", pszFullname, + pszFullname, pszAccess); psHooks->Error(pszMessage); free(pszMessage); @@ -387,10 +301,12 @@ SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszLayer, const char *pszAccess, } memcpy(pszFullname + nLenWithoutExtension, ".shx", 5); - psSHP->fpSHX = psSHP->sHooks.FOpen(pszFullname, pszAccess); + psSHP->fpSHX = + psSHP->sHooks.FOpen(pszFullname, pszAccess, psSHP->sHooks.pvUserData); if (psSHP->fpSHX == SHPLIB_NULLPTR) { memcpy(pszFullname + nLenWithoutExtension, ".SHX", 5); - psSHP->fpSHX = psSHP->sHooks.FOpen(pszFullname, pszAccess); + psSHP->fpSHX = psSHP->sHooks.FOpen(pszFullname, pszAccess, + psSHP->sHooks.pvUserData); } if (psSHP->fpSHX == SHPLIB_NULLPTR) { @@ -416,7 +332,7 @@ SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszLayer, const char *pszAccess, /* -------------------------------------------------------------------- */ /* Read the file size from the SHP file. */ /* -------------------------------------------------------------------- */ - uchar *pabyBuf = STATIC_CAST(uchar *, malloc(100)); + unsigned char *pabyBuf = STATIC_CAST(unsigned char *, malloc(100)); if (psSHP->sHooks.FRead(pabyBuf, 100, 1, psSHP->fpSHP) != 1) { psSHP->sHooks.Error(".shp file is unreadable, or corrupt."); psSHP->sHooks.FClose(psSHP->fpSHP); @@ -489,43 +405,51 @@ SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszLayer, const char *pszAccess, /* -------------------------------------------------------------------- */ double dValue; - if (bBigEndian) - SwapWord(8, pabyBuf + 36); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyBuf + 36); +#endif memcpy(&dValue, pabyBuf + 36, 8); psSHP->adBoundsMin[0] = dValue; - if (bBigEndian) - SwapWord(8, pabyBuf + 44); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyBuf + 44); +#endif memcpy(&dValue, pabyBuf + 44, 8); psSHP->adBoundsMin[1] = dValue; - if (bBigEndian) - SwapWord(8, pabyBuf + 52); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyBuf + 52); +#endif memcpy(&dValue, pabyBuf + 52, 8); psSHP->adBoundsMax[0] = dValue; - if (bBigEndian) - SwapWord(8, pabyBuf + 60); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyBuf + 60); +#endif memcpy(&dValue, pabyBuf + 60, 8); psSHP->adBoundsMax[1] = dValue; - if (bBigEndian) - SwapWord(8, pabyBuf + 68); /* z */ +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyBuf + 68); /* z */ +#endif memcpy(&dValue, pabyBuf + 68, 8); psSHP->adBoundsMin[2] = dValue; - if (bBigEndian) - SwapWord(8, pabyBuf + 76); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyBuf + 76); +#endif memcpy(&dValue, pabyBuf + 76, 8); psSHP->adBoundsMax[2] = dValue; - if (bBigEndian) - SwapWord(8, pabyBuf + 84); /* z */ +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyBuf + 84); /* z */ +#endif memcpy(&dValue, pabyBuf + 84, 8); psSHP->adBoundsMin[3] = dValue; - if (bBigEndian) - SwapWord(8, pabyBuf + 92); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyBuf + 92); +#endif memcpy(&dValue, pabyBuf + 92, 8); psSHP->adBoundsMax[3] = dValue; @@ -546,7 +470,8 @@ SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszLayer, const char *pszAccess, if (bLazySHXLoading) pabyBuf = SHPLIB_NULLPTR; else - pabyBuf = STATIC_CAST(uchar *, malloc(8 * MAX(1, psSHP->nRecords))); + pabyBuf = + STATIC_CAST(unsigned char *, malloc(8 * MAX(1, psSHP->nRecords))); if (psSHP->panRecOffset == SHPLIB_NULLPTR || psSHP->panRecSize == SHPLIB_NULLPTR || @@ -612,13 +537,15 @@ SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszLayer, const char *pszAccess, for (int i = 0; i < psSHP->nRecords; i++) { unsigned int nOffset; memcpy(&nOffset, pabyBuf + i * 8, 4); - if (!bBigEndian) - SwapWord(4, &nOffset); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nOffset); +#endif unsigned int nLength; memcpy(&nLength, pabyBuf + i * 8 + 4, 4); - if (!bBigEndian) - SwapWord(4, &nLength); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nLength); +#endif if (nOffset > STATIC_CAST(unsigned int, INT_MAX)) { char str[128]; @@ -657,7 +584,7 @@ SHPHandle SHPAPI_CALL SHPOpenLL(const char *pszLayer, const char *pszAccess, /************************************************************************/ SHPHandle SHPAPI_CALL SHPOpenLLEx(const char *pszLayer, const char *pszAccess, - SAHooks *psHooks, int bRestoreSHX) + const SAHooks *psHooks, int bRestoreSHX) { if (!bRestoreSHX) return SHPOpenLL(pszLayer, pszAccess, psHooks); @@ -678,7 +605,7 @@ SHPHandle SHPAPI_CALL SHPOpenLLEx(const char *pszLayer, const char *pszAccess, /************************************************************************/ int SHPAPI_CALL SHPRestoreSHX(const char *pszLayer, const char *pszAccess, - SAHooks *psHooks) + const SAHooks *psHooks) { /* -------------------------------------------------------------------- */ /* Ensure the access string is one of the legal ones. We */ @@ -693,19 +620,6 @@ int SHPAPI_CALL SHPRestoreSHX(const char *pszLayer, const char *pszAccess, pszAccess = "rb"; } -/* -------------------------------------------------------------------- */ -/* Establish the byte order on this machine. */ -/* -------------------------------------------------------------------- */ -#if !defined(bBigEndian) - { - int i = 1; - if (*((uchar *)&i) == 1) - bBigEndian = false; - else - bBigEndian = true; - } -#endif - /* -------------------------------------------------------------------- */ /* Open the .shp file. Note that files pulled from */ /* a PC to Unix with upper case filenames won't work! */ @@ -714,10 +628,10 @@ int SHPAPI_CALL SHPRestoreSHX(const char *pszLayer, const char *pszAccess, char *pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5)); memcpy(pszFullname, pszLayer, nLenWithoutExtension); memcpy(pszFullname + nLenWithoutExtension, ".shp", 5); - SAFile fpSHP = psHooks->FOpen(pszFullname, pszAccess); + SAFile fpSHP = psHooks->FOpen(pszFullname, pszAccess, psHooks->pvUserData); if (fpSHP == SHPLIB_NULLPTR) { memcpy(pszFullname + nLenWithoutExtension, ".SHP", 5); - fpSHP = psHooks->FOpen(pszFullname, pszAccess); + fpSHP = psHooks->FOpen(pszFullname, pszAccess, psHooks->pvUserData); } if (fpSHP == SHPLIB_NULLPTR) { @@ -738,7 +652,7 @@ int SHPAPI_CALL SHPRestoreSHX(const char *pszLayer, const char *pszAccess, /* -------------------------------------------------------------------- */ /* Read the file size from the SHP file. */ /* -------------------------------------------------------------------- */ - uchar *pabyBuf = STATIC_CAST(uchar *, malloc(100)); + unsigned char *pabyBuf = STATIC_CAST(unsigned char *, malloc(100)); if (psHooks->FRead(pabyBuf, 100, 1, fpSHP) != 1) { psHooks->Error(".shp file is unreadable, or corrupt."); psHooks->FClose(fpSHP); @@ -759,7 +673,8 @@ int SHPAPI_CALL SHPRestoreSHX(const char *pszLayer, const char *pszAccess, memcpy(pszFullname + nLenWithoutExtension, ".shx", 5); const char pszSHXAccess[] = "w+b"; - SAFile fpSHX = psHooks->FOpen(pszFullname, pszSHXAccess); + SAFile fpSHX = + psHooks->FOpen(pszFullname, pszSHXAccess, psHooks->pvUserData); if (fpSHX == SHPLIB_NULLPTR) { size_t nMessageLen = strlen(pszFullname) * 2 + 256; char *pszMessage = STATIC_CAST(char *, malloc(nMessageLen)); @@ -789,25 +704,70 @@ int SHPAPI_CALL SHPRestoreSHX(const char *pszLayer, const char *pszAccess, // unsigned int nCurrentRecordOffset = 0; unsigned int nCurrentSHPOffset = 100; unsigned int nRealSHXContentSize = 100; - unsigned int niRecord = 0; - unsigned int nRecordLength = 0; + int nRetCode = TRUE; unsigned int nRecordOffset = 50; - char abyReadRecord[8]; while (nCurrentSHPOffset < nSHPFilesize) { + unsigned int niRecord = 0; + unsigned int nRecordLength = 0; + int nSHPType; + if (psHooks->FRead(&niRecord, 4, 1, fpSHP) == 1 && - psHooks->FRead(&nRecordLength, 4, 1, fpSHP) == 1) { - if (!bBigEndian) - SwapWord(4, &nRecordOffset); - memcpy(abyReadRecord, &nRecordOffset, 4); + psHooks->FRead(&nRecordLength, 4, 1, fpSHP) == 1 && + psHooks->FRead(&nSHPType, 4, 1, fpSHP) == 1) { + char abyReadRecord[8]; + unsigned int nRecordOffsetBE = nRecordOffset; + +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nRecordOffsetBE); +#endif + memcpy(abyReadRecord, &nRecordOffsetBE, 4); memcpy(abyReadRecord + 4, &nRecordLength, 4); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nRecordLength); +#endif +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nSHPType); +#endif + + // Sanity check on record length + if (nRecordLength < 1 || + nRecordLength > (nSHPFilesize - (nCurrentSHPOffset + 8)) / 2) { + char szErrorMsg[200]; + snprintf(szErrorMsg, sizeof(szErrorMsg), + "Error parsing .shp to restore .shx. " + "Invalid record length = %u at record starting at " + "offset %u", + nRecordLength, nCurrentSHPOffset); + psHooks->Error(szErrorMsg); + + nRetCode = FALSE; + break; + } + + // Sanity check on record type + if (nSHPType != SHPT_NULL && nSHPType != SHPT_POINT && + nSHPType != SHPT_ARC && nSHPType != SHPT_POLYGON && + nSHPType != SHPT_MULTIPOINT && nSHPType != SHPT_POINTZ && + nSHPType != SHPT_ARCZ && nSHPType != SHPT_POLYGONZ && + nSHPType != SHPT_MULTIPOINTZ && nSHPType != SHPT_POINTM && + nSHPType != SHPT_ARCM && nSHPType != SHPT_POLYGONM && + nSHPType != SHPT_MULTIPOINTM && nSHPType != SHPT_MULTIPATCH) { + char szErrorMsg[200]; + snprintf(szErrorMsg, sizeof(szErrorMsg), + "Error parsing .shp to restore .shx. " + "Invalid shape type = %d at record starting at " + "offset %u", + nSHPType, nCurrentSHPOffset); + psHooks->Error(szErrorMsg); + + nRetCode = FALSE; + break; + } + psHooks->FWrite(abyReadRecord, 8, 1, fpSHX); - if (!bBigEndian) - SwapWord(4, &nRecordOffset); - if (!bBigEndian) - SwapWord(4, &nRecordLength); nRecordOffset += nRecordLength + 4; // nCurrentRecordOffset += 8; nCurrentSHPOffset += 8 + nRecordLength * 2; @@ -816,21 +776,30 @@ int SHPAPI_CALL SHPRestoreSHX(const char *pszLayer, const char *pszAccess, nRealSHXContentSize += 8; } else { - psHooks->Error("Error parsing .shp to restore .shx"); - - psHooks->FClose(fpSHX); - psHooks->FClose(fpSHP); - - free(pabySHXHeader); - free(pszFullname); + char szErrorMsg[200]; + snprintf(szErrorMsg, sizeof(szErrorMsg), + "Error parsing .shp to restore .shx. " + "Cannot read first bytes of record starting at " + "offset %u", + nCurrentSHPOffset); + psHooks->Error(szErrorMsg); - return (0); + nRetCode = FALSE; + break; } } + if (nRetCode && nCurrentSHPOffset != nSHPFilesize) { + psHooks->Error("Error parsing .shp to restore .shx. " + "Not expected number of bytes"); + + nRetCode = FALSE; + } nRealSHXContentSize /= 2; // Bytes counted -> WORDs - if (!bBigEndian) - SwapWord(4, &nRealSHXContentSize); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nRealSHXContentSize); +#endif + psHooks->FSeek(fpSHX, 24, 0); psHooks->FWrite(&nRealSHXContentSize, 4, 1, fpSHX); @@ -840,13 +809,13 @@ int SHPAPI_CALL SHPRestoreSHX(const char *pszLayer, const char *pszAccess, free(pszFullname); free(pabySHXHeader); - return (1); + return nRetCode; } /************************************************************************/ /* SHPClose() */ -/* */ -/* Close the .shp and .shx files. */ +/* */ +/* Close the .shp and .shx files. */ /************************************************************************/ void SHPAPI_CALL SHPClose(SHPHandle psSHP) @@ -855,7 +824,7 @@ void SHPAPI_CALL SHPClose(SHPHandle psSHP) return; /* -------------------------------------------------------------------- */ - /* Update the header if we have modified anything. */ + /* Update the header if we have modified anything. */ /* -------------------------------------------------------------------- */ if (psSHP->bUpdated) SHPWriteHeader(psSHP); @@ -914,8 +883,9 @@ void SHPAPI_CALL SHPSetFastModeReadObject(SHPHandle hSHP, int bFastMode) /* Fetch general information about the shape file. */ /************************************************************************/ -void SHPAPI_CALL SHPGetInfo(SHPHandle psSHP, int *pnEntities, int *pnShapeType, - double *padfMinBound, double *padfMaxBound) +void SHPAPI_CALL SHPGetInfo(const SHPHandle psSHP, int *pnEntities, + int *pnShapeType, double *padfMinBound, + double *padfMaxBound) { if (psSHP == SHPLIB_NULLPTR) return; @@ -958,21 +928,8 @@ SHPHandle SHPAPI_CALL SHPCreate(const char *pszLayer, int nShapeType) /************************************************************************/ SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszLayer, int nShapeType, - SAHooks *psHooks) + const SAHooks *psHooks) { -/* -------------------------------------------------------------------- */ -/* Establish the byte order on this system. */ -/* -------------------------------------------------------------------- */ -#if !defined(bBigEndian) - { - int i = 1; - if (*((uchar *)&i) == 1) - bBigEndian = false; - else - bBigEndian = true; - } -#endif - /* -------------------------------------------------------------------- */ /* Open the two files so we can write their headers. */ /* -------------------------------------------------------------------- */ @@ -980,7 +937,7 @@ SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszLayer, int nShapeType, char *pszFullname = STATIC_CAST(char *, malloc(nLenWithoutExtension + 5)); memcpy(pszFullname, pszLayer, nLenWithoutExtension); memcpy(pszFullname + nLenWithoutExtension, ".shp", 5); - SAFile fpSHP = psHooks->FOpen(pszFullname, "wb"); + SAFile fpSHP = psHooks->FOpen(pszFullname, "w+b", psHooks->pvUserData); if (fpSHP == SHPLIB_NULLPTR) { char szErrorMsg[200]; snprintf(szErrorMsg, sizeof(szErrorMsg), "Failed to create file %s: %s", @@ -988,11 +945,11 @@ SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszLayer, int nShapeType, psHooks->Error(szErrorMsg); free(pszFullname); - return NULL; + return SHPLIB_NULLPTR; } memcpy(pszFullname + nLenWithoutExtension, ".shx", 5); - SAFile fpSHX = psHooks->FOpen(pszFullname, "wb"); + SAFile fpSHX = psHooks->FOpen(pszFullname, "w+b", psHooks->pvUserData); if (fpSHX == SHPLIB_NULLPTR) { char szErrorMsg[200]; snprintf(szErrorMsg, sizeof(szErrorMsg), "Failed to create file %s: %s", @@ -1001,7 +958,7 @@ SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszLayer, int nShapeType, free(pszFullname); psHooks->FClose(fpSHP); - return NULL; + return SHPLIB_NULLPTR; } free(pszFullname); @@ -1010,26 +967,29 @@ SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszLayer, int nShapeType, /* -------------------------------------------------------------------- */ /* Prepare header block for .shp file. */ /* -------------------------------------------------------------------- */ - uchar abyHeader[100]; + unsigned char abyHeader[100]; memset(abyHeader, 0, sizeof(abyHeader)); abyHeader[2] = 0x27; /* magic cookie */ abyHeader[3] = 0x0a; - int32 i32 = 50; /* file size */ + uint32_t i32 = 50; /* file size */ ByteCopy(&i32, abyHeader + 24, 4); - if (!bBigEndian) - SwapWord(4, abyHeader + 24); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(abyHeader + 24); +#endif i32 = 1000; /* version */ ByteCopy(&i32, abyHeader + 28, 4); - if (bBigEndian) - SwapWord(4, abyHeader + 28); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(abyHeader + 28); +#endif i32 = nShapeType; /* shape type */ ByteCopy(&i32, abyHeader + 32, 4); - if (bBigEndian) - SwapWord(4, abyHeader + 32); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(abyHeader + 32); +#endif double dValue = 0.0; /* set bounds */ ByteCopy(&dValue, abyHeader + 36, 8); @@ -1051,7 +1011,7 @@ SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszLayer, int nShapeType, free(pszFullname); psHooks->FClose(fpSHP); psHooks->FClose(fpSHX); - return NULL; + return SHPLIB_NULLPTR; } /* -------------------------------------------------------------------- */ @@ -1059,8 +1019,9 @@ SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszLayer, int nShapeType, /* -------------------------------------------------------------------- */ i32 = 50; /* file size */ ByteCopy(&i32, abyHeader + 24, 4); - if (!bBigEndian) - SwapWord(4, abyHeader + 24); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(abyHeader + 24); +#endif if (psHooks->FWrite(abyHeader, 100, 1, fpSHX) != 1) { char szErrorMsg[200]; @@ -1073,16 +1034,37 @@ SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszLayer, int nShapeType, free(pszFullname); psHooks->FClose(fpSHP); psHooks->FClose(fpSHX); - return NULL; + return SHPLIB_NULLPTR; } - /* -------------------------------------------------------------------- */ - /* Close the files, and then open them as regular existing files. */ - /* -------------------------------------------------------------------- */ - psHooks->FClose(fpSHP); - psHooks->FClose(fpSHX); + SHPHandle psSHP = STATIC_CAST(SHPHandle, calloc(1, sizeof(SHPInfo))); - return (SHPOpenLL(pszLayer, "r+b", psHooks)); + psSHP->bUpdated = FALSE; + memcpy(&(psSHP->sHooks), psHooks, sizeof(SAHooks)); + + psSHP->fpSHP = fpSHP; + psSHP->fpSHX = fpSHX; + psSHP->nShapeType = nShapeType; + psSHP->nFileSize = 100; + psSHP->panRecOffset = + STATIC_CAST(unsigned int *, malloc(sizeof(unsigned int))); + psSHP->panRecSize = + STATIC_CAST(unsigned int *, malloc(sizeof(unsigned int))); + + if (psSHP->panRecOffset == SHPLIB_NULLPTR || + psSHP->panRecSize == SHPLIB_NULLPTR) { + psSHP->sHooks.Error("Not enough memory to allocate requested memory"); + psSHP->sHooks.FClose(psSHP->fpSHP); + psSHP->sHooks.FClose(psSHP->fpSHX); + if (psSHP->panRecOffset) + free(psSHP->panRecOffset); + if (psSHP->panRecSize) + free(psSHP->panRecSize); + free(psSHP); + return SHPLIB_NULLPTR; + } + + return psSHP; } /************************************************************************/ @@ -1092,19 +1074,19 @@ SHPHandle SHPAPI_CALL SHPCreateLL(const char *pszLayer, int nShapeType, /* indicated location in the record. */ /************************************************************************/ -static void _SHPSetBounds(uchar *pabyRec, SHPObject *psShape) +static void _SHPSetBounds(unsigned char *pabyRec, const SHPObject *psShape) { ByteCopy(&(psShape->dfXMin), pabyRec + 0, 8); ByteCopy(&(psShape->dfYMin), pabyRec + 8, 8); ByteCopy(&(psShape->dfXMax), pabyRec + 16, 8); ByteCopy(&(psShape->dfYMax), pabyRec + 24, 8); - if (bBigEndian) { - SwapWord(8, pabyRec + 0); - SwapWord(8, pabyRec + 8); - SwapWord(8, pabyRec + 16); - SwapWord(8, pabyRec + 24); - } +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + 0); + SHP_SWAP64(pabyRec + 8); + SHP_SWAP64(pabyRec + 16); + SHP_SWAP64(pabyRec + 24); +#endif } /************************************************************************/ @@ -1159,7 +1141,7 @@ SHPObject SHPAPI_CALL1(*) psObject->bMeasureIsUsed = FALSE; /* -------------------------------------------------------------------- */ - /* Establish whether this shape type has M, and Z values. */ + /* Establish whether this shape type has M, and Z values. */ /* -------------------------------------------------------------------- */ bool bHasM; bool bHasZ; @@ -1191,7 +1173,7 @@ SHPObject SHPAPI_CALL1(*) psObject->nParts = MAX(1, nParts); psObject->panPartStart = - STATIC_CAST(int *, calloc(sizeof(int), psObject->nParts)); + STATIC_CAST(int *, calloc(psObject->nParts, sizeof(int))); psObject->panPartType = STATIC_CAST(int *, malloc(sizeof(int) * psObject->nParts)); @@ -1208,8 +1190,7 @@ SHPObject SHPAPI_CALL1(*) psObject->panPartType[i] = SHPP_RING; } - if (psObject->panPartStart[0] != 0) - psObject->panPartStart[0] = 0; + psObject->panPartStart[0] = 0; } /* -------------------------------------------------------------------- */ @@ -1219,16 +1200,16 @@ SHPObject SHPAPI_CALL1(*) const size_t nSize = sizeof(double) * nVertices; psObject->padfX = STATIC_CAST(double *, padfX ? malloc(nSize) - : calloc(sizeof(double), nVertices)); + : calloc(nVertices, sizeof(double))); psObject->padfY = STATIC_CAST(double *, padfY ? malloc(nSize) - : calloc(sizeof(double), nVertices)); + : calloc(nVertices, sizeof(double))); psObject->padfZ = STATIC_CAST( double *, - padfZ &&bHasZ ? malloc(nSize) : calloc(sizeof(double), nVertices)); + padfZ &&bHasZ ? malloc(nSize) : calloc(nVertices, sizeof(double))); psObject->padfM = STATIC_CAST( double *, - padfM &&bHasM ? malloc(nSize) : calloc(sizeof(double), nVertices)); + padfM &&bHasM ? malloc(nSize) : calloc(nVertices, sizeof(double))); if (padfX != SHPLIB_NULLPTR) memcpy(psObject->padfX, padfX, nSize); if (padfY != SHPLIB_NULLPTR) @@ -1273,7 +1254,7 @@ SHPObject SHPAPI_CALL1(*) /************************************************************************/ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, - SHPObject *psObject) + const SHPObject *psObject) { psSHP->bUpdated = TRUE; @@ -1298,22 +1279,32 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, /* Add the new entity to the in memory index. */ /* -------------------------------------------------------------------- */ if (nShapeId == -1 && psSHP->nRecords + 1 > psSHP->nMaxRecords) { + /* This cannot overflow given that we check that the file size does + * not grow over 4 GB, and the minimum size of a record is 12 bytes, + * hence the maximm value for nMaxRecords is 357,913,941 + */ int nNewMaxRecords = psSHP->nMaxRecords + psSHP->nMaxRecords / 3 + 100; unsigned int *panRecOffsetNew; unsigned int *panRecSizeNew; panRecOffsetNew = STATIC_CAST( - unsigned int *, SfRealloc(psSHP->panRecOffset, - sizeof(unsigned int) * nNewMaxRecords)); - if (panRecOffsetNew == SHPLIB_NULLPTR) + unsigned int *, realloc(psSHP->panRecOffset, + sizeof(unsigned int) * nNewMaxRecords)); + if (panRecOffsetNew == SHPLIB_NULLPTR) { + psSHP->sHooks.Error("Failed to write shape object. " + "Memory allocation error."); return -1; + } psSHP->panRecOffset = panRecOffsetNew; panRecSizeNew = STATIC_CAST( - unsigned int *, SfRealloc(psSHP->panRecSize, - sizeof(unsigned int) * nNewMaxRecords)); - if (panRecSizeNew == SHPLIB_NULLPTR) + unsigned int *, + realloc(psSHP->panRecSize, sizeof(unsigned int) * nNewMaxRecords)); + if (panRecSizeNew == SHPLIB_NULLPTR) { + psSHP->sHooks.Error("Failed to write shape object. " + "Memory allocation error."); return -1; + } psSHP->panRecSize = panRecSizeNew; psSHP->nMaxRecords = nNewMaxRecords; @@ -1322,14 +1313,28 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, /* -------------------------------------------------------------------- */ /* Initialize record. */ /* -------------------------------------------------------------------- */ - uchar *pabyRec = - STATIC_CAST(uchar *, malloc(psObject->nVertices * 4 * sizeof(double) + - psObject->nParts * 8 + 128)); - if (pabyRec == SHPLIB_NULLPTR) + + /* The following computation cannot overflow on 32-bit platforms given that + * the user had to allocate arrays of at least that size. */ + size_t nRecMaxSize = + psObject->nVertices * 4 * sizeof(double) + psObject->nParts * 8; + /* But the following test could trigger on 64-bit platforms on huge + * geometries. */ + const unsigned nExtraSpaceForGeomHeader = 128; + if (nRecMaxSize > UINT_MAX - nExtraSpaceForGeomHeader) { + psSHP->sHooks.Error("Failed to write shape object. Too big geometry."); return -1; + } + nRecMaxSize += nExtraSpaceForGeomHeader; + unsigned char *pabyRec = STATIC_CAST(unsigned char *, malloc(nRecMaxSize)); + if (pabyRec == SHPLIB_NULLPTR) { + psSHP->sHooks.Error("Failed to write shape object. " + "Memory allocation error."); + return -1; + } /* -------------------------------------------------------------------- */ - /* Extract vertices for a Polygon or Arc. */ + /* Extract vertices for a Polygon or Arc. */ /* -------------------------------------------------------------------- */ unsigned int nRecordSize = 0; const bool bFirstFeature = psSHP->nRecords == 0; @@ -1339,15 +1344,15 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, psObject->nSHPType == SHPT_POLYGONM || psObject->nSHPType == SHPT_ARC || psObject->nSHPType == SHPT_ARCZ || psObject->nSHPType == SHPT_ARCM || psObject->nSHPType == SHPT_MULTIPATCH) { - int32 nPoints = psObject->nVertices; - int32 nParts = psObject->nParts; + uint32_t nPoints = psObject->nVertices; + uint32_t nParts = psObject->nParts; _SHPSetBounds(pabyRec + 12, psObject); - if (bBigEndian) - SwapWord(4, &nPoints); - if (bBigEndian) - SwapWord(4, &nParts); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nPoints); + SHP_SWAP32(&nParts); +#endif ByteCopy(&nPoints, pabyRec + 40 + 8, 4); ByteCopy(&nParts, pabyRec + 36 + 8, 4); @@ -1360,8 +1365,9 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, ByteCopy(psObject->panPartStart, pabyRec + 44 + 8, 4 * psObject->nParts); for (int i = 0; i < psObject->nParts; i++) { - if (bBigEndian) - SwapWord(4, pabyRec + 44 + 8 + 4 * i); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(pabyRec + 44 + 8 + 4 * i); +#endif nRecordSize += 4; } @@ -1372,8 +1378,9 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, memcpy(pabyRec + nRecordSize, psObject->panPartType, 4 * psObject->nParts); for (int i = 0; i < psObject->nParts; i++) { - if (bBigEndian) - SwapWord(4, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(pabyRec + nRecordSize); +#endif nRecordSize += 4; } } @@ -1385,11 +1392,10 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, ByteCopy(psObject->padfX + i, pabyRec + nRecordSize, 8); ByteCopy(psObject->padfY + i, pabyRec + nRecordSize + 8, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); - - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize + 8); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); + SHP_SWAP64(pabyRec + nRecordSize + 8); +#endif nRecordSize += 2 * 8; } @@ -1401,19 +1407,22 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, psObject->nSHPType == SHPT_ARCZ || psObject->nSHPType == SHPT_MULTIPATCH) { ByteCopy(&(psObject->dfZMin), pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; ByteCopy(&(psObject->dfZMax), pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; for (int i = 0; i < psObject->nVertices; i++) { ByteCopy(psObject->padfZ + i, pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; } } @@ -1430,65 +1439,72 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, || psObject->nSHPType == SHPT_POLYGONZ || psObject->nSHPType == SHPT_ARCZ)) { ByteCopy(&(psObject->dfMMin), pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; ByteCopy(&(psObject->dfMMax), pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; for (int i = 0; i < psObject->nVertices; i++) { ByteCopy(psObject->padfM + i, pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; } } } /* -------------------------------------------------------------------- */ - /* Extract vertices for a MultiPoint. */ + /* Extract vertices for a MultiPoint. */ /* -------------------------------------------------------------------- */ else if (psObject->nSHPType == SHPT_MULTIPOINT || psObject->nSHPType == SHPT_MULTIPOINTZ || psObject->nSHPType == SHPT_MULTIPOINTM) { - int32 nPoints = psObject->nVertices; + uint32_t nPoints = psObject->nVertices; _SHPSetBounds(pabyRec + 12, psObject); - if (bBigEndian) - SwapWord(4, &nPoints); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nPoints); +#endif ByteCopy(&nPoints, pabyRec + 44, 4); for (int i = 0; i < psObject->nVertices; i++) { ByteCopy(psObject->padfX + i, pabyRec + 48 + i * 16, 8); ByteCopy(psObject->padfY + i, pabyRec + 48 + i * 16 + 8, 8); - if (bBigEndian) - SwapWord(8, pabyRec + 48 + i * 16); - if (bBigEndian) - SwapWord(8, pabyRec + 48 + i * 16 + 8); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + 48 + i * 16); + SHP_SWAP64(pabyRec + 48 + i * 16 + 8); +#endif } nRecordSize = 48 + 16 * psObject->nVertices; if (psObject->nSHPType == SHPT_MULTIPOINTZ) { ByteCopy(&(psObject->dfZMin), pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; ByteCopy(&(psObject->dfZMax), pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; for (int i = 0; i < psObject->nVertices; i++) { ByteCopy(psObject->padfZ + i, pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; } } @@ -1497,26 +1513,29 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, (psObject->nSHPType == SHPT_MULTIPOINTZ || psObject->nSHPType == SHPT_MULTIPOINTM)) { ByteCopy(&(psObject->dfMMin), pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; ByteCopy(&(psObject->dfMMax), pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; for (int i = 0; i < psObject->nVertices; i++) { ByteCopy(psObject->padfM + i, pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; } } } /* -------------------------------------------------------------------- */ - /* Write point. */ + /* Write point. */ /* -------------------------------------------------------------------- */ else if (psObject->nSHPType == SHPT_POINT || psObject->nSHPType == SHPT_POINTZ || @@ -1524,25 +1543,27 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, ByteCopy(psObject->padfX, pabyRec + 12, 8); ByteCopy(psObject->padfY, pabyRec + 20, 8); - if (bBigEndian) - SwapWord(8, pabyRec + 12); - if (bBigEndian) - SwapWord(8, pabyRec + 20); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + 12); + SHP_SWAP64(pabyRec + 20); +#endif nRecordSize = 28; if (psObject->nSHPType == SHPT_POINTZ) { ByteCopy(psObject->padfZ, pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; } if (psObject->bMeasureIsUsed && (psObject->nSHPType == SHPT_POINTZ || psObject->nSHPType == SHPT_POINTM)) { ByteCopy(psObject->padfM, pabyRec + nRecordSize, 8); - if (bBigEndian) - SwapWord(8, pabyRec + nRecordSize); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP64(pabyRec + nRecordSize); +#endif nRecordSize += 8; } } @@ -1598,20 +1619,23 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, /* -------------------------------------------------------------------- */ /* Set the shape type, record number, and record size. */ /* -------------------------------------------------------------------- */ - int32 i32 = + uint32_t i32 = (nShapeId < 0) ? psSHP->nRecords + 1 : nShapeId + 1; /* record # */ - if (!bBigEndian) - SwapWord(4, &i32); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&i32); +#endif ByteCopy(&i32, pabyRec, 4); i32 = (nRecordSize - 8) / 2; /* record size */ - if (!bBigEndian) - SwapWord(4, &i32); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&i32); +#endif ByteCopy(&i32, pabyRec + 4, 4); i32 = psObject->nSHPType; /* shape type */ - if (bBigEndian) - SwapWord(4, &i32); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&i32); +#endif ByteCopy(&i32, pabyRec + 8, 4); /* -------------------------------------------------------------------- */ @@ -1666,7 +1690,7 @@ int SHPAPI_CALL SHPWriteObject(SHPHandle psSHP, int nShapeId, psSHP->panRecSize[nShapeId] = nRecordSize - 8; /* -------------------------------------------------------------------- */ - /* Expand file wide bounds based on this shape. */ + /* Expand file wide bounds based on this shape. */ /* -------------------------------------------------------------------- */ if (bFirstFeature) { if (psObject->nSHPType == SHPT_NULL || psObject->nVertices == 0) { @@ -1754,11 +1778,11 @@ static unsigned char *SHPReallocObjectBufIfNecessary(SHPHandle psSHP, /************************************************************************/ /* SHPReadObject() */ /* */ -/* Read the vertices, parts, and other non-attribute information */ -/* for one shape. */ +/* Read the vertices, parts, and other non-attribute information */ +/* for one shape. */ /************************************************************************/ -SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) +SHPObject SHPAPI_CALL1(*) SHPReadObject(const SHPHandle psSHP, int hEntity) { /* -------------------------------------------------------------------- */ /* Validate the record/entity number. */ @@ -1786,10 +1810,10 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) psSHP->sHooks.Error(str); return SHPLIB_NULLPTR; } - if (!bBigEndian) - SwapWord(4, &nOffset); - if (!bBigEndian) - SwapWord(4, &nLength); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nOffset); + SHP_SWAP32(&nLength); +#endif if (nOffset > STATIC_CAST(unsigned int, INT_MAX)) { char str[128]; @@ -1859,8 +1883,8 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) } } - uchar *pabyRecNew = - STATIC_CAST(uchar *, SfRealloc(psSHP->pabyRec, nNewBufSize)); + unsigned char *pabyRecNew = + STATIC_CAST(unsigned char *, realloc(psSHP->pabyRec, nNewBufSize)); if (pabyRecNew == SHPLIB_NULLPTR) { char szErrorMsg[160]; snprintf(szErrorMsg, sizeof(szErrorMsg), @@ -1919,8 +1943,9 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) /* Do a sanity check */ int nSHPContentLength; memcpy(&nSHPContentLength, psSHP->pabyRec + 4, 4); - if (!bBigEndian) - SwapWord(4, &(nSHPContentLength)); +#if !defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&(nSHPContentLength)); +#endif if (nSHPContentLength < 0 || nSHPContentLength > INT_MAX / 2 - 4 || 2 * nSHPContentLength + 8 != nBytesRead) { char str[128]; @@ -1962,11 +1987,12 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) int nSHPType; memcpy(&nSHPType, psSHP->pabyRec + 8, 4); - if (bBigEndian) - SwapWord(4, &(nSHPType)); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&(nSHPType)); +#endif /* -------------------------------------------------------------------- */ - /* Allocate and minimally initialize the object. */ + /* Allocate and minimally initialize the object. */ /* -------------------------------------------------------------------- */ SHPObject *psShape; if (psSHP->bFastModeReadObject) { @@ -1988,7 +2014,7 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) psShape->bFastModeReadObject = psSHP->bFastModeReadObject; /* ==================================================================== */ - /* Extract vertices for a Polygon or Arc. */ + /* Extract vertices for a Polygon or Arc. */ /* ==================================================================== */ if (psShape->nSHPType == SHPT_POLYGON || psShape->nSHPType == SHPT_ARC || psShape->nSHPType == SHPT_POLYGONZ || @@ -2007,22 +2033,20 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) } /* -------------------------------------------------------------------- */ - /* Get the X/Y bounds. */ + /* Get the X/Y bounds. */ /* -------------------------------------------------------------------- */ - memcpy(&(psShape->dfXMin), psSHP->pabyRec + 8 + 4, 8); - memcpy(&(psShape->dfYMin), psSHP->pabyRec + 8 + 12, 8); - memcpy(&(psShape->dfXMax), psSHP->pabyRec + 8 + 20, 8); - memcpy(&(psShape->dfYMax), psSHP->pabyRec + 8 + 28, 8); - - if (bBigEndian) - SwapWord(8, &(psShape->dfXMin)); - if (bBigEndian) - SwapWord(8, &(psShape->dfYMin)); - if (bBigEndian) - SwapWord(8, &(psShape->dfXMax)); - if (bBigEndian) - SwapWord(8, &(psShape->dfYMax)); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(&psShape->dfXMin, psSHP->pabyRec + 8 + 4); + SHP_SWAPDOUBLE_CPY(&psShape->dfYMin, psSHP->pabyRec + 8 + 12); + SHP_SWAPDOUBLE_CPY(&psShape->dfXMax, psSHP->pabyRec + 8 + 20); + SHP_SWAPDOUBLE_CPY(&psShape->dfYMax, psSHP->pabyRec + 8 + 28); +#else + memcpy(&psShape->dfXMin, psSHP->pabyRec + 8 + 4, 8); + memcpy(&psShape->dfYMin, psSHP->pabyRec + 8 + 12, 8); + memcpy(&psShape->dfXMax, psSHP->pabyRec + 8 + 20, 8); + memcpy(&psShape->dfYMax, psSHP->pabyRec + 8 + 28, 8); +#endif /* -------------------------------------------------------------------- */ @@ -2030,15 +2054,15 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) /* to proper size. */ /* -------------------------------------------------------------------- */ - int32 nPoints; + uint32_t nPoints; memcpy(&nPoints, psSHP->pabyRec + 40 + 8, 4); - int32 nParts; + uint32_t nParts; memcpy(&nParts, psSHP->pabyRec + 36 + 8, 4); - if (bBigEndian) - SwapWord(4, &nPoints); - if (bBigEndian) - SwapWord(4, &nParts); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nPoints); + SHP_SWAP32(&nParts); +#endif /* nPoints and nParts are unsigned */ if (/* nPoints < 0 || nParts < 0 || */ @@ -2121,7 +2145,7 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) return SHPLIB_NULLPTR; } - for (int i = 0; STATIC_CAST(int32, i) < nParts; i++) + for (int i = 0; STATIC_CAST(uint32_t, i) < nParts; i++) psShape->panPartType[i] = SHPP_RING; /* -------------------------------------------------------------------- @@ -2130,9 +2154,10 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) /* -------------------------------------------------------------------- */ memcpy(psShape->panPartStart, psSHP->pabyRec + 44 + 8, 4 * nParts); - for (int i = 0; STATIC_CAST(int32, i) < nParts; i++) { - if (bBigEndian) - SwapWord(4, psShape->panPartStart + i); + for (int i = 0; STATIC_CAST(uint32_t, i) < nParts; i++) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(psShape->panPartStart + i); +#endif /* We check that the offset is inside the vertex array */ if (psShape->panPartStart[i] < 0 || @@ -2174,9 +2199,10 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) */ if (psShape->nSHPType == SHPT_MULTIPATCH) { memcpy(psShape->panPartType, psSHP->pabyRec + nOffset, 4 * nParts); - for (int i = 0; STATIC_CAST(int32, i) < nParts; i++) { - if (bBigEndian) - SwapWord(4, psShape->panPartType + i); + for (int i = 0; STATIC_CAST(uint32_t, i) < nParts; i++) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(psShape->panPartType + i); +#endif } nOffset += 4 * nParts; @@ -2187,16 +2213,17 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) /* Copy out the vertices from the record. */ /* -------------------------------------------------------------------- */ - for (int i = 0; STATIC_CAST(int32, i) < nPoints; i++) { + for (int i = 0; STATIC_CAST(uint32_t, i) < nPoints; i++) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(psShape->padfX + i, + psSHP->pabyRec + nOffset + i * 16); + SHP_SWAPDOUBLE_CPY(psShape->padfY + i, + psSHP->pabyRec + nOffset + i * 16 + 8); +#else memcpy(psShape->padfX + i, psSHP->pabyRec + nOffset + i * 16, 8); - memcpy(psShape->padfY + i, psSHP->pabyRec + nOffset + i * 16 + 8, 8); - - if (bBigEndian) - SwapWord(8, psShape->padfX + i); - if (bBigEndian) - SwapWord(8, psShape->padfY + i); +#endif } nOffset += 16 * nPoints; @@ -2209,19 +2236,23 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) if (psShape->nSHPType == SHPT_POLYGONZ || psShape->nSHPType == SHPT_ARCZ || psShape->nSHPType == SHPT_MULTIPATCH) { - memcpy(&(psShape->dfZMin), psSHP->pabyRec + nOffset, 8); - memcpy(&(psShape->dfZMax), psSHP->pabyRec + nOffset + 8, 8); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(&psShape->dfZMin, psSHP->pabyRec + nOffset); + SHP_SWAPDOUBLE_CPY(&psShape->dfZMax, psSHP->pabyRec + nOffset + 8); +#else + memcpy(&psShape->dfZMin, psSHP->pabyRec + nOffset, 8); + memcpy(&psShape->dfZMax, psSHP->pabyRec + nOffset + 8, 8); - if (bBigEndian) - SwapWord(8, &(psShape->dfZMin)); - if (bBigEndian) - SwapWord(8, &(psShape->dfZMax)); +#endif - for (int i = 0; STATIC_CAST(int32, i) < nPoints; i++) { + for (int i = 0; STATIC_CAST(uint32_t, i) < nPoints; i++) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(psShape->padfZ + i, + psSHP->pabyRec + nOffset + 16 + i * 8); +#else memcpy(psShape->padfZ + i, psSHP->pabyRec + nOffset + 16 + i * 8, 8); - if (bBigEndian) - SwapWord(8, psShape->padfZ + i); +#endif } nOffset += 16 + 8 * nPoints; @@ -2239,19 +2270,22 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) /* -------------------------------------------------------------------- */ if (nEntitySize >= STATIC_CAST(int, nOffset + 16 + 8 * nPoints)) { - memcpy(&(psShape->dfMMin), psSHP->pabyRec + nOffset, 8); - memcpy(&(psShape->dfMMax), psSHP->pabyRec + nOffset + 8, 8); - - if (bBigEndian) - SwapWord(8, &(psShape->dfMMin)); - if (bBigEndian) - SwapWord(8, &(psShape->dfMMax)); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(&psShape->dfMMin, psSHP->pabyRec + nOffset); + SHP_SWAPDOUBLE_CPY(&psShape->dfMMax, psSHP->pabyRec + nOffset + 8); +#else + memcpy(&psShape->dfMMin, psSHP->pabyRec + nOffset, 8); + memcpy(&psShape->dfMMax, psSHP->pabyRec + nOffset + 8, 8); +#endif - for (int i = 0; STATIC_CAST(int32, i) < nPoints; i++) { + for (int i = 0; STATIC_CAST(uint32_t, i) < nPoints; i++) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(psShape->padfM + i, + psSHP->pabyRec + nOffset + 16 + i * 8); +#else memcpy(psShape->padfM + i, psSHP->pabyRec + nOffset + 16 + i * 8, 8); - if (bBigEndian) - SwapWord(8, psShape->padfM + i); +#endif } psShape->bMeasureIsUsed = TRUE; } @@ -2261,7 +2295,7 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) } /* ==================================================================== */ - /* Extract vertices for a MultiPoint. */ + /* Extract vertices for a MultiPoint. */ /* ==================================================================== */ else if (psShape->nSHPType == SHPT_MULTIPOINT || psShape->nSHPType == SHPT_MULTIPOINTM || @@ -2276,11 +2310,12 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) SHPDestroyObject(psShape); return SHPLIB_NULLPTR; } - int32 nPoints; + uint32_t nPoints; memcpy(&nPoints, psSHP->pabyRec + 44, 4); - if (bBigEndian) - SwapWord(4, &nPoints); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAP32(&nPoints); +#endif /* nPoints is unsigned */ if (/* nPoints < 0 || */ nPoints > 50 * 1000 * 1000) { @@ -2346,36 +2381,36 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) return SHPLIB_NULLPTR; } - for (int i = 0; STATIC_CAST(int32, i) < nPoints; i++) { + for (int i = 0; STATIC_CAST(uint32_t, i) < nPoints; i++) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(psShape->padfX + i, + psSHP->pabyRec + 48 + 16 * i); + SHP_SWAPDOUBLE_CPY(psShape->padfY + i, + psSHP->pabyRec + 48 + 16 * i + 8); +#else memcpy(psShape->padfX + i, psSHP->pabyRec + 48 + 16 * i, 8); memcpy(psShape->padfY + i, psSHP->pabyRec + 48 + 16 * i + 8, 8); - - if (bBigEndian) - SwapWord(8, psShape->padfX + i); - if (bBigEndian) - SwapWord(8, psShape->padfY + i); +#endif } int nOffset = 48 + 16 * nPoints; /* -------------------------------------------------------------------- */ - /* Get the X/Y bounds. */ + /* Get the X/Y bounds. */ /* -------------------------------------------------------------------- */ - memcpy(&(psShape->dfXMin), psSHP->pabyRec + 8 + 4, 8); - memcpy(&(psShape->dfYMin), psSHP->pabyRec + 8 + 12, 8); - memcpy(&(psShape->dfXMax), psSHP->pabyRec + 8 + 20, 8); - memcpy(&(psShape->dfYMax), psSHP->pabyRec + 8 + 28, 8); - - if (bBigEndian) - SwapWord(8, &(psShape->dfXMin)); - if (bBigEndian) - SwapWord(8, &(psShape->dfYMin)); - if (bBigEndian) - SwapWord(8, &(psShape->dfXMax)); - if (bBigEndian) - SwapWord(8, &(psShape->dfYMax)); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(&psShape->dfXMin, psSHP->pabyRec + 8 + 4); + SHP_SWAPDOUBLE_CPY(&psShape->dfYMin, psSHP->pabyRec + 8 + 12); + SHP_SWAPDOUBLE_CPY(&psShape->dfXMax, psSHP->pabyRec + 8 + 20); + SHP_SWAPDOUBLE_CPY(&psShape->dfYMax, psSHP->pabyRec + 8 + 28); +#else + memcpy(&psShape->dfXMin, psSHP->pabyRec + 8 + 4, 8); + memcpy(&psShape->dfYMin, psSHP->pabyRec + 8 + 12, 8); + memcpy(&psShape->dfXMax, psSHP->pabyRec + 8 + 20, 8); + memcpy(&psShape->dfYMax, psSHP->pabyRec + 8 + 28, 8); +#endif /* -------------------------------------------------------------------- */ @@ -2383,19 +2418,22 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) /* -------------------------------------------------------------------- */ if (psShape->nSHPType == SHPT_MULTIPOINTZ) { - memcpy(&(psShape->dfZMin), psSHP->pabyRec + nOffset, 8); - memcpy(&(psShape->dfZMax), psSHP->pabyRec + nOffset + 8, 8); - - if (bBigEndian) - SwapWord(8, &(psShape->dfZMin)); - if (bBigEndian) - SwapWord(8, &(psShape->dfZMax)); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(&psShape->dfZMin, psSHP->pabyRec + nOffset); + SHP_SWAPDOUBLE_CPY(&psShape->dfZMax, psSHP->pabyRec + nOffset + 8); +#else + memcpy(&psShape->dfZMin, psSHP->pabyRec + nOffset, 8); + memcpy(&psShape->dfZMax, psSHP->pabyRec + nOffset + 8, 8); +#endif - for (int i = 0; STATIC_CAST(int32, i) < nPoints; i++) { + for (int i = 0; STATIC_CAST(uint32_t, i) < nPoints; i++) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(psShape->padfZ + i, + psSHP->pabyRec + nOffset + 16 + i * 8); +#else memcpy(psShape->padfZ + i, psSHP->pabyRec + nOffset + 16 + i * 8, 8); - if (bBigEndian) - SwapWord(8, psShape->padfZ + i); +#endif } nOffset += 16 + 8 * nPoints; @@ -2412,19 +2450,22 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) /* -------------------------------------------------------------------- */ if (nEntitySize >= STATIC_CAST(int, nOffset + 16 + 8 * nPoints)) { - memcpy(&(psShape->dfMMin), psSHP->pabyRec + nOffset, 8); - memcpy(&(psShape->dfMMax), psSHP->pabyRec + nOffset + 8, 8); - - if (bBigEndian) - SwapWord(8, &(psShape->dfMMin)); - if (bBigEndian) - SwapWord(8, &(psShape->dfMMax)); +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(&psShape->dfMMin, psSHP->pabyRec + nOffset); + SHP_SWAPDOUBLE_CPY(&psShape->dfMMax, psSHP->pabyRec + nOffset + 8); +#else + memcpy(&psShape->dfMMin, psSHP->pabyRec + nOffset, 8); + memcpy(&psShape->dfMMax, psSHP->pabyRec + nOffset + 8, 8); +#endif - for (int i = 0; STATIC_CAST(int32, i) < nPoints; i++) { + for (int i = 0; STATIC_CAST(uint32_t, i) < nPoints; i++) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(psShape->padfM + i, + psSHP->pabyRec + nOffset + 16 + i * 8); +#else memcpy(psShape->padfM + i, psSHP->pabyRec + nOffset + 16 + i * 8, 8); - if (bBigEndian) - SwapWord(8, psShape->padfM + i); +#endif } psShape->bMeasureIsUsed = TRUE; } @@ -2465,13 +2506,13 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) SHPDestroyObject(psShape); return SHPLIB_NULLPTR; } +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(psShape->padfX, psSHP->pabyRec + 12); + SHP_SWAPDOUBLE_CPY(psShape->padfY, psSHP->pabyRec + 20); +#else memcpy(psShape->padfX, psSHP->pabyRec + 12, 8); memcpy(psShape->padfY, psSHP->pabyRec + 20, 8); - - if (bBigEndian) - SwapWord(8, psShape->padfX); - if (bBigEndian) - SwapWord(8, psShape->padfY); +#endif int nOffset = 20 + 8; @@ -2481,10 +2522,11 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) /* -------------------------------------------------------------------- */ if (psShape->nSHPType == SHPT_POINTZ) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(psShape->padfZ, psSHP->pabyRec + nOffset); +#else memcpy(psShape->padfZ, psSHP->pabyRec + nOffset, 8); - - if (bBigEndian) - SwapWord(8, psShape->padfZ); +#endif nOffset += 8; } @@ -2498,10 +2540,11 @@ SHPObject SHPAPI_CALL1(*) SHPReadObject(SHPHandle psSHP, int hEntity) /* -------------------------------------------------------------------- */ if (nEntitySize >= nOffset + 8) { +#if defined(SHP_BIG_ENDIAN) + SHP_SWAPDOUBLE_CPY(psShape->padfM, psSHP->pabyRec + nOffset); +#else memcpy(psShape->padfM, psSHP->pabyRec + nOffset, 8); - - if (bBigEndian) - SwapWord(8, psShape->padfM); +#endif psShape->bMeasureIsUsed = TRUE; } @@ -2739,8 +2782,9 @@ static int SHPRewindIsInnerRing(const SHPObject *psObject, int iOpRing, /* specification. */ /************************************************************************/ -int SHPAPI_CALL SHPRewindObject(CPL_UNUSED SHPHandle hSHP, SHPObject *psObject) +int SHPAPI_CALL SHPRewindObject(const SHPHandle hSHP, SHPObject *psObject) { + (void)hSHP; /* -------------------------------------------------------------------- */ /* Do nothing if this is not a polygon object. */ /* -------------------------------------------------------------------- */ diff --git a/lib/gis/getl.c b/lib/gis/getl.c index 7daae816a70..34df9b04ad0 100644 --- a/lib/gis/getl.c +++ b/lib/gis/getl.c @@ -19,8 +19,7 @@ * \brief Gets a line of text from a file * * This routine runs fgets() to fetch a line of text from a file - * (advancing file pointer) and removes trailing newline. fgets() does - * not recognize '\\r' as an EOL and will read past * it. + * (advancing file pointer) and removes trailing newline. * * \param buf string buffer to receive read data * \param n maximum number of bytes to read @@ -28,23 +27,18 @@ * * \return 1 on success * \return 0 EOF + * + * \see G_getl2() */ int G_getl(char *buf, int n, FILE *fd) { - if (!fgets(buf, n, fd)) - return 0; - - for (; *buf && *buf != '\n'; buf++) - ; - *buf = 0; - - return 1; + return G_getl2(buf, n, fd); } /*! * \brief Gets a line of text from a file of any pedigree * - * This routine is like G_getl() but is more portable. It supports + * This routine supports * text files created on various platforms (UNIX, MacOS9, DOS), * i.e. \\n (\\012), \\r (\\015), and * \\r\\n (\\015\\012) style newlines. diff --git a/lib/gis/gislib.dox b/lib/gis/gislib.dox index fbe1df178e6..852159228cb 100644 --- a/lib/gis/gislib.dox +++ b/lib/gis/gislib.dox @@ -1179,6 +1179,14 @@ The next routines replaces character(s) from string. Replace all occurrences of character in string with new. + - G_str_to_sql() + +Make string SQL compliant. + + - G_str_replace() + +Replace all occurrences of old_str in buffer with new_str. + This next routine copies a string to allocated memory. - G_store() @@ -1186,6 +1194,14 @@ This next routine copies a string to allocated memory. This routine allocates enough memory to hold the string, and returns a pointer to the allocated memory. + - G_store_lower() + +Copy string to allocated memory and convert copied string to lower case. + + - G_store_upper() + +Copy string to allocated memory and convert copied string to upper case. + The next 2 routines convert between upper and lower case. - G_tolcase() @@ -1203,12 +1219,6 @@ equivalent. This routine remove trailing zeros from decimal number for example: 23.45000 would come back as 23.45. - - G_index() - - - G_rindex() - -Get position of delimiter. - - G_strcasecmp() - G_strncasecmp() @@ -1220,11 +1230,24 @@ String compare ignoring case (upper or lower). Return a pointer to the first occurrence of subString in mainString, or NULL if no occurrences are found. - - G_strdup() + - G_str_concat() + +Concatenation of a list of strings, separated by a given character. + + - G_tokenize() + - G_tokenize2() + +Tokenize string. Create array of strings from an input string split up with +given delimiter characters. + + - G_strlcat() + +Size-bounded string concatenation (wrapper function to strlcat()). + + - G_strlcpy() + +Size-bounded string copying (wrapper function to strlcpy()). -Returns a pointer to a string that is a duplicate of the string given -to G_strdup. The duplicate is created using malloc. If unable to -allocate the required space, NULL is returned. \section Enhanced_UNIX_Routines Enhanced UNIX Routines diff --git a/lib/gis/strlcat.c b/lib/gis/strlcat.c new file mode 100644 index 00000000000..635ffbdedb8 --- /dev/null +++ b/lib/gis/strlcat.c @@ -0,0 +1,92 @@ +/*! + * \file lib/gis/strlcat.c + * + * \brief GIS Library - GRASS implementation of strlcat(). + * + * If available, G_strlcat() calls system strlcat(), otherwise it uses + * implementation by Todd C. Miller of OpenBSD. + * + * Addition to GRASS GIS by Nicklas Larsson, 2024 + * + * Original OpenBSD implementation notes: + * + * Copyright (c) 1998, 2015 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include + +static size_t G__strlcat(char *restrict dst, const char *restrict src, + size_t dsize); + +/** + * \brief Size-bounded string concatenation + * + * Appends string src to the end of dst. It will append at most + * dstsize - strlen(dst) - 1 characters. It will then NUL-terminate, unless + * dstsize is 0 or the original dst string was longer than dstsize (in practice + * this should not happen as it means that either dstsize is incorrect or that + * dst is not a proper string). + * + * If the src and dst strings overlap, the behavior is undefined. + * This function is a safer alternative to strncat. + * + * \param[out] dst Pointer to the destination buffer. Must be a NUL-terminated + * C string. + * \param[in] src Pointer to the source string, which will be appended. Must + * be a NUL-terminated C string. + * \param[in] dsize The size of the destination buffer. + * + * \return The total length of the string src, which was attempted to be + * created (the initial length of dst plus the length of src, not + * including the terminating NUL character). If the return value + * is >= dsize, truncation occurred. + */ +size_t G_strlcat(char *dst, const char *src, size_t dsize) +{ +#ifdef HAVE_STRLCAT + return strlcat(dst, src, dsize); +#else + return G__strlcat(dst, src, dsize); +#endif +} + +static size_t G__strlcat(char *restrict dst, const char *restrict src, + size_t dsize) +{ + const char *odst = dst; + const char *osrc = src; + size_t n = dsize; + size_t dlen; + + /* Find the end of dst and adjust bytes left but don't go past end. */ + while (n-- != 0 && *dst != '\0') + dst++; + dlen = dst - odst; + n = dsize - dlen; + + if (n-- == 0) + return (dlen + strlen(src)); + while (*src != '\0') { + if (n != 0) { + *dst++ = *src; + n--; + } + src++; + } + *dst = '\0'; + + return (dlen + (src - osrc)); /* count does not include NUL */ +} diff --git a/lib/gis/strlcpy.c b/lib/gis/strlcpy.c index 5c0601391f5..a2d6e8918e7 100644 --- a/lib/gis/strlcpy.c +++ b/lib/gis/strlcpy.c @@ -22,6 +22,9 @@ #include +static size_t G__strlcpy(char *restrict dst, const char *restrict src, + size_t dsize); + /** * \brief Safe string copy function. * @@ -46,12 +49,18 @@ * \warning The src string must be a valid NUL-terminated C string. Passing an * unterminated string may result in buffer overrun. */ - -size_t G_strlcpy(char *restrict dst, const char *restrict src, size_t dsize) +size_t G_strlcpy(char *dst, const char *src, size_t dsize) { #ifdef HAVE_STRLCPY return strlcpy(dst, src, dsize); #else + return G__strlcpy(dst, src, dsize); +#endif +} + +static size_t G__strlcpy(char *restrict dst, const char *restrict src, + size_t dsize) +{ const char *osrc = src; size_t nleft = dsize; @@ -72,5 +81,4 @@ size_t G_strlcpy(char *restrict dst, const char *restrict src, size_t dsize) } return (src - osrc - 1); /* count does not include NUL */ -#endif } diff --git a/lib/gis/testsuite/test_gis_lib_getl.py b/lib/gis/testsuite/test_gis_lib_getl.py new file mode 100644 index 00000000000..98092955ab2 --- /dev/null +++ b/lib/gis/testsuite/test_gis_lib_getl.py @@ -0,0 +1,81 @@ +"""Test of gis library line reading functions + +@author Vaclav Petras +""" + +import ctypes +import pathlib +import platform +import unittest + +import grass.lib.gis as libgis +from grass.gunittest.case import TestCase +from grass.gunittest.main import test + + +class TestNewlinesWithGetlFunctions(TestCase): + """Test C functions G_getl() and G_getl2() from gis library""" + + @classmethod + def setUpClass(cls): + cls.libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) + cls.libc.fopen.restype = ctypes.POINTER(libgis.FILE) + cls.libc.fopen.argtypes = [ctypes.c_char_p, ctypes.c_char_p] + cls.file_path = pathlib.Path("test.txt") + + def tearDown(self): + self.file_path.unlink() + + def read_lines_and_assert(self, get_line_function, newline): + """Write and read lines and then assert they are as expected""" + lines = ["Line 1", "Line 2", "Line 3"] + with open(self.file_path, mode="w", newline=newline) as stream: + for line in lines: + # Python text newline here. + # The specific newline is added by the stream. + stream.write(f"{line}\n") + + file_ptr = self.libc.fopen(str(self.file_path).encode("utf-8"), b"r") + if not file_ptr: + raise FileNotFoundError(f"Could not open file: {self.file_path}") + + try: + buffer_size = 50 + buffer = ctypes.create_string_buffer(buffer_size) + + for line in lines: + get_line_function(buffer, ctypes.sizeof(buffer), file_ptr) + result = buffer.value.decode("utf-8") if buffer else None + self.assertEqual(line, result) + finally: + self.libc.fclose(file_ptr) + + def test_getl_lf(self): + r"""Check G_getl() with LF (\n)""" + self.read_lines_and_assert(libgis.G_getl, "\n") + + @unittest.expectedFailure + def test_getl_cr(self): + r"""Check G_getl() with CR (\r)""" + self.read_lines_and_assert(libgis.G_getl, "\r") + + def test_getl_crlf(self): + r"""Check G_getl() with CRLF (\r\n)""" + self.read_lines_and_assert(libgis.G_getl, "\r\n") + + def test_getl2_lf(self): + r"""Check G_getl2() with LF (\n)""" + self.read_lines_and_assert(libgis.G_getl2, "\n") + + @unittest.expectedFailure + def test_getl2_cr(self): + r"""Check G_getl2() with CR (\r)""" + self.read_lines_and_assert(libgis.G_getl2, "\r") + + def test_getl2_crlf(self): + r"""Check G_getl2() with CRLF (\r\n)""" + self.read_lines_and_assert(libgis.G_getl2, "\r\n") + + +if __name__ == "__main__": + test() diff --git a/lib/gis/testsuite/test_parser_json.py b/lib/gis/testsuite/test_parser_json.py index 918fb453d04..74ff9673c7f 100644 --- a/lib/gis/testsuite/test_parser_json.py +++ b/lib/gis/testsuite/test_parser_json.py @@ -10,11 +10,14 @@ import subprocess from grass.gunittest.case import TestCase +from grass.gunittest.utils import xfail_windows from grass.script import decode import json class TestParserJson(TestCase): + + @xfail_windows def test_r_slope_aspect_json(self): args = [ "r.slope.aspect", @@ -58,6 +61,7 @@ def test_r_slope_aspect_json(self): self.assertEqual(json_code["inputs"], inputs) self.assertEqual(json_code["outputs"], outputs) + @xfail_windows def test_v_out_ascii(self): args = [ "v.out.ascii", @@ -91,6 +95,7 @@ def test_v_out_ascii(self): self.assertEqual(json_code["inputs"], inputs) self.assertEqual(json_code["outputs"], outputs) + @xfail_windows def test_v_info(self): args = ["v.info", "map=hospitals@PERMANENT", "-c", "--json"] diff --git a/lib/gmath/ATLAS_wrapper_blas_level_1.c b/lib/gmath/CBLAS_wrapper_blas_level_1.c similarity index 80% rename from lib/gmath/ATLAS_wrapper_blas_level_1.c rename to lib/gmath/CBLAS_wrapper_blas_level_1.c index 24390a61dfb..556f1654b46 100644 --- a/lib/gmath/ATLAS_wrapper_blas_level_1.c +++ b/lib/gmath/CBLAS_wrapper_blas_level_1.c @@ -21,15 +21,19 @@ #include #include -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) +#if defined(HAVE_CBLAS_ATLAS_H) +#include +#else #include #endif +#endif /* HAVE_LIBBLAS */ /*! * \brief Compute the dot product of vector x and y - * using the ATLAS routine cblas_ddot + * using the CBLAS routine cblas_ddot * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_f_x_dot_y, the OpenMP multi threaded * grass implementatiom * @@ -41,7 +45,7 @@ * */ double G_math_ddot(double *x, double *y, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) return cblas_ddot(rows, x, 1, y, 1); #else double val; @@ -53,9 +57,9 @@ double G_math_ddot(double *x, double *y, int rows) /*! * \brief Compute the dot product of vector x and y - * using the ATLAS routine cblas_sdsdot + * using the CBLAS routine cblas_sdsdot * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_f_x_dot_y, the OpenMP multi threaded * grass implementatiom * @@ -68,7 +72,7 @@ double G_math_ddot(double *x, double *y, int rows) * */ float G_math_sdsdot(float *x, float *y, float a, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) return cblas_sdsdot(rows, a, x, 1, y, 1); #else float val; @@ -80,9 +84,9 @@ float G_math_sdsdot(float *x, float *y, float a, int rows) /*! * \brief Compute the euclidean norm of vector x - * using the ATLAS routine cblas_dnrm2 + * using the CBLAS routine cblas_dnrm2 * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_d_euclid_norm, the OpenMP multi threaded * grass implementatiom * @@ -93,7 +97,7 @@ float G_math_sdsdot(float *x, float *y, float a, int rows) * */ double G_math_dnrm2(double *x, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) return cblas_dnrm2(rows, x, 1); #else double val; @@ -105,9 +109,9 @@ double G_math_dnrm2(double *x, int rows) /*! * \brief Compute the absolute sum norm of vector x - * using the ATLAS routine cblas_dasum + * using the CBLAS routine cblas_dasum * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_d_asum_norm, the OpenMP multi threaded * grass implementatiom * @@ -118,7 +122,7 @@ double G_math_dnrm2(double *x, int rows) * */ double G_math_dasum(double *x, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) return cblas_dasum(rows, x, 1); #else double val; @@ -130,9 +134,9 @@ double G_math_dasum(double *x, int rows) /*! * \brief Compute the maximum norm of vector x - * using the ATLAS routine cblas_idamax + * using the CBLAS routine cblas_idamax * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_d_max_norm, the OpenMP multi threaded * grass implementatiom * @@ -143,7 +147,7 @@ double G_math_dasum(double *x, int rows) * */ double G_math_idamax(double *x, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) return cblas_idamax(rows, x, 1); #else double val; @@ -155,9 +159,9 @@ double G_math_idamax(double *x, int rows) /*! * \brief Scale vector x with scalar a - * using the ATLAS routine cblas_dscal + * using the CBLAS routine cblas_dscal * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_d_ax_by, the OpenMP multi threaded * grass implementatiom * @@ -169,7 +173,7 @@ double G_math_idamax(double *x, int rows) * */ void G_math_dscal(double *x, double a, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) cblas_dscal(rows, a, x, 1); #else G_math_d_ax_by(x, x, x, a, 0.0, rows); @@ -181,7 +185,7 @@ void G_math_dscal(double *x, double a, int rows) /*! * \brief Copy vector x to vector y * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_d_copy * * \param x (double *) @@ -192,7 +196,7 @@ void G_math_dscal(double *x, double a, int rows) * */ void G_math_dcopy(double *x, double *y, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) cblas_dcopy(rows, x, 1, y, 1); #else G_math_d_copy(x, y, rows); @@ -206,7 +210,7 @@ void G_math_dcopy(double *x, double *y, int rows) * * \f[ {\bf z} = a{\bf x} + {\bf y} \f] * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_d_ax_by, the * grass implementatiom @@ -220,7 +224,7 @@ void G_math_dcopy(double *x, double *y, int rows) * */ void G_math_daxpy(double *x, double *y, double a, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) cblas_daxpy(rows, a, x, 1, y, 1); #else G_math_d_ax_by(x, y, y, a, 1.0, rows); @@ -231,15 +235,15 @@ void G_math_daxpy(double *x, double *y, double a, int rows) /****************************************************************** */ -/********* F L O A T / S I N G L E P E P R E C I S I O N ******** */ +/********* F L O A T / S I N G L E P R E C I S I O N ********* */ /****************************************************************** */ /*! * \brief Compute the dot product of vector x and y - * using the ATLAS routine cblas_sdot + * using the CBLAS routine cblas_sdot * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_f_x_dot_y, the OpenMP multi threaded * grass implementatiom * @@ -251,7 +255,7 @@ void G_math_daxpy(double *x, double *y, double a, int rows) * */ float G_math_sdot(float *x, float *y, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) return cblas_sdot(rows, x, 1, y, 1); #else float val; @@ -263,9 +267,9 @@ float G_math_sdot(float *x, float *y, int rows) /*! * \brief Compute the euclidean norm of vector x - * using the ATLAS routine cblas_dnrm2 + * using the CBLAS routine cblas_dnrm2 * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_f_euclid_norm, the OpenMP multi threaded * grass implementatiom * @@ -276,7 +280,7 @@ float G_math_sdot(float *x, float *y, int rows) * */ float G_math_snrm2(float *x, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) return cblas_snrm2(rows, x, 1); #else float val; @@ -288,9 +292,9 @@ float G_math_snrm2(float *x, int rows) /*! * \brief Compute the absolute sum norm of vector x - * using the ATLAS routine cblas_dasum + * using the CBLAS routine cblas_dasum * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_f_asum_norm, the OpenMP multi threaded * grass implementatiom * @@ -301,7 +305,7 @@ float G_math_snrm2(float *x, int rows) * */ float G_math_sasum(float *x, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) return cblas_sasum(rows, x, 1); #else float val; @@ -313,9 +317,9 @@ float G_math_sasum(float *x, int rows) /*! * \brief Compute the maximum norm of vector x - * using the ATLAS routine cblas_idamax + * using the CBLAS routine cblas_idamax * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_f_max_norm, the OpenMP multi threaded * grass implementatiom * @@ -326,7 +330,7 @@ float G_math_sasum(float *x, int rows) * */ float G_math_isamax(float *x, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) return cblas_isamax(rows, x, 1); #else float val; @@ -338,9 +342,9 @@ float G_math_isamax(float *x, int rows) /*! * \brief Scale vector x with scalar a - * using the ATLAS routine cblas_dscal + * using the CBLAS routine cblas_dscal * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_f_ax_by, the OpenMP multi threaded * grass implementatiom * @@ -352,7 +356,7 @@ float G_math_isamax(float *x, int rows) * */ void G_math_sscal(float *x, float a, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) cblas_sscal(rows, a, x, 1); #else G_math_f_ax_by(x, x, x, a, 0.0, rows); @@ -364,7 +368,7 @@ void G_math_sscal(float *x, float a, int rows) /*! * \brief Copy vector x to vector y * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_f_copy, the * grass implementatiom * @@ -376,7 +380,7 @@ void G_math_sscal(float *x, float a, int rows) * */ void G_math_scopy(float *x, float *y, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) cblas_scopy(rows, x, 1, y, 1); #else G_math_f_copy(x, y, rows); @@ -390,7 +394,7 @@ void G_math_scopy(float *x, float *y, int rows) * * \f[ {\bf z} = a{\bf x} + {\bf y} \f] * - * If grass was not compiled with ATLAS support + * If grass was not compiled with CBLAS support * it will call #G_math_f_ax_by, the * grass implementatiom @@ -404,7 +408,7 @@ void G_math_scopy(float *x, float *y, int rows) * */ void G_math_saxpy(float *x, float *y, float a, int rows) { -#if defined(HAVE_ATLAS) +#if defined(HAVE_LIBBLAS) cblas_saxpy(rows, a, x, 1, y, 1); #else G_math_f_ax_by(x, y, y, a, 1.0, rows); diff --git a/lib/gmath/Makefile b/lib/gmath/Makefile index 0fd6e14f55d..2927d32dec6 100644 --- a/lib/gmath/Makefile +++ b/lib/gmath/Makefile @@ -1,7 +1,7 @@ MODULE_TOPDIR = ../.. EXTRA_LIBS = $(OPENMP_LIBPATH) $(OPENMP_LIB) -EXTRA_INC = $(OPENMP_INCPATH) +EXTRA_INC = $(OPENMP_INCPATH) $(BLASINC) $(LAPACKINC) EXTRA_CFLAGS = $(FFTWINC) $(OPENMP_CFLAGS) LIB = GMATH diff --git a/lib/gmath/la.c b/lib/gmath/la.c index 5c0e59cb862..5696a174bda 100644 --- a/lib/gmath/la.c +++ b/lib/gmath/la.c @@ -22,14 +22,21 @@ ******************************************************************************/ -#include /* needed here for ifdef/else */ +#include + +#if defined(HAVE_LIBBLAS) && defined(HAVE_LIBLAPACK) + +#include +#include #include #include -#include -#include - -#if defined(HAVE_LIBLAPACK) && defined(HAVE_LIBBLAS) +#include +#if defined(HAVE_CBLAS_ATLAS_H) +#include +#else +#include +#endif // HAVE_CBLAS_ATLAS_H #include #include @@ -66,7 +73,7 @@ mat_struct *G_matrix_init(int rows, int cols, int ldim) tmp_arry->type = MATRIX_; tmp_arry->v_indx = -1; - tmp_arry->vals = (doublereal *)G_calloc(ldim * cols, sizeof(doublereal)); + tmp_arry->vals = (double *)G_calloc(ldim * cols, sizeof(double)); tmp_arry->is_init = 1; return tmp_arry; @@ -86,7 +93,7 @@ int G_matrix_zero(mat_struct *A) if (!A->vals) return 0; - memset(A->vals, 0, (A->ldim * A->cols) * sizeof(doublereal)); + memset(A->vals, 0, (A->ldim * A->cols) * sizeof(double)); return 1; } @@ -119,7 +126,7 @@ int G_matrix_set(mat_struct *A, int rows, int cols, int ldim) A->type = MATRIX_; A->v_indx = -1; - A->vals = (doublereal *)G_calloc(ldim * cols, sizeof(doublereal)); + A->vals = (double *)G_calloc(ldim * cols, sizeof(double)); A->is_init = 1; return 0; @@ -150,7 +157,8 @@ mat_struct *G_matrix_copy(const mat_struct *A) return NULL; } - memcpy(&B->vals[0], &A->vals[0], A->cols * A->ldim * sizeof(doublereal)); + memcpy(&B->vals[0], &A->vals[0], + (size_t)A->cols * A->ldim * sizeof(double)); return B; } @@ -225,7 +233,7 @@ mat_struct *G_matrix_scalar_mul(double scalar, mat_struct *matrix, for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { - doublereal value = scalar * G_matrix_get_element(matrix, i, j); + double value = scalar * G_matrix_get_element(matrix, i, j); G_matrix_set_element(out, i, j, value); } @@ -328,8 +336,6 @@ mat_struct *G__matrix_add(mat_struct *mt1, mat_struct *mt2, const double c1, return mt3; } -#if defined(HAVE_LIBBLAS) - /*! * \fn mat_struct *G_matrix_product (mat_struct *mt1, mat_struct *mt2) * @@ -346,9 +352,8 @@ mat_struct *G__matrix_add(mat_struct *mt1, mat_struct *mt2, const double c1, mat_struct *G_matrix_product(mat_struct *mt1, mat_struct *mt2) { mat_struct *mt3; - doublereal unity = 1, zero = 0; - integer rows, cols, interdim, lda, ldb; - integer1 no_trans = 'n'; + double unity = 1., zero = 0.; + int rows, cols, interdim, lda, ldb; if (!((mt1->is_init) || (mt2->is_init))) { G_warning(_("One or both input matrices uninitialised")); @@ -367,23 +372,19 @@ mat_struct *G_matrix_product(mat_struct *mt1, mat_struct *mt2) /* Call the driver */ - rows = (integer)mt1->rows; - interdim = (integer)mt1->cols; - cols = (integer)mt2->cols; + rows = (int)mt1->rows; + interdim = (int)mt1->cols; + cols = (int)mt2->cols; - lda = (integer)mt1->ldim; - ldb = (integer)mt2->ldim; + lda = (int)mt1->ldim; + ldb = (int)mt2->ldim; - f77_dgemm(&no_trans, &no_trans, &rows, &cols, &interdim, &unity, mt1->vals, - &lda, mt2->vals, &ldb, &zero, mt3->vals, &lda); + cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, rows, cols, interdim, + unity, mt1->vals, lda, mt2->vals, ldb, zero, mt3->vals, lda); return mt3; } -#else /* defined(HAVE_LIBBLAS) */ -#warning G_matrix_product() not compiled; requires BLAS library -#endif /* defined(HAVE_LIBBLAS) */ - /*! * \fn mat_struct *G_matrix_transpose (mat_struct *mt) * @@ -401,7 +402,7 @@ mat_struct *G_matrix_transpose(mat_struct *mt) { mat_struct *mt1; int ldim, ldo; - doublereal *dbo, *dbt, *dbx, *dby; + double *dbo, *dbt, *dbx, *dby; int cnt, cnt2; /* Word align the workspace blocks */ @@ -438,8 +439,6 @@ mat_struct *G_matrix_transpose(mat_struct *mt) return mt1; } -#if defined(HAVE_LIBBLAS) && defined(HAVE_LIBLAPACK) - /*! * \fn int G_matrix_LU_solve (const mat_struct *mt1, mat_struct **xmat0, * const mat_struct *bmat, mat_type mtype) @@ -509,20 +508,20 @@ int G_matrix_LU_solve(const mat_struct *mt1, mat_struct **xmat0, switch (mtype) { case NONSYM: { - integer *perm, res_info; - integer num_eqns, nrhs, lda, ldb; + int *perm, res_info; + int num_eqns, nrhs, lda, ldb; - perm = (integer *)G_malloc(wmat->rows * sizeof(integer)); + perm = (int *)G_malloc(wmat->rows * sizeof(int)); /* Set fields to pass to fortran routine */ - num_eqns = (integer)mt1->rows; - nrhs = (integer)wmat->cols; - lda = (integer)mt1->ldim; - ldb = (integer)wmat->ldim; + num_eqns = (int)mt1->rows; + nrhs = (int)wmat->cols; + lda = (int)mt1->ldim; + ldb = (int)wmat->ldim; /* Call LA driver */ - f77_dgesv(&num_eqns, &nrhs, mtx->vals, &lda, perm, wmat->vals, &ldb, - &res_info); + res_info = LAPACKE_dgesv(LAPACK_COL_MAJOR, num_eqns, nrhs, mtx->vals, + lda, perm, wmat->vals, ldb); /* Copy the results from the modified data matrix, taking account of pivot permutations ??? @@ -545,7 +544,7 @@ int G_matrix_LU_solve(const mat_struct *mt1, mat_struct **xmat0, */ memcpy(xmat->vals, wmat->vals, - wmat->cols * wmat->ldim * sizeof(doublereal)); + (size_t)wmat->cols * wmat->ldim * sizeof(double)); /* Free temp arrays */ G_free(perm); @@ -574,12 +573,6 @@ int G_matrix_LU_solve(const mat_struct *mt1, mat_struct **xmat0, return 0; } -#else /* defined(HAVE_LIBBLAS) && defined(HAVE_LIBLAPACK) */ -#warning G_matrix_LU_solve() not compiled; requires BLAS and LAPACK libraries -#endif /* defined(HAVE_LIBBLAS) && defined(HAVE_LIBLAPACK) */ - -#if defined(HAVE_LIBBLAS) && defined(HAVE_LIBLAPACK) - /*! * \fn mat_struct *G_matrix_inverse (mat_struct *mt) * @@ -635,10 +628,6 @@ mat_struct *G_matrix_inverse(mat_struct *mt) } } -#else /* defined(HAVE_LIBBLAS) && defined(HAVE_LIBLAPACK) */ -#warning G_matrix_inverse() not compiled; requires BLAS and LAPACK libraries -#endif /* defined(HAVE_LIBBLAS) && defined(HAVE_LIBLAPACK) */ - /*! * \fn void G_matrix_free (mat_struct *mt) * @@ -672,14 +661,14 @@ void G_matrix_free(mat_struct *mt) void G_matrix_print(mat_struct *mt) { int i, j; - char buf[64], numbuf[64]; + char buf[2048], numbuf[64]; for (i = 0; i < mt->rows; i++) { - strcpy(buf, ""); + G_strlcpy(buf, "", sizeof(buf)); for (j = 0; j < mt->cols; j++) { - - sprintf(numbuf, "%14.6f", G_matrix_get_element(mt, i, j)); + snprintf(numbuf, sizeof(numbuf), "%14.6f", + G_matrix_get_element(mt, i, j)); strcat(buf, numbuf); if (j < mt->cols - 1) strcat(buf, ", "); @@ -720,7 +709,7 @@ int G_matrix_set_element(mat_struct *mt, int rowval, int colval, double val) return -1; } - mt->vals[rowval + colval * mt->ldim] = (doublereal)val; + mt->vals[rowval + colval * mt->ldim] = (double)val; return 0; } @@ -918,7 +907,7 @@ int G_matvect_retrieve_matrix(vec_struct *vc) vec_struct *G_matvect_product(mat_struct *A, vec_struct *b, vec_struct *out) { unsigned int i, m, n, j; - register doublereal sum; + register double sum; /* G_message("A=%d,%d,%d", A->cols, A->rows, A->ldim); */ /* G_message("B=%d,%d,%d", b->cols, b->rows, b->ldim); */ @@ -997,8 +986,7 @@ vec_struct *G_vector_init(int cells, int ldim, vtype vt) tmp_arry->v_indx = 0; - tmp_arry->vals = - (doublereal *)G_calloc(ldim * tmp_arry->cols, sizeof(doublereal)); + tmp_arry->vals = (double *)G_calloc(ldim * tmp_arry->cols, sizeof(double)); tmp_arry->is_init = 1; return tmp_arry; @@ -1144,14 +1132,12 @@ int G_vector_set(vec_struct *A, int cells, int ldim, vtype vt, int vindx) else A->v_indx = vindx; - A->vals = (doublereal *)G_calloc(ldim * A->cols, sizeof(doublereal)); + A->vals = (double *)G_calloc(ldim * A->cols, sizeof(double)); A->is_init = 1; return 0; } -#if defined(HAVE_LIBBLAS) - /*! * \fn double G_vector_norm_euclid (vec_struct *vc) * @@ -1166,22 +1152,22 @@ int G_vector_set(vec_struct *A, int cells, int ldim, vtype vt, int vindx) double G_vector_norm_euclid(vec_struct *vc) { - integer incr, Nval; - doublereal *startpt; + int incr, Nval; + double *startpt; if (!vc->is_init) G_fatal_error(_("Matrix is not initialised")); if (vc->type == ROWVEC_) { - Nval = (integer)vc->cols; - incr = (integer)vc->ldim; + Nval = (int)vc->cols; + incr = (int)vc->ldim; if (vc->v_indx < 0) startpt = vc->vals; else startpt = vc->vals + vc->v_indx; } else { - Nval = (integer)vc->rows; + Nval = (int)vc->rows; incr = 1; if (vc->v_indx < 0) startpt = vc->vals; @@ -1190,13 +1176,9 @@ double G_vector_norm_euclid(vec_struct *vc) } /* Call the BLAS routine dnrm2_() */ - return (double)f77_dnrm2(&Nval, startpt, &incr); + return cblas_dnrm2(Nval, startpt, incr); } -#else /* defined(HAVE_LIBBLAS) */ -#warning G_vector_norm_euclid() not compiled; requires BLAS library -#endif /* defined(HAVE_LIBBLAS) */ - /*! * \fn double G_vector_norm_maxval (vec_struct *vc, int vflag) * @@ -1216,7 +1198,7 @@ double G_vector_norm_euclid(vec_struct *vc) double G_vector_norm_maxval(vec_struct *vc, int vflag) { - doublereal xval, *startpt, *curpt; + double xval, *startpt, *curpt; double cellval; int ncells, incr; @@ -1224,15 +1206,15 @@ double G_vector_norm_maxval(vec_struct *vc, int vflag) G_fatal_error(_("Matrix is not initialised")); if (vc->type == ROWVEC_) { - ncells = (integer)vc->cols; - incr = (integer)vc->ldim; + ncells = (int)vc->cols; + incr = (int)vc->ldim; if (vc->v_indx < 0) startpt = vc->vals; else startpt = vc->vals + vc->v_indx; } else { - ncells = (integer)vc->rows; + ncells = (int)vc->rows; incr = 1; if (vc->v_indx < 0) startpt = vc->vals; @@ -1360,9 +1342,6 @@ vec_struct *G_vector_product(vec_struct *v1, vec_struct *v2, vec_struct *out) return NULL; } -#if defined(HAVE_LAPACK) && defined(HAVE_LIBBLAS) - f77_dhad(v1->cols, 1.0, v1->vals, 1, v2->vals, 1, 0.0, out->vals, 1.0); -#else idx1 = (v1->v_indx > 0) ? v1->v_indx : 0; idx2 = (v2->v_indx > 0) ? v2->v_indx : 0; idx0 = (out->v_indx > 0) ? out->v_indx : 0; @@ -1379,7 +1358,6 @@ vec_struct *G_vector_product(vec_struct *v1, vec_struct *v2, vec_struct *out) G_matrix_get_element(v1, i, idx1) * G_matrix_get_element(v2, i, idx2)); } -#endif return out; } @@ -1399,7 +1377,7 @@ vec_struct *G_vector_copy(const vec_struct *vc1, int comp_flag) { vec_struct *tmp_arry; int incr1, incr2; - doublereal *startpt1, *startpt2, *curpt1, *curpt2; + double *startpt1, *startpt2, *curpt1, *curpt2; int cnt; if (!vc1->is_init) { @@ -1441,8 +1419,8 @@ vec_struct *G_vector_copy(const vec_struct *vc1, int comp_flag) return NULL; } - tmp_arry->vals = (doublereal *)G_calloc(tmp_arry->ldim * tmp_arry->cols, - sizeof(doublereal)); + tmp_arry->vals = + (double *)G_calloc(tmp_arry->ldim * tmp_arry->cols, sizeof(double)); if (comp_flag == DO_COMPACT) { if (tmp_arry->type == ROWVEC_) { startpt1 = tmp_arry->vals; @@ -1482,7 +1460,7 @@ vec_struct *G_vector_copy(const vec_struct *vc1, int comp_flag) } while (cnt > 0) { - memcpy(curpt1, curpt2, sizeof(doublereal)); + memcpy(curpt1, curpt2, sizeof(double)); curpt1 += incr1; curpt2 += incr2; cnt--; @@ -1633,7 +1611,7 @@ int G_matrix_eigen_sort(vec_struct *d, mat_struct *m) } /* sort the combined matrix */ - qsort(tmp.vals, tmp.cols, tmp.ldim * sizeof(doublereal), egcmp); + qsort(tmp.vals, tmp.cols, tmp.ldim * sizeof(double), egcmp); /* split tmp into m and d */ for (i = 0; i < m->cols; i++) { @@ -1652,8 +1630,8 @@ int G_matrix_eigen_sort(vec_struct *d, mat_struct *m) static int egcmp(const void *pa, const void *pb) { - double a = *(doublereal *const)pa; - double b = *(doublereal *const)pb; + double a = *(double *const)pa; + double b = *(double *const)pb; if (a > b) return 1; @@ -1663,4 +1641,6 @@ static int egcmp(const void *pa, const void *pb) return 0; } -#endif /* HAVE_BLAS && HAVE_LAPACK && HAVE_G2C */ +#endif // HAVE_LIBLAPACK HAVE_LIBBLAS + +typedef int suppress_empty_translation_unit_compiler_warning; diff --git a/lib/imagery/testsuite/test_imagery_sigfile.py b/lib/imagery/testsuite/test_imagery_sigfile.py index 104cd5a59b4..8d0e288561d 100644 --- a/lib/imagery/testsuite/test_imagery_sigfile.py +++ b/lib/imagery/testsuite/test_imagery_sigfile.py @@ -9,10 +9,10 @@ for details """ -import os import stat import ctypes import shutil +from pathlib import Path from grass.gunittest.case import TestCase from grass.gunittest.main import test @@ -80,7 +80,7 @@ def test_roundtrip_signature_v1_norgb_one_label(self): # Write signatures to file p_new_sigfile = I_fopen_signature_file_new(self.sig_name) - sig_stat = os.stat(f"{self.sig_dir}/sig") + sig_stat = Path(self.sig_dir, "sig").stat() self.assertTrue(stat.S_ISREG(sig_stat.st_mode)) I_write_signatures(p_new_sigfile, ctypes.byref(So)) self.libc.fclose(p_new_sigfile) @@ -136,7 +136,7 @@ def test_broken_signature_v1_norgb(self): # Write signatures to file p_new_sigfile = I_fopen_signature_file_new(self.sig_name) - sig_stat = os.stat(f"{self.sig_dir}/sig") + sig_stat = Path(self.sig_dir, "sig").stat() self.assertTrue(stat.S_ISREG(sig_stat.st_mode)) I_write_signatures(p_new_sigfile, ctypes.byref(So)) self.libc.fclose(p_new_sigfile) @@ -188,7 +188,7 @@ def test_roundtrip_signature_v1_norgb_two_labelss(self): # Write signatures to file p_new_sigfile = I_fopen_signature_file_new(self.sig_name) - sig_stat = os.stat(f"{self.sig_dir}/sig") + sig_stat = Path(self.sig_dir, "sig").stat() self.assertTrue(stat.S_ISREG(sig_stat.st_mode)) I_write_signatures(p_new_sigfile, ctypes.byref(So)) self.libc.fclose(p_new_sigfile) @@ -277,7 +277,7 @@ def test_roundtrip_signature_v2_norgb_two_labels_oclass(self): # Write signatures to file p_new_sigfile = I_fopen_signature_file_new(self.sig_name) - sig_stat = os.stat(f"{self.sig_dir}/sig") + sig_stat = Path(self.sig_dir, "sig").stat() self.assertTrue(stat.S_ISREG(sig_stat.st_mode)) I_write_signatures(p_new_sigfile, ctypes.byref(So)) self.libc.fclose(p_new_sigfile) diff --git a/lib/imagery/testsuite/test_imagery_signature_management.py b/lib/imagery/testsuite/test_imagery_signature_management.py index 7b1dc8bdc57..42c55c45123 100644 --- a/lib/imagery/testsuite/test_imagery_signature_management.py +++ b/lib/imagery/testsuite/test_imagery_signature_management.py @@ -15,6 +15,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows from grass.script.core import tempname import grass.script as gs @@ -44,16 +45,19 @@ class GetSignaturesDirTestCase(TestCase): + @xfail_windows def test_get_sig(self): cdir = ctypes.create_string_buffer(GNAME_MAX) I_get_signatures_dir(cdir, I_SIGFILE_TYPE_SIG) self.assertEqual(utils.decode(cdir.value), f"signatures{HOST_DIRSEP}sig") + @xfail_windows def test_get_sigset(self): cdir = ctypes.create_string_buffer(GNAME_MAX) I_get_signatures_dir(cdir, I_SIGFILE_TYPE_SIGSET) self.assertEqual(utils.decode(cdir.value), f"signatures{HOST_DIRSEP}sigset") + @xfail_windows def test_get_libsvm(self): elem = ctypes.create_string_buffer(GNAME_MAX) I_get_signatures_dir(elem, I_SIGFILE_TYPE_LIBSVM) diff --git a/lib/imagery/testsuite/test_imagery_sigsetfile.py b/lib/imagery/testsuite/test_imagery_sigsetfile.py index b8bcb566520..d526e920885 100644 --- a/lib/imagery/testsuite/test_imagery_sigsetfile.py +++ b/lib/imagery/testsuite/test_imagery_sigsetfile.py @@ -9,10 +9,10 @@ for details """ -import os import stat import ctypes import shutil +from pathlib import Path from grass.gunittest.case import TestCase from grass.gunittest.main import test @@ -84,7 +84,7 @@ def test_roundtrip_sigset_v1_one_label(self): # Write signatures to file p_new_sigfile = I_fopen_sigset_file_new(self.sig_name) - sig_stat = os.stat(f"{self.sig_dir}/sig") + sig_stat = Path(self.sig_dir, "sig").stat() self.assertTrue(stat.S_ISREG(sig_stat.st_mode)) I_WriteSigSet(p_new_sigfile, ctypes.byref(So)) self.libc.fclose(p_new_sigfile) @@ -139,7 +139,7 @@ def test_read_fail_sigset_v1_one_label(self): # Write signatures to file p_new_sigfile = I_fopen_sigset_file_new(self.sig_name) - sig_stat = os.stat(f"{self.sig_dir}/sig") + sig_stat = Path(self.sig_dir, "sig").stat() self.assertTrue(stat.S_ISREG(sig_stat.st_mode)) I_WriteSigSet(p_new_sigfile, ctypes.byref(So)) self.libc.fclose(p_new_sigfile) @@ -183,7 +183,7 @@ def test_roundtrip_sigset_v1_two_labels(self): # Write signatures to file p_new_sigfile = I_fopen_sigset_file_new(self.sig_name) - sig_stat = os.stat(f"{self.sig_dir}/sig") + sig_stat = Path(self.sig_dir, "sig").stat() self.assertTrue(stat.S_ISREG(sig_stat.st_mode)) I_WriteSigSet(p_new_sigfile, ctypes.byref(So)) self.libc.fclose(p_new_sigfile) diff --git a/lib/init/grass.py b/lib/init/grass.py index 87a69f5ef65..d2d8301c52b 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -400,7 +400,7 @@ def create_grass_config_dir(): os.makedirs(directory) except OSError as e: # Can happen as a race condition - if not e.errno == errno.EEXIST or not os.path.isdir(directory): + if e.errno != errno.EEXIST or not os.path.isdir(directory): fatal( _( "Failed to create configuration directory '{}' with error: {}" @@ -484,7 +484,7 @@ def create_gisrc(tmpdir, gisrcrc): if "UNKNOWN" in s: try_remove(gisrcrc) s = None - except: + except Exception: s = None # Copy the global grassrc file to the session grassrc file @@ -496,7 +496,7 @@ def create_gisrc(tmpdir, gisrcrc): def read_gisrc(filename): kv = {} try: - f = open(filename, "r") + f = open(filename) except OSError: return kv @@ -522,7 +522,7 @@ def write_gisrcrc(gisrcrc, gisrc, skip_variable=None): """Reads gisrc file and write to gisrcrc""" debug("Reading %s" % gisrc) number = 0 - with open(gisrc, "r") as f: + with open(gisrc) as f: lines = f.readlines() for line in lines: if skip_variable in line: @@ -535,7 +535,7 @@ def write_gisrcrc(gisrcrc, gisrc, skip_variable=None): def read_env_file(path): kv = {} - f = open(path, "r") + f = open(path) for line in f: k, v = line.split(":", 1) kv[k.strip()] = v.strip() @@ -620,7 +620,7 @@ def create_initial_gisrc(filename): LOCATION_NAME: MAPSET: """ - % os.getcwd() + % Path.cwd() ) writefile(filename, s) @@ -737,22 +737,21 @@ def cannot_create_location_reason(gisdbase, location): " the project <{location}>" " already exists." ).format(**locals()) - elif os.path.isfile(path): + if os.path.isfile(path): return _( "Unable to create new project <{location}> because <{path}> is a file." ).format(**locals()) - elif os.path.isdir(path): + if os.path.isdir(path): return _( "Unable to create new project <{location}> because" " the directory <{path}>" " already exists." ).format(**locals()) - else: - return _( - "Unable to create new project in" - " the directory <{path}>" - " for an unknown reason." - ).format(**locals()) + return _( + "Unable to create new project in" + " the directory <{path}>" + " for an unknown reason." + ).format(**locals()) def set_mapset( @@ -789,7 +788,7 @@ def set_mapset( # non-empty element as the last element (which is good for both mapset # and location split) if arg == ".": - arg = os.getcwd() + arg = str(Path.cwd()) elif not os.path.isabs(arg): arg = os.path.abspath(arg) if arg.endswith(os.path.sep): @@ -1057,9 +1056,7 @@ def load_env(grass_env_file): v = v.strip('"') # we'll keep expand=True to expand $var's inside "value" because # they are within double quotes - elif ( - v.startswith("'") or v.endswith("'") or v.startswith('"') or v.endswith('"') - ): + elif v.startswith(("'", '"')) or v.endswith(("'", '"')): # here, let's try to ignore unmatching single/double quotes, which # might be a multi-line variable or just a user error debug("Ignoring multi-line environmental variable {0}".format(k)) @@ -1073,20 +1070,6 @@ def load_env(grass_env_file): # create a new environment variable os.environ[k] = v - # Allow for mixed ISIS-GRASS Environment - if os.getenv("ISISROOT"): - isis = os.getenv("ISISROOT") - os.environ["ISIS_LIB"] = isis + os.sep + "lib" - os.environ["ISIS_3RDPARTY"] = isis + os.sep + "3rdParty" + os.sep + "lib" - os.environ["QT_PLUGIN_PATH"] = isis + os.sep + "3rdParty" + os.sep + "plugins" - # os.environ['ISIS3DATA'] = isis + "$ISIS3DATA" - libpath = os.getenv("LD_LIBRARY_PATH", "") - isislibpath = os.getenv("ISIS_LIB") - isis3rdparty = os.getenv("ISIS_3RDPARTY") - os.environ["LD_LIBRARY_PATH"] = ( - libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty - ) - def install_notranslation(): # If locale is not supported, _ function might be missing @@ -1114,7 +1097,7 @@ def set_language(grass_config_dir): # Override value is stored in wxGUI preferences file. try: - with open(os.path.join(grass_config_dir, "wx.json"), "r") as json_file: + with open(os.path.join(grass_config_dir, "wx.json")) as json_file: try: language = json.load(json_file)["language"]["locale"]["lc_all"] except KeyError: @@ -1176,7 +1159,7 @@ def set_language(grass_config_dir): encoding = "UTF-8" normalized = locale.normalize("%s.%s" % (language, encoding)) locale.setlocale(locale.LC_ALL, normalized) - except locale.Error as e: + except locale.Error: if language == "en": # A workaround for Python Issue30755 # https://bugs.python.org/issue30755 @@ -1202,7 +1185,7 @@ def set_language(grass_config_dir): # See bugs #3441 and #3423 try: locale.setlocale(locale.LC_ALL, "C.UTF-8") - except locale.Error as e: + except locale.Error: # All lost. Setting to C as much as possible. # We can not call locale.normalize on C as it # will transform it to en_US and we already know @@ -1297,64 +1280,6 @@ def set_language(grass_config_dir): gettext.install("grasslibs", gpath("locale")) -def lock_mapset(mapset_path, force_gislock_removal, user): - """Lock the mapset and return name of the lock file - - Behavior on error must be changed somehow; now it fatals but GUI case is - unresolved. - """ - if not os.path.exists(mapset_path): - fatal(_("Path '%s' doesn't exist") % mapset_path) - if not os.access(mapset_path, os.W_OK): - error = _("Path '%s' not accessible.") % mapset_path - stat_info = os.stat(mapset_path) - mapset_uid = stat_info.st_uid - if mapset_uid != os.getuid(): - # GTC %s is mapset's folder path - error = "%s\n%s" % ( - error, - _("You are not the owner of '%s'.") % mapset_path, - ) - fatal(error) - # Check for concurrent use - lockfile = os.path.join(mapset_path, ".gislock") - ret = call([gpath("etc", "lock"), lockfile, "%d" % os.getpid()]) - msg = None - if ret == 2: - if not force_gislock_removal: - msg = _( - "%(user)s is currently running GRASS in selected mapset" - " (file %(file)s found). Concurrent use not allowed.\n" - "You can force launching GRASS using -f flag" - " (note that you need permission for this operation)." - " Have another look in the processor " - "manager just to be sure..." % {"user": user, "file": lockfile} - ) - else: - try_remove(lockfile) - message( - _( - "%(user)s is currently running GRASS in selected mapset" - " (file %(file)s found). Forcing to launch GRASS..." - % {"user": user, "file": lockfile} - ) - ) - elif ret != 0: - msg = ( - _("Unable to properly access '%s'.\nPlease notify system personnel.") - % lockfile - ) - - if msg: - raise Exception(msg) - debug( - "Mapset <{mapset}> locked using '{lockfile}'".format( - mapset=mapset_path, lockfile=lockfile - ) - ) - return lockfile - - # TODO: the gisrcrc here does not make sense, remove it from load_gisrc def unlock_gisrc_mapset(gisrc, gisrcrc): """Unlock mapset from the gisrc file""" @@ -1493,7 +1418,7 @@ def script_path(batch_job): if script_in_addon_path and os.path.exists(script_in_addon_path): batch_job[0] = script_in_addon_path return script_in_addon_path - elif os.path.exists(batch_job[0]): + if os.path.exists(batch_job[0]): return batch_job[0] try: @@ -1585,7 +1510,7 @@ def say_hello(): revision = linerev.split(" ")[1] sys.stderr.write(" (" + revision + ")") - except: + except Exception: pass @@ -1705,7 +1630,7 @@ def sh_like_startup(location, location_name, grass_env_file, sh): # save command history in mapset dir and remember more # bash history file handled in specific_addition - if not sh == "bash": + if sh != "bash": os.environ["HISTFILE"] = os.path.join(location, sh_history) # instead of changing $HOME, start bash with: @@ -1742,8 +1667,8 @@ def sh_like_startup(location, location_name, grass_env_file, sh): ) ) + mask2d_test = "r.mask.status -t" # TODO: have a function and/or module to test this - mask2d_test = 'test -f "$MAPSET_PATH/cell/MASK"' mask3d_test = 'test -d "$MAPSET_PATH/grid3/RASTER3D_MASK"' specific_addition = "" @@ -1951,7 +1876,7 @@ def print_params(params): try: revision = linerev.split(" ")[1] sys.stdout.write("%s\n" % revision[1:]) - except: + except Exception: sys.stdout.write("No SVN revision defined\n") elif arg == "version": sys.stdout.write("%s\n" % GRASS_VERSION) @@ -2436,14 +2361,16 @@ def main(): location = mapset_settings.full_mapset + from grass.app.data import lock_mapset, MapsetLockingException + try: # check and create .gislock file lock_mapset( - mapset_settings.full_mapset, - user=user, - force_gislock_removal=params.force_gislock_removal, + mapset_path=mapset_settings.full_mapset, + force_lock_removal=params.force_gislock_removal, + message_callback=message, ) - except Exception as e: + except MapsetLockingException as e: fatal(e.args[0]) sys.exit(_("Exiting...")) diff --git a/lib/init/testsuite/test_grass_tmp_mapset.py b/lib/init/testsuite/test_grass_tmp_mapset.py index 7a488dadb5f..9379957cd3f 100644 --- a/lib/init/testsuite/test_grass_tmp_mapset.py +++ b/lib/init/testsuite/test_grass_tmp_mapset.py @@ -18,6 +18,7 @@ import os import shutil import subprocess +from grass.gunittest.utils import xfail_windows # Note that unlike rest of GRASS GIS, here we are using unittest package @@ -43,6 +44,7 @@ def tearDown(self): """Deletes the location""" shutil.rmtree(self.location, ignore_errors=True) + @xfail_windows def test_command_runs(self): """Check that correct parameters are accepted""" return_code = subprocess.call( @@ -57,6 +59,7 @@ def test_command_runs(self): ), ) + @xfail_windows def test_command_fails_without_location(self): """Check that the command fails with a nonexistent location""" return_code = subprocess.call( @@ -78,6 +81,7 @@ def test_command_fails_without_location(self): ), ) + @xfail_windows def test_mapset_metadata_correct(self): """Check that metadata is readable and have expected value (XY CRS)""" output = subprocess.check_output( @@ -91,6 +95,7 @@ def test_mapset_metadata_correct(self): ), ) + @xfail_windows def test_mapset_deleted(self): """Check that mapset is deleted at the end of execution""" subprocess.check_call( diff --git a/lib/lidar/raster.c b/lib/lidar/raster.c index 4d7305c9a9b..ad531865df7 100644 --- a/lib/lidar/raster.c +++ b/lib/lidar/raster.c @@ -3,6 +3,7 @@ #include #include #include +#include /*------------------------------------------------------------------------------------------------*/ void P_Sparse_Points(struct Map_info *Out, struct Cell_head *Elaboration, @@ -187,6 +188,7 @@ void P_Sparse_Points(struct Map_info *Out, struct Cell_head *Elaboration, } /*IF*/} /*FOR*/ db_commit_transaction(driver); + Vect_destroy_line_struct(point); return; } diff --git a/lib/linkm/test/try.c b/lib/linkm/test/try.c index 4f2a431e003..3b71b6f684a 100644 --- a/lib/linkm/test/try.c +++ b/lib/linkm/test/try.c @@ -61,7 +61,7 @@ int main(int argc, char *argv[]) exit(0); } -int add_link_rev(struct link *List, struct link *link) +void add_link_rev(struct link *List, struct link *link) { struct link *p; @@ -70,7 +70,7 @@ int add_link_rev(struct link *List, struct link *link) link->next = p; } -int add_link(struct link *List, struct link *link) +void add_link(struct link *List, struct link *link) { struct link *p; @@ -81,7 +81,7 @@ int add_link(struct link *List, struct link *link) link->next = NULL; } -int dumplist(struct link *List) +void dumplist(struct link *List) { struct link *p; diff --git a/lib/linkm/test/try2.c b/lib/linkm/test/try2.c index ad226826795..7eb153f16f3 100644 --- a/lib/linkm/test/try2.c +++ b/lib/linkm/test/try2.c @@ -63,7 +63,7 @@ int main(int argc, char *argv[]) exit(0); } -int add_link_rev(struct link *List, struct link *link) +void add_link_rev(struct link *List, struct link *link) { struct link *p; @@ -72,7 +72,7 @@ int add_link_rev(struct link *List, struct link *link) link->next = p; } -int add_link(struct link *List, struct link *link) +void add_link(struct link *List, struct link *link) { struct link *p; @@ -83,7 +83,7 @@ int add_link(struct link *List, struct link *link) link->next = NULL; } -int dumplist(struct link *List) +void dumplist(struct link *List) { struct link *p; diff --git a/lib/ogsf/gk.c b/lib/ogsf/gk.c index 3390598960a..b4fea635cc4 100644 --- a/lib/ogsf/gk.c +++ b/lib/ogsf/gk.c @@ -172,8 +172,8 @@ void gk_follow_frames(Viewnode *view, int numsteps, Keylist *keys, int step, GS_get_from(tmp); G_debug(3, "gk_follow_frames():"); - G_debug(3, " MASK: %lx", mask); - G_debug(3, " FROM: %f %f %f", tmp[X], tmp[Y], tmp[Z]); + G_debug(3, " mask: %lx", mask); + G_debug(3, " from: %f %f %f", tmp[X], tmp[Y], tmp[Z]); /* ACS 1 line: was GS_get_focus(tmp); with this kanimator works also for flythrough navigation diff --git a/lib/ogsf/gvd.c b/lib/ogsf/gvd.c index 6a6176526a2..84867123c5e 100644 --- a/lib/ogsf/gvd.c +++ b/lib/ogsf/gvd.c @@ -201,7 +201,7 @@ int gvd_vect(geovect *gv, geosurf *gs, int do_fast) } gsd_endline(); } - /* need to handle MASK! */ + /* need to handle mask! */ else if (src == CONST_ATT) { /* for now - but later, do seg intersect maskedge */ if (gs_point_is_masked(gs, bgn) || diff --git a/lib/raster/mask_info.c b/lib/raster/mask_info.c index 792510879dc..317bab75b63 100644 --- a/lib/raster/mask_info.c +++ b/lib/raster/mask_info.c @@ -1,30 +1,17 @@ -/* - ************************************************************* - * char * Rast_mask_info () +/** + * \file lib/raster/mask_info.c * - * returns a printable text of mask information + * \brief Raster Library - Get mask information * - ************************************************************ - * Rast__mask_info (name, mapset) + * (C) 1999-2024 by Vaclav Petras and the GRASS Development Team * - * char name[GNAME_MAX], mapset[GMAPSET_MAX]; + * This program is free software under the GNU General Public + * License (>=v2). Read the file COPYING that comes with GRASS + * for details. * - * function: - * determine the status off the automatic masking - * and the name of the cell file which forms the mask - * - * (the mask file is actually MASK in the current mapset, - * but is usually a reclassed cell file, and the reclass - * name and mapset are returned) - * - * returns: - * -1 no masking (name, mapset undefined) - * name, mapset are undefined - * - * 1 mask file present, masking on - * name, mapset hold mask file name, mapset - * - ***************************************************************/ + * \author CERL + * \author Vaclav Petras, NC State University, Center for Geospatial Analytics + */ #include @@ -32,6 +19,15 @@ #include #include +/** + * @brief Get a printable text with information about raster mask + * + * Determines if 2D raster mask is present and returns textual information about + * the mask suitable for end-user display. The resulting text is translated. + * Caller is responsible for freeing the memory of the returned string. + * + * @return New string with textual information + */ char *Rast_mask_info(void) { char text[GNAME_MAX + GMAPSET_MAX + 16]; @@ -53,16 +49,88 @@ char *Rast_mask_info(void) return G_store(text); } +/** + * @brief Get raster mask status information + * + * _is_mask_reclass_ is a pointer to a bool variable which + * will be set to true if mask raster is a reclass and false otherwise. + * + * If you are not interested in the underlying reclassified raster map, + * pass NULL pointers for the three reclass parameters: + * + * ``` + * Rast_mask_status(name, mapset, NULL, NULL, NULL); + * ``` + * + * @param[out] name Name of the raster map used as mask + * @param[out] mapset Name of the mapset the raster is in + * @param[out] is_mask_reclass Will be set to true if mask raster is a reclass + * @param[out] reclass_name Name of the underlying reclassified raster map + * @param[out] reclass_mapset Name of the mapset the reclassified raster is in + * + * @return true if mask is present, false otherwise + */ +bool Rast_mask_status(char *name, char *mapset, bool *is_mask_reclass, + char *reclass_name, char *reclass_mapset) +{ + int present = Rast__mask_info(name, mapset); + + if (is_mask_reclass && reclass_name && reclass_mapset) { + if (present) { + *is_mask_reclass = Rast_is_reclass("MASK", G_mapset(), reclass_name, + reclass_mapset) > 0; + if (*is_mask_reclass) { + // The original mask values were overwritten in the initial + // info call. Put back the original values, so that we can + // report them to the caller. + strcpy(name, "MASK"); + strcpy(mapset, G_mapset()); + } + } + else { + *is_mask_reclass = false; + } + } + + if (present == 1) + return true; + else + return false; +} + +/** + * @brief Get information about the current mask + * + * Determines the status of the automatic masking and the name of the 2D + * raster which forms the mask. Typically, mask is raster called MASK in the + * current mapset, but when used with r.mask, it is usually a reclassed + * raster, and so when a MASK raster is present and it is a reclass raster, + * the name and mapset of the underlying reclassed raster are returned. + * + * The name and mapset is written to the parameter which need to be defined + * with a sufficient size, least as `char name[GNAME_MAX], mapset[GMAPSET_MAX]`. + * + * When the masking is not active, -1 is returned and name and mapset are + * undefined. When the masking is active, 1 is returned and name and mapset + * will hold the name and mapset of the underlying raster. + * + * @param[out] name Name of the raster map used as mask + * @param[out] mapset Name of the map's mapset + * + * @return 1 if mask is present, -1 otherwise + */ int Rast__mask_info(char *name, char *mapset) { char rname[GNAME_MAX], rmapset[GMAPSET_MAX]; - strcpy(name, "MASK"); - strcpy(mapset, G_mapset()); + strcpy(rname, "MASK"); + (void)G_strlcpy(rmapset, G_mapset(), GMAPSET_MAX); - if (!G_find_raster(name, mapset)) + if (!G_find_raster(rname, rmapset)) return -1; + strcpy(name, rname); + strcpy(mapset, rmapset); if (Rast_is_reclass(name, mapset, rname, rmapset) > 0) { strcpy(name, rname); strcpy(mapset, rmapset); @@ -70,3 +138,13 @@ int Rast__mask_info(char *name, char *mapset) return 1; } + +/** + * @brief Check presence of 2D raster mask + * + * @return true if mask is present, false otherwise + */ +bool Rast_mask_is_present(void) +{ + return G_find_raster("MASK", G_mapset()) != NULL; +} diff --git a/lib/vector/Vlib/color_read.c b/lib/vector/Vlib/color_read.c index 0a023a89a7d..4e0b3b04837 100644 --- a/lib/vector/Vlib/color_read.c +++ b/lib/vector/Vlib/color_read.c @@ -49,7 +49,10 @@ int Vect_read_colors(const char *name, const char *mapset, if (colors) Rast_init_colors(colors); - strcpy(xname, name); + if (G_strlcpy(xname, name, sizeof(xname)) >= sizeof(xname)) { + G_warning(_("Vector map name <%s> is too long"), name); + return -1; + } mapset = G_find_vector(xname, mapset); if (!mapset) return -1; @@ -58,12 +61,12 @@ int Vect_read_colors(const char *name, const char *mapset, if (strcmp(mapset, G_mapset()) == 0) { /* look for the regular color table */ - sprintf(buf, "%s/%s", GV_DIRECTORY, name); + (void)snprintf(buf, sizeof(buf), "%s/%s", GV_DIRECTORY, name); ret = Rast__read_colors(buf, GV_COLR_ELEMENT, mapset, colors); } else { /* look for secondary color table in current mapset */ - sprintf(buf, "%s/%s", GV_COLR2_DIRECTORY, mapset); + (void)snprintf(buf, sizeof(buf), "%s/%s", GV_COLR2_DIRECTORY, mapset); ret = Rast__read_colors(buf, name, G_mapset(), colors); } if (ret == -2) diff --git a/lib/vector/Vlib/geos.c b/lib/vector/Vlib/geos.c index 719e0fdd270..2c68a0a6fba 100644 --- a/lib/vector/Vlib/geos.c +++ b/lib/vector/Vlib/geos.c @@ -290,7 +290,7 @@ GEOSCoordSequence *V1_read_line_geos(struct Map_info *Map, long offset, long size; double *x, *y, *z; - GEOSCoordSequence *pseq; + GEOSCoordSequence *pseq = NULL; G_debug(3, "V1_read_line_geos(): offset = %ld", offset); @@ -353,8 +353,6 @@ GEOSCoordSequence *V1_read_line_geos(struct Map_info *Map, long offset, G_debug(3, " n_points = %d dim = %d", n_points, (Map->head.with_z) ? 3 : 2); - pseq = GEOSCoordSeq_create(n_points, (Map->head.with_z) ? 3 : 2); - x = (double *)G_malloc(n_points * sizeof(double)); y = (double *)G_malloc(n_points * sizeof(double)); if (Map->head.with_z) @@ -362,17 +360,22 @@ GEOSCoordSequence *V1_read_line_geos(struct Map_info *Map, long offset, else z = NULL; - if (0 >= dig__fread_port_D(x, n_points, &(Map->dig_fp))) - return NULL; /* end of file */ + if (0 >= dig__fread_port_D(x, n_points, &(Map->dig_fp))) { + goto free_return; /* end of file */ + } - if (0 >= dig__fread_port_D(y, n_points, &(Map->dig_fp))) - return NULL; /* end of file */ + if (0 >= dig__fread_port_D(y, n_points, &(Map->dig_fp))) { + goto free_return; /* end of file */ + } if (Map->head.with_z) { - if (0 >= dig__fread_port_D(z, n_points, &(Map->dig_fp))) - return NULL; /* end of file */ + if (0 >= dig__fread_port_D(z, n_points, &(Map->dig_fp))) { + goto free_return; /* end of file */ + } } + pseq = GEOSCoordSeq_create(n_points, (Map->head.with_z) ? 3 : 2); + for (i = 0; i < n_points; i++) { GEOSCoordSeq_setX(pseq, i, x[i]); GEOSCoordSeq_setY(pseq, i, y[i]); @@ -382,6 +385,7 @@ GEOSCoordSequence *V1_read_line_geos(struct Map_info *Map, long offset, G_debug(3, " off = %ld", (long)dig_ftell(&(Map->dig_fp))); +free_return: G_free((void *)x); G_free((void *)y); if (z) diff --git a/lib/vector/Vlib/open.c b/lib/vector/Vlib/open.c index 501b31eb4cb..0008156c34a 100644 --- a/lib/vector/Vlib/open.c +++ b/lib/vector/Vlib/open.c @@ -572,6 +572,7 @@ int Vect__open_old(struct Map_info *Map, const char *name, const char *mapset, if (access(file_path, F_OK) == 0) /* fidx file exists? */ unlink(file_path); } + Map->support_updated = TRUE; } return level; diff --git a/locale/grass_po_stats.py b/locale/grass_po_stats.py index b5f15026691..bfae49629d3 100644 --- a/locale/grass_po_stats.py +++ b/locale/grass_po_stats.py @@ -21,10 +21,12 @@ import subprocess import sys +from pathlib import Path + def read_po_files(inputdirpath): """Return a dictionary with for each language the list of *.po files""" - originalpath = os.getcwd() + originalpath = Path.cwd() os.chdir(inputdirpath) languages = {} for pofile in sorted(glob.glob("*.po")): @@ -79,10 +81,9 @@ def langDefinition(fil): f.close() if len(lang) == 2: return " ".join(lang) - elif len(lang) == 1: + if len(lang) == 1: return lang[0] - else: - return "" + return "" def get_stats(languages, directory): @@ -144,7 +145,7 @@ def writejson(stats, outfile): fout.close() try: os.remove("messages.mo") - except: + except OSError: pass diff --git a/man/build_check.py b/man/build_check.py index 6111a4dbe9f..9d9675fb7ac 100644 --- a/man/build_check.py +++ b/man/build_check.py @@ -9,7 +9,7 @@ import sys import os -from build_html import * +from build_html import html_dir, message_tmpl, html_files, read_file os.chdir(html_dir) diff --git a/man/build_check_rest.py b/man/build_check_rest.py index 159be8453db..f9868dfd697 100644 --- a/man/build_check_rest.py +++ b/man/build_check_rest.py @@ -9,7 +9,7 @@ import sys import os -from build_rest import * +from build_rest import rest_dir, message_tmpl, rest_files, read_file os.chdir(rest_dir) diff --git a/man/build_class.py b/man/build_class.py index 8300c62079f..564fb5c20e6 100644 --- a/man/build_class.py +++ b/man/build_class.py @@ -9,7 +9,20 @@ import sys import os -from build_html import * +from build_html import ( + html_dir, + write_html_header, + grass_version, + modclass_intro_tmpl, + modclass_tmpl, + to_title, + html_files, + check_for_desc_override, + get_desc, + desc2_tmpl, + write_html_footer, + replace_file, +) no_intro_page_classes = ["display", "general", "miscellaneous", "postscript"] diff --git a/man/build_class_graphical.py b/man/build_class_graphical.py index 955f5c2a63e..554c950d3a8 100644 --- a/man/build_class_graphical.py +++ b/man/build_class_graphical.py @@ -91,10 +91,7 @@ def file_matches(filename, patterns): - for pattern in patterns: - if fnmatch.fnmatch(filename, pattern): - return True - return False + return any(fnmatch.fnmatch(filename, pattern) for pattern in patterns) def starts_with_module(string, module) -> bool: @@ -102,9 +99,7 @@ def starts_with_module(string, module) -> bool: # module = module.replace('wxGUI.', 'g.gui.') # TODO: matches g.mapsets images for g.mapset and d.rast.num for d.rast return bool( - string.startswith(module.replace(".", "_")) - or string.startswith(module.replace(".", "")) - or string.startswith(module) + string.startswith((module.replace(".", "_"), module.replace(".", ""), module)) ) diff --git a/man/build_class_rest.py b/man/build_class_rest.py index c1de3d623d0..05aec125d04 100644 --- a/man/build_class_rest.py +++ b/man/build_class_rest.py @@ -9,7 +9,19 @@ import sys import os -from build_rest import * +from build_rest import ( + rest_dir, + grass_version, + modclass_intro_tmpl, + modclass_tmpl, + desc2_tmpl, + write_rest_header, + write_rest_footer, + rest_files, + check_for_desc_override, + get_desc, + replace_file, +) os.chdir(rest_dir) diff --git a/man/build_full_index.py b/man/build_full_index.py index 76379787905..7d2ce03e342 100644 --- a/man/build_full_index.py +++ b/man/build_full_index.py @@ -9,7 +9,23 @@ import sys import os -from build_html import * +from operator import itemgetter + +from build_html import ( + html_dir, + grass_version, + html_files, + write_html_header, + write_html_footer, + check_for_desc_override, + get_desc, + replace_file, + to_title, + full_index_header, + toc, + cmd2_tmpl, + desc1_tmpl, +) year = None if len(sys.argv) > 1: @@ -36,7 +52,7 @@ prefix = cmd.split(".")[0] if prefix not in [item[0] for item in classes]: classes.append((prefix, class_labels.get(prefix, prefix))) -classes.sort(key=lambda tup: tup[0]) +classes.sort(key=itemgetter(0)) # begin full index: filename = "full_index.html" diff --git a/man/build_full_index_rest.py b/man/build_full_index_rest.py index 14167df0f84..26183505393 100644 --- a/man/build_full_index_rest.py +++ b/man/build_full_index_rest.py @@ -8,7 +8,20 @@ import os -from build_rest import * +from build_rest import ( + rest_dir, + rest_files, + write_rest_header, + grass_version, + full_index_header, + sections, + cmd2_tmpl, + check_for_desc_override, + get_desc, + desc1_tmpl, + write_rest_footer, + replace_file, +) os.chdir(rest_dir) diff --git a/man/build_html.py b/man/build_html.py index daa38b557f4..0ef860d42f3 100644 --- a/man/build_html.py +++ b/man/build_html.py @@ -393,7 +393,7 @@ def check_for_desc_override(basename): def read_file(name): - f = open(name, "r") + f = open(name) s = f.read() f.close() return s @@ -476,7 +476,7 @@ def write_html_footer(f, index_url, year=None): def get_desc(cmd): - f = open(cmd, "r") + f = open(cmd) while True: line = f.readline() if not line: @@ -494,8 +494,7 @@ def get_desc(cmd): sp = line.split("-", 1) if len(sp) > 1: return sp[1].strip() - else: - return None + return None return "" diff --git a/man/build_index.py b/man/build_index.py index 5a01787afe3..12de7f01162 100644 --- a/man/build_index.py +++ b/man/build_index.py @@ -9,7 +9,14 @@ import sys import os -from build_html import * +from build_html import ( + html_dir, + grass_version, + write_html_header, + write_html_cmd_overview, + write_html_footer, + replace_file, +) os.chdir(html_dir) diff --git a/man/build_index_rest.py b/man/build_index_rest.py index 68463bbb753..b919042e4af 100644 --- a/man/build_index_rest.py +++ b/man/build_index_rest.py @@ -9,7 +9,14 @@ import os -from build_rest import * +from build_rest import ( + rest_dir, + grass_version, + write_rest_header, + write_rest_cmd_overview, + write_rest_footer, + replace_file, +) os.chdir(rest_dir) diff --git a/man/build_keywords.py b/man/build_keywords.py index 477c1a131ff..b0dfe95e0e3 100644 --- a/man/build_keywords.py +++ b/man/build_keywords.py @@ -21,7 +21,13 @@ import os import sys import glob -from build_html import * +from build_html import ( + grass_version, + header1_tmpl, + headerkeywords_tmpl, + write_html_footer, +) + blacklist = [ "Display", @@ -81,17 +87,17 @@ def get_module_man_html_file_path(module): try: index_keys = lines.index("

    KEYWORDS

    \n") + 1 index_desc = lines.index("

    NAME

    \n") + 1 - except: + except Exception: continue try: keys = lines[index_keys].split(",") - except: + except Exception: continue for key in keys: key = key.strip() try: key = key.split(">")[1].split("<")[0] - except: + except Exception: pass if not key: sys.exit("Empty keyword from file %s line: %s" % (fname, lines[index_keys])) @@ -104,10 +110,10 @@ def get_module_man_html_file_path(module): for black in blacklist: try: del keywords[black] - except: + except Exception: try: del keywords[black.lower()] - except: + except Exception: continue for key in sorted(keywords.keys()): @@ -152,7 +158,7 @@ def get_module_man_html_file_path(module): for k in sorted(char_list.keys()): test_length += 1 # toc += '
  • %s
  • ' % (char_list[k], k) - if test_length % 4 == 0 and not test_length == all_keys: + if test_length % 4 == 0 and test_length != all_keys: toc += '\n%s, ' % (char_list[k], k) elif test_length % 4 == 0 and test_length == all_keys: toc += '\n%s' % (char_list[k], k) diff --git a/man/build_manual_gallery.py b/man/build_manual_gallery.py index 3d381e27877..a8b077be8f9 100755 --- a/man/build_manual_gallery.py +++ b/man/build_manual_gallery.py @@ -102,10 +102,7 @@ def img_in_html(filename, imagename) -> bool: def file_matches(filename, patterns): - for pattern in patterns: - if fnmatch.fnmatch(filename, pattern): - return True - return False + return any(fnmatch.fnmatch(filename, pattern) for pattern in patterns) def get_files(directory, patterns, exclude_patterns): @@ -135,8 +132,7 @@ def title_from_names(module_name, img_name): img_name = img_name.strip() if img_name: return "{name} ({desc})".format(name=module_name, desc=img_name) - else: - return "{name}".format(name=module_name) + return "{name}".format(name=module_name) def get_module_name(filename): diff --git a/man/build_rest.py b/man/build_rest.py index ea1dd7692d2..a98a099a076 100644 --- a/man/build_rest.py +++ b/man/build_rest.py @@ -271,7 +271,7 @@ def check_for_desc_override(basename): def read_file(name): - f = open(name, "r") + f = open(name) s = f.read() f.close() return s @@ -337,7 +337,7 @@ def write_rest_footer(f, index_url): def get_desc(cmd): - f = open(cmd, "r") + f = open(cmd) while True: line = f.readline() if not line: @@ -355,8 +355,7 @@ def get_desc(cmd): sp = line.split("-", 1) if len(sp) > 1: return sp[1].strip() - else: - return None + return None return "" diff --git a/man/build_topics.py b/man/build_topics.py index bd0606d1aeb..be5f2962d2c 100644 --- a/man/build_topics.py +++ b/man/build_topics.py @@ -6,7 +6,15 @@ import os import sys import glob -from build_html import * +from build_html import ( + grass_version, + header1_tmpl, + headertopics_tmpl, + headerkey_tmpl, + desc1_tmpl, + moduletopics_tmpl, + write_html_footer, +) path = sys.argv[1] year = os.getenv("VERSION_DATE") @@ -24,16 +32,16 @@ try: index_keys = lines.index("

    KEYWORDS

    \n") + 1 index_desc = lines.index("

    NAME

    \n") + 1 - except: + except Exception: continue try: key = lines[index_keys].split(",")[1].strip().replace(" ", "_") key = key.split(">")[1].split("<")[0] - except: + except Exception: continue try: desc = lines[index_desc].split("-", 1)[1].strip() - except: + except Exception: desc.strip() if key not in keywords.keys(): keywords[key] = {} diff --git a/man/parser_standard_options.py b/man/parser_standard_options.py index 15d1e0fc9ae..ad027a1b6b4 100644 --- a/man/parser_standard_options.py +++ b/man/parser_standard_options.py @@ -47,8 +47,7 @@ def split_opt_line(line): index = line.index("=") key = line[:index].strip() default = line[index + 1 :].strip() - if default.startswith("_("): - default = default[2:] + default = default.removeprefix("_(") return key, default def parse_glines(glines): diff --git a/mswindows/osgeo4w/build_osgeo4w.sh b/mswindows/osgeo4w/build_osgeo4w.sh index 6885bfe02f8..d38354d4b78 100755 --- a/mswindows/osgeo4w/build_osgeo4w.sh +++ b/mswindows/osgeo4w/build_osgeo4w.sh @@ -38,7 +38,7 @@ export ARCH=x86_64-w64-mingw32 --with-nls \ --with-readline \ --with-blas \ - --with-lapack-includes=/mingw64/include/lapack \ + --with-lapack \ --with-freetype \ --with-freetype-includes=${OSGEO4W_ROOT_MSYS}/include/freetype2 \ --with-proj-share=${OSGEO4W_ROOT_MSYS}/share/proj \ diff --git a/ps/ps.map/do_geogrid.c b/ps/ps.map/do_geogrid.c index 0fac5f80cac..c22ef86379c 100644 --- a/ps/ps.map/do_geogrid.c +++ b/ps/ps.map/do_geogrid.c @@ -300,6 +300,7 @@ void get_ll_bounds(double *w, double *e, double *s, double *n) double ew, ns; int first; + east = west = north = south = 0.0; e1 = PS.w.east; w1 = PS.w.west; n1 = PS.w.north; diff --git a/ps/ps.map/do_scalebar.c b/ps/ps.map/do_scalebar.c index a53325172f3..760a6825288 100644 --- a/ps/ps.map/do_scalebar.c +++ b/ps/ps.map/do_scalebar.c @@ -2,6 +2,7 @@ #include #include +#include #include #include "local_proto.h" #include "distance.h" @@ -182,17 +183,17 @@ int do_scalebar(void) /* draw units label */ if (sb.units == SB_UNITS_AUTO) - strcpy(num, G_database_unit_name(TRUE)); + (void)G_strlcpy(num, G_database_unit_name(TRUE), sizeof(num)); else if (sb.units == SB_UNITS_METERS) - strcpy(num, _("meters")); + (void)G_strlcpy(num, _("meters"), sizeof(num)); else if (sb.units == SB_UNITS_KM) - strcpy(num, _("kilometers")); + (void)G_strlcpy(num, _("kilometers"), sizeof(num)); else if (sb.units == SB_UNITS_FEET) - strcpy(num, _("feet")); + (void)G_strlcpy(num, _("feet"), sizeof(num)); else if (sb.units == SB_UNITS_MILES) - strcpy(num, _("miles")); + (void)G_strlcpy(num, _("miles"), sizeof(num)); else if (sb.units == SB_UNITS_NMILES) - strcpy(num, _("nautical miles")); + (void)G_strlcpy(num, _("nautical miles"), sizeof(num)); text_box_path(72.0 * (x + length / 2), 72.0 * (PS.page_height - (sb.y + 0.075)), CENTER, UPPER, num, diff --git a/ps/ps.map/ps_header.c b/ps/ps.map/ps_header.c index fd7eb996588..9a454824d9b 100644 --- a/ps/ps.map/ps_header.c +++ b/ps/ps.map/ps_header.c @@ -16,7 +16,7 @@ extern int rotate_plot; int write_PS_header(void) { struct Categories cats; - int cats_ok; + int cats_ok = 0; if (PS.do_raster) cats_ok = Rast_read_cats(PS.cell_name, PS.cell_mapset, &cats) >= 0; diff --git a/ps/ps.map/ps_vareas.c b/ps/ps.map/ps_vareas.c index 5cd3471a6a8..3968140bd25 100644 --- a/ps/ps.map/ps_vareas.c +++ b/ps/ps.map/ps_vareas.c @@ -65,6 +65,7 @@ static int plot_area(struct Map_info *P_map, int area, double shift) if (0 > (ret = Vect_get_area_points(P_map, area, Points))) { if (ret == -1) G_warning(_("Read error in vector map")); + Vect_destroy_line_struct(Points); return 0; } construct_path(Points, shift, WHOLE_PATH); @@ -76,10 +77,12 @@ static int plot_area(struct Map_info *P_map, int area, double shift) if (0 > (ret = Vect_get_isle_points(P_map, island, Points))) { if (ret == -1) G_warning(_("Read error in vector map")); + Vect_destroy_line_struct(Points); return -1; } construct_path(Points, shift, WHOLE_PATH); } + Vect_destroy_line_struct(Points); return 1; } diff --git a/ps/ps.map/ps_vpoints.c b/ps/ps.map/ps_vpoints.c index 80b29a349b1..cd320b46f11 100644 --- a/ps/ps.map/ps_vpoints.c +++ b/ps/ps.map/ps_vpoints.c @@ -268,5 +268,6 @@ int PS_vpoints_plot(struct Map_info *P_map, int vec) } /* for (line) */ fprintf(PS.fp, "\n"); + Vect_destroy_cats_struct(Cats); return 0; } diff --git a/ps/ps.map/r_instructions.c b/ps/ps.map/r_instructions.c index 0e2c012fd92..87a2e4bbfcf 100644 --- a/ps/ps.map/r_instructions.c +++ b/ps/ps.map/r_instructions.c @@ -29,7 +29,7 @@ static char *help[] = { "read unix-file eps Encapsulated PostScript file", "border [y|n] mapinfo map information", "window region definition region region definition", - "maskcolor MASK color", + "maskcolor mask color", "rectangle east north east north", "scale 1:#|# inches|# panels|1 inch = # miles", "outline map composition outline", diff --git a/pyproject.toml b/pyproject.toml index eb866cb0e08..2a2287aaaad 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ requires-python = ">=3.9" [tool.black] required-version = '24' line-length = 88 -target-version = ['py38', 'py39', 'py310', 'py311', 'py312'] +target-version = ['py39', 'py310', 'py311', 'py312', 'py313'] # 'extend-exclude' excludes files or directories in addition to the defaults extend-exclude = ''' ( @@ -98,9 +98,7 @@ ignore = [ "B904", # raise-without-from-inside-except "B909", # loop-iterator-mutation "BLE001", # blind-except - "C404", # unnecessary-list-comprehension-dict "C414", # unnecessary-double-cast-or-process - "C416", # unnecessary-comprehension "COM812", # missing-trailing-comma "COM818", # trailing-comma-on-bare-tuple "D1", @@ -145,7 +143,6 @@ ignore = [ "FBT001", # boolean-type-hint-positional-argument "FBT002", # boolean-default-value-positional-argument "FBT003", # boolean-positional-value-in-call - "FURB118", # reimplemented-operator "I001", # unsorted-imports "ISC003", # explicit-string-concatenation "PERF203", # try-except-in-loop @@ -153,8 +150,6 @@ ignore = [ "PERF402", # manual-list-copy "PERF403", # manual-dict-comprehension "PIE794", # duplicate-class-field-definition - "PIE808", # unnecessary-range-start - "PIE810", # multiple-starts-ends-with "PLC0415", # import-outside-top-level "PLC1901", # compare-to-empty-string "PLC2701", # import-private-name @@ -181,13 +176,7 @@ ignore = [ "PLW1641", # eq-without-hash "PLW2901", # redefined-loop-name "PLW3201", # bad-dunder-method-name - "PT001", # pytest-fixture-incorrect-parentheses-style - "PT004", # pytest-missing-fixture-name-underscore - "PT006", # pytest-parametrize-names-wrong-type - "PT009", # pytest-unittest-assertion - "PT011", # pytest-raises-too-broad - "PT018", # pytest-composite-assertion - "PT023", # pytest-incorrect-mark-parentheses-style + "PT004", # pytest-missing-fixture-name-underscore # deprecated, so doesn't appear with --preview "PTH100", # os-path-abspath "PTH101", # os-chmod "PTH102", # os-mkdir @@ -196,12 +185,10 @@ ignore = [ "PTH106", # os-rmdir "PTH107", # os-remove "PTH108", # os-unlink - "PTH109", # os-getcwd "PTH110", # os-path-exists "PTH111", # os-path-expanduser "PTH112", # os-path-isdir "PTH113", # os-path-isfile - "PTH116", # os-stat "PTH117", # os-path-isabs "PTH118", # os-path-join "PTH119", # os-path-basename @@ -214,11 +201,9 @@ ignore = [ "RET501", # unnecessary-return-none "RET502", # implicit-return-value "RET503", # implicit-return - "RET505", # superfluous-else-return "RET506", # superfluous-else-raise "RET507", # superfluous-else-continue "RET508", # superfluous-else-break - "RSE102", # unnecessary-paren-on-raise-exception "RUF003", # ambiguous-unicode-character-comment "RUF005", # collection-literal-concatenation "RUF012", # mutable-class-default @@ -247,18 +232,12 @@ ignore = [ "S606", # start-process-with-no-shell "S607", # start-process-with-partial-path "S608", # hardcoded-sql-expression - "SIM101", # duplicate-isinstance-call "SIM102", # collapsible-if "SIM105", # suppressible-exception "SIM108", # if-else-block-instead-of-if-exp - "SIM109", # compare-with-tuple - "SIM110", # reimplemented-builtin "SIM113", # enumerate-for-loop - "SIM114", # if-with-same-arms - "SIM115", # open-file-with-context-handler "SIM116", # if-else-block-instead-of-dict-lookup "SIM118", # in-dict-keys - "SIM201", # negate-equal-op "SIM223", # expr-and-false "SIM401", # if-else-block-instead-of-dict-get "SLF001", # private-member-access @@ -268,142 +247,125 @@ ignore = [ "TRY201", # verbose-raise "TRY300", # try-consider-else "TRY301", # raise-within-try - "UP015", # redundant-open-modes "UP030", # format-literals "UP031", # printf-string-formatting "UP032", # f-string "UP036", # outdated-version-block - "W605", # invalid-escape-sequence ] [tool.ruff.lint.per-file-ignores] # See https://docs.astral.sh/ruff/settings/#lint_per-file-ignores # "A005", # builtin-module-shadowing -# "INT002", # f-string-in-get-text-func-call -# "INT001", # format-in-get-text-func-call -# "INT003", # printf-in-get-text-func-call # "PLW0108", # unnecessary-lambda # Ignore `E402` (import violations) in all `__init__.py` files "*/testsuite/**.py" = ["PT009", "PT027"] "__init__.py" = ["E402"] -"general/g.parser/test.py" = ["INT003"] +"display/d.mon/render_cmd.py" = ["SIM115"] "gui/**" = ["PLW0108"] # See https://github.com/OSGeo/grass/issues/4124 -"gui/wxpython/animation/dialogs.py" = ["INT002"] -"gui/wxpython/animation/temporal_manager.py" = ["INT003"] -"gui/wxpython/core/debug.py" = ["INT002"] -"gui/wxpython/core/render.py" = ["INT003"] -"gui/wxpython/gcp/manager.py" = ["INT002"] -"gui/wxpython/gmodeler/model.py" = ["INT001"] -"gui/wxpython/gmodeler/panels.py" = ["INT002", "INT003"] -"gui/wxpython/gui_core/ghelp.py" = ["INT003"] -"gui/wxpython/gui_core/gselect.py" = ["INT002"] -"gui/wxpython/gui_core/pyedit.py" = ["INT002"] -"gui/wxpython/gui_core/pystc.py" = ["INT002"] -"gui/wxpython/gui_core/query.py" = ["INT003"] -"gui/wxpython/history/browser.py" = ["INT002"] -"gui/wxpython/iclass/dialogs.py" = ["INT003"] -"gui/wxpython/iclass/frame.py" = ["FLY002", "INT003"] -"gui/wxpython/iclass/plots.py" = ["INT003"] +"gui/wxpython/animation/temporal_manager.py" = ["SIM115"] +"gui/wxpython/core/*.py" = ["SIM115"] +"gui/wxpython/dbmgr/base.py" = ["SIM115"] +"gui/wxpython/gcp/manager.py" = ["SIM115"] +"gui/wxpython/gmodeler/*.py" = ["SIM115"] +"gui/wxpython/gui_core/*.py" = ["SIM115"] +"gui/wxpython/iclass/frame*.py" = ["SIM115"] +"gui/wxpython/iclass/frame.py" = ["FLY002"] "gui/wxpython/iclass/statistics.py" = ["A005"] -"gui/wxpython/image2target/ii2t_gis_set.py" = ["INT003"] -"gui/wxpython/iscatt/controllers.py" = ["INT003"] -"gui/wxpython/iscatt/dialogs.py" = ["INT003"] -"gui/wxpython/iscatt/frame.py" = ["INT003"] -"gui/wxpython/iscatt/iscatt_core.py" = ["INT003"] +"gui/wxpython/image2target/*.py" = ["SIM115"] "gui/wxpython/iscatt/plots.py" = ["PLW0108"] -"gui/wxpython/lmgr/frame.py" = ["INT003"] -"gui/wxpython/lmgr/workspace.py" = ["INT002"] -"gui/wxpython/location_wizard/dialogs.py" = ["INT003"] -"gui/wxpython/location_wizard/wizard.py" = ["INT003"] -"gui/wxpython/main_window/frame.py" = ["INT003"] -"gui/wxpython/mapdisp/frame.py" = ["INT003"] -"gui/wxpython/mapdisp/test_mapdisp.py" = ["INT003"] -"gui/wxpython/mapwin/analysis.py" = ["INT003"] +"gui/wxpython/lmgr/workspace.py" = ["SIM115"] +"gui/wxpython/location_wizard/wizard.py" = ["SIM115"] +"gui/wxpython/mapdisp/main.py" = ["SIM115"] +"gui/wxpython/modules/colorrules.py" = ["SIM115"] +"gui/wxpython/modules/mcalc_builder.py" = ["SIM115"] +"gui/wxpython/photo2image/*.py" = ["SIM115"] +"gui/wxpython/psmap/*.py" = ["SIM115"] "gui/wxpython/psmap/utils.py" = ["PGH004"] -"gui/wxpython/rdigit/g.gui.rdigit.py" = ["INT002"] -"gui/wxpython/rlisetup/frame.py" = ["INT002"] -"gui/wxpython/rlisetup/functions.py" = ["INT003"] -"gui/wxpython/rlisetup/wizard.py" = ["INT003"] -"gui/wxpython/startup/locdownload.py" = ["INT002"] -"gui/wxpython/timeline/frame.py" = ["FLY002", "INT003"] -"gui/wxpython/tplot/frame.py" = ["FLY002", "INT002", "INT003"] -"gui/wxpython/vnet/vnet_data.py" = ["INT003"] -"gui/wxpython/web_services/dialogs.py" = ["INT003"] -"gui/wxpython/web_services/widgets.py" = ["INT003"] -"gui/wxpython/wxgui.py" = ["INT002"] +"gui/wxpython/rdigit/controller.py" = ["SIM115"] +"gui/wxpython/rlisetup/*.py" = ["SIM115"] +"gui/wxpython/timeline/frame.py" = ["FLY002"] +"gui/wxpython/tools/update_menudata.py" = ["SIM115"] +"gui/wxpython/tplot/frame.py" = ["FLY002"] +"gui/wxpython/vdigit/mapwindow.py" = ["SIM115"] +"gui/wxpython/vnet/*.py" = ["SIM115"] +"gui/wxpython/web_services/dialogs.py" = ["SIM115"] +"gui/wxpython/wxplot/profile*.py" = ["SIM115"] "gui/wxpython/wxplot/profile.py" = ["A005"] +"imagery/i.atcorr/create_iwave.py" = ["SIM115"] +"lib/imagery/testsuite/test_imagery_signature_management.py" = ["SIM115"] "lib/imagery/testsuite/test_imagery_sigsetfile.py" = ["FURB152"] -"lib/init/grass.py" = ["INT003"] +"lib/init/grass.py" = ["SIM115"] +"locale/grass_po_stats.py" = ["SIM115"] +"man/build_*.py" = ["SIM115"] +"man/parser_standard_options.py" = ["SIM115"] "python/grass/__init__.py" = ["PYI056"] "python/grass/exp*/tests/grass_script_mapset_session_test.py" = ["SIM117"] "python/grass/exp*/tests/grass_script_tmp_mapset_session_test.py" = ["SIM117"] +"python/grass/gunittest/case.py" = ["PT009"] "python/grass/gunittest/loader.py" = ["PYI024"] "python/grass/gunittest/multireport.py" = ["PYI024"] "python/grass/gunittest/testsu*/d*/s*/s*/subsub*/t*/test_segfaut.py" = ["B018"] "python/grass/gunittest/testsuite/test_assertions_rast3d.py" = ["FLY002"] -"python/grass/jupyter/tests/reprojection_renderer_test.py" = ["PT013"] +"python/grass/imaging/images2*.py" = ["SIM115"] "python/grass/jupyter/testsuite/interactivemap_test.py" = ["PGH004"] "python/grass/jupyter/testsuite/map_test.py" = ["PGH004"] "python/grass/pydispatch/signal.py" = ["A005"] -"python/grass/pygrass/raster/category.py" = ["INT002"] -"python/grass/pygrass/vector/__init__.py" = ["INT003"] +"python/grass/pygrass/modules/grid/grid.py" = ["SIM115"] +"python/grass/pygrass/modules/interface/env.py" = ["SIM115"] +"python/grass/pygrass/raster/segment.py" = ["SIM115"] +"python/grass/pygrass/tests/*.py" = ["SIM115"] "python/grass/pygrass/vector/geometry.py" = ["PYI024"] "python/grass/pygrass/vector/sql.py" = ["FLY002"] "python/grass/pygrass/vector/testsuite/test_table.py" = ["PLW0108"] "python/grass/script/array.py" = ["A005"] -"python/grass/script/raster.py" = ["INT003"] -"python/grass/temporal/abstract_space_time_dataset.py" = ["INT003"] -"python/grass/temporal/aggregation.py" = ["INT003"] -"python/grass/temporal/c_libraries_interface.py" = ["INT003"] -"python/grass/temporal/core.py" = ["INT002", "INT003"] -"python/grass/temporal/datetime_math.py" = ["INT003"] -"python/grass/temporal/mapcalc.py" = ["INT003"] -"python/grass/temporal/space_time_datasets.py" = ["INT003"] -"python/grass/temporal/stds_export.py" = ["INT003"] -"python/grass/temporal/stds_import.py" = ["INT003"] -"python/grass/temporal/temporal_algebra.py" = ["INT003"] -"python/grass/temporal/temporal_raster_base_algebra.py" = ["INT003"] -"python/grass/temporal/univar_statistics.py" = ["INT002"] +"python/grass/script/core.py" = ["SIM115"] +"python/grass/script/db.py" = ["SIM115"] +"python/grass/script/raster.py" = ["SIM115"] +"python/grass/script/utils.py" = ["SIM115"] +"python/grass/temporal/aggregation.py" = ["SIM115"] +"python/grass/temporal/register.py" = ["SIM115"] +"python/grass/temporal/stds_export.py" = ["SIM115"] +"python/grass/temporal/stds_import.py" = ["SIM115"] +"python/grass/temporal/univar_statistics.py" = ["SIM115"] +"python/grass/utils/download.py" = ["SIM115"] +"raster/r.*/testsuite/*.py" = ["SIM115"] +"raster/r.topidx/*.py" = ["SIM115"] "raster3d/r3.flow/testsuite/r3flow_test.py" = ["FLY002"] "raster3d/r3.gradient/testsuite/r3gradient_test.py" = ["FLY002"] -"scripts/d.polar/d.polar.py" = ["FURB154", "INT002"] -"scripts/g.extension.all/g.extension.all.py" = ["INT002"] -"scripts/g.extension/g.extension.py" = ["INT002"] -"scripts/i.oif/i.oif.py" = ["INT003"] -"scripts/i.pansharpen/i.pansharpen.py" = ["FLY002", "INT003"] -"scripts/i.spectral/i.spectral.py" = ["FLY002", "INT002"] -"scripts/r.in.srtm/r.in.srtm.py" = ["FLY002"] -"scripts/r.in.wms/wms_base.py" = ["INT003"] -"scripts/r.in.wms/wms_cap_parsers.py" = ["INT003"] -"scripts/r.in.wms/wms_drv.py" = ["INT003"] -"scripts/r.in.wms/wms_gdal_drv.py" = ["INT003"] -"scripts/r.pack/r.pack.py" = ["INT003"] -"scripts/r.tileset/r.tileset.py" = ["INT003"] -"scripts/r.unpack/r.unpack.py" = ["INT002"] -"scripts/v.rast.stats/v.rast.stats.py" = ["INT002"] -"scripts/v.to.lines/v.to.lines.py" = ["INT003"] -"scripts/v.unpack/v.unpack.py" = ["INT002", "INT003"] -"scripts/v.what.strds/v.what.strds.py" = ["INT003"] -"temporal/t.rast.accdetect/t.rast.accdetect.py" = ["INT003"] -"temporal/t.rast.accumulate/t.rast.accumulate.py" = ["INT003"] +"scripts/d.correlate/d.correlate.py" = ["SIM115"] +"scripts/d.frame/d.frame.py" = ["SIM115"] +"scripts/d.polar/d.polar.py" = ["FURB154", "SIM115"] +"scripts/db.in.ogr/db.in.ogr.py" = ["SIM115"] +"scripts/db.test/db.test.py" = ["SIM115"] +"scripts/db.univar/db.univar.py" = ["SIM115"] +"scripts/g.extension.all/g.extension.all.py" = ["SIM115"] +"scripts/g.extension/g.extension.py" = ["SIM115"] +"scripts/g.search.modules/g.search.modules.py" = ["SIM115"] +"scripts/i.in.spotvgt/i.in.spotvgt.py" = ["SIM115"] +"scripts/i.oif/i.oif*.py" = ["SIM115"] +"scripts/i.pansharpen/i.pansharpen.py" = ["FLY002", "SIM115"] +"scripts/i.spectral/i.spectral.py" = ["FLY002", "SIM115"] +"scripts/m.proj/m.proj.py" = ["SIM115"] +"scripts/r.fillnulls/r.fillnulls.py" = ["SIM115"] +"scripts/r.in.srtm/r.in.srtm.py" = ["FLY002", "SIM115"] +"scripts/r.in.wms/wms_*.py" = ["SIM115"] +"scripts/r.tileset/r.tileset.py" = ["SIM115"] +"scripts/v.*/v.*.py" = ["SIM115"] +"scripts/wxpyimgview/wxpyimgview_gui.py" = ["SIM115"] +"temporal/t.list/t.list.py" = ["SIM115"] "temporal/t.rast.algebra/testsu*/*_algebra_arithmetic.py" = ["FLY002"] -"temporal/t.rast.export/t.rast.export.py" = ["INT002"] -"temporal/t.rast.gapfill/t.rast.gapfill.py" = ["INT003"] -"temporal/t.rast.list/t.rast.list.py" = ["INT002"] -"temporal/t.rast.out.vtk/t.rast.out.vtk.py" = ["INT003"] -"temporal/t.rast.series/t.rast.series.py" = ["INT002"] -"temporal/t.rast.to.rast3/t.rast.to.rast3.py" = ["INT003"] -"temporal/t.rast.what/t.rast.what.py" = ["INT003"] +"temporal/t.rast.colors/t.rast.colors.py" = ["SIM115"] +"temporal/t.rast.series/t.rast.series.py" = ["SIM115"] +"temporal/t.rast.what/t.rast.what.py" = ["SIM115"] "temporal/t.register/testsu*/*_raster_different_local.py" = ["FLY002"] "temporal/t.register/testsu*/*_raster_mapmetadata.py" = ["FLY002"] "temporal/t.register/testsuite/test_t_register_raster.py" = ["FLY002"] "temporal/t.register/testsuite/test_t_register_raster_file.py" = ["FLY002"] -"temporal/t.remove/t.remove.py" = ["INT002", "INT003"] -"temporal/t.unregister/t.unregister.py" = ["INT003"] -"temporal/t.vect.observe.strds/t.vect.observe.strds.py" = ["INT003"] +"temporal/t.remove/t.remove.py" = ["SIM115"] +"temporal/t.unregister/t.unregister.py" = ["SIM115"] +"utils/**.py" = ["SIM115"] "utils/generate_release_notes.py" = ["PGH004"] -"utils/mkhtml.py" = ["INT002"] "vector/v.fill.holes/examples.ipynb" = ["PTH201"] [tool.ruff.lint.flake8-import-conventions.extend-aliases] diff --git a/python/grass/app/data.py b/python/grass/app/data.py index 439a6c3c4d1..10997cd59e8 100644 --- a/python/grass/app/data.py +++ b/python/grass/app/data.py @@ -15,8 +15,12 @@ import os import tempfile import getpass +import subprocess import sys from shutil import copytree, ignore_patterns +from pathlib import Path + +import grass.script as gs import grass.grassdb.config as cfg from grass.grassdb.checks import is_location_valid @@ -162,3 +166,69 @@ def ensure_default_data_hierarchy(): mapset_path = os.path.join(gisdbase, location, mapset) return gisdbase, location, mapset, mapset_path + + +class MapsetLockingException(Exception): + pass + + +def lock_mapset(mapset_path, force_lock_removal, message_callback): + """Acquire a lock for a mapset and return name of new lock file + + Raises MapsetLockingException when it is not possible to acquire a lock for the + given mapset either because of existing lock or due to insufficient permissions. + A corresponding localized message is given in the exception. + + A *message_callback* is a function which will be called to report messages about + certain states. Specifically, the function is called when forcibly unlocking the + mapset. + + Assumes that the runtime is set up (specifically that GISBASE is in + the environment). + """ + if not os.path.exists(mapset_path): + raise MapsetLockingException(_("Path '{}' doesn't exist").format(mapset_path)) + if not os.access(mapset_path, os.W_OK): + error = _("Path '{}' not accessible.").format(mapset_path) + stat_info = Path(mapset_path).stat() + mapset_uid = stat_info.st_uid + if mapset_uid != os.getuid(): + error = "{error}\n{detail}".format( + error=error, + detail=_("You are not the owner of '{}'.").format(mapset_path), + ) + raise MapsetLockingException(error) + # Check for concurrent use + lockfile = os.path.join(mapset_path, ".gislock") + locker_path = os.path.join(os.environ["GISBASE"], "etc", "lock") + ret = subprocess.run( + [locker_path, lockfile, "%d" % os.getpid()], check=False + ).returncode + msg = None + if ret == 2: + if not force_lock_removal: + msg = _( + "{user} is currently running GRASS in selected mapset" + " (file {file} found). Concurrent use of one mapset not allowed.\n" + "You can force launching GRASS using -f flag" + " (assuming your have sufficient access permissions)." + " Confirm in a process manager " + "that there is no other process using the mapset." + ).format(user=Path(lockfile).owner(), file=lockfile) + else: + message_callback( + _( + "{user} is currently running GRASS in selected mapset" + " (file {file} found), but forcing to launch GRASS anyway..." + ).format(user=Path(lockfile).owner(), file=lockfile) + ) + gs.try_remove(lockfile) + elif ret != 0: + msg = _( + "Unable to properly access lock file '{name}'.\n" + "Please resolve this with your system administrator." + ).format(name=lockfile) + + if msg: + raise MapsetLockingException(msg) + return lockfile diff --git a/python/grass/app/runtime.py b/python/grass/app/runtime.py index 5da00bae0df..3f3805c9dfd 100644 --- a/python/grass/app/runtime.py +++ b/python/grass/app/runtime.py @@ -129,6 +129,7 @@ def set_paths(install_path, grass_config_dir, ld_library_path_variable_name): # retrieving second time, but now it is always set addon_base = os.getenv("GRASS_ADDON_BASE") set_man_path(install_path=install_path, addon_base=addon_base, env=os.environ) + set_isis() def set_man_path(install_path, addon_base, env): @@ -274,6 +275,25 @@ def set_browser(install_path): os.environ["GRASS_HTML_BROWSER"] = browser +def set_isis(): + """Enable a mixed ISIS-GRASS environment + + ISIS is Integrated Software for Imagers and Spectrometers by USGS. + """ + if os.getenv("ISISROOT"): + isis = os.getenv("ISISROOT") + os.environ["ISIS_LIB"] = isis + os.sep + "lib" + os.environ["ISIS_3RDPARTY"] = isis + os.sep + "3rdParty" + os.sep + "lib" + os.environ["QT_PLUGIN_PATH"] = isis + os.sep + "3rdParty" + os.sep + "plugins" + # os.environ['ISIS3DATA'] = isis + "$ISIS3DATA" + libpath = os.getenv("LD_LIBRARY_PATH", "") + isislibpath = os.getenv("ISIS_LIB") + isis3rdparty = os.getenv("ISIS_3RDPARTY") + os.environ["LD_LIBRARY_PATH"] = ( + libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty + ) + + def ensure_home(): """Set HOME if not set on MS Windows""" if WINDOWS and not os.getenv("HOME"): diff --git a/python/grass/experimental/tests/grass_script_mapset_session_test.py b/python/grass/experimental/tests/grass_script_mapset_session_test.py index 3877e61576e..740770937dd 100644 --- a/python/grass/experimental/tests/grass_script_mapset_session_test.py +++ b/python/grass/experimental/tests/grass_script_mapset_session_test.py @@ -68,7 +68,8 @@ def test_create_overwrite(xy_session): .strip() .split() ) - assert len(rasters) == 1 and rasters[0] == "a" + assert len(rasters) == 1 + assert rasters[0] == "a" with experimental.MapsetSession( name, create=True, overwrite=True, env=xy_session.env ) as session: @@ -86,7 +87,8 @@ def test_create_overwrite(xy_session): .strip() .split() ) - assert len(rasters) == 1 and rasters[0] == "a" + assert len(rasters) == 1 + assert rasters[0] == "a" assert os.path.exists(session_file) @@ -103,7 +105,8 @@ def test_ensure(xy_session): .strip() .split() ) - assert len(rasters) == 1 and rasters[0] == "a" + assert len(rasters) == 1 + assert rasters[0] == "a" with experimental.MapsetSession(name, ensure=True, env=xy_session.env) as session: session_mapset = gs.read_command("g.mapset", flags="p", env=session.env).strip() assert name == session_mapset @@ -112,7 +115,8 @@ def test_ensure(xy_session): .strip() .split() ) - assert len(rasters) == 1 and rasters[0] == "a" + assert len(rasters) == 1 + assert rasters[0] == "a" gs.run_command("r.mapcalc", expression="b = 1", env=session.env) rasters = ( gs.read_command("g.list", type="raster", mapset=".", env=session.env) diff --git a/python/grass/experimental/tests/grass_script_tmp_mapset_session_test.py b/python/grass/experimental/tests/grass_script_tmp_mapset_session_test.py index 744becc1e7b..f7098004527 100644 --- a/python/grass/experimental/tests/grass_script_tmp_mapset_session_test.py +++ b/python/grass/experimental/tests/grass_script_tmp_mapset_session_test.py @@ -74,7 +74,7 @@ def test_without_context_manager(xy_session): def test_multiple_sequential_with_context_manager(xy_session): """Session creates, starts, and finishes""" session_file = xy_session.env["GISRC"] - for i in range(0, 5): + for i in range(5): with experimental.TemporaryMapsetSession(env=xy_session.env) as session: assert session.active gs.run_command("g.region", flags="p", env=session.env) @@ -104,7 +104,7 @@ def test_multiple_parallel_without_context_manager(xy_session): """Session creates, starts, and finishes""" session_file = xy_session.env["GISRC"] sessions = [] - for i in range(0, 5): + for i in range(5): session_file = xy_session.env["GISRC"] session = experimental.TemporaryMapsetSession(env=xy_session.env) gs.run_command("g.region", flags="p", env=session.env) diff --git a/python/grass/grassdb/checks.py b/python/grass/grassdb/checks.py index 4de65a4cba3..369cdf60e62 100644 --- a/python/grass/grassdb/checks.py +++ b/python/grass/grassdb/checks.py @@ -113,7 +113,7 @@ def is_current_user_mapset_owner(mapset_path): # Mapset needs to be owned by user. if sys.platform == "win32": return True - stat_info = os.stat(mapset_path) + stat_info = Path(mapset_path).stat() mapset_uid = stat_info.st_uid return mapset_uid == os.getuid() @@ -159,7 +159,7 @@ def is_first_time_user(): genv = gisenv() if "LAST_MAPSET_PATH" in genv.keys(): return genv["LAST_MAPSET_PATH"] == os.path.join( - os.getcwd(), cfg.unknown_location, cfg.unknown_mapset + Path.cwd(), cfg.unknown_location, cfg.unknown_mapset ) return False @@ -222,13 +222,13 @@ def get_reason_id_mapset_not_usable(mapset_path): if not os.path.exists(mapset_path): return "non-existent" # Check whether mapset is valid - elif not is_mapset_valid(mapset_path): + if not is_mapset_valid(mapset_path): return "invalid" # Check whether mapset is owned by current user - elif not is_current_user_mapset_owner(mapset_path): + if not is_current_user_mapset_owner(mapset_path): return "different-owner" # Check whether mapset is locked - elif is_mapset_locked(mapset_path): + if is_mapset_locked(mapset_path): return "locked" return None diff --git a/python/grass/grassdb/history.py b/python/grass/grassdb/history.py index 60b5459700d..d7c22eb36fc 100644 --- a/python/grass/grassdb/history.py +++ b/python/grass/grassdb/history.py @@ -81,9 +81,7 @@ def _read_from_plain_text(history_path): stores only executed commands.""" content_list = [] try: - with open( - history_path, encoding="utf-8", mode="r", errors="replace" - ) as file_history: + with open(history_path, encoding="utf-8", errors="replace") as file_history: content_list = [ {"command": line.strip(), "command_info": None} for line in file_history ] @@ -287,7 +285,7 @@ def _add_entry_to_JSON(history_path, entry): :param dict entry: entry consisting of 'command' and 'command_info' keys """ try: - with open(history_path, encoding="utf-8", mode="r") as file_history: + with open(history_path, encoding="utf-8") as file_history: existing_data = json.load(file_history) except (OSError, ValueError): existing_data = [] diff --git a/python/grass/grassdb/testsuite/test_manage.py b/python/grass/grassdb/testsuite/test_manage.py index a2788d4f1a8..43b8945bd31 100644 --- a/python/grass/grassdb/testsuite/test_manage.py +++ b/python/grass/grassdb/testsuite/test_manage.py @@ -18,6 +18,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.gmodules import call_module from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows class TestMapsetPath(TestCase): @@ -38,6 +39,7 @@ def test_mapset_from_path_object(self): self.assertEqual(mapset_path.mapset, mapset_name) self.assertEqual(mapset_path.path, Path(path) / location_name / mapset_name) + @xfail_windows def test_mapset_from_str(self): """Check with path from str and database directory as Path""" path = "does/not/exist" @@ -60,6 +62,7 @@ def test_mapset_from_str(self): class TestSplitMapsetPath(TestCase): """Check that split works with different parameters""" + @xfail_windows def test_split_path(self): """Check that pathlib.Path is correctly split""" ref_db = "does/not/exist" @@ -71,6 +74,7 @@ def test_split_path(self): self.assertEqual(new_location, ref_location) self.assertEqual(new_mapset, ref_mapset) + @xfail_windows def test_split_str(self): """Check that path as str is correctly split""" ref_db = "does/not/exist" @@ -82,6 +86,7 @@ def test_split_str(self): self.assertEqual(new_location, ref_location) self.assertEqual(new_mapset, ref_mapset) + @xfail_windows def test_split_str_trailing_slash(self): """Check that path as str with a trailing slash is correctly split""" ref_db = "does/not/exist" diff --git a/python/grass/gunittest/case.py b/python/grass/gunittest/case.py index 4d1b37bdfed..1277ee542b5 100644 --- a/python/grass/gunittest/case.py +++ b/python/grass/gunittest/case.py @@ -10,6 +10,7 @@ """ import os +from pathlib import Path import shutil import subprocess import hashlib @@ -694,7 +695,7 @@ def assertFileMd5(self, filename, md5, text=False, msg=None): actual = text_file_md5(filename) else: actual = file_md5(filename) - if not actual == md5: + if actual != md5: standardMsg = ( "File <{name}> does not have the right MD5 sum.\n" "Expected is <{expected}>," @@ -735,10 +736,9 @@ def _get_unique_name(self, name): # and ensure uniqueness by add UUID if self.readable_names: return "tmp_" + self.id().replace(".", "_") + "_" + name - else: - # UUID might be overkill (and expensive) but it's safe and simple - # alternative is to create hash from the readable name - return "tmp_" + str(uuid.uuid4()).replace("-", "") + # UUID might be overkill (and expensive) but it's safe and simple + # alternative is to create hash from the readable name + return "tmp_" + str(uuid.uuid4()).replace("-", "") def _compute_difference_raster(self, first, second, name_part): """Compute difference of two rasters (first - second) @@ -1227,8 +1227,9 @@ def assertVectorAsciiEqualsVectorAscii( """ import difflib - fromlines = open(actual).readlines() - tolines = open(reference).readlines() + with open(actual) as f1, open(reference) as f2: + fromlines = f1.readlines() + tolines = f2.readlines() context_lines = 3 # number of context lines # TODO: filenames are set to "actual" and "reference", isn't it too general? # it is even more useful if map names or file names are some generated @@ -1252,18 +1253,18 @@ def assertVectorAsciiEqualsVectorAscii( os.remove(reference) stdmsg = "There is a difference between vectors when compared as ASCII files.\n" - output = StringIO() # TODO: there is a diff size constant which we can use # we are setting it unlimited but we can just set it large maxlines = 100 i = 0 - for line in diff: - if i >= maxlines: - break - output.write(line) - i += 1 - stdmsg += output.getvalue() - output.close() + with StringIO() as output: + for line in diff: + if i >= maxlines: + break + output.write(line) + i += 1 + stdmsg += output.getvalue() + # it seems that there is not better way of asking whether there was # a difference (always a iterator object is returned) if i > 0: @@ -1288,11 +1289,9 @@ def assertVectorAsciiEqualsVectorAscii( "actual", context=True, numlines=context_lines, + charset="utf-8", ) - htmldiff_file = open(htmldiff_file_name, "w") - for line in htmldiff: - htmldiff_file.write(line) - htmldiff_file.close() + Path(htmldiff_file_name).write_text(htmldiff, encoding="utf-8") self.fail(self._formatMessage(msg, stdmsg)) diff --git a/python/grass/gunittest/checkers.py b/python/grass/gunittest/checkers.py index fb46a1deb66..c63f6d08ff0 100644 --- a/python/grass/gunittest/checkers.py +++ b/python/grass/gunittest/checkers.py @@ -638,7 +638,7 @@ def text_file_md5( if prepend_lines: for line in prepend_lines: hasher.update(encode(line)) - with open(filename, "r") as f: + with open(filename) as f: for line in f: # replace platform newlines by standard newline if os.linesep != "\n": diff --git a/python/grass/gunittest/loader.py b/python/grass/gunittest/loader.py index 33234e2b083..50fa368f62a 100644 --- a/python/grass/gunittest/loader.py +++ b/python/grass/gunittest/loader.py @@ -6,17 +6,28 @@ License (>=v2). Read the file COPYING that comes with GRASS GIS for details. -:authors: Vaclav Petras +:authors: Vaclav Petras, Edouard Choinière """ -import os -import fnmatch -import unittest +from __future__ import annotations + import collections +import fnmatch +import os import re +import unittest +from pathlib import PurePath +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Iterable -def fnmatch_exclude_with_base(files, base, exclude): +def fnmatch_exclude_with_base( + files: Iterable[str], + base: str | os.PathLike, + exclude: Iterable[str | os.PathLike | PurePath], +) -> list[str]: """Return list of files not matching any exclusion pattern :param files: list of file names @@ -24,23 +35,13 @@ def fnmatch_exclude_with_base(files, base, exclude): :param exclude: list of fnmatch glob patterns for exclusion """ not_excluded = [] - patterns = [] - # Make all dir separators slashes and drop leading current dir - # for both patterns and (later) for files. - for pattern in exclude: - pattern = pattern.replace(os.sep, "/") - if pattern.startswith("./"): - patterns.append(pattern[2:]) - else: - patterns.append(pattern) + patterns = {str(PurePath(item)) for item in exclude} + base_path = PurePath(base) for filename in files: - full_file_path = os.path.join(base, filename) - test_filename = full_file_path.replace(os.sep, "/") - if full_file_path.startswith("./"): - test_filename = full_file_path[2:] + test_filename: PurePath = base_path / filename matches = False for pattern in patterns: - if fnmatch.fnmatch(test_filename, pattern): + if fnmatch.fnmatch(str(test_filename), pattern): matches = True break if not matches: @@ -116,16 +117,16 @@ def discover_modules( dirs.remove(testsuite_dir) # do not recurse to testsuite full = os.path.join(root, testsuite_dir) - all_files = os.listdir(full) + files = os.listdir(full) if file_pattern: - files = fnmatch.filter(all_files, file_pattern) + files = fnmatch.filter(files, file_pattern) if file_regexp: - files = [f for f in all_files if re.match(file_regexp, f)] + files = [f for f in files if re.match(file_regexp, f)] if exclude: files = fnmatch_exclude_with_base(files, full, exclude) files = sorted(files) # get test/module name without .py - # extpecting all files to end with .py + # expecting all files to end with .py # this will not work for invoking bat files but it works fine # as long as we handle only Python files (and using Python # interpreter for invoking) @@ -234,4 +235,18 @@ def discover(self, start_dir, pattern="test*.py", top_level_dir=None): if __name__ == "__main__": - GrassTestLoader().discover() + for expression in [r".*\.py$", r".*\.sh$"]: + modules = discover_modules( + start_dir=".", + grass_location="all", + file_regexp=expression, + skip_dirs=GrassTestLoader.skip_dirs, + testsuite_dir=GrassTestLoader.testsuite_dir, + all_locations_value=GrassTestLoader.all_tests_value, + universal_location_value=GrassTestLoader.universal_tests_value, + import_modules=False, + exclude=None, + ) + print("Expression:", expression) + print(len(modules)) + print([module.file_path for module in modules]) diff --git a/python/grass/gunittest/multireport.py b/python/grass/gunittest/multireport.py index edeb98636ee..c5f36a6e0db 100644 --- a/python/grass/gunittest/multireport.py +++ b/python/grass/gunittest/multireport.py @@ -16,6 +16,7 @@ import datetime import operator from collections import defaultdict, namedtuple +from pathlib import Path from grass.gunittest.checkers import text_to_keyvalue from grass.gunittest.utils import ensure_dir @@ -103,8 +104,7 @@ def median(values): sorted_values = sorted(values) if n % 2 == 0: return (sorted_values[n / 2 - 1] + sorted_values[n / 2]) / 2 - else: - return sorted_values[n / 2] + return sorted_values[n / 2] # this is useful for debugging or some other stat # cmeans = [] @@ -472,7 +472,7 @@ def main(): # skipping incomplete reports # use only results list for further processing continue - summary = text_to_keyvalue(open(summary_file).read(), sep="=") + summary = text_to_keyvalue(Path(summary_file).read_text(), sep="=") if use_timestamps: test_timestamp = datetime.datetime.fromtimestamp( os.path.getmtime(summary_file) @@ -516,147 +516,156 @@ def main(): except KeyError as e: print("File %s does not have right values (%s)" % (report, e.message)) - locations_main_page = open(os.path.join(output, "index.html"), "w") - locations_main_page.write( - "" - "

    Test reports grouped by location type

    " - "
    207Worldview4 Red band (639nm - 711nm)
    208Worldview4 NIR1 band (732nm - 962nm)
    208AVIRIS b1 band (365nm)
    209AVIRIS b2 band (375nm)
    209AVIRIS b1 band (365nm)
    210AVIRIS b2 band (375nm)
    .AVIRIS b. band (+10nm)
    431AVIRIS b223 band (2486nm)
    432AVIRIS b224 band (2496nm)
    433Hyperion VNIR b8 band (427nm)
    433Hyperion VNIR b8 band (427nm)
    434Hyperion VNIR b9 band (437.16326nm)
    .Hyperion VNIR b. band (+10.16326nm)
    480Hyperion VNIR b56 band (914.83648nm)
    " - "" - "" - "" - "" - "" - ) + with open(os.path.join(output, "index.html"), "w") as locations_main_page: + locations_main_page.write( + "" + "

    Test reports grouped by location type

    " + "
    LocationSuccessful filesSuccessful tests
    " + "" + "" + "" + "" + "" + ) - PlotStyle = namedtuple( - "PlotStyle", - ["linestyle", "linewidth", "success_color", "fail_color", "total_color"], - ) - plot_style = PlotStyle( - linestyle="-", linewidth=4.0, success_color="g", fail_color="r", total_color="b" - ) + PlotStyle = namedtuple( + "PlotStyle", + ["linestyle", "linewidth", "success_color", "fail_color", "total_color"], + ) + plot_style = PlotStyle( + linestyle="-", + linewidth=4.0, + success_color="g", + fail_color="r", + total_color="b", + ) - for location_type, results in results_in_locations.items(): - results = sorted(results, key=operator.attrgetter("timestamp")) - # TODO: document: location type must be a valid dir name - directory = os.path.join(output, location_type) - ensure_dir(directory) + for location_type, results in results_in_locations.items(): + results = sorted(results, key=operator.attrgetter("timestamp")) + # TODO: document: location type must be a valid dir name + directory = os.path.join(output, location_type) + ensure_dir(directory) - if location_type == "unknown": - title = "Test reports" - else: - title = "Test reports for <{type}> location type".format( - type=location_type + if location_type == "unknown": + title = "Test reports" + else: + title = "Test reports for <{type}> location type".format( + type=location_type + ) + + x = [date2num(result.timestamp) for result in results] + # the following would be an alternative but it does not work with + # labels and automatic axis limits even after removing another date fun + # x = [result.svn_revision for result in results] + xlabels = [ + result.timestamp.strftime("%Y-%m-%d") + + " (r" + + result.svn_revision + + ")" + for result in results + ] + step = len(x) / 10 + xticks = x[step::step] + xlabels = xlabels[step::step] + tests_successful_plot( + x=x, + xticks=xticks, + xlabels=xlabels, + results=results, + filename=os.path.join(directory, "tests_successful_plot.png"), + style=plot_style, + ) + files_successful_plot( + x=x, + xticks=xticks, + xlabels=xlabels, + results=results, + filename=os.path.join(directory, "files_successful_plot.png"), + style=plot_style, + ) + tests_plot( + x=x, + xticks=xticks, + xlabels=xlabels, + results=results, + filename=os.path.join(directory, "tests_plot.png"), + style=plot_style, + ) + tests_percent_plot( + x=x, + xticks=xticks, + xlabels=xlabels, + results=results, + filename=os.path.join(directory, "tests_percent_plot.png"), + style=plot_style, + ) + files_plot( + x=x, + xticks=xticks, + xlabels=xlabels, + results=results, + filename=os.path.join(directory, "files_plot.png"), + style=plot_style, + ) + files_percent_plot( + x=x, + xticks=xticks, + xlabels=xlabels, + results=results, + filename=os.path.join(directory, "files_percent_plot.png"), + style=plot_style, + ) + info_plot( + x=x, + xticks=xticks, + xlabels=xlabels, + results=results, + filename=os.path.join(directory, "info_plot.png"), + style=plot_style, ) - x = [date2num(result.timestamp) for result in results] - # the following would be an alternative but it does not work with - # labels and automatic axis limits even after removing another date fun - # x = [result.svn_revision for result in results] - xlabels = [ - result.timestamp.strftime("%Y-%m-%d") + " (r" + result.svn_revision + ")" - for result in results - ] - step = len(x) / 10 - xticks = x[step::step] - xlabels = xlabels[step::step] - tests_successful_plot( - x=x, - xticks=xticks, - xlabels=xlabels, - results=results, - filename=os.path.join(directory, "tests_successful_plot.png"), - style=plot_style, - ) - files_successful_plot( - x=x, - xticks=xticks, - xlabels=xlabels, - results=results, - filename=os.path.join(directory, "files_successful_plot.png"), - style=plot_style, - ) - tests_plot( - x=x, - xticks=xticks, - xlabels=xlabels, - results=results, - filename=os.path.join(directory, "tests_plot.png"), - style=plot_style, - ) - tests_percent_plot( - x=x, - xticks=xticks, - xlabels=xlabels, - results=results, - filename=os.path.join(directory, "tests_percent_plot.png"), - style=plot_style, - ) - files_plot( - x=x, - xticks=xticks, - xlabels=xlabels, - results=results, - filename=os.path.join(directory, "files_plot.png"), - style=plot_style, - ) - files_percent_plot( - x=x, - xticks=xticks, - xlabels=xlabels, - results=results, - filename=os.path.join(directory, "files_percent_plot.png"), - style=plot_style, - ) - info_plot( - x=x, - xticks=xticks, - xlabels=xlabels, - results=results, - filename=os.path.join(directory, "info_plot.png"), - style=plot_style, - ) + main_page( + results=results, + filename="index.html", + images=[ + "tests_successful_plot.png", + "files_successful_plot.png", + "tests_plot.png", + "files_plot.png", + "tests_percent_plot.png", + "files_percent_plot.png", + "info_plot.png", + ], + captions=[ + "Success of individual tests in percents", + "Success of test files in percents", + "Successes, failures and number of individual tests", + "Successes, failures and number of test files", + "Successes and failures of individual tests in percent", + "Successes and failures of test files in percents", + "Additional information", + ], + directory=directory, + title=title, + ) - main_page( - results=results, - filename="index.html", - images=[ - "tests_successful_plot.png", - "files_successful_plot.png", - "tests_plot.png", - "files_plot.png", - "tests_percent_plot.png", - "files_percent_plot.png", - "info_plot.png", - ], - captions=[ - "Success of individual tests in percents", - "Success of test files in percents", - "Successes, failures and number of individual tests", - "Successes, failures and number of test files", - "Successes and failures of individual tests in percent", - "Successes and failures of test files in percents", - "Additional information", - ], - directory=directory, - title=title, - ) + files_successes = sum(result.files_successes for result in results) + files_total = sum(result.files_total for result in results) + successes = sum(result.successes for result in results) + total = sum(result.total for result in results) + per_test = success_to_html_percent(total=total, successes=successes) + per_file = success_to_html_percent( + total=files_total, successes=files_successes + ) + locations_main_page.write( + "" + "" + "" + "".format(location=location_type, pfiles=per_file, ptests=per_test) + ) + locations_main_page.write("
    LocationSuccessful filesSuccessful tests
    {location}{pfiles}{ptests}
    ") + locations_main_page.write("") - files_successes = sum(result.files_successes for result in results) - files_total = sum(result.files_total for result in results) - successes = sum(result.successes for result in results) - total = sum(result.total for result in results) - per_test = success_to_html_percent(total=total, successes=successes) - per_file = success_to_html_percent(total=files_total, successes=files_successes) - locations_main_page.write( - "" - "{location}" - "{pfiles}{ptests}" - "".format(location=location_type, pfiles=per_file, ptests=per_test) - ) - locations_main_page.write("") - locations_main_page.write("") - locations_main_page.close() return 0 diff --git a/python/grass/gunittest/multirunner.py b/python/grass/gunittest/multirunner.py index fd648406332..ebb9e80049a 100644 --- a/python/grass/gunittest/multirunner.py +++ b/python/grass/gunittest/multirunner.py @@ -30,15 +30,13 @@ def _get_encoding(): def decode(bytes_, encoding=None): if isinstance(bytes_, bytes): return bytes_.decode(_get_encoding()) - else: - return bytes_ + return bytes_ def encode(string, encoding=None): if isinstance(string, str): return string.encode(_get_encoding()) - else: - return string + return string def text_to_string(text): diff --git a/python/grass/gunittest/reporters.py b/python/grass/gunittest/reporters.py index 0911ca0fdd7..09f371dfffc 100644 --- a/python/grass/gunittest/reporters.py +++ b/python/grass/gunittest/reporters.py @@ -51,12 +51,9 @@ def replace_in_file(file_path, pattern, repl): """ # using tmp file to store the replaced content tmp_file_path = file_path + ".tmp" - old_file = open(file_path, "r") - new_file = open(tmp_file_path, "w") - for line in old_file: - new_file.write(re.sub(pattern=pattern, string=line, repl=repl)) - new_file.close() - old_file.close() + with open(file_path) as old_file, open(tmp_file_path, "w") as new_file: + for line in old_file: + new_file.write(re.sub(pattern=pattern, string=line, repl=repl)) # remove old file since it must not exist for rename/move os.remove(file_path) # replace old file by new file @@ -113,8 +110,7 @@ def get_source_url(path, revision, line=None): tracurl = "http://trac.osgeo.org/grass/browser/" if line: return "{tracurl}{path}?rev={revision}#L{line}".format(**locals()) - else: - return "{tracurl}{path}?rev={revision}".format(**locals()) + return "{tracurl}{path}?rev={revision}".format(**locals()) def html_escape(text): @@ -153,8 +149,7 @@ def to_web_path(path): """ if os.path.sep != "/": return path.replace(os.path.sep, "/") - else: - return path + return path def get_svn_revision(): @@ -172,14 +167,12 @@ def get_svn_revision(): rc = p.poll() if not rc: stdout = stdout.strip() - if stdout.endswith("M"): - stdout = stdout[:-1] + stdout = stdout.removesuffix("M") if ":" in stdout: # the first one is the one of source code stdout = stdout.split(":")[0] return stdout - else: - return None + return None def get_svn_info(): @@ -211,8 +204,7 @@ def get_svn_info(): if relurl is not None: relurl = relurl.text # relative path has ^ at the beginning in SVN version 1.8.8 - if relurl.startswith("^"): - relurl = relurl[1:] + relurl = relurl.removeprefix("^") else: # SVN version 1.8.8 supports relative-url but older do not # so, get relative part from absolute URL @@ -441,9 +433,9 @@ def end_file_test(self, returncode, **kwargs): def percent_to_html(percent): if percent is None: return 'unknown percentage' - elif percent > 100 or percent < 0: + if percent > 100 or percent < 0: return "? {:.2f}% ?".format(percent) - elif percent < 40: + if percent < 40: color = "red" elif percent < 70: color = "orange" @@ -457,13 +449,11 @@ def percent_to_html(percent): def wrap_stdstream_to_html(infile, outfile, module, stream): before = "

    %s

    " % (module.name + " " + stream)
         after = "
    " - html = open(outfile, "w") - html.write(before) - with open(infile) as text: + with open(outfile, "w") as html, open(infile) as text: + html.write(before) for line in text: html.write(color_error_line(html_escape(line))) - html.write(after) - html.close() + html.write(after) def html_file_preview(filename): @@ -484,7 +474,7 @@ def html_file_preview(filename): elif size < 10 * max_size: def tail(filename, n): - return collections.deque(open(filename), n) + return collections.deque(open(filename), n) # noqa: SIM115 html.write("... (lines omitted)\n") for line in tail(filename, 50): @@ -502,9 +492,8 @@ def returncode_to_html_text(returncode, timed_out=None): else: extra = "" return f'FAILED{extra}' - else: - # alternatives: SUCCEEDED, passed, OK - return 'succeeded' + # alternatives: SUCCEEDED, passed, OK + return 'succeeded' # not used @@ -514,31 +503,28 @@ def returncode_to_html_sentence(returncode): '' " Test failed (return code %d)" % (returncode) ) - else: - return ( - '' - " Test succeeded (return code %d)" % (returncode) - ) + return ( + '' + " Test succeeded (return code %d)" % (returncode) + ) def returncode_to_success_html_par(returncode): if returncode: return '

    Test failed

    ' - else: - return '

    Test succeeded

    ' + return '

    Test succeeded

    ' def success_to_html_text(total, successes): if successes < total: return 'FAILED' - elif successes == total: + if successes == total: # alternatives: SUCCEEDED, passed, OK return 'succeeded' - else: - return ( - '' - "? more successes than total ?" - ) + return ( + '' + "? more successes than total ?" + ) UNKNOWN_NUMBER_HTML = 'unknown' @@ -566,7 +552,8 @@ def start(self, results_dir): super().start(results_dir) # having all variables public although not really part of API main_page_name = os.path.join(results_dir, self._main_page_name) - self.main_index = open(main_page_name, "w") + # TODO: Ensure file is closed in all situations + self.main_index = open(main_page_name, "w") # noqa: SIM115 # TODO: this can be moved to the counter class self.failures = 0 @@ -633,8 +620,7 @@ def finish(self): def format_percentage(percentage): if percentage is not None: return "{nsper:.0f}%".format(nsper=percentage) - else: - return "unknown percentage" + return "unknown percentage" summary_sentence = ( "\nExecuted {nfiles} test files in {time:}." @@ -735,8 +721,7 @@ def end_file_test( ) file_index_path = os.path.join(cwd, "index.html") - file_index = open(file_index_path, "w") - file_index.write( + header = ( '' "

    {m.name}

    " "

    {m.tested_dir} – {m.name}

    " @@ -775,7 +760,6 @@ def end_file_test( dur=self.file_time, ) ) - file_index.write(summary_section) modules = test_summary.get("tested_modules", None) if modules: @@ -784,12 +768,6 @@ def end_file_test( # alternatively a link to module test summary if type(modules) is not list: modules = [modules] - file_index.write( - "Tested modules{0}".format( - ", ".join(sorted(set(modules))) - ) - ) - file_index.write("") # here we would have also links to coverage, profiling, ... # '
  • code coverage
  • ' @@ -799,7 +777,6 @@ def end_file_test( '
  • standard output (stdout)
  • ' '
  • standard error output (stderr)
  • ' ) - file_index.write(files_section) supplementary_files = test_summary.get("supplementary_files", None) if supplementary_files: @@ -811,17 +788,31 @@ def end_file_test( # moreover something can be shared with other explicitly # using constructors as seems advantageous for counting self._file_anonymizer.anonymize(supplementary_files) - for f in supplementary_files: - file_index.write('
  • {f}
  • '.format(f=f)) - file_index.write("") + with open(file_index_path, "w") as file_index: + file_index.write(header) + file_index.write(summary_section) + if modules: + file_index.write( + "Tested modules{0}".format( + ", ".join(sorted(set(modules))) + ) + ) + file_index.write("") - if returncode: - file_index.write("

    Standard error output (stderr)

    ") - file_index.write(html_file_preview(stderr)) + file_index.write(files_section) + + if supplementary_files: + for f in supplementary_files: + file_index.write('
  • {f}
  • '.format(f=f)) + + file_index.write("") - file_index.write("") - file_index.close() + if returncode: + file_index.write("

    Standard error output (stderr)

    ") + file_index.write(html_file_preview(stderr)) + + file_index.write("") if returncode: pass @@ -986,8 +977,7 @@ def finish(self): def format_percentage(percentage): if percentage is not None: return "{nsper:.0f}%".format(nsper=percentage) - else: - return "unknown percentage" + return "unknown percentage" summary_sentence = ( "\nExecuted {nfiles} test files in {time:}." @@ -1095,7 +1085,7 @@ def report_for_dir(self, root, directory, test_files): os.path.join(root, directory) ) == os.path.abspath(root): page_name = os.path.join(root, self.top_level_testsuite_page_name) - page = open(page_name, "w") + # TODO: should we use forward slashes also for the HTML because # it is simpler are more consistent with the rest on MS Windows? head = "

    {name} testsuite results

    ".format(name=directory) @@ -1108,106 +1098,108 @@ def report_for_dir(self, root, directory, test_files): "FailedPercent successful" "" ) - page.write(head) - page.write(tests_table_head) - for test_file_name in test_files: - # TODO: put keyvalue fine name to constant - summary_filename = os.path.join( - root, directory, test_file_name, "test_keyvalue_result.txt" - ) - # if os.path.exists(summary_filename): - summary = text_to_keyvalue(Path(summary_filename).read_text(), sep="=") - # else: - # TODO: write else here - # summary = None - - if "total" not in summary: - bad_ones = successes = UNKNOWN_NUMBER_HTML - total = None - else: - bad_ones = summary["failures"] + summary["errors"] - successes = summary["successes"] - total = summary["total"] - - self.failures += summary["failures"] - self.errors += summary["errors"] - self.skipped += summary["skipped"] - self.successes += summary["successes"] - self.expected_failures += summary["expected_failures"] - self.unexpected_successes += summary["unexpected_successes"] - self.total += summary["total"] - - dir_failures += summary["failures"] - dir_errors += summary["failures"] - dir_skipped += summary["skipped"] - dir_successes += summary["successes"] - dir_expected_failures += summary["expected_failures"] - dir_unexpected_success += summary["unexpected_successes"] - dir_total += summary["total"] - - # TODO: keyvalue method should have types for keys function - # perhaps just the current post processing function is enough - test_file_authors = summary.get("test_file_authors") - if not test_file_authors: - test_file_authors = [] - if type(test_file_authors) is not list: - test_file_authors = [test_file_authors] - test_files_authors.extend(test_file_authors) - - file_total += 1 - # Use non-zero return code in case it is missing. - # (This can happen when the test has timed out.) - return_code = summary.get("returncode", 1) - file_successes += 0 if return_code else 1 + with open(page_name, "w") as page: + page.write(head) + page.write(tests_table_head) + for test_file_name in test_files: + # TODO: put keyvalue fine name to constant + summary_filename = os.path.join( + root, directory, test_file_name, "test_keyvalue_result.txt" + ) + # if os.path.exists(summary_filename): + summary = text_to_keyvalue(Path(summary_filename).read_text(), sep="=") + # else: + # TODO: write else here + # summary = None + + if "total" not in summary: + bad_ones = successes = UNKNOWN_NUMBER_HTML + total = None + else: + bad_ones = summary["failures"] + summary["errors"] + successes = summary["successes"] + total = summary["total"] + + self.failures += summary["failures"] + self.errors += summary["errors"] + self.skipped += summary["skipped"] + self.successes += summary["successes"] + self.expected_failures += summary["expected_failures"] + self.unexpected_successes += summary["unexpected_successes"] + self.total += summary["total"] + + dir_failures += summary["failures"] + dir_errors += summary["failures"] + dir_skipped += summary["skipped"] + dir_successes += summary["successes"] + dir_expected_failures += summary["expected_failures"] + dir_unexpected_success += summary["unexpected_successes"] + dir_total += summary["total"] + + # TODO: keyvalue method should have types for keys function + # perhaps just the current post processing function is enough + test_file_authors = summary.get("test_file_authors") + if not test_file_authors: + test_file_authors = [] + if type(test_file_authors) is not list: + test_file_authors = [test_file_authors] + test_files_authors.extend(test_file_authors) + + file_total += 1 + # Use non-zero return code in case it is missing. + # (This can happen when the test has timed out.) + return_code = summary.get("returncode", 1) + file_successes += 0 if return_code else 1 + + pass_per = success_to_html_percent(total=total, successes=successes) + row = ( + "" + '{f}' + "{status}" + "{ntests}{stests}" + "{ftests}{ptests}" + "".format( + f=test_file_name, + status=returncode_to_html_text(return_code), + stests=successes, + ftests=bad_ones, + ntests=total, + ptests=pass_per, + ) + ) + page.write(row) - pass_per = success_to_html_percent(total=total, successes=successes) - row = ( - "" - '{f}' + self.testsuites += 1 + self.testsuites_successes += 1 if file_successes == file_total else 0 + self.files += file_total + self.files_successes += file_successes + + dir_pass_per = success_to_html_percent( + total=dir_total, successes=dir_successes + ) + file_pass_per = success_to_html_percent( + total=file_total, successes=file_successes + ) + tests_table_foot = ( + "" + "Summary" "{status}" "{ntests}{stests}" "{ftests}{ptests}" - "".format( - f=test_file_name, - status=returncode_to_html_text(return_code), - stests=successes, - ftests=bad_ones, - ntests=total, - ptests=pass_per, + "".format( + status=file_pass_per, + stests=dir_successes, + ftests=dir_failures + dir_errors, + ntests=dir_total, + ptests=dir_pass_per, ) ) - page.write(row) - - self.testsuites += 1 - self.testsuites_successes += 1 if file_successes == file_total else 0 - self.files += file_total - self.files_successes += file_successes - - dir_pass_per = success_to_html_percent(total=dir_total, successes=dir_successes) - file_pass_per = success_to_html_percent( - total=file_total, successes=file_successes - ) - tests_table_foot = ( - "" - "Summary" - "{status}" - "{ntests}{stests}" - "{ftests}{ptests}" - "".format( - status=file_pass_per, - stests=dir_successes, - ftests=dir_failures + dir_errors, - ntests=dir_total, - ptests=dir_pass_per, + page.write(tests_table_foot) + test_authors = get_html_test_authors_table( + directory=directory, tests_authors=test_files_authors ) - ) - page.write(tests_table_foot) - test_authors = get_html_test_authors_table( - directory=directory, tests_authors=test_files_authors - ) - page.write(test_authors) - page.write("") - page.close() + page.write(test_authors) + page.write("") status = success_to_html_text(total=file_total, successes=file_successes) return ( @@ -1235,7 +1227,6 @@ def report_for_dirs(self, root, directories): # absolute/relative paths page_name = os.path.join(root, self.main_page_name) - page = open(page_name, "w") head = "

    Testsuites results

    " tests_table_head = ( "" @@ -1248,14 +1239,6 @@ def report_for_dirs(self, root, directories): "" "" ) - page.write(head) - page.write(tests_table_head) - - for directory, test_files in directories.items(): - row = self.report_for_dir( - root=root, directory=directory, test_files=test_files - ) - page.write(row) pass_per = success_to_html_percent(total=self.total, successes=self.successes) file_pass_per = success_to_html_percent( @@ -1283,5 +1266,16 @@ def report_for_dirs(self, root, directories): ptests=pass_per, ) ) - page.write(tests_table_foot) - page.write("") + + with open(page_name, "w") as page: + page.write(head) + page.write(tests_table_head) + + for directory, test_files in directories.items(): + row = self.report_for_dir( + root=root, directory=directory, test_files=test_files + ) + page.write(row) + + page.write(tests_table_foot) + page.write("") diff --git a/python/grass/gunittest/runner.py b/python/grass/gunittest/runner.py index b99c6704c89..0bbd0f361b9 100644 --- a/python/grass/gunittest/runner.py +++ b/python/grass/gunittest/runner.py @@ -83,8 +83,7 @@ def getDescription(self, test): doc_first_line = test.shortDescription() if self.descriptions and doc_first_line: return "\n".join((str(test), doc_first_line)) - else: - return str(test) + return str(test) def startTest(self, test): super().startTest(test) diff --git a/python/grass/gunittest/testsuite/test_assertions.py b/python/grass/gunittest/testsuite/test_assertions.py index 3af538132f3..ed27c0e54fb 100644 --- a/python/grass/gunittest/testsuite/test_assertions.py +++ b/python/grass/gunittest/testsuite/test_assertions.py @@ -11,6 +11,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows class TestTextAssertions(TestCase): @@ -34,6 +35,7 @@ def test_assertLooksLike(self): def test_assertLooksLike_multiline(self): self.assertLooksLike("a=123\nb=456\nc=789", "a=...\nb=...\nc=...") + @xfail_windows def test_assertLooksLike_multiline_platform_dependent(self): self.assertLooksLike( "a=123\nb=456\nc=789", "a=...{nl}b=...{nl}c=...".format(nl=os.linesep) @@ -384,6 +386,7 @@ def test_assertFileExists_empty_file(self): self.failureException, self.assertFileExists, filename=self.emtpy_file ) + @xfail_windows def test_assertFileMd5(self): self.assertFileMd5(filename=self.file_with_md5, md5=self.file_md5) self.assertRaises( diff --git a/python/grass/gunittest/testsuite/test_assertions_vect.py b/python/grass/gunittest/testsuite/test_assertions_vect.py index 8b3288ad2ca..0a73580ba58 100644 --- a/python/grass/gunittest/testsuite/test_assertions_vect.py +++ b/python/grass/gunittest/testsuite/test_assertions_vect.py @@ -5,6 +5,7 @@ from grass.exceptions import CalledModuleError from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows V_UNIVAR_SCHOOLS_WIDTH_SUBSET = """n=144 @@ -281,6 +282,7 @@ def test_assertVectorAsciiEqualsVectorAscii_diff_content(self): self.assertFileExists(self.simple_base_file) self.assertFileExists(self.simple_modified_file) + @xfail_windows def test_assertVectorEqualsAscii_by_import(self): amap = "simple_vector_map_imported_base" self.runModule( diff --git a/python/grass/gunittest/testsuite/test_checkers.py b/python/grass/gunittest/testsuite/test_checkers.py index d35ffcb19d8..b11b25778a3 100644 --- a/python/grass/gunittest/testsuite/test_checkers.py +++ b/python/grass/gunittest/testsuite/test_checkers.py @@ -24,6 +24,7 @@ file_md5, text_file_md5, ) +from grass.gunittest.utils import xfail_windows class TestValuesEqual(TestCase): @@ -386,6 +387,7 @@ def tearDownClass(cls): try_remove(cls.correct_file_name_unix_nl) try_remove(cls.wrong_file_name) + @xfail_windows def test_text_file_binary(self): r"""File with ``\n`` (LF) newlines as binary (MD5 has ``\n``).""" self.assertEqual( diff --git a/python/grass/gunittest/utils.py b/python/grass/gunittest/utils.py index c1afea3d5ad..5313dbb9bc8 100644 --- a/python/grass/gunittest/utils.py +++ b/python/grass/gunittest/utils.py @@ -14,6 +14,8 @@ from pathlib import Path import shutil import sys +from unittest import expectedFailure +import warnings def ensure_dir(directory): @@ -80,3 +82,17 @@ def safe_repr(obj, short=False): if not short or len(result) < _MAX_LENGTH: return result return result[:_MAX_LENGTH] + " [truncated]..." + + +def xfail_windows(test_item): + """Marks a test as an expected failure or error only on Windows + Equivalent to applying @unittest.expectedFailure only when running + on Windows. + """ + if not sys.platform.startswith("win"): + return lambda func: func + warnings.warn( + "Once the test is fixed and passing, remove the @xfail_windows decorator", + stacklevel=2, + ) + return expectedFailure(test_item) diff --git a/python/grass/imaging/images2avi.py b/python/grass/imaging/images2avi.py index f0b1904823d..1b0d9d8cd20 100644 --- a/python/grass/imaging/images2avi.py +++ b/python/grass/imaging/images2avi.py @@ -137,11 +137,10 @@ def writeAvi( + "\n" + _("Could not write avi.") ) - else: - # An error occurred, show - print(gs.decode(outPut)) - print(gs.decode(S.stderr.read())) - raise RuntimeError(_("Could not write avi.")) + # An error occurred, show + print(gs.decode(outPut)) + print(gs.decode(S.stderr.read())) + raise RuntimeError(_("Could not write avi.")) else: try: # Copy avi @@ -151,8 +150,7 @@ def writeAvi( _cleanDir(tempDir) if bg_task: return str(err) - else: - raise + raise # Clean up _cleanDir(tempDir) diff --git a/python/grass/imaging/images2gif.py b/python/grass/imaging/images2gif.py index a4dc2dc0824..4084dade509 100644 --- a/python/grass/imaging/images2gif.py +++ b/python/grass/imaging/images2gif.py @@ -265,7 +265,7 @@ def handleSubRectangles(self, images, subRectangles): xy = (0, 0) if hasattr(xy, "__len__"): if len(xy) == len(images): - xy = [xxyy for xxyy in xy] + xy = list(xy) else: raise ValueError("len(xy) doesn't match amount of images.") else: @@ -594,7 +594,7 @@ def writeGifVisvis( # Check duration if hasattr(duration, "__len__"): if len(duration) == len(images): - duration = [d for d in duration] + duration = list(duration) else: raise ValueError("len(duration) doesn't match amount of images.") else: @@ -1060,9 +1060,8 @@ def quantize(self, image): """ if get_cKDTree(): return self.quantize_with_scipy(image) - else: - print("Scipy not available, falling back to slower version.") - return self.quantize_without_scipy(image) + print("Scipy not available, falling back to slower version.") + return self.quantize_without_scipy(image) def quantize_with_scipy(self, image): w, h = image.size diff --git a/python/grass/imaging/images2ims.py b/python/grass/imaging/images2ims.py index 31088a22f2e..a5cee9b49de 100644 --- a/python/grass/imaging/images2ims.py +++ b/python/grass/imaging/images2ims.py @@ -31,6 +31,7 @@ """ import os +from operator import itemgetter try: import numpy as np @@ -92,8 +93,7 @@ def checkImages(images): def _getFilenameParts(filename): if "*" in filename: return tuple(filename.split("*", 1)) - else: - return os.path.splitext(filename) + return os.path.splitext(filename) def _getFilenameWithFormatter(filename, N): @@ -214,7 +214,7 @@ def readIms(filename, asNumpy=True): images.append((im.copy(), nr)) # Sort images - images.sort(key=lambda x: x[1]) + images.sort(key=itemgetter(1)) images = [im[0] for im in images] # Convert to numpy if needed diff --git a/python/grass/imaging/images2swf.py b/python/grass/imaging/images2swf.py index 0a08ed9d46d..7d6f5a25f9b 100644 --- a/python/grass/imaging/images2swf.py +++ b/python/grass/imaging/images2swf.py @@ -392,7 +392,7 @@ def __init__(self): def ProcessTag(self): """Implement this to create the tag.""" - raise NotImplementedError() + raise NotImplementedError def GetTag(self): """Calls processTag and attaches the header.""" @@ -796,7 +796,7 @@ def writeSwf(filename, images, duration=0.1, repeat=True): # Check duration if hasattr(duration, "__len__"): if len(duration) == len(images2): - duration = [d for d in duration] + duration = list(duration) else: raise ValueError("len(duration) doesn't match amount of images.") else: diff --git a/python/grass/jupyter/baseseriesmap.py b/python/grass/jupyter/baseseriesmap.py index 634e172f3c5..4497b16593d 100644 --- a/python/grass/jupyter/baseseriesmap.py +++ b/python/grass/jupyter/baseseriesmap.py @@ -25,7 +25,7 @@ import grass.script as gs from .map import Map -from .utils import get_number_of_cores +from .utils import get_number_of_cores, save_gif class BaseSeriesMap: @@ -210,3 +210,49 @@ def change_image(index): width="100%", display="inline-flex", flex_flow="row wrap" ) return widgets.HBox([play, slider, out_img], layout=layout) + + def save( + self, + filename, + duration=500, + label=True, + font=None, + text_size=12, + text_color="gray", + ): + """ + Creates a GIF animation of rendered layers. + + Text color must be in a format accepted by PIL ImageColor module. For supported + formats, visit: + https://pillow.readthedocs.io/en/stable/reference/ImageColor.html#color-names + + param str filename: name of output GIF file + param int duration: time to display each frame; milliseconds + param bool label: include label on each frame + param str font: font file + param int text_size: size of label text + param str text_color: color to use for the text. + """ + + # Render images if they have not been already + if not self._layers_rendered: + self.render() + + input_files = [] + for index in self._indices: + input_files.append(self._base_filename_dict[index]) + + save_gif( + input_files, + filename, + duration=duration, + label=label, + labels=self._labels, + font=font, + text_size=text_size, + text_color=text_color, + ) + + # Display the GIF + return filename diff --git a/python/grass/jupyter/interactivemap.py b/python/grass/jupyter/interactivemap.py index 085c2843fe7..d843ac3b6b6 100644 --- a/python/grass/jupyter/interactivemap.py +++ b/python/grass/jupyter/interactivemap.py @@ -178,7 +178,7 @@ def add_to(self, interactive_map): else: import ipyleaflet # pylint: disable=import-outside-toplevel - with open(self._filename, "r", encoding="utf-8") as file: + with open(self._filename, encoding="utf-8") as file: data = json.load(file) # allow using opacity directly to keep interface # consistent for both backends diff --git a/python/grass/jupyter/seriesmap.py b/python/grass/jupyter/seriesmap.py index 8615ad488fb..ae6bde911b6 100644 --- a/python/grass/jupyter/seriesmap.py +++ b/python/grass/jupyter/seriesmap.py @@ -20,7 +20,6 @@ from .map import Map from .region import RegionManagerForSeries -from .utils import save_gif from .baseseriesmap import BaseSeriesMap @@ -165,49 +164,3 @@ def render(self): ) tasks = [(i,) for i in range(self.baseseries)] self._render(tasks) - - def save( - self, - filename, - duration=500, - label=True, - font=None, - text_size=12, - text_color="gray", - ): - """ - Creates a GIF animation of rendered layers. - - Text color must be in a format accepted by PIL ImageColor module. For supported - formats, visit: - https://pillow.readthedocs.io/en/stable/reference/ImageColor.html#color-names - - param str filename: name of output GIF file - param int duration: time to display each frame; milliseconds - param bool label: include label on each frame - param str font: font file - param int text_size: size of label text - param str text_color: color to use for the text - """ - - # Render images if they have not been already - if not self._layers_rendered: - self.render() - - tmp_files = [] - for file in self._base_filename_dict.values(): - tmp_files.append(file) - - save_gif( - tmp_files, - filename, - duration=duration, - label=label, - labels=self._labels, - font=font, - text_size=text_size, - text_color=text_color, - ) - - # Display the GIF - return filename diff --git a/python/grass/jupyter/tests/grass_jupyter_session_test.py b/python/grass/jupyter/tests/grass_jupyter_session_test.py index 7b6bc89e4ed..17b6e7fbf5d 100644 --- a/python/grass/jupyter/tests/grass_jupyter_session_test.py +++ b/python/grass/jupyter/tests/grass_jupyter_session_test.py @@ -27,8 +27,8 @@ def test_init_finish(tmp_path): import os import grass.script as gs import grass.jupyter as gj -gs.core._create_location_xy("{tmp_path}", "{location}") -session = gj.init("{tmp_path / location}") +gs.core._create_location_xy(r"{tmp_path}", r"{location}") +session = gj.init(r"{tmp_path / location}") gs.read_command("g.region", flags="p") print(os.environ["GISRC"]) session.finish() @@ -49,8 +49,8 @@ def test_init_with_auto_finish(tmp_path): import os import grass.script as gs import grass.jupyter as gj -gs.core._create_location_xy("{tmp_path}", "{location}") -session = gj.init("{tmp_path / location}") +gs.core._create_location_xy(r"{tmp_path}", r"{location}") +session = gj.init(r"{tmp_path / location}") print(os.environ["GISRC"]) """ diff --git a/python/grass/jupyter/tests/reprojection_renderer_test.py b/python/grass/jupyter/tests/reprojection_renderer_test.py index 907522ab2f8..f9ef7888110 100644 --- a/python/grass/jupyter/tests/reprojection_renderer_test.py +++ b/python/grass/jupyter/tests/reprojection_renderer_test.py @@ -1,7 +1,7 @@ """Test ReprojectionRenderer functions""" from pathlib import Path -from pytest import approx +import pytest from grass.jupyter.reprojection_renderer import ReprojectionRenderer @@ -21,8 +21,8 @@ def test_render_raster(simple_dataset): assert Path(filename).exists() # Test bounding box is correct # Raster is same extent as region so no need to test bbox for use_region=True - assert bbox[0] == approx([0.00072155, -85.48874388]) - assert bbox[1] == approx([0.00000000, -85.48766880]) + assert bbox[0] == pytest.approx([0.00072155, -85.48874388]) + assert bbox[1] == pytest.approx([0.00000000, -85.48766880]) # render_vector produces json diff --git a/python/grass/jupyter/testsuite/interactivemap_test.py b/python/grass/jupyter/testsuite/interactivemap_test.py index 6b8a7379548..493578596b5 100644 --- a/python/grass/jupyter/testsuite/interactivemap_test.py +++ b/python/grass/jupyter/testsuite/interactivemap_test.py @@ -103,24 +103,26 @@ def test_query_button(self): # Create InteractiveMap with ipyleaflet backend interactive_map = gj.InteractiveMap(map_backend="ipyleaflet") interactive_map.add_raster("elevation") - interactive_map.add_vector("roadsmajor") - interactive_map.add_query_button() - self.assertIsNotNone(interactive_map.map) - self.assertTrue(interactive_map.query_mode is False) - # Toggle query button to activate - interactive_map.query_mode = True - self.assertTrue(interactive_map.query_mode) - # Toggle query button to deactivate - interactive_map.query_mode = False - self.assertFalse(interactive_map.query_mode) + button = interactive_map.setup_query_interface() + self.assertIsNotNone(interactive_map._controllers[button].query_raster((0, 0))) + + @unittest.skipIf(not can_import_ipyleaflet(), "Cannot import ipyleaflet") + def test_draw(self): + """Test the draw_computational_region method.""" + # Create InteractiveMap + interactive_map = gj.InteractiveMap(map_backend="ipyleaflet") + button = interactive_map.setup_drawing_interface() + interactive_map._controllers[button].activate() + self.assertIsNotNone(interactive_map._controllers[button].save_button_control) @unittest.skipIf(not can_import_ipyleaflet(), "Cannot import ipyleaflet") def test_draw_computational_region(self): """Test the draw_computational_region method.""" # Create InteractiveMap - interactive_map = gj.InteractiveMap() - interactive_map.draw_computational_region() - self.assertTrue(callable(interactive_map.draw_computational_region)) + interactive_map = gj.InteractiveMap(map_backend="ipyleaflet") + button = interactive_map.setup_computational_region_interface() + interactive_map._controllers[button].activate() + self.assertIsNotNone(interactive_map._controllers[button].save_button_control) if __name__ == "__main__": diff --git a/python/grass/jupyter/testsuite/map3d_test.py b/python/grass/jupyter/testsuite/map3d_test.py index b28b6a03a5b..5f88fad24e7 100644 --- a/python/grass/jupyter/testsuite/map3d_test.py +++ b/python/grass/jupyter/testsuite/map3d_test.py @@ -26,6 +26,7 @@ import grass.jupyter as gj from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows def can_import_ipython(): @@ -81,12 +82,14 @@ def tearDown(self): else: file.unlink(missing_ok=True) + @xfail_windows def test_defaults(self): """Check that default settings work""" renderer = gj.Map3D() renderer.render(elevation_map="elevation", color_map="elevation") self.assertFileExists(renderer.filename) + @xfail_windows def test_filename(self): """Check that custom filename works""" custom_filename = "test_filename.png" @@ -96,12 +99,14 @@ def test_filename(self): renderer.render(elevation_map="elevation", color_map="elevation") self.assertFileExists(custom_filename) + @xfail_windows def test_hw(self): """Check that custom width and height works""" renderer = gj.Map3D(width=200, height=400) renderer.render(elevation_map="elevation", color_map="elevation") self.assertFileExists(renderer.filename) + @xfail_windows def test_overlay(self): """Check that overlay works""" renderer = gj.Map3D() diff --git a/python/grass/jupyter/timeseriesmap.py b/python/grass/jupyter/timeseriesmap.py index 3ac94bea93e..2acfa575126 100644 --- a/python/grass/jupyter/timeseriesmap.py +++ b/python/grass/jupyter/timeseriesmap.py @@ -20,7 +20,6 @@ from .map import Map from .region import RegionManagerForTimeSeries -from .utils import save_gif from .baseseriesmap import BaseSeriesMap @@ -312,49 +311,3 @@ def render(self): filename = os.path.join(self._tmpdir.name, f"{layer}.png") tasks.append((date, layer, filename)) self._render(tasks) - - def save( - self, - filename, - duration=500, - label=True, - font="DejaVuSans.ttf", - text_size=12, - text_color="gray", - ): - """ - Creates a GIF animation of rendered layers. - - Text color must be in a format accepted by PIL ImageColor module. For supported - formats, visit: - https://pillow.readthedocs.io/en/stable/reference/ImageColor.html#color-names - - param str filename: name of output GIF file - param int duration: time to display each frame; milliseconds - param bool label: include date/time stamp on each frame - param str font: font file - param int text_size: size of date/time text - param str text_color: color to use for the text. - """ - - # Render images if they have not been already - if not self._layers_rendered: - self.render() - - input_files = [] - for date in self._labels: - input_files.append(self._base_filename_dict[date]) - - save_gif( - input_files, - filename, - duration=duration, - label=label, - labels=self._labels, - font=font, - text_size=text_size, - text_color=text_color, - ) - - # Display the GIF - return filename diff --git a/python/grass/pydispatch/robustapply.py b/python/grass/pydispatch/robustapply.py index a050f54341a..2ec88443a1a 100644 --- a/python/grass/pydispatch/robustapply.py +++ b/python/grass/pydispatch/robustapply.py @@ -35,7 +35,7 @@ def function(receiver): if hasattr(receiver, im_func): # an instance-method... return receiver, getattr(getattr(receiver, im_func), func_code), 1 - elif not hasattr(receiver, func_code): + if not hasattr(receiver, func_code): raise ValueError("unknown receiver type %s %s" % (receiver, type(receiver))) return receiver, getattr(receiver, func_code), 0 @@ -86,5 +86,5 @@ def robustApply(receiver, *arguments, **named): ) # fc does not have a **kwds type parameter, therefore # remove unacceptable arguments. - named = dict([(k, v) for k, v in named.items() if k in acceptable]) + named = {k: v for k, v in named.items() if k in acceptable} return receiver(*arguments, **named) diff --git a/python/grass/pydispatch/saferef.py b/python/grass/pydispatch/saferef.py index a802a1982c1..90769c46b36 100644 --- a/python/grass/pydispatch/saferef.py +++ b/python/grass/pydispatch/saferef.py @@ -35,8 +35,7 @@ def safeRef(target, onDelete=None): return BoundMethodWeakref(target=target, onDelete=onDelete) if onDelete is not None: return weakref.ref(target, onDelete) - else: - return weakref.ref(target) + return weakref.ref(target) class BoundMethodWeakref: @@ -92,11 +91,10 @@ def __new__(cls, target, onDelete=None, *arguments, **named): if current is not None: current.deletionMethods.append(onDelete) return current - else: - base = super().__new__(cls) - cls._allInstances[key] = base - base.__init__(target, onDelete, *arguments, **named) - return base + base = super().__new__(cls) + cls._allInstances[key] = base + base.__init__(target, onDelete, *arguments, **named) + return base def __init__(self, target, onDelete=None): """Return a weak-reference-like instance for a bound method diff --git a/python/grass/pygrass/errors.py b/python/grass/pygrass/errors.py index a63b300a862..a017b85b33f 100644 --- a/python/grass/pygrass/errors.py +++ b/python/grass/pygrass/errors.py @@ -11,9 +11,8 @@ def must_be_open(method): def wrapper(self, *args, **kargs): if self.is_open(): return method(self, *args, **kargs) - else: - msgr = get_msgr() - msgr.warning(_("The map is close!")) + msgr = get_msgr() + msgr.warning(_("The map is close!")) return wrapper @@ -23,10 +22,7 @@ def mapinfo_must_be_set(method): def wrapper(self, *args, **kargs): if self.c_mapinfo: return method(self, *args, **kargs) - else: - raise GrassError( - _("The self.c_mapinfo pointer must be correctly initiated") - ) + raise GrassError(_("The self.c_mapinfo pointer must be correctly initiated")) return wrapper @@ -36,9 +32,6 @@ def must_be_in_current_mapset(method): def wrapper(self, *args, **kargs): if self.mapset == libgis.G_mapset().decode(): return method(self, *args, **kargs) - else: - raise GrassError( - _("Map <{}> not found in current mapset").format(self.name) - ) + raise GrassError(_("Map <{}> not found in current mapset").format(self.name)) return wrapper diff --git a/python/grass/pygrass/gis/__init__.py b/python/grass/pygrass/gis/__init__.py index 3f380368d28..597c4bf75fa 100644 --- a/python/grass/pygrass/gis/__init__.py +++ b/python/grass/pygrass/gis/__init__.py @@ -162,8 +162,7 @@ def __getitem__(self, location): """ if location in self.locations(): return Location(location, self.name) - else: - raise KeyError("Location: %s does not exist" % location) + raise KeyError("Location: %s does not exist" % location) def __iter__(self): for loc in self.locations(): @@ -234,8 +233,7 @@ def _set_name(self, name): def __getitem__(self, mapset): if mapset in self.mapsets(): return Mapset(mapset) - else: - raise KeyError("Mapset: %s does not exist" % mapset) + raise KeyError("Mapset: %s does not exist" % mapset) def __iter__(self): lpath = self.path() @@ -271,7 +269,7 @@ def mapsets(self, pattern=None, permissions=True): [...] """ - mapsets = [mapset for mapset in self] + mapsets = [mapset for mapset in self] # noqa: C416 if permissions: mapsets = [ mapset @@ -430,7 +428,7 @@ def __iter__(self): def read(self): """Return the mapsets in the search path""" try: - with open(self.spath, "r") as f: + with open(self.spath) as f: lines = f.readlines() if lines: return [line.strip() for line in lines] diff --git a/python/grass/pygrass/gis/region.py b/python/grass/pygrass/gis/region.py index 98c75a15631..892a3664b49 100644 --- a/python/grass/pygrass/gis/region.py +++ b/python/grass/pygrass/gis/region.py @@ -331,10 +331,7 @@ def __eq__(self, reg): "zone", "proj", ] - for attr in attrs: - if getattr(self, attr) != getattr(reg, attr): - return False - return True + return all(getattr(self, attr) == getattr(reg, attr) for attr in attrs) def __ne__(self, other): return not self == other diff --git a/python/grass/pygrass/modules/grid/grid.py b/python/grass/pygrass/modules/grid/grid.py index fb338ca973a..ffae173ca79 100644 --- a/python/grass/pygrass/modules/grid/grid.py +++ b/python/grass/pygrass/modules/grid/grid.py @@ -121,10 +121,8 @@ def read_gisrc(gisrc): ... genv['GISDBASE'])) True """ - with open(gisrc, "r") as gfile: - gis = dict( - [(k.strip(), v.strip()) for k, v in [row.split(":", 1) for row in gfile]] - ) + with open(gisrc) as gfile: + gis = {k.strip(): v.strip() for k, v in [row.split(":", 1) for row in gfile]} return gis["MAPSET"], gis["LOCATION_NAME"], gis["GISDBASE"] @@ -147,7 +145,7 @@ def get_mapset(gisrc_src, gisrc_dst): copy_special_mapset_files(path_src, path_dst) src = Mapset(msrc, lsrc, gsrc) dst = Mapset(mdst, ldst, gdst) - visible = [m for m in src.visible] + visible = list(src.visible) if src.name not in visible: visible.append(src.name) dst.visible.extend(visible) @@ -189,7 +187,7 @@ def rmloc(r): # change gisdbase to src env["GISRC"] = gisrc_src get_grp(group=grp, env_=env) - rasts = [r for r in get_grp.outputs.stdout.split()] + rasts = list(get_grp.outputs.stdout.split()) # change gisdbase to dst env["GISRC"] = gisrc_dst rast2cp = [r for r in rasts if rmloc(r) not in all_rasts] @@ -497,15 +495,15 @@ def __init__( self.gisrc_dst = write_gisrc( self.n_mset.gisdbase, self.n_mset.location, self.n_mset.name ) - rasters = [r for r in select(self.module.inputs, "raster")] + rasters = list(select(self.module.inputs, "raster")) if rasters: copy_rasters( rasters, self.gisrc_src, self.gisrc_dst, region=self.region ) - vectors = [v for v in select(self.module.inputs, "vector")] + vectors = list(select(self.module.inputs, "vector")) if vectors: copy_vectors(vectors, self.gisrc_src, self.gisrc_dst) - groups = [g for g in select(self.module.inputs, "group")] + groups = list(select(self.module.inputs, "group")) if groups: copy_groups(groups, self.gisrc_src, self.gisrc_dst, region=self.region) self.bboxes = split_region_in_overlapping_tiles( @@ -592,7 +590,7 @@ def get_works(self): else: ldst, gdst = self.mset.location, self.mset.gisdbase cmd = self.module.get_dict() - groups = [g for g in select(self.module.inputs, "group")] + groups = list(select(self.module.inputs, "group")) for row, box_row in enumerate(self.bboxes): for col, box in enumerate(box_row): inms = None @@ -603,7 +601,7 @@ def get_works(self): indx = row * cols + col inms[key] = "%s@%s" % (self.inlist[key][indx], self.mset.name) # set the computational region, prepare the region parameters - bbox = dict([(k[0], str(v)) for k, v in box.items()[:-2]]) + bbox = {k[0]: str(v) for k, v in box.items()[:-2]} bbox["nsres"] = "%f" % reg.nsres bbox["ewres"] = "%f" % reg.ewres new_mset = ( diff --git a/python/grass/pygrass/modules/interface/docstring.py b/python/grass/pygrass/modules/interface/docstring.py index 2fde05f73de..397338fcbb8 100644 --- a/python/grass/pygrass/modules/interface/docstring.py +++ b/python/grass/pygrass/modules/interface/docstring.py @@ -44,8 +44,7 @@ def __init__(self, class_doc, fget): def __get__(self, obj, type=None): if obj is None: return self.class_doc - else: - return self.fget(obj) + return self.fget(obj) def __set__(self, obj, value): raise AttributeError("can't set attribute") diff --git a/python/grass/pygrass/modules/interface/env.py b/python/grass/pygrass/modules/interface/env.py index ad6e4c4800e..d3d6e371238 100644 --- a/python/grass/pygrass/modules/interface/env.py +++ b/python/grass/pygrass/modules/interface/env.py @@ -13,13 +13,10 @@ def get_env(): gisrc = os.environ.get("GISRC") if gisrc is None: raise RuntimeError("You are not in a GRASS session, GISRC not found.") - with open(gisrc, mode="r") as grc: - return dict( - [ - (k.strip(), v.strip()) - for k, v in [row.split(":", 1) for row in grc if row] - ] - ) + with open(gisrc) as grc: + return { + k.strip(): v.strip() for k, v in [row.split(":", 1) for row in grc if row] + } def get_debug_level(): diff --git a/python/grass/pygrass/modules/interface/flag.py b/python/grass/pygrass/modules/interface/flag.py index b2e78e30717..b6f00fdb744 100644 --- a/python/grass/pygrass/modules/interface/flag.py +++ b/python/grass/pygrass/modules/interface/flag.py @@ -52,10 +52,8 @@ def get_bash(self): if self.value: if self.special: return "--%s" % self.name[0] - else: - return "-%s" % self.name - else: - return "" + return "-%s" % self.name + return "" def get_python(self): """Return the python representation of a flag. diff --git a/python/grass/pygrass/modules/interface/module.py b/python/grass/pygrass/modules/interface/module.py index c8a1e723a05..392d7571015 100644 --- a/python/grass/pygrass/modules/interface/module.py +++ b/python/grass/pygrass/modules/interface/module.py @@ -720,12 +720,11 @@ def get_python(self): # pre name par flg special if flags and special: return "%s.%s(%s, flags=%r, %s)" % (prefix, name, params, flags, special) - elif flags: + if flags: return "%s.%s(%s, flags=%r)" % (prefix, name, params, flags) - elif special: + if special: return "%s.%s(%s, %s)" % (prefix, name, params, special) - else: - return "%s.%s(%s)" % (prefix, name, params) + return "%s.%s(%s)" % (prefix, name, params) def __str__(self): """Return the command string that can be executed in a shell""" @@ -1026,16 +1025,15 @@ def run(self): module.finish_ = True module.run() return None + if self.set_temp_region is True: + self.p = Process( + target=run_modules_in_temp_region, args=[self.module_list, self.q] + ) else: - if self.set_temp_region is True: - self.p = Process( - target=run_modules_in_temp_region, args=[self.module_list, self.q] - ) - else: - self.p = Process(target=run_modules, args=[self.module_list, self.q]) - self.p.start() + self.p = Process(target=run_modules, args=[self.module_list, self.q]) + self.p.start() - return self.p + return self.p def wait(self): """Wait for all processes to finish. Call this method diff --git a/python/grass/pygrass/modules/interface/parameter.py b/python/grass/pygrass/modules/interface/parameter.py index 798efde56b7..3b58ea2b372 100644 --- a/python/grass/pygrass/modules/interface/parameter.py +++ b/python/grass/pygrass/modules/interface/parameter.py @@ -216,7 +216,7 @@ def __init__(self, xparameter=None, diz=None): # if "gisprompt" in diz and diz["gisprompt"]: self.typedesc = diz["gisprompt"].get("prompt", "") - self.input = not diz["gisprompt"]["age"] == "new" + self.input = diz["gisprompt"]["age"] != "new" else: self.input = True diff --git a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py index 6a9915b6a14..c4ada9c4667 100644 --- a/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py +++ b/python/grass/pygrass/modules/tests/grass_pygrass_grid_test.py @@ -210,7 +210,7 @@ def run_grid_module(): @xfail_mp_spawn @pytest.mark.parametrize( - "width, height, processes", + ("width", "height", "processes"), [ (None, None, max_processes()), (10, None, max_processes()), @@ -249,7 +249,7 @@ def run_grid_module(): @xfail_mp_spawn @pytest.mark.needs_solo_run @pytest.mark.parametrize( - "processes, backend", + ("processes", "backend"), [ (1, "RasterRow"), (9, "RasterRow"), diff --git a/python/grass/pygrass/raster/__init__.py b/python/grass/pygrass/raster/__init__.py index 0356513e017..61ec85841cb 100644 --- a/python/grass/pygrass/raster/__init__.py +++ b/python/grass/pygrass/raster/__init__.py @@ -327,17 +327,16 @@ def __setitem__(self, key, row): if isinstance(key, slice): # Get the start, stop, and step from the slice return [self.put_row(ii, row) for ii in range(*key.indices(len(self)))] - elif isinstance(key, tuple): + if isinstance(key, tuple): x, y = key return self.put(x, y, row) - elif isinstance(key, int): + if isinstance(key, int): if key < 0: # Handle negative indices key += self._rows if key >= self._rows: raise IndexError(_("Index out of range: %r.") % key) return self.put_row(key, row) - else: - raise TypeError("Invalid argument type.") + raise TypeError("Invalid argument type.") @must_be_open def map2segment(self): diff --git a/python/grass/pygrass/raster/abstract.py b/python/grass/pygrass/raster/abstract.py index edea42e7bdd..68b5e501ed4 100644 --- a/python/grass/pygrass/raster/abstract.py +++ b/python/grass/pygrass/raster/abstract.py @@ -393,10 +393,10 @@ def __getitem__(self, key): if isinstance(key, slice): # Get the start, stop, and step from the slice return (self.get_row(ii) for ii in range(*key.indices(len(self)))) - elif isinstance(key, tuple): + if isinstance(key, tuple): x, y = key return self.get(x, y) - elif isinstance(key, int): + if isinstance(key, int): if not self.is_open(): raise IndexError("Can not operate on a closed map. Call open() first.") if key < 0: # Handle negative indices @@ -408,8 +408,7 @@ def __getitem__(self, key): ) ) return self.get_row(key) - else: - fatal("Invalid argument type.") + fatal("Invalid argument type.") def __iter__(self): """Return a constructor of the class""" @@ -434,8 +433,7 @@ def exist(self): self.mapset = mapset or "" return bool(mapset) return bool(utils.get_mapset_raster(self.name, self.mapset)) - else: - return False + return False def is_open(self): """Return True if the map is open False otherwise. @@ -485,8 +483,7 @@ def name_mapset(self, name=None, mapset=None): if mapset and mapset != gis_env["MAPSET"]: return "{name}@{mapset}".format(name=name, mapset=mapset) - else: - return name + return name def rename(self, newname): """Rename the map""" diff --git a/python/grass/pygrass/raster/buffer.py b/python/grass/pygrass/raster/buffer.py index 51420f16610..0e34ac84159 100644 --- a/python/grass/pygrass/raster/buffer.py +++ b/python/grass/pygrass/raster/buffer.py @@ -20,13 +20,12 @@ class Buffer(np.ndarray): def mtype(self): if self.dtype in CELL: return "CELL" - elif self.dtype in FCELL: + if self.dtype in FCELL: return "FCELL" - elif self.dtype in DCELL: + if self.dtype in DCELL: return DCELL - else: - err = "Raster type: %r not supported by GRASS." - raise TypeError(err % self.dtype) + err = "Raster type: %r not supported by GRASS." + raise TypeError(err % self.dtype) def __new__( cls, shape, mtype="FCELL", buffer=None, offset=0, strides=None, order=None diff --git a/python/grass/pygrass/raster/category.py b/python/grass/pygrass/raster/category.py index 00381f91130..fa4e8d37b12 100644 --- a/python/grass/pygrass/raster/category.py +++ b/python/grass/pygrass/raster/category.py @@ -68,7 +68,7 @@ def _get_mtype(self): def _set_mtype(self, mtype): if mtype.upper() not in {"CELL", "FCELL", "DCELL"}: - raise ValueError(_("Raster type: {0} not supported".format(mtype))) + raise ValueError(_("Raster type: {0} not supported").format(mtype)) self._mtype = mtype self._gtype = RTYPE[self.mtype]["grass type"] @@ -187,7 +187,7 @@ def _set_c_cat(self, label, min_cat, max_cat=None): # Manage C function Errors if err == 1: return None - elif err == 0: + if err == 0: raise GrassError(_("Null value detected")) elif err == -1: raise GrassError(_("Error executing: Rast_set_cat")) @@ -299,7 +299,7 @@ def read_rules(self, filename, sep=":"): """ self.reset() - with open(filename, "r") as f: + with open(filename) as f: for row in f: cat = row.strip().split(sep) if len(cat) == 2: diff --git a/python/grass/pygrass/raster/history.py b/python/grass/pygrass/raster/history.py index 5ec855cf1bb..8f227affabc 100644 --- a/python/grass/pygrass/raster/history.py +++ b/python/grass/pygrass/raster/history.py @@ -59,10 +59,7 @@ def __del__(self): """Rast_free_history""" def __eq__(self, hist): - for attr in self.attrs: - if getattr(self, attr) != getattr(hist, attr): - return False - return True + return all(getattr(self, attr) == getattr(hist, attr) for attr in self.attrs) def __len__(self): return self.length() diff --git a/python/grass/pygrass/raster/testsuite/test_category.py b/python/grass/pygrass/raster/testsuite/test_category.py index 527c43b894f..113264c82f6 100644 --- a/python/grass/pygrass/raster/testsuite/test_category.py +++ b/python/grass/pygrass/raster/testsuite/test_category.py @@ -6,6 +6,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows from grass.pygrass.raster import RasterRow from grass.pygrass.raster.category import Category @@ -76,6 +77,7 @@ def testFirstCat(self): self.assertEqual(cats[7], cat7) self.assertEqual(cats[15], cat15) + @xfail_windows def testWrite(self): tmpfile = tempfile(False) cats = Category(self.name) diff --git a/python/grass/pygrass/raster/testsuite/test_numpy.py b/python/grass/pygrass/raster/testsuite/test_numpy.py index 5f0b2309544..b23926d8ba7 100644 --- a/python/grass/pygrass/raster/testsuite/test_numpy.py +++ b/python/grass/pygrass/raster/testsuite/test_numpy.py @@ -6,6 +6,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows from numpy.random import default_rng from grass.pygrass.raster import raster2numpy, numpy2raster, RasterRow @@ -48,6 +49,7 @@ def test_len(self): self.assertTrue(len(self.numpy_obj), 40) self.assertTrue(len(self.numpy_obj[0]), 60) + @xfail_windows def test_write(self): rng = default_rng() numpy2raster(rng.random([40, 60]), "FCELL", self.name, True) diff --git a/python/grass/pygrass/raster/testsuite/test_raster_img.py b/python/grass/pygrass/raster/testsuite/test_raster_img.py index bbc1cb2dabd..b873b16a86b 100644 --- a/python/grass/pygrass/raster/testsuite/test_raster_img.py +++ b/python/grass/pygrass/raster/testsuite/test_raster_img.py @@ -3,6 +3,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows from grass.pygrass.raster import raster2numpy_img from grass.pygrass.gis.region import Region @@ -149,6 +150,7 @@ def test_resampling_to_numpy_img_1(self): self.assertEqual(len(a), region.rows * region.cols * 4) + @xfail_windows def test_resampling_to_numpy_img_2(self): region = Region() region.ewres = 1 @@ -159,6 +161,7 @@ def test_resampling_to_numpy_img_2(self): self.assertEqual(len(a), region.rows * region.cols * 4) + @xfail_windows def test_resampling_to_numpy_img_3(self): region = Region() region.ewres = 0.4 @@ -169,6 +172,7 @@ def test_resampling_to_numpy_img_3(self): self.assertEqual(len(a), region.rows * region.cols * 1) + @xfail_windows def test_resampling_to_numpy_img_4(self): region = Region() region.ewres = 0.1 diff --git a/python/grass/pygrass/tests/benchmark.py b/python/grass/pygrass/tests/benchmark.py index 75e32541a59..fa7f0c01a65 100644 --- a/python/grass/pygrass/tests/benchmark.py +++ b/python/grass/pygrass/tests/benchmark.py @@ -12,11 +12,11 @@ import copy import cProfile import sys -import os from jinja2 import Template +from pathlib import Path -sys.path.append(os.getcwd()) -sys.path.append("%s/.." % (os.getcwd())) +sys.path.append(str(Path.cwd())) +sys.path.append("%s/.." % (str(Path.cwd()))) import grass.lib.gis as libgis import grass.lib.raster as libraster diff --git a/python/grass/pygrass/tests/set_mapset.py b/python/grass/pygrass/tests/set_mapset.py index f9d4a96fabf..105735efa5a 100644 --- a/python/grass/pygrass/tests/set_mapset.py +++ b/python/grass/pygrass/tests/set_mapset.py @@ -13,7 +13,7 @@ def read_gisrc(gisrcpath): - gisrc = open(gisrcpath, "r") + gisrc = open(gisrcpath) diz = {} for row in gisrc: key, val = row.split(":") diff --git a/python/grass/pygrass/utils.py b/python/grass/pygrass/utils.py index a04e3936a64..d8804665b1e 100644 --- a/python/grass/pygrass/utils.py +++ b/python/grass/pygrass/utils.py @@ -83,24 +83,23 @@ def find_in_gisdbase(type, pattern, gisdbase): (m, mset.name, mset.location, mset.gisdbase) for m in mset.glist(type, pattern) ] - elif gisdbase and location: + if gisdbase and location: loc = Location(location, gisdbase) return find_in_location(type, pattern, loc) - elif gisdbase: + if gisdbase: gis = Gisdbase(gisdbase) return find_in_gisdbase(type, pattern, gis) - elif location: + if location: loc = Location(location) return find_in_location(type, pattern, loc) - elif mapset: + if mapset: mset = Mapset(mapset) return [ (m, mset.name, mset.location, mset.gisdbase) for m in mset.glist(type, pattern) ] - else: - gis = Gisdbase() - return find_in_gisdbase(type, pattern, gis) + gis = Gisdbase() + return find_in_gisdbase(type, pattern, gis) def remove(oldname, maptype): @@ -136,11 +135,10 @@ def decode(obj, encoding=None): """ if isinstance(obj, String): return grassutils.decode(obj.data, encoding=encoding) - elif isinstance(obj, bytes): + if isinstance(obj, bytes): return grassutils.decode(obj) - else: - # eg None - return obj + # eg None + return obj def getenv(env): @@ -337,9 +335,8 @@ def get_raster_for_points(poi_vector, raster, column=None, region=None): result.append((poi.id, poi.x, poi.y, None)) if not column: return result - else: - poi.attrs.commit() - return True + poi.attrs.commit() + return True def r_export(rast, output="", fmt="png", **kargs): @@ -355,8 +352,7 @@ def r_export(rast, output="", fmt="png", **kargs): **kargs, ) return output - else: - raise ValueError("Raster map does not exist.") + raise ValueError("Raster map does not exist.") def get_lib_path(modname, libname=None): diff --git a/python/grass/pygrass/vector/__init__.py b/python/grass/pygrass/vector/__init__.py index 6f29a167b2e..461050807b0 100644 --- a/python/grass/pygrass/vector/__init__.py +++ b/python/grass/pygrass/vector/__init__.py @@ -70,8 +70,7 @@ def __init__(self, name, mapset="", *args, **kwargs): def __repr__(self): if self.exist(): return "%s(%r, %r)" % (self._class_name, self.name, self.mapset) - else: - return "%s(%r)" % (self._class_name, self.name) + return "%s(%r)" % (self._class_name, self.name) def __iter__(self): """:: @@ -315,10 +314,9 @@ def __getitem__(self, key): key.step or 1, ) ] - elif isinstance(key, int): + if isinstance(key, int): return self.read(key) - else: - raise ValueError("Invalid argument type: %r." % key) + raise ValueError("Invalid argument type: %r." % key) @must_be_open def num_primitive_of(self, primitive): @@ -392,11 +390,9 @@ def number_of(self, vtype): if isinstance(_NUMOF[vtype], tuple): fn, ptype = _NUMOF[vtype] return fn(self.c_mapinfo, ptype) - else: - return _NUMOF[vtype](self.c_mapinfo) - else: - keys = "', '".join(sorted(_NUMOF.keys())) - raise ValueError("vtype not supported, use one of: '%s'" % keys) + return _NUMOF[vtype](self.c_mapinfo) + keys = "', '".join(sorted(_NUMOF.keys())) + raise ValueError("vtype not supported, use one of: '%s'" % keys) @must_be_open def num_primitives(self): @@ -526,17 +522,16 @@ def cat(self, cat_id, vtype, layer=None, generator=False, geo=None): ) for v_id in ilist ) - else: - return [ - read_line( - feature_id=v_id, - c_mapinfo=self.c_mapinfo, - table=self.table, - writeable=self.writeable, - is2D=is2D, - ) - for v_id in ilist - ] + return [ + read_line( + feature_id=v_id, + c_mapinfo=self.c_mapinfo, + table=self.table, + writeable=self.writeable, + is2D=is2D, + ) + for v_id in ilist + ] @must_be_open def read(self, feature_id): @@ -855,7 +850,7 @@ def features_to_wkb_list(self, bbox=None, feature_type="point", field=1): if not barray: if error == -1: raise GrassError( - _("Unable to read line of feature %i" % (f_id)) + _("Unable to read line of feature %i") % (f_id) ) if error == -2: print("Empty feature %i" % (f_id)) @@ -947,7 +942,7 @@ def areas_to_wkb_list(self, bbox=None, field=1): self.c_mapinfo, a_id, ctypes.byref(size) ) if not barray: - raise GrassError(_("Unable to read area with id %i" % (a_id))) + raise GrassError(_("Unable to read area with id %i") % (a_id)) pcat = None c_ok = libvect.Vect_get_area_cats( diff --git a/python/grass/pygrass/vector/abstract.py b/python/grass/pygrass/vector/abstract.py index 3929006ef25..79307f0d354 100644 --- a/python/grass/pygrass/vector/abstract.py +++ b/python/grass/pygrass/vector/abstract.py @@ -299,8 +299,7 @@ def exist(self): self.mapset = mapset or "" return bool(mapset) return bool(utils.get_mapset_vector(self.name, self.mapset)) - else: - return False + return False def is_open(self): """Return if the Vector is open""" @@ -458,14 +457,14 @@ def close(self, build=False): if hasattr(self, "table") and self.table is not None: self.table.conn.close() if self.is_open(): - if libvect.Vect_close(self.c_mapinfo) != 0: - str_err = "Error when trying to close the map with Vect_close" - raise GrassError(str_err) if ( self.c_mapinfo.contents.mode in {libvect.GV_MODE_RW, libvect.GV_MODE_WRITE} ) and build: self.build() + if libvect.Vect_close(self.c_mapinfo) != 0: + str_err = "Error when trying to close the map with Vect_close" + raise GrassError(str_err) def remove(self): """Remove vector map""" @@ -475,16 +474,11 @@ def remove(self): def build(self): """Close the vector map and build vector Topology""" - self.close() - libvect.Vect_set_open_level(1) - if libvect.Vect_open_old2(self.c_mapinfo, self.name, self.mapset, "0") != 1: - str_err = "Error when trying to open the vector map." - raise GrassError(str_err) - # Vect_build returns 1 on success and 0 on error (bool approach) - if libvect.Vect_build(self.c_mapinfo) != 1: - str_err = "Error when trying build topology with Vect_build" - raise GrassError(str_err) - libvect.Vect_close(self.c_mapinfo) + if self.is_open(): + # Vect_build returns 1 on success and 0 on error (bool approach) + if libvect.Vect_build(self.c_mapinfo) != 1: + str_err = "Error when trying build topology with Vect_build" + raise GrassError(str_err) if __name__ == "__main__": diff --git a/python/grass/pygrass/vector/basic.py b/python/grass/pygrass/vector/basic.py index 079f7ac829f..f031e23ff98 100644 --- a/python/grass/pygrass/vector/basic.py +++ b/python/grass/pygrass/vector/basic.py @@ -149,8 +149,7 @@ def nsewtb(self, tb=True): """ if tb: return (self.north, self.south, self.east, self.west, self.top, self.bottom) - else: - return (self.north, self.south, self.east, self.west) + return (self.north, self.south, self.east, self.west) class BoxList: @@ -308,14 +307,13 @@ def __getitem__(self, key): self.c_ilist.contents.value[indx] for indx in range(*key.indices(len(self))) ] - elif isinstance(key, int): + if isinstance(key, int): if key < 0: # Handle negative indices key += self.c_ilist.contents.n_values if key >= self.c_ilist.contents.n_values: raise IndexError("Index out of range") return self.c_ilist.contents.value[key] - else: - raise ValueError("Invalid argument type: %r." % key) + raise ValueError("Invalid argument type: %r." % key) def __setitem__(self, key, value): if self.contains(value): @@ -329,7 +327,7 @@ def __iter__(self): return (self.c_ilist.contents.value[i] for i in range(self.__len__())) def __repr__(self): - return "Ilist(%r)" % [i for i in self.__iter__()] + return "Ilist(%r)" % list(self.__iter__()) def __contains__(self, item): return item in self.__iter__() diff --git a/python/grass/pygrass/vector/find.py b/python/grass/pygrass/vector/find.py index 9333497f110..25ce9aca8f4 100644 --- a/python/grass/pygrass/vector/find.py +++ b/python/grass/pygrass/vector/find.py @@ -490,11 +490,10 @@ def geos(self, bbox, type="all", bboxlist_only=False): ): if bboxlist_only: return found - else: - return ( - read_line(f_id, self.c_mapinfo, self.table, self.writeable) - for f_id in found.ids - ) + return ( + read_line(f_id, self.c_mapinfo, self.table, self.writeable) + for f_id in found.ids + ) @must_be_open def nodes(self, bbox): @@ -592,16 +591,15 @@ def areas(self, bbox, boxlist=None, bboxlist_only=False): ): if bboxlist_only: return boxlist - else: - return ( - Area( - v_id=a_id, - c_mapinfo=self.c_mapinfo, - table=self.table, - writeable=self.writeable, - ) - for a_id in boxlist.ids + return ( + Area( + v_id=a_id, + c_mapinfo=self.c_mapinfo, + table=self.table, + writeable=self.writeable, ) + for a_id in boxlist.ids + ) @must_be_open def islands(self, bbox, bboxlist_only=False): @@ -652,16 +650,15 @@ def islands(self, bbox, bboxlist_only=False): ): if bboxlist_only: return found - else: - return ( - Isle( - v_id=i_id, - c_mapinfo=self.c_mapinfo, - table=self.table, - writeable=self.writeable, - ) - for i_id in found.ids + return ( + Isle( + v_id=i_id, + c_mapinfo=self.c_mapinfo, + table=self.table, + writeable=self.writeable, ) + for i_id in found.ids + ) class PolygonFinder(AbstractFinder): diff --git a/python/grass/pygrass/vector/geometry.py b/python/grass/pygrass/vector/geometry.py index 1c5d378e6ef..10ecb1d2d13 100644 --- a/python/grass/pygrass/vector/geometry.py +++ b/python/grass/pygrass/vector/geometry.py @@ -94,8 +94,7 @@ def intersects(lineA, lineB, with_z=False): lineA.c_points, lineB.c_points, line.c_points, int(with_z) ): return line - else: - return [] + return [] # ============================================= @@ -370,8 +369,7 @@ def cat(self): def has_topology(self): if self.c_mapinfo is not None: return self.c_mapinfo.contents.level == 2 - else: - return False + return False @mapinfo_must_be_set def read(self): @@ -539,8 +537,7 @@ def coords(self): """ if self.is2D: return self.x, self.y - else: - return self.x, self.y, self.z + return self.x, self.y, self.z def to_wkt_p(self): """Return a "well know text" (WKT) geometry string Python implementation. :: @@ -577,10 +574,9 @@ def distance(self, pnt): """ if self.is2D or pnt.is2D: return libvect.Vect_points_distance(self.x, self.y, 0, pnt.x, pnt.y, 0, 0) - else: - return libvect.Vect_points_distance( - self.x, self.y, self.z, pnt.x, pnt.y, pnt.z, 1 - ) + return libvect.Vect_points_distance( + self.x, self.y, self.z, pnt.x, pnt.y, pnt.z, 1 + ) def buffer( self, dist=None, dist_x=None, dist_y=None, angle=0, round_=True, tol=0.1 @@ -675,7 +671,7 @@ def __getitem__(self, key): ) for indx in range(*key.indices(len(self))) ] - elif isinstance(key, int): + if isinstance(key, int): if key < 0: # Handle negative indices key += self.c_points.contents.n_points if key >= self.c_points.contents.n_points: @@ -685,8 +681,7 @@ def __getitem__(self, key): self.c_points.contents.y[key], None if self.is2D else self.c_points.contents.z[key], ) - else: - raise ValueError("Invalid argument type: %r." % key) + raise ValueError("Invalid argument type: %r." % key) def __setitem__(self, indx, pnt): """Change the coordinate of point. :: @@ -1373,8 +1368,7 @@ def _centroid(self, side, idonly=False): v_id = v_id or None if idonly: return v_id - else: - return Centroid(v_id=v_id, c_mapinfo=self.c_mapinfo) + return Centroid(v_id=v_id, c_mapinfo=self.c_mapinfo) def left_centroid(self, idonly=False): """Return left centroid @@ -1869,7 +1863,7 @@ def c_read_next_line(c_mapinfo, c_points, c_cats): v_id = v_id if v_id != 0 else None ftype = libvect.Vect_read_next_line(c_mapinfo, c_points, c_cats) if ftype == -2: - raise StopIteration() + raise StopIteration if ftype == -1: raise return ftype, v_id, c_points, c_cats @@ -1914,8 +1908,7 @@ def c_read_line(feature_id, c_mapinfo, c_points, c_cats): if feature_id > 0: ftype = libvect.Vect_read_line(c_mapinfo, c_points, c_cats, feature_id) return feature_id, ftype, c_points, c_cats - else: - raise ValueError("The index must be >0, %r given." % feature_id) + raise ValueError("The index must be >0, %r given." % feature_id) def read_line( diff --git a/python/grass/pygrass/vector/table.py b/python/grass/pygrass/vector/table.py index 4b7e99c0a83..9c8d0c3f9a2 100644 --- a/python/grass/pygrass/vector/table.py +++ b/python/grass/pygrass/vector/table.py @@ -65,14 +65,13 @@ def get_path(path, vect_name=None): """ if "$" not in path: return path - else: - mapset = Mapset() - path = path.replace("$GISDBASE", mapset.gisdbase) - path = path.replace("$LOCATION_NAME", mapset.location) - path = path.replace("$MAPSET", mapset.name) - if vect_name is not None: - path = path.replace("$MAP", vect_name) - return path + mapset = Mapset() + path = path.replace("$GISDBASE", mapset.gisdbase) + path = path.replace("$LOCATION_NAME", mapset.location) + path = path.replace("$MAPSET", mapset.name) + if vect_name is not None: + path = path.replace("$MAP", vect_name) + return path class Filters: @@ -326,8 +325,7 @@ def sql_descr(self, remove=None): return ", ".join( ["%s %s" % (key, val) for key, val in self.items() if key != remove] ) - else: - return ", ".join(["%s %s" % (key, val) for key, val in self.items()]) + return ", ".join(["%s %s" % (key, val) for key, val in self.items()]) def types(self): """Return a list with the column types. @@ -372,8 +370,7 @@ def names(self, remove=None, unicod=True): nams = list(self.odict.keys()) if unicod: return nams - else: - return [str(name) for name in nams] + return [str(name) for name in nams] def items(self): """Return a list of tuple with column name and column type. @@ -791,10 +788,7 @@ def __eq__(self, link): False """ attrs = ["layer", "name", "table_name", "key", "driver"] - for attr in attrs: - if getattr(self, attr) != getattr(link, attr): - return False - return True + return all(getattr(self, attr) == getattr(link, attr) for attr in attrs) def __ne__(self, other): return not self == other @@ -850,7 +844,7 @@ def connection(self): if not os.path.exists(dbdirpath): os.mkdir(dbdirpath) return sqlite3.connect(dbpath) - elif driver == "pg": + if driver == "pg": try: import psycopg2 @@ -943,11 +937,10 @@ def __iter__(self): def __getitem__(self, item): if isinstance(item, int): return self.by_index(item) - else: - return self.by_name(item) + return self.by_name(item) def __repr__(self): - return "DBlinks(%r)" % [link for link in self.__iter__()] + return "DBlinks(%r)" % list(self.__iter__()) def by_index(self, indx): """Return a Link object by index diff --git a/python/grass/pygrass/vector/testsuite/test_table.py b/python/grass/pygrass/vector/testsuite/test_table.py index 1acb410a10f..d87786fb3bd 100644 --- a/python/grass/pygrass/vector/testsuite/test_table.py +++ b/python/grass/pygrass/vector/testsuite/test_table.py @@ -65,7 +65,7 @@ def get_table_random_values(nrows, columns): raise TypeError("Unknown column type %s for: %s" % (ctype, cname)) vals.append(COL2VALS[ctype](nrows)) dtype.append((cname, vals[-1].dtype.str)) - return np.array([v for v in zip(*vals)], dtype=dtype) + return np.array(list(zip(*vals)), dtype=dtype) class DBconnection: diff --git a/python/grass/script/core.py b/python/grass/script/core.py index a86738926f0..4f70f525133 100644 --- a/python/grass/script/core.py +++ b/python/grass/script/core.py @@ -127,8 +127,7 @@ def _make_unicode(val, enc): if enc == "default": return decode(val) - else: - return decode(val, encoding=enc) + return decode(val, encoding=enc) def get_commands(*, env=None): @@ -349,7 +348,7 @@ def get_module_and_code(args, kwargs): return result if handler.lower() == "ignore": return result - elif handler.lower() == "fatal": + if handler.lower() == "fatal": module, code = get_module_and_code(args, kwargs) fatal( _( @@ -1066,7 +1065,7 @@ def _text_to_key_value_dict( {'a': ['Hello'], 'c': [1, 2, 3, 4, 5], 'b': [1.0], 'd': ['hello', 8, 0.1]} """ - text = open(filename, "r").readlines() + text = open(filename).readlines() kvdict = KeyValue() for line in text: @@ -1276,7 +1275,7 @@ def region_env(region3d=False, flags=None, env=None, **kwargs): windfile = os.path.join( gis_env["GISDBASE"], gis_env["LOCATION_NAME"], gis_env["MAPSET"], "WIND" ) - with open(windfile, "r") as fd: + with open(windfile) as fd: grass_region = "" for line in fd: key, value = (x.strip() for x in line.split(":", 1)) @@ -1650,8 +1649,7 @@ def verbosity(): vbstr = os.getenv("GRASS_VERBOSE") if vbstr: return int(vbstr) - else: - return 2 + return 2 # Various utilities, not specific to GRASS @@ -1894,7 +1892,7 @@ def _create_location_xy(database, location): :param database: GRASS database where to create new location :param location: location name """ - cur_dir = os.getcwd() + cur_dir = Path.cwd() try: os.chdir(database) os.mkdir(location) diff --git a/python/grass/script/db.py b/python/grass/script/db.py index 2725ff06ebe..60813379501 100644 --- a/python/grass/script/db.py +++ b/python/grass/script/db.py @@ -229,8 +229,7 @@ def db_table_in_vector(table, mapset=".", env=None): break if len(used) > 0: return used - else: - return None + return None def db_begin_transaction(driver): diff --git a/python/grass/script/raster.py b/python/grass/script/raster.py index f9937902dab..bcaab7ef596 100644 --- a/python/grass/script/raster.py +++ b/python/grass/script/raster.py @@ -65,8 +65,8 @@ def raster_history(map, overwrite=False, env=None): _( "Unable to write history for <%(map)s>. " "Raster map <%(map)s> not found in current mapset." - % {"map": map, "map": map} ) + % {"map": map, "map": map} ) return False @@ -88,8 +88,7 @@ def raster_info(map, env=None): def float_or_null(s): if s == "NULL": return None - else: - return float(s) + return float(s) s = read_command("r.info", flags="gre", map=map, env=env) kv = parse_key_val(s) diff --git a/python/grass/script/raster3d.py b/python/grass/script/raster3d.py index 3b89b4fb707..e3db5398158 100644 --- a/python/grass/script/raster3d.py +++ b/python/grass/script/raster3d.py @@ -47,8 +47,7 @@ def raster3d_info(map, env=None): def float_or_null(s): if s == "NULL": return None - else: - return float(s) + return float(s) s = read_command("r3.info", flags="rg", map=map, env=env) kv = parse_key_val(s) diff --git a/python/grass/script/task.py b/python/grass/script/task.py index 35234ba65e6..cf398c59214 100644 --- a/python/grass/script/task.py +++ b/python/grass/script/task.py @@ -90,8 +90,7 @@ def get_name(self): name, ext = os.path.splitext(self.name) if ext in {".py", ".sh"}: return name - else: - return self.name + return self.name return self.name @@ -103,10 +102,8 @@ def get_description(self, full=True): if self.label: if full: return self.label + " " + self.description - else: - return self.label - else: - return self.description + return self.label + return self.description def get_keywords(self): """Get module's keywords""" @@ -247,11 +244,7 @@ def get_options(self): def has_required(self): """Check if command has at least one required parameter""" - for p in self.params: - if p.get("required", False): - return True - - return False + return any(p.get("required", False) for p in self.params) def set_param(self, aParam, aValue, element="value"): """Set param value/values.""" diff --git a/python/grass/script/tests/grass_script_setup_test.py b/python/grass/script/tests/grass_script_setup_test.py index 62a0ca37b74..36dfbb77dbb 100644 --- a/python/grass/script/tests/grass_script_setup_test.py +++ b/python/grass/script/tests/grass_script_setup_test.py @@ -51,7 +51,7 @@ def test_init_session_finish(tmp_path): gs.run_command("g.region", flags="p", env=session.env) session_file = session.env["GISRC"] session.finish() - with pytest.raises(ValueError): + with pytest.raises(ValueError): # noqa: PT011 session.finish() assert not session.active assert not os.path.exists(session_file) diff --git a/python/grass/script/testsuite/test_start_command_functions.py b/python/grass/script/testsuite/test_start_command_functions.py index 414a68cd270..368669263a8 100644 --- a/python/grass/script/testsuite/test_start_command_functions.py +++ b/python/grass/script/testsuite/test_start_command_functions.py @@ -4,6 +4,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows from grass.script.core import start_command, PIPE, run_command, write_command from grass.script.core import read_command, find_program @@ -85,6 +86,7 @@ def setUpClass(cls): def tearDownClass(cls): cls.runModule("g.remove", type="raster", name=cls.raster, flags="f") + @xfail_windows def test_write_labels_unicode(self): """This tests if Python module works""" find_program("ls", "--version") @@ -99,6 +101,7 @@ def test_write_labels_unicode(self): self.assertEqual(res, "1:kůň\n2:kráva\n3:ovečka\n4:býk") self.assertIsInstance(res, str) + @xfail_windows def test_write_labels_bytes(self): """This tests if Python module works""" write_command( diff --git a/python/grass/script/testsuite/test_utils.py b/python/grass/script/testsuite/test_utils.py index db12041d66d..67d2c59dd69 100644 --- a/python/grass/script/testsuite/test_utils.py +++ b/python/grass/script/testsuite/test_utils.py @@ -2,6 +2,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows from grass.script import utils @@ -39,6 +40,7 @@ def test_bytes(self): def test_unicode(self): self.assertEqual(b"text", utils.encode("text")) + @xfail_windows def test_bytes_garbage_in_out(self): """If the input is bytes we should not touch it for encoding""" self.assertEqual( diff --git a/python/grass/script/utils.py b/python/grass/script/utils.py index 13d049412a4..448289b57aa 100644 --- a/python/grass/script/utils.py +++ b/python/grass/script/utils.py @@ -28,6 +28,8 @@ import random import string +from pathlib import Path + def float_or_dms(s): """Convert DMS to float. @@ -67,13 +69,13 @@ def separator(sep): """ if sep == "pipe": return "|" - elif sep == "comma": + if sep == "comma": return "," - elif sep == "space": + if sep == "space": return " " - elif sep in {"tab", "\\t"}: + if sep in {"tab", "\\t"}: return "\t" - elif sep in {"newline", "\\n"}: + if sep in {"newline", "\\n"}: return "\n" return sep @@ -89,8 +91,8 @@ def diff_files(filename_a, filename_b): import difflib differ = difflib.Differ() - fh_a = open(filename_a, "r") - fh_b = open(filename_b, "r") + fh_a = open(filename_a) + fh_b = open(filename_b) return list(differ.compare(fh_a.readlines(), fh_b.readlines())) @@ -371,10 +373,9 @@ def get_lib_path(modname, libname=None): getenv("GRASS_ADDON_BASE") and libname and isdir(join(getenv("GRASS_ADDON_BASE"), "etc", modname, libname)) - ): - path = join(getenv("GRASS_ADDON_BASE"), "etc", modname) - elif getenv("GRASS_ADDON_BASE") and isdir( - join(getenv("GRASS_ADDON_BASE"), "etc", modname) + ) or ( + getenv("GRASS_ADDON_BASE") + and isdir(join(getenv("GRASS_ADDON_BASE"), "etc", modname)) ): path = join(getenv("GRASS_ADDON_BASE"), "etc", modname) elif getenv("GRASS_ADDON_BASE") and isdir( @@ -383,7 +384,7 @@ def get_lib_path(modname, libname=None): path = join(os.getenv("GRASS_ADDON_BASE"), modname, modname) else: # used by g.extension compilation process - cwd = os.getcwd() + cwd = str(Path.cwd()) idx = cwd.find(modname) if idx < 0: return None @@ -463,10 +464,10 @@ def set_path(modulename, dirname=None, path="."): import sys # TODO: why dirname is checked first - the logic should be revised - pathlib = None + _pathlib = None if dirname: - pathlib = os.path.join(path, dirname) - if pathlib and os.path.exists(pathlib): + _pathlib = os.path.join(path, dirname) + if _pathlib and os.path.exists(_pathlib): # we are running the script from the script directory, therefore # we add the path to sys.path to reach the directory (dirname) sys.path.append(os.path.abspath(path)) @@ -477,7 +478,7 @@ def set_path(modulename, dirname=None, path="."): pathname = os.path.join(modulename, dirname) if dirname else modulename raise ImportError( "Not able to find the path '%s' directory " - "(current dir '%s')." % (pathname, os.getcwd()) + "(current dir '%s')." % (pathname, Path.cwd()) ) sys.path.insert(0, path) diff --git a/python/grass/temporal/abstract_dataset.py b/python/grass/temporal/abstract_dataset.py index cfe3c83a841..bf30afa21dd 100644 --- a/python/grass/temporal/abstract_dataset.py +++ b/python/grass/temporal/abstract_dataset.py @@ -76,7 +76,7 @@ def get_number_of_relations(self): """ if self.is_temporal_topology_build() and not self.is_spatial_topology_build(): return self.get_number_of_temporal_relations() - elif self.is_spatial_topology_build() and not self.is_temporal_topology_build(): + if self.is_spatial_topology_build() and not self.is_temporal_topology_build(): self.get_number_of_spatial_relations() else: return ( @@ -511,8 +511,7 @@ def is_time_absolute(self): """ if "temporal_type" in self.base.D: return self.base.get_ttype() == "absolute" - else: - return None + return None def is_time_relative(self): """Return True in case the temporal type is relative @@ -521,8 +520,7 @@ def is_time_relative(self): """ if "temporal_type" in self.base.D: return self.base.get_ttype() == "relative" - else: - return None + return None def get_temporal_extent(self): """Return the temporal extent of the correct internal type""" diff --git a/python/grass/temporal/abstract_map_dataset.py b/python/grass/temporal/abstract_map_dataset.py index f58bcb82d66..ecbf761d139 100644 --- a/python/grass/temporal/abstract_map_dataset.py +++ b/python/grass/temporal/abstract_map_dataset.py @@ -232,8 +232,7 @@ def build_id_from_search_path(name, element): if layer is not None: return f"{name}:{layer}@{mapset}" - else: - return f"{name}@{mapset}" + return f"{name}@{mapset}" @staticmethod def build_id(name, mapset, layer=None): @@ -258,8 +257,7 @@ def build_id(name, mapset, layer=None): if layer is not None: return f"{name}:{layer}@{mapset}" - else: - return f"{name}@{mapset}" + return f"{name}@{mapset}" def get_layer(self): """Return the layer of the map @@ -443,15 +441,11 @@ def set_absolute_time(self, start_time, end_time=None): } ) return False - else: - self.msgr.error( - _( - "Start time must be of type datetime for " - "%(type)s map <%(id)s>" - ) - % {"type": self.get_type(), "id": self.get_map_id()} - ) - return False + self.msgr.error( + _("Start time must be of type datetime for %(type)s map <%(id)s>") + % {"type": self.get_type(), "id": self.get_map_id()} + ) + return False if end_time and not isinstance(end_time, datetime): if self.get_layer(): @@ -467,12 +461,11 @@ def set_absolute_time(self, start_time, end_time=None): } ) return False - else: - self.msgr.error( - _("End time must be of type datetime for %(type)s map <%(id)s>") - % {"type": self.get_type(), "id": self.get_map_id()} - ) - return False + self.msgr.error( + _("End time must be of type datetime for %(type)s map <%(id)s>") + % {"type": self.get_type(), "id": self.get_map_id()} + ) + return False if start_time is not None and end_time is not None: if start_time > end_time: @@ -490,17 +483,16 @@ def set_absolute_time(self, start_time, end_time=None): } ) return False - else: - self.msgr.error( - _( - "End time must be greater than start " - "time for %(type)s map <%(id)s>" - ) - % {"type": self.get_type(), "id": self.get_map_id()} + self.msgr.error( + _( + "End time must be greater than start " + "time for %(type)s map <%(id)s>" ) - return False + % {"type": self.get_type(), "id": self.get_map_id()} + ) + return False # Do not create an interval in case start and end time are equal - elif start_time == end_time: + if start_time == end_time: end_time = None self.base.set_ttype("absolute") @@ -618,7 +610,7 @@ def set_relative_time(self, start_time, end_time, unit): ) return False # Do not create an interval in case start and end time are equal - elif start_time == end_time: + if start_time == end_time: end_time = None self.base.set_ttype("relative") diff --git a/python/grass/temporal/abstract_space_time_dataset.py b/python/grass/temporal/abstract_space_time_dataset.py index 515502ff3f1..d17baaab6ae 100644 --- a/python/grass/temporal/abstract_space_time_dataset.py +++ b/python/grass/temporal/abstract_space_time_dataset.py @@ -16,6 +16,7 @@ class that is the base class for all space time datasets. import uuid from abc import ABCMeta, abstractmethod from datetime import datetime +from pathlib import Path from .abstract_dataset import AbstractDataset, AbstractDatasetComparisonKeyStartTime from .core import ( @@ -395,9 +396,7 @@ def insert(self, dbif=None, execute=True): # %s;"%(stds_register_table + "_index", stds_register_table)) # Read the SQL template - sql = open( - os.path.join(sql_path, "stds_map_register_table_template.sql"), "r" - ).read() + sql = Path(sql_path, "stds_map_register_table_template.sql").read_text() # Create a raster, raster3d or vector tables sql = sql.replace("SPACETIME_REGISTER_TABLE", stds_register_table) @@ -1627,8 +1626,7 @@ def leading_zero(value): try: if value.startswith("0"): return value.lstrip("0") - else: - return "{0:02d}".format(int(value)) + return "{0:02d}".format(int(value)) except ValueError: return None @@ -2025,7 +2023,7 @@ def shift(self, gran, dbif=None): ) if not check_granularity_string(gran, self.get_temporal_type()): - self.msgr.error(_("Wrong granularity format: %s" % (gran))) + self.msgr.error(_("Wrong granularity format: %s") % (gran)) return False dbif, connection_state_changed = init_dbif(dbif) @@ -2818,13 +2816,10 @@ def update_from_registered_maps(self, dbif=None): ) if old_sqlite_version: template_suffix = "_old" - sql = open( - os.path.join( - sql_path, - f"update_stds_spatial_temporal_extent_template{template_suffix}.sql", - ), - "r", - ).read() + sql = Path( + sql_path, + f"update_stds_spatial_temporal_extent_template{template_suffix}.sql", + ).read_text() sql = sql.replace("GRASS_MAP", self.get_new_map_instance(None).get_type()) sql = sql.replace("SPACETIME_REGISTER_TABLE", stds_register_table) sql = sql.replace("SPACETIME_ID", self.base.get_id()) @@ -2834,13 +2829,10 @@ def update_from_registered_maps(self, dbif=None): sql_script += "\n" # Update type specific metadata - sql = open( - os.path.join( - sql_path, - f"update_{self.get_type()}_metadata_template{template_suffix}.sql", - ), - "r", - ).read() + sql = Path( + sql_path, + f"update_{self.get_type()}_metadata_template{template_suffix}.sql", + ).read_text() # Comment out update of semantic labels for DB version < 3 if get_tgis_db_version_from_metadata() < 3: @@ -2853,10 +2845,9 @@ def update_from_registered_maps(self, dbif=None): "-- count(distinct semantic_label)", ) elif old_sqlite_version and self.get_type() == "strds": - semantic_label_sql = open( - os.path.join(sql_path, "update_strds_metadata_template_v3.sql"), - "r", - ).read() + semantic_label_sql = Path( + sql_path, "update_strds_metadata_template_v3.sql" + ).read_text() sql = sql + "\n" + semantic_label_sql sql = sql.replace("SPACETIME_REGISTER_TABLE", stds_register_table) diff --git a/python/grass/temporal/aggregation.py b/python/grass/temporal/aggregation.py index 1ea60eaeea1..354600855e0 100644 --- a/python/grass/temporal/aggregation.py +++ b/python/grass/temporal/aggregation.py @@ -154,16 +154,14 @@ def aggregate_raster_maps( _( "Raster map <%(name)s> is already in temporal " "database, use overwrite flag to overwrite" - % ({"name": new_map.get_name()}) ) + % ({"name": new_map.get_name()}) ) return msgr.verbose( - _( - "Computing aggregation of maps between %(st)s - %(end)s" - % {"st": str(start), "end": str(end)} - ) + _("Computing aggregation of maps between %(st)s - %(end)s") + % {"st": str(start), "end": str(end)} ) # Create the r.series input file @@ -356,8 +354,9 @@ def aggregate_by_topology( _( "Unable to perform aggregation. Output raster " "map <%(name)s> exists and overwrite flag was " - "not set" % ({"name": output_name}) + "not set" ) + % ({"name": output_name}) ) output_list.append(map_layer) @@ -380,8 +379,8 @@ def aggregate_by_topology( "reached (%i). The module r.series will " "be run with flag z, to avoid open " "files limit exceeding." - % (int(file_limit), len(aggregation_list)) ) + % (int(file_limit), len(aggregation_list)) ) mod(flags="z") process_queue.put(mod) diff --git a/python/grass/temporal/base.py b/python/grass/temporal/base.py index 9296a22dfa1..ebb4b715e29 100644 --- a/python/grass/temporal/base.py +++ b/python/grass/temporal/base.py @@ -466,10 +466,9 @@ def get_update_statement(self, ident=None): return self.serialize( "UPDATE", self.get_table_name(), "WHERE id = '" + str(ident) + "'" ) - else: - return self.serialize( - "UPDATE", self.get_table_name(), "WHERE id = '" + str(self.ident) + "'" - ) + return self.serialize( + "UPDATE", self.get_table_name(), "WHERE id = '" + str(self.ident) + "'" + ) def get_update_statement_mogrified(self, dbif=None, ident=None): """Return the update statement as mogrified string @@ -529,12 +528,11 @@ def get_update_all_statement(self, ident=None): return self.serialize( "UPDATE ALL", self.get_table_name(), "WHERE id = '" + str(ident) + "'" ) - else: - return self.serialize( - "UPDATE ALL", - self.get_table_name(), - "WHERE id = '" + str(self.ident) + "'", - ) + return self.serialize( + "UPDATE ALL", + self.get_table_name(), + "WHERE id = '" + str(self.ident) + "'", + ) def get_update_all_statement_mogrified(self, dbif=None, ident=None): """Return the update all statement as mogrified string @@ -749,8 +747,7 @@ def get_id(self): """ if "id" in self.D: return self.D["id"] - else: - return None + return None def get_map_id(self): """Convenient method to get the unique map identifier @@ -763,10 +760,8 @@ def get_map_id(self): if self.id.find(":") >= 0: # Remove the layer identifier from the id return self.id.split("@")[0].split(":")[0] + "@" + self.id.split("@")[1] - else: - return self.id - else: - return None + return self.id + return None def get_layer(self): """Convenient method to get the layer of the map (part of primary key) @@ -777,48 +772,42 @@ def get_layer(self): """ if "layer" in self.D: return self.D["layer"] - else: - return None + return None def get_name(self): """Get the name of the dataset :return: None if not found""" if "name" in self.D: return self.D["name"] - else: - return None + return None def get_mapset(self): """Get the name of mapset of this dataset :return: None if not found""" if "mapset" in self.D: return self.D["mapset"] - else: - return None + return None def get_creator(self): """Get the creator of the dataset :return: None if not found""" if "creator" in self.D: return self.D["creator"] - else: - return None + return None def get_ctime(self): """Get the creation time of the dataset, datatype is datetime :return: None if not found""" if "creation_time" in self.D: return self.D["creation_time"] - else: - return None + return None def get_ttype(self): """Get the temporal type of the map :return: None if not found""" if "temporal_type" in self.D: return self.D["temporal_type"] - else: - return None + return None # Properties of this class id = property(fget=get_id, fset=set_id) @@ -1027,8 +1016,7 @@ def get_semantic_type(self): """ if "semantic_type" in self.D: return self.D["semantic_type"] - else: - return None + return None def get_mtime(self): """Get the modification time of the space time dataset, datatype is @@ -1038,8 +1026,7 @@ def get_mtime(self): """ if "modification_time" in self.D: return self.D["modification_time"] - else: - return None + return None semantic_type = property(fget=get_semantic_type, fset=set_semantic_type) @@ -1201,8 +1188,7 @@ def get_id(self): """ if "id" in self.D: return self.D["id"] - else: - return None + return None def get_registered_stds(self): """Get the comma separated list of space time datasets ids @@ -1212,8 +1198,7 @@ def get_registered_stds(self): """ if "registered_stds" in self.D: return self.D["registered_stds"] - else: - return None + return None # Properties of this class id = property(fget=get_id, fset=set_id) diff --git a/python/grass/temporal/c_libraries_interface.py b/python/grass/temporal/c_libraries_interface.py index 6b67dfb9869..85a19a3ec6e 100644 --- a/python/grass/temporal/c_libraries_interface.py +++ b/python/grass/temporal/c_libraries_interface.py @@ -815,7 +815,7 @@ def _read_raster3d_info(name, mapset): ) if not g3map: - logging.error(_("Unable to open 3D raster map <%s>" % (name))) + logging.error(_("Unable to open 3D raster map <%s>"), (name)) return None maptype = libraster3d.Rast3d_file_type_map(g3map) @@ -830,7 +830,7 @@ def _read_raster3d_info(name, mapset): max = libgis.DCELL() ret = libraster3d.Rast3d_range_load(g3map) if not ret: - logging.error(_("Unable to load range of 3D raster map <%s>" % (name))) + logging.error(_("Unable to load range of 3D raster map <%s>"), (name)) return None libraster3d.Rast3d_range_min_max(g3map, byref(min), byref(max)) @@ -844,7 +844,7 @@ def _read_raster3d_info(name, mapset): kvp["max"] = float(max.value) if not libraster3d.Rast3d_close(g3map): - logging.error(_("Unable to close 3D raster map <%s>" % (name))) + logging.error(_("Unable to close 3D raster map <%s>"), (name)) return None return kvp @@ -887,10 +887,8 @@ def _read_vector_info(name, mapset): with_topo = False if libvector.Vect_open_old2(byref(Map), name, mapset, "1") < 1: logging.error( - _( - "Unable to open vector map <%s>" - % (libvector.Vect_get_full_name(byref(Map))) - ) + _("Unable to open vector map <%s>"), + (libvector.Vect_get_full_name(byref(Map))), ) return None @@ -1013,13 +1011,12 @@ def _read_raster_history(name, mapset): if ret < 0: logging.warning(_("Unable to read history file")) return None - else: - kvp["creation_time"] = decode( - libraster.Rast_get_history(byref(hist), libraster.HIST_MAPID) - ) - kvp["creator"] = decode( - libraster.Rast_get_history(byref(hist), libraster.HIST_CREATOR) - ) + kvp["creation_time"] = decode( + libraster.Rast_get_history(byref(hist), libraster.HIST_MAPID) + ) + kvp["creator"] = decode( + libraster.Rast_get_history(byref(hist), libraster.HIST_CREATOR) + ) return kvp @@ -1051,13 +1048,12 @@ def _read_raster3d_history(name, mapset): if ret < 0: logging.warning(_("Unable to read history file")) return None - else: - kvp["creation_time"] = decode( - libraster.Rast_get_history(byref(hist), libraster3d.HIST_MAPID) - ) - kvp["creator"] = decode( - libraster.Rast_get_history(byref(hist), libraster3d.HIST_CREATOR) - ) + kvp["creation_time"] = decode( + libraster.Rast_get_history(byref(hist), libraster3d.HIST_MAPID) + ) + kvp["creator"] = decode( + libraster.Rast_get_history(byref(hist), libraster3d.HIST_CREATOR) + ) return kvp @@ -1144,43 +1140,42 @@ def _convert_timestamp_from_grass(ts): # ATTENTION: We ignore the time zone # TODO: Write time zone support return (pdt1, pdt2) - else: - unit = None - start = None - end = None - if count.value >= 1: - if dt1.year > 0: - unit = "years" - start = dt1.year - elif dt1.month > 0: - unit = "months" - start = dt1.month - elif dt1.day > 0: - unit = "days" - start = dt1.day - elif dt1.hour > 0: - unit = "hours" - start = dt1.hour - elif dt1.minute > 0: - unit = "minutes" - start = dt1.minute - elif dt1.second > 0: - unit = "seconds" - start = dt1.second - if count.value == 2: - if dt2.year > 0: - end = dt2.year - elif dt2.month > 0: - end = dt2.month - elif dt2.day > 0: - end = dt2.day - elif dt2.hour > 0: - end = dt2.hour - elif dt2.minute > 0: - end = dt2.minute - elif dt2.second > 0: - end = dt2.second - return (start, end, unit) + unit = None + start = None + end = None + if count.value >= 1: + if dt1.year > 0: + unit = "years" + start = dt1.year + elif dt1.month > 0: + unit = "months" + start = dt1.month + elif dt1.day > 0: + unit = "days" + start = dt1.day + elif dt1.hour > 0: + unit = "hours" + start = dt1.hour + elif dt1.minute > 0: + unit = "minutes" + start = dt1.minute + elif dt1.second > 0: + unit = "seconds" + start = dt1.second + if count.value == 2: + if dt2.year > 0: + end = dt2.year + elif dt2.month > 0: + end = dt2.month + elif dt2.day > 0: + end = dt2.day + elif dt2.hour > 0: + end = dt2.hour + elif dt2.minute > 0: + end = dt2.minute + elif dt2.second > 0: + end = dt2.second + return (start, end, unit) ############################################################################### diff --git a/python/grass/temporal/core.py b/python/grass/temporal/core.py index dc74bff151d..321c73d5408 100644 --- a/python/grass/temporal/core.py +++ b/python/grass/temporal/core.py @@ -769,12 +769,12 @@ def init(raise_fatal_error=False, skip_db_version_check=False): "Temporal database version mismatch detected.\n{backup}" "Supported temporal database version is: {tdb}\n" "Your existing temporal database version: {ctdb}\n" - "Current temporal database info: {info}".format( - backup=backup_howto, - tdb=tgis_db_version, - ctdb=tgis_db_version_meta, - info=get_database_info_string(), - ) + "Current temporal database info: {info}" + ).format( + backup=backup_howto, + tdb=tgis_db_version, + ctdb=tgis_db_version_meta, + info=get_database_info_string(), ) if tgis_db_version_meta == 2 and tgis_db_version == 3: @@ -784,8 +784,8 @@ def init(raise_fatal_error=False, skip_db_version_check=False): msgr.fatal( _( "The format of your actual temporal database is " - "not supported any more. {m}".format(m=message) - ) + "not supported any more. {m}" + ).format(m=message) ) return @@ -862,7 +862,7 @@ def create_temporal_database(dbif): stvds_tables_sql = stds_tables_template_sql.replace("STDS", "stvds") str3ds_tables_sql = stds_tables_template_sql.replace("STDS", "str3ds") - msgr.message(_("Creating temporal database: %s" % (str(tgis_database_string)))) + msgr.message(_("Creating temporal database: %s") % (str(tgis_database_string))) if tgis_backend == "sqlite": # We need to create the sqlite3 database path if it does not exist @@ -875,8 +875,9 @@ def create_temporal_database(dbif): _( "Unable to create SQLite temporal database\n" "Exception: %s\nPlease use t.connect to set a " - "read- and writable temporal database path" % (e) + "read- and writable temporal database path" ) + % (e) ) # Set up the trigger that takes care of @@ -1375,7 +1376,7 @@ def mogrify_sql_statement(self, content): if self.dbmi.__name__ == "psycopg2": if len(args) == 0: return sql - elif self.connected: + if self.connected: try: return self.cursor.mogrify(sql, args) except Exception as exc: @@ -1390,57 +1391,56 @@ def mogrify_sql_statement(self, content): elif self.dbmi.__name__ == "sqlite3": if len(args) == 0: return sql - else: - # Unfortunately as sqlite does not support - # the transformation of sql strings and qmarked or - # named arguments we must make our hands dirty - # and do it by ourself. :( - # Doors are open for SQL injection because of the - # limited python sqlite3 implementation!!! - pos = 0 - count = 0 - maxcount = 100 - statement = sql - - while count < maxcount: - pos = statement.find("?", pos + 1) - if pos == -1: - break - - if args[count] is None: - statement = "%sNULL%s" % ( - statement[0:pos], - statement[pos + 1 :], - ) - elif isinstance(args[count], int): - statement = "%s%d%s" % ( - statement[0:pos], - args[count], - statement[pos + 1 :], - ) - elif isinstance(args[count], float): - statement = "%s%f%s" % ( - statement[0:pos], - args[count], - statement[pos + 1 :], - ) - elif isinstance(args[count], datetime): - statement = "%s'%s'%s" % ( - statement[0:pos], - str(args[count]), - statement[pos + 1 :], - ) - else: - # Default is a string, this works for datetime - # objects too - statement = "%s'%s'%s" % ( - statement[0:pos], - str(args[count]), - statement[pos + 1 :], - ) - count += 1 + # Unfortunately as sqlite does not support + # the transformation of sql strings and qmarked or + # named arguments we must make our hands dirty + # and do it by ourself. :( + # Doors are open for SQL injection because of the + # limited python sqlite3 implementation!!! + pos = 0 + count = 0 + maxcount = 100 + statement = sql + + while count < maxcount: + pos = statement.find("?", pos + 1) + if pos == -1: + break + + if args[count] is None: + statement = "%sNULL%s" % ( + statement[0:pos], + statement[pos + 1 :], + ) + elif isinstance(args[count], int): + statement = "%s%d%s" % ( + statement[0:pos], + args[count], + statement[pos + 1 :], + ) + elif isinstance(args[count], float): + statement = "%s%f%s" % ( + statement[0:pos], + args[count], + statement[pos + 1 :], + ) + elif isinstance(args[count], datetime): + statement = "%s'%s'%s" % ( + statement[0:pos], + str(args[count]), + statement[pos + 1 :], + ) + else: + # Default is a string, this works for datetime + # objects too + statement = "%s'%s'%s" % ( + statement[0:pos], + str(args[count]), + statement[pos + 1 :], + ) + count += 1 - return statement + return statement def check_table(self, table_name): """Check if a table exists in the temporal database @@ -1502,7 +1502,7 @@ def execute(self, statement, args=None): except: if connected: self.close() - self.msgr.error(_("Unable to execute :\n %(sql)s" % {"sql": statement})) + self.msgr.error(_("Unable to execute :\n %(sql)s") % {"sql": statement}) raise if connected: @@ -1546,7 +1546,7 @@ def execute_transaction(self, statement, mapset=None): if connected: self.close() self.msgr.error( - _("Unable to execute transaction:\n %(sql)s" % {"sql": statement}) + _("Unable to execute transaction:\n %(sql)s") % {"sql": statement} ) raise diff --git a/python/grass/temporal/datetime_math.py b/python/grass/temporal/datetime_math.py index 9b680760775..1031582fe23 100644 --- a/python/grass/temporal/datetime_math.py +++ b/python/grass/temporal/datetime_math.py @@ -828,7 +828,7 @@ def check_datetime_string(time_string, use_dateutil=True): try: return datetime.strptime(time_string, time_format) except: - return _("Unable to parse time string: %s" % time_string) + return _("Unable to parse time string: %s") % time_string ############################################################################### diff --git a/python/grass/temporal/mapcalc.py b/python/grass/temporal/mapcalc.py index 5f29cd32747..8761e86160f 100644 --- a/python/grass/temporal/mapcalc.py +++ b/python/grass/temporal/mapcalc.py @@ -508,90 +508,72 @@ def _parse_start_operators(expr, is_time_absolute, current): if expr.find("start_year()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("start_*") - ) + _("The temporal operators <%s> support only absolute time.") + % ("start_*") ) expr = expr.replace("start_year()", str(start.year)) if expr.find("start_month()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("start_*") - ) + _("The temporal operators <%s> support only absolute time.") + % ("start_*") ) expr = expr.replace("start_month()", str(start.month)) if expr.find("start_week()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("start_*") - ) + _("The temporal operators <%s> support only absolute time.") + % ("start_*") ) expr = expr.replace("start_week()", str(start.isocalendar()[1])) if expr.find("start_day()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("start_*") - ) + _("The temporal operators <%s> support only absolute time.") + % ("start_*") ) expr = expr.replace("start_day()", str(start.day)) if expr.find("start_hour()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("start_*") - ) + _("The temporal operators <%s> support only absolute time.") + % ("start_*") ) expr = expr.replace("start_hour()", str(start.hour)) if expr.find("start_minute()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("start_*") - ) + _("The temporal operators <%s> support only absolute time.") + % ("start_*") ) expr = expr.replace("start_minute()", str(start.minute)) if expr.find("start_second()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("start_*") - ) + _("The temporal operators <%s> support only absolute time.") + % ("start_*") ) expr = expr.replace("start_second()", str(start.second)) if expr.find("start_dow()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("start_*") - ) + _("The temporal operators <%s> support only absolute time.") + % ("start_*") ) expr = expr.replace("start_dow()", str(start.isoweekday())) if expr.find("start_doy()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("start_*") - ) + _("The temporal operators <%s> support only absolute time.") + % ("start_*") ) year = datetime(start.year, 1, 1) delta = start - year @@ -628,10 +610,7 @@ def _parse_end_operators(expr, is_time_absolute, current): if expr.find("end_year()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("end_*") - ) + _("The temporal operators <%s> support only absolute time.") % ("end_*") ) if not end: expr = expr.replace("end_year()", "null()") @@ -641,10 +620,7 @@ def _parse_end_operators(expr, is_time_absolute, current): if expr.find("end_month()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("end_*") - ) + _("The temporal operators <%s> support only absolute time.") % ("end_*") ) if not end: expr = expr.replace("end_month()", "null()") @@ -654,10 +630,7 @@ def _parse_end_operators(expr, is_time_absolute, current): if expr.find("end_week()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("end_*") - ) + _("The temporal operators <%s> support only absolute time.") % ("end_*") ) if not end: expr = expr.replace("end_week()", "null()") @@ -667,10 +640,7 @@ def _parse_end_operators(expr, is_time_absolute, current): if expr.find("end_day()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("end_*") - ) + _("The temporal operators <%s> support only absolute time.") % ("end_*") ) if not end: expr = expr.replace("end_day()", "null()") @@ -680,10 +650,7 @@ def _parse_end_operators(expr, is_time_absolute, current): if expr.find("end_hour()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("end_*") - ) + _("The temporal operators <%s> support only absolute time.") % ("end_*") ) if not end: expr = expr.replace("end_hour()", "null()") @@ -693,10 +660,7 @@ def _parse_end_operators(expr, is_time_absolute, current): if expr.find("end_minute()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("end_*") - ) + _("The temporal operators <%s> support only absolute time.") % ("end_*") ) if not end: expr = expr.replace("end_minute()", "null()") @@ -706,10 +670,7 @@ def _parse_end_operators(expr, is_time_absolute, current): if expr.find("end_second()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("end_*") - ) + _("The temporal operators <%s> support only absolute time.") % ("end_*") ) if not end: expr = expr.replace("end_second()", "null()") @@ -719,10 +680,7 @@ def _parse_end_operators(expr, is_time_absolute, current): if expr.find("end_dow()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("end_*") - ) + _("The temporal operators <%s> support only absolute time.") % ("end_*") ) if not end: expr = expr.replace("end_dow()", "null()") @@ -732,10 +690,7 @@ def _parse_end_operators(expr, is_time_absolute, current): if expr.find("end_doy()") >= 0: if not is_time_absolute: msgr.fatal( - _( - "The temporal operators <%s> support only absolute " - "time." % ("end_*") - ) + _("The temporal operators <%s> support only absolute time.") % ("end_*") ) if not end: expr = expr.replace("end_doy()", "null()") diff --git a/python/grass/temporal/metadata.py b/python/grass/temporal/metadata.py index 6094bbbe146..4be4c568a76 100644 --- a/python/grass/temporal/metadata.py +++ b/python/grass/temporal/metadata.py @@ -174,72 +174,63 @@ def get_id(self): """ if "id" in self.D: return self.D["id"] - else: - return None + return None def get_datatype(self): """Get the map type :return: None if not found""" if "datatype" in self.D: return self.D["datatype"] - else: - return None + return None def get_cols(self): """Get number of cols :return: None if not found""" if "cols" in self.D: return self.D["cols"] - else: - return None + return None def get_rows(self): """Get number of rows :return: None if not found""" if "rows" in self.D: return self.D["rows"] - else: - return None + return None def get_number_of_cells(self): """Get number of cells :return: None if not found""" if "number_of_cells" in self.D: return self.D["number_of_cells"] - else: - return None + return None def get_nsres(self): """Get the north-south resolution :return: None if not found""" if "nsres" in self.D: return self.D["nsres"] - else: - return None + return None def get_ewres(self): """Get east-west resolution :return: None if not found""" if "ewres" in self.D: return self.D["ewres"] - else: - return None + return None def get_min(self): """Get the minimum cell value :return: None if not found""" if "min" in self.D: return self.D["min"] - else: - return None + return None def get_max(self): """Get the maximum cell value :return: None if not found""" if "max" in self.D: return self.D["max"] - else: - return None + return None # Properties datatype = property(fget=get_datatype, fset=set_datatype) @@ -251,6 +242,26 @@ def get_max(self): min = property(fget=get_min, fset=set_min) max = property(fget=get_max, fset=set_max) + def print_info(self): + """Print information about this class in human readable style""" + self._print_info_body(shell=False) + + def print_shell_info(self): + """Print information about this class in shell style""" + self._print_info_body(shell=True) + + def _print_info_head(self, shell=False): + """Print information about this class (head part). + + No header printed in shell style mode. + + :param bool shell: True for human readable style otherwise shell style + """ + if not shell: + print( + " +-------------------- Metadata information ----------------------------------+" # noqa: E501 + ) + def _print_info_body(self, shell=False): """Print information about this class (body part). @@ -331,6 +342,7 @@ class RasterMetadata(RasterMetadataBase): | East-west resolution:....... 0.1 | Minimum value:.............. 0.0 | Maximum value:.............. 100.0 + | Semantic label:............. None >>> meta.print_shell_info() datatype=CELL cols=100 @@ -340,6 +352,7 @@ class RasterMetadata(RasterMetadataBase): ewres=0.1 min=0.0 max=100.0 + semantic_label=None """ @@ -379,22 +392,23 @@ def get_semantic_label(self): :return: None if not found""" if "semantic_label" in self.D: return self.D["semantic_label"] - else: - return None + return None semantic_label = property(fget=get_semantic_label, fset=set_semantic_label) - def _print_info_body(self, shell=False): - """Print information about this class (body part). + def print_info(self): + """Print information about this class.""" + self._print_info_head(shell=False) + self._print_info_body(shell=False) + # semantic label section (raster specific only) + print(" | Semantic label:............. " + str(self.get_semantic_label())) - :param bool shell: True for human readable style otherwise shell style - """ - super()._print_info_body(shell) + def print_shell_info(self): + """Print information about this class in shell style""" + self._print_info_head(shell=True) + self._print_info_body(shell=True) # semantic label section (raster specific only) - if shell: - print("semantic_label=" + str(self.get_semantic_label())) - else: - print(" | Semantic label:............. " + str(self.get_semantic_label())) + print("semantic_label=" + str(self.get_semantic_label())) ############################################################################### @@ -525,32 +539,31 @@ def get_depths(self): :return: None if not found""" if "depths" in self.D: return self.D["depths"] - else: - return None + return None def get_tbres(self): """Get top-bottom resolution :return: None if not found""" if "tbres" in self.D: return self.D["tbres"] - else: - return None + return None depths = property(fget=get_depths, fset=set_depths) tbres = property(fget=get_tbres, fset=set_tbres) - def _print_info_body(self, shell=False): - """Print information about this class (body part). + def print_info(self): + """Print information about this class.""" + self._print_info_head(shell=False) + self._print_info_body(shell=False) + print(" | Number of depths:........... " + str(self.get_depths())) + print(" | Top-Bottom resolution:...... " + str(self.get_tbres())) - :param bool shell: True for human readable style otherwise shell style - """ - super()._print_info_body(shell) - if shell: - print("depths=" + str(self.get_depths())) - print("tbres=" + str(self.get_tbres())) - else: - print(" | Number of depths:........... " + str(self.get_depths())) - print(" | Top-Bottom resolution:...... " + str(self.get_tbres())) + def print_shell_info(self): + """Print information about this class in shell style""" + self._print_info_head(shell=True) + self._print_info_body(shell=True) + print("depths=" + str(self.get_depths())) + print("tbres=" + str(self.get_tbres())) ############################################################################### @@ -741,112 +754,98 @@ def get_id(self): """ if "id" in self.D: return self.D["id"] - else: - return None + return None def get_3d_info(self): """Return True if the map is three dimensional, False if not and None if not info was found""" if "is_3d" in self.D: return self.D["is_3d"] - else: - return None + return None def get_number_of_points(self): """Get the number of points of the vector map :return: None if not found""" if "points" in self.D: return self.D["points"] - else: - return None + return None def get_number_of_lines(self): """Get the number of lines of the vector map :return: None if not found""" if "lines" in self.D: return self.D["lines"] - else: - return None + return None def get_number_of_boundaries(self): """Get the number of boundaries of the vector map :return: None if not found""" if "boundaries" in self.D: return self.D["boundaries"] - else: - return None + return None def get_number_of_centroids(self): """Get the number of centroids of the vector map :return: None if not found""" if "centroids" in self.D: return self.D["centroids"] - else: - return None + return None def get_number_of_faces(self): """Get the number of faces of the vector map :return: None if not found""" if "faces" in self.D: return self.D["faces"] - else: - return None + return None def get_number_of_kernels(self): """Get the number of kernels of the vector map :return: None if not found""" if "kernels" in self.D: return self.D["kernels"] - else: - return None + return None def get_number_of_primitives(self): """Get the number of primitives of the vector map :return: None if not found""" if "primitives" in self.D: return self.D["primitives"] - else: - return None + return None def get_number_of_nodes(self): """Get the number of nodes of the vector map :return: None if not found""" if "nodes" in self.D: return self.D["nodes"] - else: - return None + return None def get_number_of_areas(self): """Get the number of areas of the vector map :return: None if not found""" if "areas" in self.D: return self.D["areas"] - else: - return None + return None def get_number_of_islands(self): """Get the number of islands of the vector map :return: None if not found""" if "islands" in self.D: return self.D["islands"] - else: - return None + return None def get_number_of_holes(self): """Get the number of holes of the vector map :return: None if not found""" if "holes" in self.D: return self.D["holes"] - else: - return None + return None def get_number_of_volumes(self): """Get the number of volumes of the vector map :return: None if not found""" if "volumes" in self.D: return self.D["volumes"] - else: - return None + return None # Set the properties id = property(fget=get_id, fset=set_id) @@ -870,53 +869,40 @@ def get_number_of_volumes(self): number_of_holes = property(fget=get_number_of_holes, fset=set_number_of_holes) number_of_volumes = property(fget=get_number_of_volumes, fset=set_number_of_volumes) - def _print_info_body(self, shell=False): - """Print information about this class (body part). + def print_info(self): + """Print information about this class in human readable style""" + print( + " +-------------------- Metadata information ----------------------------------+" # noqa: E501 + ) + print(" | Is map 3d .................. " + str(self.get_3d_info())) + print(" | Number of points ........... " + str(self.get_number_of_points())) + print(" | Number of lines ............ " + str(self.get_number_of_lines())) + print(" | Number of boundaries ....... " + str(self.get_number_of_boundaries())) + print(" | Number of centroids ........ " + str(self.get_number_of_centroids())) + print(" | Number of faces ............ " + str(self.get_number_of_faces())) + print(" | Number of kernels .......... " + str(self.get_number_of_kernels())) + print(" | Number of primitives ....... " + str(self.get_number_of_primitives())) + print(" | Number of nodes ............ " + str(self.get_number_of_nodes())) + print(" | Number of areas ............ " + str(self.get_number_of_areas())) + print(" | Number of islands .......... " + str(self.get_number_of_islands())) + print(" | Number of holes ............ " + str(self.get_number_of_holes())) + print(" | Number of volumes .......... " + str(self.get_number_of_volumes())) - :param bool shell: True for human readable style otherwise shell style - """ - if shell: - print("is_3d=" + str(self.get_3d_info())) - print("points=" + str(self.get_number_of_points())) - print("lines=" + str(self.get_number_of_lines())) - print("boundaries=" + str(self.get_number_of_boundaries())) - print("centroids=" + str(self.get_number_of_centroids())) - print("faces=" + str(self.get_number_of_faces())) - print("kernels=" + str(self.get_number_of_kernels())) - print("primitives=" + str(self.get_number_of_primitives())) - print("nodes=" + str(self.get_number_of_nodes())) - print("areas=" + str(self.get_number_of_areas())) - print("islands=" + str(self.get_number_of_islands())) - print("holes=" + str(self.get_number_of_holes())) - print("volumes=" + str(self.get_number_of_volumes())) - else: - print(" | Is map 3d .................. " + str(self.get_3d_info())) - print(" | Number of points ........... " + str(self.get_number_of_points())) - print(" | Number of lines ............ " + str(self.get_number_of_lines())) - print( - " | Number of boundaries ....... " - + str(self.get_number_of_boundaries()) - ) - print( - " | Number of centroids ........ " + str(self.get_number_of_centroids()) - ) - print(" | Number of faces ............ " + str(self.get_number_of_faces())) - print( - " | Number of kernels .......... " + str(self.get_number_of_kernels()) - ) - print( - " | Number of primitives ....... " - + str(self.get_number_of_primitives()) - ) - print(" | Number of nodes ............ " + str(self.get_number_of_nodes())) - print(" | Number of areas ............ " + str(self.get_number_of_areas())) - print( - " | Number of islands .......... " + str(self.get_number_of_islands()) - ) - print(" | Number of holes ............ " + str(self.get_number_of_holes())) - print( - " | Number of volumes .......... " + str(self.get_number_of_volumes()) - ) + def print_shell_info(self): + """Print information about this class in shell style""" + print("is_3d=" + str(self.get_3d_info())) + print("points=" + str(self.get_number_of_points())) + print("lines=" + str(self.get_number_of_lines())) + print("boundaries=" + str(self.get_number_of_boundaries())) + print("centroids=" + str(self.get_number_of_centroids())) + print("faces=" + str(self.get_number_of_faces())) + print("kernels=" + str(self.get_number_of_kernels())) + print("primitives=" + str(self.get_number_of_primitives())) + print("nodes=" + str(self.get_number_of_nodes())) + print("areas=" + str(self.get_number_of_areas())) + print("islands=" + str(self.get_number_of_islands())) + print("holes=" + str(self.get_number_of_holes())) + print("volumes=" + str(self.get_number_of_volumes())) ############################################################################### @@ -990,32 +976,28 @@ def get_id(self): """ if "id" in self.D: return self.D["id"] - else: - return None + return None def get_title(self): """Get the title :return: None if not found""" if "title" in self.D: return self.D["title"] - else: - return None + return None def get_description(self): """Get description :return: None if not found""" if "description" in self.D: return self.D["description"] - else: - return None + return None def get_command(self): """Get command :return: None if not found""" if "command" in self.D: return self.D["command"] - else: - return None + return None def get_number_of_maps(self): """Get the number of registered maps, @@ -1024,8 +1006,7 @@ def get_number_of_maps(self): :return: None if not found""" if "number_of_maps" in self.D: return self.D["number_of_maps"] - else: - return None + return None id = property(fget=get_id, fset=set_id) title = property(fget=get_title, fset=set_title) @@ -1034,13 +1015,11 @@ def get_number_of_maps(self): def print_info(self): """Print information about this class in human readable style""" - self._print_info_head(shell=False) self._print_info_body(shell=False) self._print_info_tail(shell=False) def print_shell_info(self): """Print information about this class in shell style""" - self._print_info_head(shell=True) self._print_info_body(shell=True) self._print_info_tail(shell=True) @@ -1056,6 +1035,12 @@ def _print_info_head(self, shell=False): " +-------------------- Metadata information ----------------------------------+" # noqa: E501 ) + def _print_info_body(self, shell=False): + """Print information about this class (body part). + + :param bool shell: True for human readable style otherwise shell style + """ + def _print_info_tail(self, shell=False): """Print information about this class (tail part). @@ -1204,8 +1189,7 @@ def get_aggregation_type(self): """ if "aggregation_type" in self.D: return self.D["aggregation_type"] - else: - return None + return None def get_max_min(self): """Get the minimal maximum of all registered maps, @@ -1214,8 +1198,7 @@ def get_max_min(self): :return: None if not found""" if "max_min" in self.D: return self.D["max_min"] - else: - return None + return None def get_min_min(self): """Get the minimal minimum of all registered maps, @@ -1224,8 +1207,7 @@ def get_min_min(self): :return: None if not found""" if "min_min" in self.D: return self.D["min_min"] - else: - return None + return None def get_max_max(self): """Get the maximal maximum of all registered maps, @@ -1234,8 +1216,7 @@ def get_max_max(self): :return: None if not found""" if "max_max" in self.D: return self.D["max_max"] - else: - return None + return None def get_min_max(self): """Get the maximal minimum of all registered maps, @@ -1244,8 +1225,7 @@ def get_min_max(self): :return: None if not found""" if "min_max" in self.D: return self.D["min_max"] - else: - return None + return None def get_nsres_min(self): """Get the minimal north-south resolution of all registered maps, @@ -1254,8 +1234,7 @@ def get_nsres_min(self): :return: None if not found""" if "nsres_min" in self.D: return self.D["nsres_min"] - else: - return None + return None def get_nsres_max(self): """Get the maximal north-south resolution of all registered maps, @@ -1264,8 +1243,7 @@ def get_nsres_max(self): :return: None if not found""" if "nsres_max" in self.D: return self.D["nsres_max"] - else: - return None + return None def get_ewres_min(self): """Get the minimal east-west resolution of all registered maps, @@ -1274,8 +1252,7 @@ def get_ewres_min(self): :return: None if not found""" if "ewres_min" in self.D: return self.D["ewres_min"] - else: - return None + return None def get_ewres_max(self): """Get the maximal east-west resolution of all registered maps, @@ -1284,8 +1261,7 @@ def get_ewres_max(self): :return: None if not found""" if "ewres_max" in self.D: return self.D["ewres_max"] - else: - return None + return None nsres_min = property(fget=get_nsres_min) nsres_max = property(fget=get_nsres_max) @@ -1419,8 +1395,7 @@ def get_raster_register(self): :return: None if not found""" if "raster_register" in self.D: return self.D["raster_register"] - else: - return None + return None def get_number_of_semantic_labels(self): """Get the number of registered semantic labels @@ -1428,8 +1403,7 @@ def get_number_of_semantic_labels(self): """ if "number_of_semantic_labels" in self.D: return self.D["number_of_semantic_labels"] - else: - return None + return None def get_semantic_labels(self): """Get the distinct semantic labels of registered maps @@ -1467,15 +1441,23 @@ def get_semantic_labels(self): if count > 0: return string - else: - return None - else: return None + return None raster_register = property(fget=get_raster_register, fset=set_raster_register) number_of_semantic_labels = property(fget=get_number_of_semantic_labels) semantic_labels = property(fget=get_semantic_labels) + def print_info(self): + """Print information about this class in human readable style""" + self._print_info_head(shell=False) + super().print_info() + + def print_shell_info(self): + """Print information about this class in shell style""" + self._print_info_head(shell=True) + super().print_shell_info() + def _print_info_body(self, shell=False): """Print information about this class (body part). @@ -1562,6 +1544,8 @@ class STR3DSMetadata(STDSRasterMetadataBase): | Command history: >>> meta.print_shell_info() raster3d_register=None + tbres_min=None + tbres_max=None nsres_min=None nsres_max=None ewres_min=None @@ -1570,8 +1554,6 @@ class STR3DSMetadata(STDSRasterMetadataBase): min_max=None max_min=None max_max=None - tbres_min=None - tbres_max=None aggregation_type=None number_of_maps=None @@ -1597,8 +1579,7 @@ def get_raster3d_register(self): :return: None if not found""" if "raster3d_register" in self.D: return self.D["raster3d_register"] - else: - return None + return None def get_tbres_min(self): """Get the minimal top-bottom resolution of all registered maps, @@ -1607,8 +1588,7 @@ def get_tbres_min(self): :return: None if not found""" if "tbres_min" in self.D: return self.D["tbres_min"] - else: - return None + return None def get_tbres_max(self): """Get the maximal top-bottom resolution of all registered maps, @@ -1617,13 +1597,22 @@ def get_tbres_max(self): :return: None if not found""" if "tbres_max" in self.D: return self.D["tbres_max"] - else: - return None + return None raster3d_register = property(fget=get_raster3d_register, fset=set_raster3d_register) tbres_min = property(fget=get_tbres_min) tbres_max = property(fget=get_tbres_max) + def print_info(self): + """Print information about this class in human readable style""" + self._print_info_head(shell=False) + super().print_info() + + def print_shell_info(self): + """Print information about this class in shell style""" + self._print_info_head(shell=True) + super().print_shell_info() + def _print_info_body(self, shell=False): """Print information about this class (body part). @@ -1751,8 +1740,7 @@ def get_vector_register(self): :return: None if not found""" if "vector_register" in self.D: return self.D["vector_register"] - else: - return None + return None def get_number_of_points(self): """Get the number of points of all registered maps, @@ -1761,8 +1749,7 @@ def get_number_of_points(self): :return: None if not found""" if "points" in self.D: return self.D["points"] - else: - return None + return None def get_number_of_lines(self): """Get the number of lines of all registered maps, @@ -1771,8 +1758,7 @@ def get_number_of_lines(self): :return: None if not found""" if "lines" in self.D: return self.D["lines"] - else: - return None + return None def get_number_of_boundaries(self): """Get the number of boundaries of all registered maps, @@ -1781,8 +1767,7 @@ def get_number_of_boundaries(self): :return: None if not found""" if "boundaries" in self.D: return self.D["boundaries"] - else: - return None + return None def get_number_of_centroids(self): """Get the number of centroids of all registered maps, @@ -1791,8 +1776,7 @@ def get_number_of_centroids(self): :return: None if not found""" if "centroids" in self.D: return self.D["centroids"] - else: - return None + return None def get_number_of_faces(self): """Get the number of faces of all registered maps, @@ -1801,8 +1785,7 @@ def get_number_of_faces(self): :return: None if not found""" if "faces" in self.D: return self.D["faces"] - else: - return None + return None def get_number_of_kernels(self): """Get the number of kernels of all registered maps, @@ -1811,8 +1794,7 @@ def get_number_of_kernels(self): :return: None if not found""" if "kernels" in self.D: return self.D["kernels"] - else: - return None + return None def get_number_of_primitives(self): """Get the number of primitives of all registered maps, @@ -1821,8 +1803,7 @@ def get_number_of_primitives(self): :return: None if not found""" if "primitives" in self.D: return self.D["primitives"] - else: - return None + return None def get_number_of_nodes(self): """Get the number of nodes of all registered maps, @@ -1831,8 +1812,7 @@ def get_number_of_nodes(self): :return: None if not found""" if "nodes" in self.D: return self.D["nodes"] - else: - return None + return None def get_number_of_areas(self): """Get the number of areas of all registered maps, @@ -1841,8 +1821,7 @@ def get_number_of_areas(self): :return: None if not found""" if "areas" in self.D: return self.D["areas"] - else: - return None + return None def get_number_of_islands(self): """Get the number of islands of all registered maps, @@ -1851,8 +1830,7 @@ def get_number_of_islands(self): :return: None if not found""" if "islands" in self.D: return self.D["islands"] - else: - return None + return None def get_number_of_holes(self): """Get the number of holes of all registered maps, @@ -1861,8 +1839,7 @@ def get_number_of_holes(self): :return: None if not found""" if "holes" in self.D: return self.D["holes"] - else: - return None + return None def get_number_of_volumes(self): """Get the number of volumes of all registered maps, @@ -1871,8 +1848,7 @@ def get_number_of_volumes(self): :return: None if not found""" if "volumes" in self.D: return self.D["volumes"] - else: - return None + return None # Set the properties vector_register = property(fget=get_vector_register, fset=set_vector_register) @@ -1889,6 +1865,16 @@ def get_number_of_volumes(self): number_of_holes = property(fget=get_number_of_holes) number_of_volumes = property(fget=get_number_of_volumes) + def print_info(self): + """Print information about this class in human readable style""" + self._print_info_head(shell=False) + super().print_info() + + def print_shell_info(self): + """Print information about this class in shell style""" + self._print_info_head(shell=True) + super().print_shell_info() + def _print_info_body(self, shell=False): """Print information about this class (body part). diff --git a/python/grass/temporal/register.py b/python/grass/temporal/register.py index 0cd339946b9..8b7852ab557 100644 --- a/python/grass/temporal/register.py +++ b/python/grass/temporal/register.py @@ -161,7 +161,7 @@ def register_maps_in_space_time_dataset( if hasattr(file, "readline"): fd = file else: - fd = open(file, "r") + fd = open(file) line = True while True: diff --git a/python/grass/temporal/space_time_datasets.py b/python/grass/temporal/space_time_datasets.py index a73e03fff46..92721277c9e 100644 --- a/python/grass/temporal/space_time_datasets.py +++ b/python/grass/temporal/space_time_datasets.py @@ -288,10 +288,8 @@ def read_timestamp_from_grass(self): if check < 1: self.msgr.error( - _( - "Unable to read timestamp file " - "for raster map <%s>" % (self.get_map_id()) - ) + _("Unable to read timestamp file for raster map <%s>") + % (self.get_map_id()) ) return False @@ -316,19 +314,15 @@ def write_timestamp_to_grass(self): if check == -1: self.msgr.error( - _( - "Unable to create timestamp file " - "for raster map <%s>" % (self.get_map_id()) - ) + _("Unable to create timestamp file for raster map <%s>") + % (self.get_map_id()) ) return False if check == -2: self.msgr.error( - _( - "Invalid datetime in timestamp for raster map " - "<%s>" % (self.get_map_id()) - ) + _("Invalid datetime in timestamp for raster map <%s>") + % (self.get_map_id()) ) return False @@ -350,7 +344,7 @@ def remove_timestamp_from_grass(self): if check == -1: self.msgr.error( - _("Unable to remove timestamp for raster map <%s>" % (self.get_name())) + _("Unable to remove timestamp for raster map <%s>") % (self.get_name()) ) return False @@ -390,10 +384,8 @@ def write_semantic_label_to_grass(self): ) if check == -1: self.msgr.error( - _( - "Unable to write semantic label for raster map <%s>" - % (self.get_name()) - ) + _("Unable to write semantic label for raster map <%s>") + % (self.get_name()) ) return False @@ -641,15 +633,13 @@ def spatial_overlapping(self, dataset): """Return True if the spatial extents overlap""" if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds": return self.spatial_extent.overlapping(dataset.spatial_extent) - else: - return self.spatial_extent.overlapping_2d(dataset.spatial_extent) + return self.spatial_extent.overlapping_2d(dataset.spatial_extent) def spatial_relation(self, dataset): """Return the two or three dimensional spatial relation""" if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds": return self.spatial_extent.spatial_relation(dataset.spatial_extent) - else: - return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent) + return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent) def spatial_intersection(self, dataset): """Return the three or two dimensional intersection as spatial_extent @@ -660,8 +650,7 @@ def spatial_intersection(self, dataset): """ if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds": return self.spatial_extent.intersect(dataset.spatial_extent) - else: - return self.spatial_extent.intersect_2d(dataset.spatial_extent) + return self.spatial_extent.intersect_2d(dataset.spatial_extent) def spatial_union(self, dataset): """Return the three or two dimensional union as spatial_extent @@ -672,8 +661,7 @@ def spatial_union(self, dataset): """ if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds": return self.spatial_extent.union(dataset.spatial_extent) - else: - return self.spatial_extent.union_2d(dataset.spatial_extent) + return self.spatial_extent.union_2d(dataset.spatial_extent) def spatial_disjoint_union(self, dataset): """Return the three or two dimensional union as spatial_extent object. @@ -683,8 +671,7 @@ def spatial_disjoint_union(self, dataset): """ if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds": return self.spatial_extent.disjoint_union(dataset.spatial_extent) - else: - return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent) + return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent) def get_np_array(self): """Return this 3D raster map as memmap numpy style array to access the @@ -741,10 +728,8 @@ def read_timestamp_from_grass(self): if check < 1: self.msgr.error( - _( - "Unable to read timestamp file " - "for 3D raster map <%s>" % (self.get_map_id()) - ) + _("Unable to read timestamp file for 3D raster map <%s>") + % (self.get_map_id()) ) return False @@ -769,19 +754,15 @@ def write_timestamp_to_grass(self): if check == -1: self.msgr.error( - _( - "Unable to create timestamp file " - "for 3D raster map <%s>" % (self.get_map_id()) - ) + _("Unable to create timestamp file for 3D raster map <%s>") + % (self.get_map_id()) ) return False if check == -2: self.msgr.error( - _( - "Invalid datetime in timestamp for 3D raster " - "map <%s>" % (self.get_map_id()) - ) + _("Invalid datetime in timestamp for 3D raster map <%s>") + % (self.get_map_id()) ) return False @@ -802,10 +783,7 @@ def remove_timestamp_from_grass(self): if check == -1: self.msgr.error( - _( - "Unable to remove timestamp for raster map " - "<%s>" % (self.get_name()) - ) + _("Unable to remove timestamp for raster map <%s>") % (self.get_name()) ) return False @@ -1091,10 +1069,8 @@ def read_timestamp_from_grass(self): if check < 1: self.msgr.error( - _( - "Unable to read timestamp file " - "for vector map <%s>" % (self.get_map_id()) - ) + _("Unable to read timestamp file for vector map <%s>") + % (self.get_map_id()) ) return False @@ -1120,19 +1096,15 @@ def write_timestamp_to_grass(self): if check == -1: self.msgr.error( - _( - "Unable to create timestamp file " - "for vector map <%s>" % (self.get_map_id()) - ) + _("Unable to create timestamp file for vector map <%s>") + % (self.get_map_id()) ) return False if check == -2: self.msgr.error( - _( - "Invalid datetime in timestamp for vector " - "map <%s>" % (self.get_map_id()) - ) + _("Invalid datetime in timestamp for vector map <%s>") + % (self.get_map_id()) ) return False @@ -1148,9 +1120,8 @@ def remove_timestamp_from_grass(self): if check == -1: self.msgr.error( - _( - "Unable to remove timestamp for vector " - "map <%s>" % (self.get_name()) + _("Unable to remove timestamp for vector map <%s>").format( + self.get_name() ) ) return False @@ -1410,16 +1381,14 @@ def spatial_overlapping(self, dataset): if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds": return self.spatial_extent.overlapping(dataset.spatial_extent) - else: - return self.spatial_extent.overlapping_2d(dataset.spatial_extent) + return self.spatial_extent.overlapping_2d(dataset.spatial_extent) def spatial_relation(self, dataset): """Return the two or three dimensional spatial relation""" if self.get_type() == dataset.get_type() or dataset.get_type() == "str3ds": return self.spatial_extent.spatial_relation(dataset.spatial_extent) - else: - return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent) + return self.spatial_extent.spatial_relation_2d(dataset.spatial_extent) def spatial_intersection(self, dataset): """Return the three or two dimensional intersection as spatial_extent @@ -1430,8 +1399,7 @@ def spatial_intersection(self, dataset): """ if self.get_type() == dataset.get_type() or dataset.get_type() == "raster3d": return self.spatial_extent.intersect(dataset.spatial_extent) - else: - return self.spatial_extent.intersect_2d(dataset.spatial_extent) + return self.spatial_extent.intersect_2d(dataset.spatial_extent) def spatial_union(self, dataset): """Return the three or two dimensional union as spatial_extent @@ -1442,8 +1410,7 @@ def spatial_union(self, dataset): """ if self.get_type() == dataset.get_type() or dataset.get_type() == "raster3d": return self.spatial_extent.union(dataset.spatial_extent) - else: - return self.spatial_extent.union_2d(dataset.spatial_extent) + return self.spatial_extent.union_2d(dataset.spatial_extent) def spatial_disjoint_union(self, dataset): """Return the three or two dimensional union as spatial_extent object. @@ -1453,8 +1420,7 @@ def spatial_disjoint_union(self, dataset): """ if self.get_type() == dataset.get_type() or dataset.get_type() == "raster3d": return self.spatial_extent.disjoint_union(dataset.spatial_extent) - else: - return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent) + return self.spatial_extent.disjoint_union_2d(dataset.spatial_extent) def reset(self, ident): """Reset the internal structure and set the identifier""" diff --git a/python/grass/temporal/spatial_extent.py b/python/grass/temporal/spatial_extent.py index 329a0a4a684..7bec3bc35e7 100644 --- a/python/grass/temporal/spatial_extent.py +++ b/python/grass/temporal/spatial_extent.py @@ -875,7 +875,7 @@ def cover_2d(self, extent) -> bool: if eS > S and eS < N: edge_count += 1 - return not edge_count == 0 + return edge_count != 0 def cover(self, extent) -> bool: """Return True if this extent covers the provided spatial @@ -956,7 +956,7 @@ def cover(self, extent) -> bool: if eB > B and eB < T: edge_count += 1 - return not edge_count == 0 + return edge_count != 0 def covered_2d(self, extent): """Return True if this extent is covered by the provided spatial @@ -1787,8 +1787,7 @@ def get_id(self): """ if "id" in self.D: return self.D["id"] - else: - return None + return None def get_projection(self): """Get the projection of the spatial extent""" @@ -1840,48 +1839,42 @@ def get_north(self): :return: None if not found""" if "north" in self.D: return self.D["north"] - else: - return None + return None def get_south(self): """Get the southern edge of the map :return: None if not found""" if "south" in self.D: return self.D["south"] - else: - return None + return None def get_east(self): """Get the eastern edge of the map :return: None if not found""" if "east" in self.D: return self.D["east"] - else: - return None + return None def get_west(self): """Get the western edge of the map :return: None if not found""" if "west" in self.D: return self.D["west"] - else: - return None + return None def get_top(self): """Get the top edge of the map :return: None if not found""" if "top" in self.D: return self.D["top"] - else: - return None + return None def get_bottom(self): """Get the bottom edge of the map :return: None if not found""" if "bottom" in self.D: return self.D["bottom"] - else: - return None + return None id = property(fget=get_id, fset=set_id) north = property(fget=get_north, fset=set_north) diff --git a/python/grass/temporal/stds_export.py b/python/grass/temporal/stds_export.py index f2fdd7ca9bf..a01b94e1071 100644 --- a/python/grass/temporal/stds_export.py +++ b/python/grass/temporal/stds_export.py @@ -29,6 +29,7 @@ import shutil import tarfile import tempfile +from pathlib import Path import grass.script as gs from grass.exceptions import CalledModuleError @@ -126,7 +127,7 @@ def _export_raster_maps_as_gdal( except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gs.fatal(_("Unable to export raster map <%s>" % name)) + gs.fatal(_("Unable to export raster map <%s>") % name) tar.add(out_name) @@ -138,10 +139,7 @@ def _export_raster_maps_as_gdal( shutil.rmtree(new_cwd) tar.close() gs.fatal( - _( - "Unable to export color rules for raster " - "map <%s> r.out.gdal" % name - ) + _("Unable to export color rules for raster map <%s> r.out.gdal") % name ) tar.add(out_name) @@ -167,7 +165,7 @@ def _export_raster_maps(rows, tar, list_file, new_cwd, fs): except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gs.fatal(_("Unable to export raster map <%s> with r.pack" % name)) + gs.fatal(_("Unable to export raster map <%s> with r.pack") % name) tar.add(name + ".pack") @@ -200,7 +198,7 @@ def _export_vector_maps_as_gml(rows, tar, list_file, new_cwd, fs): except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gs.fatal(_("Unable to export vector map <%s> as GML with v.out.ogr" % name)) + gs.fatal(_("Unable to export vector map <%s> as GML with v.out.ogr") % name) tar.add(name + ".xml") tar.add(name + ".xsd") @@ -235,7 +233,7 @@ def _export_vector_maps_as_gpkg(rows, tar, list_file, new_cwd, fs): shutil.rmtree(new_cwd) tar.close() gs.fatal( - _("Unable to export vector map <%s> as GPKG with v.out.ogr" % name) + _("Unable to export vector map <%s> as GPKG with v.out.ogr") % name ) tar.add(name + ".gpkg") @@ -268,7 +266,7 @@ def _export_vector_maps(rows, tar, list_file, new_cwd, fs): except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gs.fatal(_("Unable to export vector map <%s> with v.pack" % name)) + gs.fatal(_("Unable to export vector map <%s> with v.pack") % name) tar.add(name + ".pack") @@ -294,7 +292,7 @@ def _export_raster3d_maps(rows, tar, list_file, new_cwd, fs): except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gs.fatal(_("Unable to export raster map <%s> with r3.pack" % name)) + gs.fatal(_("Unable to export raster map <%s> with r3.pack") % name) tar.add(name + ".pack") @@ -350,7 +348,7 @@ def export_stds( """ # Save current working directory path - old_cwd = os.getcwd() + old_cwd = Path.cwd() # Create the temporary directory and jump into it new_cwd = tempfile.mkdtemp(dir=directory) @@ -402,9 +400,7 @@ def export_stds( # Write projection and metadata proj = gs.read_command("g.proj", flags="j") - proj_file = open(proj_file_name, "w") - proj_file.write(proj) - proj_file.close() + Path(proj_file_name).write_text(proj) init_file = open(init_file_name, "w") # Create the init string @@ -431,9 +427,7 @@ def export_stds( init_file.close() metadata = gs.read_command("t.info", type=type_, input=sp.get_id()) - metadata_file = open(metadata_file_name, "w") - metadata_file.write(metadata) - metadata_file.close() + Path(metadata_file_name).write_text(metadata) read_file = open(read_file_name, "w") if type_ == "strds": diff --git a/python/grass/temporal/stds_import.py b/python/grass/temporal/stds_import.py index 03810e49b89..006ee6a387e 100644 --- a/python/grass/temporal/stds_import.py +++ b/python/grass/temporal/stds_import.py @@ -254,10 +254,8 @@ def import_stds( # Check for important files msgr = get_tgis_message_interface() msgr.message( - _( - "Checking validity of input file (size: %0.1f MB). Make take a while..." - % (os.path.getsize(input) / (1024 * 1024.0)) - ) + _("Checking validity of input file (size: %0.1f MB). Make take a while...") + % (os.path.getsize(input) / (1024 * 1024.0)) ) members = tar.getnames() # Make sure that the basenames of the files are used for comparison @@ -288,7 +286,7 @@ def import_stds( # We use a new list file name for map registration new_list_file_name = list_file_name + "_new" # Save current working directory path - old_cwd = os.getcwd() + old_cwd = Path.cwd() # Switch into the data directory os.chdir(directory) @@ -374,7 +372,7 @@ def import_stds( fs = "|" maplist = [] mapset = get_current_mapset() - list_file = open(list_file_name, "r") + list_file = open(list_file_name) new_list_file = open(new_list_file_name, "w") # get number of lines to correctly form the suffix @@ -428,7 +426,7 @@ def import_stds( # Read the init file fs = "=" init = {} - init_file = open(init_file_name, "r") + init_file = open(init_file_name) while True: line = init_file.readline() if not line: diff --git a/python/grass/temporal/temporal_algebra.py b/python/grass/temporal/temporal_algebra.py index 3736a15315a..e4717eb3326 100644 --- a/python/grass/temporal/temporal_algebra.py +++ b/python/grass/temporal/temporal_algebra.py @@ -727,11 +727,11 @@ def get_type(self): and self.value is not None ): return "global" - elif self.boolean is not None: + if self.boolean is not None: return "boolean" - elif self.relationop is not None and self.topology != []: + if self.relationop is not None and self.topology != []: return "operator" - elif self.td is not None: + if self.td is not None: return "timediff" def get_type_value(self): @@ -1195,7 +1195,7 @@ def remove_maps(self): for key, value in map_names.items(): if value: - self.msgr.message(_("Removing un-needed or empty %s maps" % (key))) + self.msgr.message(_("Removing un-needed or empty %s maps") % (key)) self._remove_maps(value, key) def _remove_maps(self, namelist, map_type): @@ -1275,15 +1275,9 @@ def check_stds(self, input, clear=False, stds_type=None, check_type=True): self.temporaltype = "absolute" elif map_i.is_time_relative() and self.temporaltype is None: self.temporaltype = "relative" - elif map_i.is_time_absolute() and self.temporaltype == "relative": - self.msgr.fatal( - _( - "Wrong temporal type of space time dataset " - "<%s> <%s> time is required" - ) - % (id_input, self.temporaltype) - ) - elif map_i.is_time_relative() and self.temporaltype == "absolute": + elif ( + map_i.is_time_absolute() and self.temporaltype == "relative" + ) or (map_i.is_time_relative() and self.temporaltype == "absolute"): self.msgr.fatal( _( "Wrong temporal type of space time dataset " @@ -1299,13 +1293,9 @@ def check_stds(self, input, clear=False, stds_type=None, check_type=True): maplist = input # Create map_value as empty list item. for map_i in maplist: - if "map_value" not in dir(map_i): - map_i.map_value = [] - elif clear: + if ("map_value" not in dir(map_i)) or clear: map_i.map_value = [] - if "condition_value" not in dir(map_i): - map_i.condition_value = [] - elif clear: + if ("condition_value" not in dir(map_i)) or clear: map_i.condition_value = [] else: self.msgr.fatal(_("Wrong type of input " + str(input))) @@ -2346,8 +2336,7 @@ def recurse_compare(conditionlist): inverselist.append(map_i) if inverse: return inverselist - else: - return resultlist + return resultlist def p_statement_assign(self, t): # The expression should always return a list of maps @@ -2392,8 +2381,8 @@ def p_statement_assign(self, t): _( "The resulting space time dataset type <%(a)s> " "is different from the requested type <%(b)s>" - % ({"a": maps_stds_type, "b": self.stdstype}) ) + % ({"a": maps_stds_type, "b": self.stdstype}) ) else: map_type_2 = map_i.get_type() diff --git a/python/grass/temporal/temporal_extent.py b/python/grass/temporal/temporal_extent.py index 42cce4599b1..29594ea8b72 100644 --- a/python/grass/temporal/temporal_extent.py +++ b/python/grass/temporal/temporal_extent.py @@ -202,9 +202,9 @@ def intersect(self, extent): return RelativeTemporalExtent( start_time=start, end_time=end, unit=self.get_unit() ) - elif issubclass(type(self), AbsoluteTemporalExtent): + if issubclass(type(self), AbsoluteTemporalExtent): return AbsoluteTemporalExtent(start_time=start, end_time=end) - elif issubclass(type(self), TemporalExtent): + if issubclass(type(self), TemporalExtent): return TemporalExtent(start_time=start, end_time=end) def disjoint_union(self, extent): @@ -391,9 +391,9 @@ def disjoint_union(self, extent): return RelativeTemporalExtent( start_time=start, end_time=end, unit=self.get_unit() ) - elif issubclass(type(self), AbsoluteTemporalExtent): + if issubclass(type(self), AbsoluteTemporalExtent): return AbsoluteTemporalExtent(start_time=start, end_time=end) - elif issubclass(type(self), TemporalExtent): + if issubclass(type(self), TemporalExtent): return TemporalExtent(start_time=start, end_time=end) def union(self, extent): @@ -986,24 +986,21 @@ def get_id(self): """ if "id" in self.D: return self.D["id"] - else: - return None + return None def get_start_time(self): """Get the valid start time of the extent :return: None if not found""" if "start_time" in self.D: return self.D["start_time"] - else: - return None + return None def get_end_time(self): """Get the valid end time of the extent :return: None if not found""" if "end_time" in self.D: return self.D["end_time"] - else: - return None + return None # Set the properties id = property(fget=get_id, fset=set_id) @@ -1153,8 +1150,7 @@ def get_granularity(self): :return: None if not found""" if "granularity" in self.D: return self.D["granularity"] - else: - return None + return None def get_map_time(self): """Get the type of the map time @@ -1169,8 +1165,7 @@ def get_map_time(self): """ if "map_time" in self.D: return self.D["map_time"] - else: - return None + return None # Properties granularity = property(fget=get_granularity, fset=set_granularity) @@ -1277,8 +1272,7 @@ def get_unit(self): :return: None if not found""" if "unit" in self.D: return self.D["unit"] - else: - return None + return None def temporal_relation(self, map): """Returns the temporal relation between temporal objects @@ -1427,8 +1421,7 @@ def get_granularity(self): :return: None if not found""" if "granularity" in self.D: return self.D["granularity"] - else: - return None + return None def get_map_time(self): """Get the type of the map time @@ -1443,8 +1436,7 @@ def get_map_time(self): """ if "map_time" in self.D: return self.D["map_time"] - else: - return None + return None # Properties granularity = property(fget=get_granularity, fset=set_granularity) diff --git a/python/grass/temporal/temporal_granularity.py b/python/grass/temporal/temporal_granularity.py index c3920b8b00b..b4043054520 100644 --- a/python/grass/temporal/temporal_granularity.py +++ b/python/grass/temporal/temporal_granularity.py @@ -146,8 +146,7 @@ def _get_row_time_tuple(db_table_row): # Check if input is list of MapDataset objects or SQLite rows if issubclass(maps[0].__class__, AbstractMapDataset): return _get_map_time_tuple - else: - return _get_row_time_tuple + return _get_row_time_tuple def _is_after(start, start1, end1) -> bool: @@ -777,8 +776,7 @@ def compute_common_absolute_time_granularity(gran_list, start_date_list=None): if int(num) > 60: if int(num) % 60 == 0: return "60 seconds" - else: - return "1 second" + return "1 second" if granule in {"minutes", "minute"}: # If the start minutes are different between the start dates @@ -790,8 +788,7 @@ def compute_common_absolute_time_granularity(gran_list, start_date_list=None): if int(num) > 60: if int(num) % 60 == 0: return "60 minutes" - else: - return "1 minute" + return "1 minute" if granule in {"hours", "hour"}: # If the start hours are different between the start dates @@ -803,8 +800,7 @@ def compute_common_absolute_time_granularity(gran_list, start_date_list=None): if int(num) > 24: if int(num) % 24 == 0: return "24 hours" - else: - return "1 hour" + return "1 hour" if granule in {"days", "day"}: # If the start days are different between the start dates @@ -816,8 +812,7 @@ def compute_common_absolute_time_granularity(gran_list, start_date_list=None): if int(num) > 365: if int(num) % 365 == 0: return "365 days" - else: - return "1 day" + return "1 day" if granule in {"months", "month"}: # If the start months are different between the start dates @@ -829,8 +824,7 @@ def compute_common_absolute_time_granularity(gran_list, start_date_list=None): if int(num) > 12: if int(num) % 12 == 0: return "12 months" - else: - return "1 month" + return "1 month" return common_granule @@ -1125,20 +1119,18 @@ def gran_singular_unit(gran): output, unit = gran.split(" ") if unit in PLURAL_GRAN: return unit[:-1] - elif unit in SINGULAR_GRAN: + if unit in SINGULAR_GRAN: return unit - else: - lists = "{gr}".format(gr=SUPPORTED_GRAN).replace("[", "").replace("]", "") - print( - _( - "Output granularity seems not to be valid. Please use " - "one of the following values : {gr}" - ).format(gr=lists) - ) - return False - else: - print(_("Invalid absolute granularity")) + lists = "{gr}".format(gr=SUPPORTED_GRAN).replace("[", "").replace("]", "") + print( + _( + "Output granularity seems not to be valid. Please use " + "one of the following values : {gr}" + ).format(gr=lists) + ) return False + print(_("Invalid absolute granularity")) + return False ####################################################################### @@ -1170,16 +1162,15 @@ def gran_plural_unit(gran): output, unit = gran.split(" ") if unit in PLURAL_GRAN: return unit - elif unit in SINGULAR_GRAN: + if unit in SINGULAR_GRAN: return f"{unit}s" - else: - lists = ", ".join(SUPPORTED_GRAN) - print( - _( - "Output granularity seems not to be valid. Please use " - "one of the following values : {gr}" - ).format(gr=lists) - ) + lists = ", ".join(SUPPORTED_GRAN) + print( + _( + "Output granularity seems not to be valid. Please use " + "one of the following values : {gr}" + ).format(gr=lists) + ) else: print(_("Invalid absolute granularity")) return False @@ -1234,8 +1225,7 @@ def _return(output, tounit, shell): if output == 1: return f"{output} {tounit}" - else: - return f"{output} {tounit}s" + return f"{output} {tounit}s" # TODO check the leap second if check_granularity_string(from_gran, "absolute"): @@ -1256,9 +1246,8 @@ def _return(output, tounit, shell): return _return(output, tounit, shell) print(_("Probably you need to invert 'from_gran' and 'to_gran'")) return False - else: - print(_("Invalid absolute granularity")) - return False + print(_("Invalid absolute granularity")) + return False ############################################################################### diff --git a/python/grass/temporal/temporal_raster_base_algebra.py b/python/grass/temporal/temporal_raster_base_algebra.py index 76517db30cc..8ff156cbed5 100644 --- a/python/grass/temporal/temporal_raster_base_algebra.py +++ b/python/grass/temporal/temporal_raster_base_algebra.py @@ -727,7 +727,7 @@ def build_condition_cmd_list( # Append map to result map list. resultlist.append(map_i) return resultlist - elif isinstance(conclusionlist, list): + if isinstance(conclusionlist, list): # Build result command map list between conditions and conclusions. if self.debug: print("build_condition_cmd_list", condition_topolist) @@ -873,7 +873,7 @@ def p_statement_assign(self, t): process_queue.put(m) else: - self.msgr.error(_("Error computing map <%s>" % map_i.get_id())) + self.msgr.error(_("Error computing map <%s>") % map_i.get_id()) count += 1 if self.dry_run is False: diff --git a/python/grass/temporal/testsuite/unittests_temporal_raster_algebra_equal_ts.py b/python/grass/temporal/testsuite/unittests_temporal_raster_algebra_equal_ts.py index 92397cd825c..f96ed12899f 100644 --- a/python/grass/temporal/testsuite/unittests_temporal_raster_algebra_equal_ts.py +++ b/python/grass/temporal/testsuite/unittests_temporal_raster_algebra_equal_ts.py @@ -12,6 +12,7 @@ import grass.temporal as tgis from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows class TestTemporalRasterAlgebraImplicitAggregation(TestCase): @@ -64,6 +65,7 @@ def tearDownClass(cls): cls.runModule("t.unregister", maps="singletmap", quiet=True) cls.del_temp_region() + @xfail_windows def test_simple_operator(self): """Test implicit aggregation @@ -149,6 +151,7 @@ def test_single_map_complex_operator(self): self.assertEqual(D.check_temporal_topology(), True) self.assertEqual(D.get_granularity(), None) + @xfail_windows def test_single_map_simple_operator(self): """Test implicit aggregation diff --git a/python/grass/temporal/univar_statistics.py b/python/grass/temporal/univar_statistics.py index 9bf29f74eba..96a9f65474d 100755 --- a/python/grass/temporal/univar_statistics.py +++ b/python/grass/temporal/univar_statistics.py @@ -65,12 +65,9 @@ def compute_univar_stats(registered_map_info, stats_module, fs, rast_region=Fals if not univar_stats: gs.warning( - _( - "Unable to get statistics for {voxel}raster map " - "<{rmap}>".format( - rmap=id, voxel="" if stats_module.name == "r.univar" else "3d " - ) - ) + _("Unable to get statistics for raster map <%s>") % id + if stats_module.name == "r.univar" + else _("Unable to get statistics for 3d raster map <%s>") % id ) return None eol = "" diff --git a/raster/Makefile b/raster/Makefile index bcd07660238..91ff54d0863 100644 --- a/raster/Makefile +++ b/raster/Makefile @@ -45,6 +45,7 @@ SUBDIRS = \ r.lake \ r.li \ r.mapcalc \ + r.mask.status \ r.mfilter \ r.mode \ r.neighbors \ diff --git a/raster/r.carve/enforce_ds.c b/raster/r.carve/enforce_ds.c index ea4d7a1ae7a..7a71dc97def 100644 --- a/raster/r.carve/enforce_ds.c +++ b/raster/r.carve/enforce_ds.c @@ -22,6 +22,7 @@ #include #include #include +#include #include "enforce.h" #ifndef MAX @@ -487,4 +488,6 @@ static void process_line_segment(const int npts, void *rbuf, Point2 *pgxypts, prevrow = row; prevcol = col; } + Vect_destroy_line_struct(points); + Vect_destroy_cats_struct(cats); } diff --git a/raster/r.circle/main.c b/raster/r.circle/main.c index 4b41a78c7c6..bd99a292f71 100644 --- a/raster/r.circle/main.c +++ b/raster/r.circle/main.c @@ -79,7 +79,9 @@ int main(int argc, char *argv[]) flag = G_define_flag(); flag->key = 'b'; - flag->description = _("Generate binary raster map"); + flag->label = _("Generate binary raster map"); + flag->description = + _("Generate binary pattern only (useful for creating mask)"); if (G_parser(argc, argv)) exit(EXIT_FAILURE); @@ -114,7 +116,7 @@ int main(int argc, char *argv[]) "using the binary flag")); if (flag->answer) - binary = 1; /* generate binary pattern only, useful for MASK */ + binary = 1; else binary = 0; diff --git a/raster/r.clump/clump.c b/raster/r.clump/clump.c index 052ad6ef034..cf94a5bf142 100644 --- a/raster/r.clump/clump.c +++ b/raster/r.clump/clump.c @@ -25,6 +25,8 @@ #include #include #include "local_proto.h" +#include +#include #define INCR 1024 @@ -92,7 +94,9 @@ static CELL do_renumber(int *in_fd, DCELL *rng, int nin, int diag, int minsize, G_percent(row, nrows, 2); coffset = (off_t)row * csize; - lseek(cfd, coffset, SEEK_SET); + if (lseek(cfd, coffset, SEEK_SET) == -1) { + G_fatal_error(_("Unable to seek: %s"), strerror(errno)); + } if (read(cfd, cur_clump, csize) != csize) G_fatal_error(_("Unable to read from temp file")); @@ -108,7 +112,9 @@ static CELL do_renumber(int *in_fd, DCELL *rng, int nin, int diag, int minsize, temp_clump++; } if (do_write) { - lseek(cfd, coffset, SEEK_SET); + if (lseek(cfd, coffset, SEEK_SET) == -1) { + G_fatal_error(_("Unable to seek: %s"), strerror(errno)); + } if (write(cfd, cur_clump, csize) != csize) G_fatal_error(_("Unable to write to temp file")); } diff --git a/raster/r.contour/testsuite/test_r_contour.py b/raster/r.contour/testsuite/test_r_contour.py index 9fc0fc17469..c9ee4c9876a 100644 --- a/raster/r.contour/testsuite/test_r_contour.py +++ b/raster/r.contour/testsuite/test_r_contour.py @@ -62,7 +62,7 @@ def test_raster_contour(self): self.assertModule("v.db.select", map=self.output, file="testReport") self.assertFileExists("testReport", msg="testReport file was not created") if os.path.isfile("testReport"): - file = open("testReport", "r") + file = open("testReport") fileData = file.read() self.assertMultiLineEqual(fileData, self.test_ref_str) file.close() @@ -87,7 +87,7 @@ def test_raster_contour_cut(self): self.assertModule("v.db.select", map=self.output + "_cut", file="testReportCut") self.assertFileExists("testReportCut", msg="testReportCut file was not created") if os.path.isfile("testReportCut"): - file = open("testReportCut", "r") + file = open("testReportCut") fileData = file.read() self.assertMultiLineEqual(fileData, self.test_ref_str) file.close() diff --git a/raster/r.external/r.external.html b/raster/r.external/r.external.html index 797cc5ea605..f20c3e059d6 100644 --- a/raster/r.external/r.external.html +++ b/raster/r.external/r.external.html @@ -17,10 +17,12 @@

    NULL data handling

    NULL cells are those whose value matches the value reported by the GDALGetRasterNoDataValue() function. -To apply the GDAL-linked the user need to either create a MASK (e.g. -with r.mask) and then "apply" it using e.g. r.resample, +

    +To introduce additional NULL values to a computation based on a GDAL-linked +raster, the user needs to either create a mask with with r.mask and +then "apply" it using e.g. r.resample or r.mapcalc, or use r.mapcalc to create a copy with the appropriate categories -changed to NULL (if() condition). +changed to NULL (if() condition).

    EXAMPLES

    diff --git a/raster/r.fill.dir/filldir.c b/raster/r.fill.dir/filldir.c index 55380b7dfc5..cfe0ae69586 100644 --- a/raster/r.fill.dir/filldir.c +++ b/raster/r.fill.dir/filldir.c @@ -145,14 +145,20 @@ void filldir(int fe, int fd, int nl, struct band3 *bnd) CELL *dir; /* fill single-cell depressions, except on outer rows and columns */ - lseek(fe, 0, SEEK_SET); + if (lseek(fe, 0, SEEK_SET) == -1) { + G_fatal_error(_("Unable to seek: %s"), strerror(errno)); + } advance_band3(fe, bnd); advance_band3(fe, bnd); for (i = 1; i < nl - 1; i += 1) { - lseek(fe, (off_t)(i + 1) * bnd->sz, SEEK_SET); + if (lseek(fe, (off_t)(i + 1) * bnd->sz, SEEK_SET) == -1) { + G_fatal_error(_("Unable to seek: %s"), strerror(errno)); + } advance_band3(fe, bnd); if (fill_row(nl, bnd->ns, bnd)) { - lseek(fe, (off_t)i * bnd->sz, SEEK_SET); + if (lseek(fe, (off_t)i * bnd->sz, SEEK_SET) == -1) { + G_fatal_error(_("Unable to seek: %s"), strerror(errno)); + } if (write(fe, bnd->b[1], bnd->sz) < 0) G_fatal_error(_("File writing error in %s() %d:%s"), __func__, errno, strerror(errno)); @@ -172,8 +178,12 @@ void filldir(int fe, int fd, int nl, struct band3 *bnd) dir = G_calloc(bnd->ns, sizeof(CELL)); bufsz = bnd->ns * sizeof(CELL); - lseek(fe, 0, SEEK_SET); - lseek(fd, 0, SEEK_SET); + if (lseek(fe, 0, SEEK_SET) == -1) { + G_fatal_error(_("Unable to seek: %s"), strerror(errno)); + } + if (lseek(fd, 0, SEEK_SET) == -1) { + G_fatal_error(_("Unable to seek: %s"), strerror(errno)); + } advance_band3(fe, bnd); for (i = 0; i < nl; i += 1) { advance_band3(fe, bnd); diff --git a/raster/r.fill.dir/r.fill.dir.html b/raster/r.fill.dir/r.fill.dir.html index 6ad8eb8019c..17173ea3dd3 100644 --- a/raster/r.fill.dir/r.fill.dir.html +++ b/raster/r.fill.dir/r.fill.dir.html @@ -69,11 +69,11 @@

    DESCRIPTION

    attributes required by other hydrological models.

    -As any GRASS GIS module, r.fill.dir is sensitive to the -computational region settings. Thus +As any GRASS GIS module, r.fill.dir respects the +computational region settings. Thus, the module can be used to generate a flow direction map for any -sub-area within the full map layer. Also, r.fill.dir is -sensitive to any raster MASK in effect. +sub-area within the full raster map layer. Also, r.fill.dir +will take into account an active raster mask.

    NOTES

    diff --git a/raster/r.in.ascii/testsuite/test_r_in_ascii.py b/raster/r.in.ascii/testsuite/test_r_in_ascii.py index 20e0c2a8f9e..cff31b7b3e2 100644 --- a/raster/r.in.ascii/testsuite/test_r_in_ascii.py +++ b/raster/r.in.ascii/testsuite/test_r_in_ascii.py @@ -32,44 +32,6 @@ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 """ -INPUT_TSV = """north: 4299000.00 -south: 4247000.00 -east: 528000.00 -west: 500000.00 -rows: 10 -cols: 15 -null: -9999 - -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 -1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 9\ 10\ 11\ 12\ 13\ 14\ 15 """ - -INPUT_UNCOMMON = """north: 4299000.00 -south: 4247000.00 -east: 528000.00 -west: 500000.00 -rows: 10 -cols: 15 -null: -9999 - -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 -1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ 10@ 11@ 12@ 13@ 14@ 15 """ - class SimpleCsvTestCase(TestCase): ascii_test = "ascii" @@ -119,38 +81,6 @@ def test_text_delimeter(self): msg="ascii_test in degrees must be between 1 and 5", ) - def test_tsv(self): - """Test loading TSV""" - self.assertModule( - "r.in.ascii", - input="-", - output=self.ascii_test, - type="CELL", - stdin_=INPUT_TSV, - ) - self.assertRasterMinMax( - map=self.ascii_test, - refmin=1, - refmax=15, - msg="ascii_test in degrees must be between 1 and 15", - ) - - def test_uncommon_delims(self): - """Test loading with uncommon delimiters""" - self.assertModule( - "r.in.ascii", - input="-", - output=self.ascii_test, - type="CELL", - stdin_=INPUT_UNCOMMON, - ) - self.assertRasterMinMax( - map=self.ascii_test, - refmin=1, - refmax=15, - msg="ascii_test in degrees must be between 1 and 15", - ) - if __name__ == "__main__": test() diff --git a/raster/r.in.gdal/testsuite/test_r_in_gdal.py b/raster/r.in.gdal/testsuite/test_r_in_gdal.py index 355e9b74eda..477ffca89c8 100644 --- a/raster/r.in.gdal/testsuite/test_r_in_gdal.py +++ b/raster/r.in.gdal/testsuite/test_r_in_gdal.py @@ -4,6 +4,7 @@ """ import unittest +import sys from subprocess import check_output @@ -306,12 +307,13 @@ def test_netCDF_3d_5(self): test_gdal_import_map.0000000105 """ - text_from_file = open("map_names_file.txt", "r").read() + text_from_file = open("map_names_file.txt").read() self.assertLooksLike(map_list, text_from_file) @unittest.skipIf( - tuple( + not sys.platform.startswith("win") + and tuple( map( int, check_output(["gdal-config", "--version"]) diff --git a/raster/r.in.gridatb/file_io.c b/raster/r.in.gridatb/file_io.c index 256f9869473..52ad174df4d 100644 --- a/raster/r.in.gridatb/file_io.c +++ b/raster/r.in.gridatb/file_io.c @@ -12,6 +12,9 @@ void rdwr_gridatb(void) float idx; fp = fopen(file, "r"); + if (!fp) { + G_fatal_error(_("Unable to open file: %s"), file); + } buf[0] = 0; if (fscanf(fp, "%[^\n]", buf) != 1) diff --git a/raster/r.in.lidar/main.c b/raster/r.in.lidar/main.c index 68d3a0fcd1b..96f562167b6 100644 --- a/raster/r.in.lidar/main.c +++ b/raster/r.in.lidar/main.c @@ -51,8 +51,8 @@ int main(int argc, char *argv[]) struct PointBinning point_binning; void *base_array; void *raster_row; - struct Cell_head region; - struct Cell_head input_region; + struct Cell_head region = {0}; + struct Cell_head input_region = {0}; int rows, last_rows, row0, cols; /* scan box size */ int row; /* counters */ @@ -100,7 +100,7 @@ int main(int argc, char *argv[]) int return_filter; const char *projstr; - struct Cell_head cellhd, loc_wind; + struct Cell_head cellhd = {0}, loc_wind = {0}; unsigned int n_filtered; diff --git a/raster/r.in.pdal/main.cpp b/raster/r.in.pdal/main.cpp index da32dcb5484..36d09558eea 100644 --- a/raster/r.in.pdal/main.cpp +++ b/raster/r.in.pdal/main.cpp @@ -69,8 +69,8 @@ int main(int argc, char *argv[]) SEGMENT base_segment; struct PointBinning point_binning; void *raster_row; - struct Cell_head region; - struct Cell_head input_region; + struct Cell_head region = {}; + struct Cell_head input_region = {}; int rows, cols; /* scan box size */ char buff[BUFFSIZE]; @@ -81,7 +81,7 @@ int main(int argc, char *argv[]) bin_index_nodes.max_nodes = 0; bin_index_nodes.nodes = NULL; - struct Cell_head loc_wind; + struct Cell_head loc_wind = {}; G_gisinit(argv[0]); diff --git a/raster/r.in.xyz/main.c b/raster/r.in.xyz/main.c index a4c7dfde6ed..b3c3fb380cf 100644 --- a/raster/r.in.xyz/main.c +++ b/raster/r.in.xyz/main.c @@ -112,7 +112,7 @@ int main(int argc, char *argv[]) char *n_array, *min_array, *max_array, *sum_array, *sumsq_array, *index_array; void *raster_row, *ptr; - struct Cell_head region; + struct Cell_head region = {0}; int rows, last_rows, row0, cols; /* scan box size */ int row, col; /* counters */ diff --git a/raster/r.kappa/testsuite/test_r_kappa.py b/raster/r.kappa/testsuite/test_r_kappa.py index 56e356ca20b..620a4f4979b 100644 --- a/raster/r.kappa/testsuite/test_r_kappa.py +++ b/raster/r.kappa/testsuite/test_r_kappa.py @@ -21,6 +21,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test from grass.gunittest.checkers import keyvalue_equals +from grass.gunittest.utils import xfail_windows class MatrixCorrectnessTest(TestCase): @@ -474,6 +475,7 @@ def test_stdout(self): keyvalue_equals(self.expected_outputs[i], json_out, precision=4) ) + @xfail_windows def test_file(self): for i in range(len(self.references)): f = NamedTemporaryFile() diff --git a/raster/r.li/TODO b/raster/r.li/TODO index 61ddd6b0941..382195402a6 100644 --- a/raster/r.li/TODO +++ b/raster/r.li/TODO @@ -24,12 +24,13 @@ d.vect forests type=boundary ######## TODO: CHECK THIS: -# MASK test -g.copy rast=fields,MASK +# Test with raster mask +r.mask raster=fields r.li.patchdensity forests conf=movwindow7 output=forests_p_dens7mask --o d.erase d.rast.leg forests_p_dens7mask -# -> no negative values! but MASK is respected +r.mask -r +# -> no negative values! but mask is respected # zero data test r.mapcalc "forests = 0" diff --git a/raster/r.mask.status/Makefile b/raster/r.mask.status/Makefile new file mode 100644 index 00000000000..62c968d044e --- /dev/null +++ b/raster/r.mask.status/Makefile @@ -0,0 +1,10 @@ +MODULE_TOPDIR = ../.. + +PGM = r.mask.status + +LIBES = $(MANAGELIB) $(RASTERLIB) $(GISLIB) $(PARSONLIB) +DEPENDENCIES = $(MANAGEDEP) $(RASTERDEP) $(GISDEP) + +include $(MODULE_TOPDIR)/include/Make/Module.make + +default: cmd diff --git a/raster/r.mask.status/main.c b/raster/r.mask.status/main.c new file mode 100644 index 00000000000..16790adf35c --- /dev/null +++ b/raster/r.mask.status/main.c @@ -0,0 +1,186 @@ +/**************************************************************************** + * + * MODULE: r.mask.status + * AUTHORS: Vaclav Petras + * PURPOSE: Report status of raster mask + * COPYRIGHT: (C) 2024 by Vaclav Petras and the GRASS Development Team + * + * This program is free software under the GNU General Public + * License (>=v2). Read the file COPYING that comes with GRASS + * for details. + * + *****************************************************************************/ + +#include +#include +#include +#include + +#include +#include +#include +#include + +struct Parameters { + struct Option *format; + struct Flag *like_test; +}; + +void parse_parameters(struct Parameters *params, int argc, char **argv) +{ + struct GModule *module; + + module = G_define_module(); + G_add_keyword(_("raster")); + G_add_keyword(_("mask")); + G_add_keyword(_("reclassification")); + module->label = _("Reports presence or absence of a raster mask"); + module->description = + _("Provides information about the presence of a 2D raster mask" + " as text output or return code"); + + params->format = G_define_option(); + params->format->key = "format"; + params->format->type = TYPE_STRING; + params->format->required = NO; + params->format->answer = "plain"; + params->format->options = "plain,json,shell,yaml"; + params->format->descriptions = + "plain;Plain text output;" + "json;JSON (JavaScript Object Notation);" + "shell;Shell script style output;" + "yaml;YAML (human-friendly data serialization language)"; + params->format->description = _("Format for reporting"); + + params->like_test = G_define_flag(); + params->like_test->key = 't'; + params->like_test->label = + _("Return code 0 when mask present, 1 otherwise"); + params->like_test->description = + _("Behave like the test utility, 0 for true, 1 for false, no output"); + // suppress_required is not required given the default value for format. + // Both no parameters and only -t work as expected. + + if (G_parser(argc, argv)) + exit(EXIT_FAILURE); +} + +int report_status(struct Parameters *params) +{ + + char name[GNAME_MAX]; + char mapset[GMAPSET_MAX]; + char reclass_name[GNAME_MAX]; + char reclass_mapset[GMAPSET_MAX]; + + bool is_mask_reclass; + bool present = Rast_mask_status(name, mapset, &is_mask_reclass, + reclass_name, reclass_mapset); + + // This does not have to be exclusive with the printing, but leaving this + // to a different boolean flag which could do the return code and printing. + // The current implementation really behaves like the test utility which + // facilitates the primary usage of this which is prompt building + // (and there any output would be noise). + if (params->like_test->answer) { + if (present) + return 0; + return 1; + } + + // Mask raster + char *full_mask = G_fully_qualified_name(name, mapset); + // Underlying raster if applicable + char *full_underlying = NULL; + if (is_mask_reclass) + full_underlying = G_fully_qualified_name(reclass_name, reclass_mapset); + + if (strcmp(params->format->answer, "json") == 0) { + JSON_Value *root_value = json_value_init_object(); + JSON_Object *root_object = json_object(root_value); + json_object_set_boolean(root_object, "present", present); + if (present) + json_object_set_string(root_object, "full_name", full_mask); + else + json_object_set_null(root_object, "full_name"); + if (is_mask_reclass) + json_object_set_string(root_object, "is_reclass_of", + full_underlying); + else + json_object_set_null(root_object, "is_reclass_of"); + char *serialized_string = json_serialize_to_string_pretty(root_value); + if (!serialized_string) + G_fatal_error(_("Failed to initialize pretty JSON string.")); + puts(serialized_string); + json_free_serialized_string(serialized_string); + json_value_free(root_value); + } + else if (strcmp(params->format->answer, "shell") == 0) { + printf("present="); + if (present) + printf("1"); + else + printf("0"); + printf("\nfull_name="); + if (present) + printf("%s", full_mask); + printf("\nis_reclass_of="); + if (is_mask_reclass) + printf("%s", full_underlying); + printf("\n"); + } + else if (strcmp(params->format->answer, "yaml") == 0) { + printf("present: "); + if (present) + printf("true"); + else + printf("false"); + printf("\nfull_name: "); + if (present) + printf("|-\n %s", full_mask); + else + printf("null"); + // Null values in YAML can be an empty (no) value (rather than null), + // so we could use that, but using the explicit null as a reasonable + // starting point. + printf("\nis_reclass_of: "); + // Using block scalar with |- to avoid need for escaping. + // Alternatively, we could check mapset naming limits against YAML + // escaping needs for different types of strings and do the necessary + // escaping here. + if (is_mask_reclass) + printf("|-\n %s", full_underlying); + else + printf("null"); + printf("\n"); + } + else { + if (present) + printf(_("Mask is active")); + else + printf(_("Mask is not present")); + if (present) { + printf("\n"); + printf(_("Mask name: %s"), full_mask); + } + if (is_mask_reclass) { + printf("\n"); + printf(_("Mask is a raster reclassified from: %s"), + full_underlying); + } + printf("\n"); + } + + G_free(full_mask); + G_free(full_underlying); + return EXIT_SUCCESS; +} + +int main(int argc, char **argv) +{ + struct Parameters params; + + G_gisinit(argv[0]); + parse_parameters(¶ms, argc, argv); + return report_status(¶ms); +} diff --git a/raster/r.mask.status/r.mask.status.html b/raster/r.mask.status/r.mask.status.html new file mode 100644 index 00000000000..248ee3ea317 --- /dev/null +++ b/raster/r.mask.status/r.mask.status.html @@ -0,0 +1,65 @@ +

    DESCRIPTION

    + +The r.mask.status reports information about the 2D raster mask and its +status. If the mask is present, the tool reports a full name of the raster (name +including the mapset) which represents the mask. It can also report full name of +the underlying raster if the mask is reclassified from another raster. + +

    +With the -t flag, no output is printed, instead a return code is used to +indicate presence or absence. The convention is the same same the POSIX +test utility, so r.mask.status returns 0 when the mask is +present and 1 otherwise. + +

    EXAMPLES

    + +

    Generate JSON output

    + +To generate JSON output in Bash, use the format option: + +
    +r.mask.status format=json
    +
    + +In Python, use: + +
    +import grass.script as gs
    +gs.parse_command("r.mask.status", format="json")
    +
    + +This returns a dictionary with keys present, +full_name, and is_reclass_of. + +

    Use as the test utility

    + +The POSIX test utility uses return code 0 to indicate presence +and 1 to indicate absence of a file, so testing existence of a file with +test -f gives return code 0 when the file exists. +r.mask.status can be used in the same with the the -t flag: + +
    +r.mask.status -t
    +
    + +In a Bash script: + +
    +# Bash
    +if r.mask.status -t; then
    +    echo "Masking is active"
    +else
    +    echo "Masking is not active"
    +fi
    +
    + +

    SEE ALSO

    + + +r.mask, +g.region + + +

    AUTHORS

    + +Vaclav Petras, NC State University, Center for Geospatial Analytics diff --git a/raster/r.mask.status/tests/conftest.py b/raster/r.mask.status/tests/conftest.py new file mode 100644 index 00000000000..e8e27315845 --- /dev/null +++ b/raster/r.mask.status/tests/conftest.py @@ -0,0 +1,25 @@ +"""Fixtures for simple sessions""" + +import os +import pytest +import grass.script as gs + + +@pytest.fixture +def session_no_data(tmp_path): + """Set up a GRASS session for the tests.""" + project = "test_project" + gs.create_project(tmp_path, project) + with gs.setup.init(tmp_path / project, env=os.environ.copy()) as session: + yield session + + +@pytest.fixture +def session_with_data(tmp_path): + """Set up a GRASS session for the tests.""" + project = tmp_path / "test_project" + gs.create_project(project) + with gs.setup.init(project, env=os.environ.copy()) as session: + gs.run_command("g.region", rows=2, cols=2, env=session.env) + gs.mapcalc("a = 1", env=session.env) + yield session diff --git a/raster/r.mask.status/tests/r_mask_status_test.py b/raster/r.mask.status/tests/r_mask_status_test.py new file mode 100644 index 00000000000..deafdfb145b --- /dev/null +++ b/raster/r.mask.status/tests/r_mask_status_test.py @@ -0,0 +1,126 @@ +"""Tests of r.mask.status""" + +import pytest + +try: + import yaml +except ImportError: + yaml = None + +import grass.script as gs + + +def test_json_no_mask(session_no_data): + """Check JSON format for no mask""" + session = session_no_data + data = gs.parse_command("r.mask.status", format="json", env=session.env) + assert "present" in data + assert "full_name" in data + assert "is_reclass_of" in data + assert data["present"] is False + assert not data["full_name"] + assert not data["is_reclass_of"] + + +def test_json_with_r_mask(session_with_data): + """Check JSON format for the r.mask case""" + session = session_with_data + gs.run_command("r.mask", raster="a", env=session.env) + data = gs.parse_command("r.mask.status", format="json", env=session.env) + assert data["present"] is True + assert data["full_name"] == "MASK@PERMANENT" + assert data["is_reclass_of"] == "a@PERMANENT" + # Now remove the mask. + gs.run_command("r.mask", flags="r", env=session.env) + data = gs.parse_command("r.mask.status", format="json", env=session.env) + assert data["present"] is False + assert not data["full_name"] + assert not data["is_reclass_of"] + + +def test_json_with_g_copy(session_with_data): + """Check JSON format for the low-level g.copy case""" + session = session_with_data + gs.run_command("g.copy", raster="a,MASK", env=session.env) + data = gs.parse_command("r.mask.status", format="json", env=session.env) + assert data["present"] is True + assert data["full_name"] == "MASK@PERMANENT" + assert not data["is_reclass_of"] + # Now remove the mask. + gs.run_command("g.remove", type="raster", name="MASK", flags="f", env=session.env) + data = gs.parse_command("r.mask.status", format="json", env=session.env) + assert data["present"] is False + assert not data["full_name"] + assert not data["is_reclass_of"] + + +def test_shell(session_with_data): + """Check shell format for the r.mask case""" + session = session_with_data + gs.run_command("r.mask", raster="a", env=session.env) + data = gs.parse_command("r.mask.status", format="shell", env=session.env) + assert int(data["present"]) + assert data["full_name"] == "MASK@PERMANENT" + assert data["is_reclass_of"] == "a@PERMANENT" + # Now remove the mask. + gs.run_command("r.mask", flags="r", env=session.env) + data = gs.parse_command("r.mask.status", format="shell", env=session.env) + assert not int(data["present"]) + assert not data["full_name"] + assert not data["is_reclass_of"] + + +@pytest.mark.skipif(yaml is None, reason="PyYAML package not available") +def test_yaml(session_with_data): + """Check YAML format for the r.mask case""" + session = session_with_data + gs.run_command("r.mask", raster="a", env=session.env) + text = gs.read_command("r.mask.status", format="yaml", env=session.env) + data = yaml.safe_load(text) + assert data["present"] is True + assert data["full_name"] == "MASK@PERMANENT" + assert data["is_reclass_of"] == "a@PERMANENT" + # Now remove the mask. + gs.run_command("r.mask", flags="r", env=session.env) + text = gs.read_command("r.mask.status", format="yaml", env=session.env) + data = yaml.safe_load(text) + assert data["present"] is False + assert not data["full_name"] + assert not data["is_reclass_of"] + + +def test_plain(session_with_data): + """Check plain text format for the r.mask case""" + session = session_with_data + gs.run_command("r.mask", raster="a", env=session.env) + text = gs.read_command("r.mask.status", format="plain", env=session.env) + assert text + assert "MASK@PERMANENT" in text + assert "a@PERMANENT" in text + # Now remove the mask. + gs.run_command("r.mask", flags="r", env=session.env) + text = gs.read_command("r.mask.status", format="plain", env=session.env) + assert text + + +def test_without_parameters(session_no_data): + """Check output is generated with no parameters""" + session = session_no_data + text = gs.read_command("r.mask.status", env=session.env) + assert text + + +def test_behavior_mimicking_test_program(session_with_data): + """Check test program like behavior for the r.mask case""" + session = session_with_data + gs.run_command("r.mask", raster="a", env=session.env) + returncode = gs.run_command( + "r.mask.status", flags="t", env=session.env, errors="status" + ) + assert returncode == 0 + # Now remove the mask. + gs.run_command("r.mask", flags="r", env=session.env) + returncode = gs.run_command( + "r.mask.status", flags="t", env=session.env, errors="status" + ) + assert returncode == 1 diff --git a/raster/r.mfilter/main.c b/raster/r.mfilter/main.c index 17ecd2182be..ad0a9dd35ae 100644 --- a/raster/r.mfilter/main.c +++ b/raster/r.mfilter/main.c @@ -132,8 +132,8 @@ int main(int argc, char **argv) "threads setting.")); nprocs = 1; #endif - if (nprocs > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (nprocs > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); nprocs = 1; } out_name = opt2->answer; diff --git a/raster/r.mfilter/testsuite/test_r_mfilter.py b/raster/r.mfilter/testsuite/test_r_mfilter.py index 3d1764b4894..c18aa7c9273 100644 --- a/raster/r.mfilter/testsuite/test_r_mfilter.py +++ b/raster/r.mfilter/testsuite/test_r_mfilter.py @@ -1,6 +1,7 @@ from tempfile import NamedTemporaryFile from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows class TestNeighbors(TestCase): @@ -202,6 +203,7 @@ def tearDownClass(cls): "g.remove", flags="f", type="raster", name=",".join(cls.to_remove) ) + @xfail_windows def test_sequential(self): """Test output with sequential filter type.""" test_case = "test_sequential" @@ -235,6 +237,7 @@ def test_sequential(self): precision=1e-5, ) + @xfail_windows def test_parallel(self): """Test output with parallel filter type.""" test_case = "test_parallel" @@ -268,6 +271,7 @@ def test_parallel(self): precision=1e-5, ) + @xfail_windows def test_sequential_null(self): """Test output with sequential filter type with null mode enabled.""" test_case = "test_sequential_null" @@ -301,6 +305,7 @@ def test_sequential_null(self): precision=1e-5, ) + @xfail_windows def test_parallel_null(self): """Test output with parallel filter type with null mode enabled.""" test_case = "test_parallel_null" @@ -361,6 +366,7 @@ def test_parallel_null(self): precision=1e-5, ) + @xfail_windows def test_multiple_filters(self): """Test output with multiple filters.""" test_case = "test_multiple_filters" @@ -394,6 +400,7 @@ def test_multiple_filters(self): precision=1e-5, ) + @xfail_windows def test_repeated_filters(self): """Test output with repeated filters.""" test_case = "test_repeated_filters" diff --git a/raster/r.neighbors/main.c b/raster/r.neighbors/main.c index 93cbaa9e3da..8885460a564 100644 --- a/raster/r.neighbors/main.c +++ b/raster/r.neighbors/main.c @@ -310,8 +310,8 @@ int main(int argc, char *argv[]) "threads setting.")); ncb.threads = 1; #endif - if (ncb.threads > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (ncb.threads > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); ncb.threads = 1; } if (strcmp(parm.weighting_function->answer, "none") && flag.circle->answer) diff --git a/raster/r.null/r.null.html b/raster/r.null/r.null.html index 0a98907af5f..4d92b027d65 100644 --- a/raster/r.null/r.null.html +++ b/raster/r.null/r.null.html @@ -49,10 +49,12 @@

    External maps

    From the r.external documentation: GDAL-linked (r.external) maps do not have or use a NULL bitmap, hence r.null cannot manipulate them directly. Here NULL cells are those whose value matches -the value reported by the GDALGetRasterNoDataValue() function. To apply the -GDAL-linked the user need to either create a MASK (e.g. with r.mask) and -then "apply" it using e.g. r.resample, or use r.mapcalc to create a copy -with the appropriate categories changed to NULL (if() condition). +the value reported by the GDALGetRasterNoDataValue() function. +To introduce additional NULL values to a computation based on a GDAL-linked +raster, the user needs to either create a mask with with r.mask and +then "apply" it using e.g. r.resample or r.mapcalc, +or use r.mapcalc to create a copy with the appropriate categories +changed to NULL (if() condition).

    EXAMPLES

    diff --git a/raster/r.out.png/main.c b/raster/r.out.png/main.c index 4d3895e5d9f..68bcc09ffef 100644 --- a/raster/r.out.png/main.c +++ b/raster/r.out.png/main.c @@ -369,8 +369,10 @@ int main(int argc, char *argv[]) /* G_free (info_ptr); */ png_destroy_write_struct(&png_ptr, &info_ptr); /* al 11/2000 */ - if (fp) + if (fp) { fclose(fp); + fp = NULL; + } if (wld_flag->answer) { if (do_stdout) diff --git a/raster/r.patch/main.c b/raster/r.patch/main.c index 3835e287440..c54482db13a 100644 --- a/raster/r.patch/main.c +++ b/raster/r.patch/main.c @@ -113,8 +113,8 @@ int main(int argc, char *argv[]) "threads setting.")); nprocs = 1; #endif - if (nprocs > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (nprocs > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); nprocs = 1; } diff --git a/raster/r.proj/testsuite/test_rproj.py b/raster/r.proj/testsuite/test_rproj.py new file mode 100644 index 00000000000..5f3834be881 --- /dev/null +++ b/raster/r.proj/testsuite/test_rproj.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python + +############################################################################## +# MODULE: r.proj +# +# AUTHOR(S): Chung-Yuan Liang +# +# PURPOSE: Unit tests for r.proj +# +# COPYRIGHT: (C) 2024 Chung-Yuan Liang and the GRASS Development Team +# +# This program is free software under the GNU General Public +# License (>=v2). Read the file COPYING that comes with GRASS +# for details. +############################################################################## + +from grass.gunittest.case import TestCase +from grass.gunittest.gmodules import call_module +import shutil + +raster_info = """north=35.8096296297222 +south=35.6874074075 +east=-78.608 +west=-78.7746666666667 +nsres=0.000740740740740727 +ewres=0.000666666666666686 +rows=165 +cols=250 +cells=41250""" + +src_project = "nc_spm_full_v2alpha2" +dst_project = "nc_latlong" + + +class TestRasterreport(TestCase): + input = "elevation" + + @classmethod + def setUpClass(cls): + cls.runModule("g.proj", project=dst_project, epsg="4326", flags="c") + cls.runModule("g.mapset", mapset="PERMANENT", project=dst_project) + + @classmethod + def tearDownClass(cls): + cls.runModule("g.mapset", mapset="PERMANENT", project=src_project) + dbase = call_module("g.gisenv", get="GISDBASE") + shutil.rmtree(f"{dbase}/{dst_project}") + + def run_rproj_test(self, method, statics): + """The main function to run r.proj check rsults according to the method + + Parameters + ---------- + method : str + The method to be used for r.proj + statics : str + The expected statics of the output raster + """ + output = method + ## Get the boundary and set up region for the projected map + stdout = call_module( + "r.proj", + project=src_project, + mapset="PERMANENT", + input=self.input, + method=method, + flags="g", + ) + settings = dict([line.split("=") for line in stdout.split()]) + + call_module( + "g.region", + n=settings["n"], + s=settings["s"], + e=settings["e"], + w=settings["w"], + rows=settings["rows"], + cols=settings["cols"], + flags="a", + res=1, + ) + + ## Project the map + self.assertModule( + "r.proj", + project=src_project, + mapset="PERMANENT", + input=self.input, + output=output, + method=method, + quiet=True, + ) + + ## Validate the output + self.assertRasterFitsUnivar(output, reference=statics, precision=1e-7) + self.assertRasterFitsInfo(output, reference=raster_info, precision=1e-7) + + def test_nearest(self): + """Testing method nearest""" + ## Set up variables and validation values + method = "nearest" + statics = """n=40930 + min=55.5787925720215 + max=156.038833618164 + mean=110.377538633405 + variance=412.751942806146""" + + self.run_rproj_test(method, statics) + + def test_bilinear(self): + """Testing method bilinear""" + ## Set up variables and validation values + method = "bilinear" + statics = """n=40845 + min=56.3932914733887 + max=156.053298950195 + mean=110.389074372679 + variance=411.487781666933""" + + self.run_rproj_test(method, statics) + + def test_bicubic(self): + """Testing method bicubic""" + ## Set up variables and validation values + method = "bicubic" + statics = """n=40677 + min=56.2407836914062 + max=156.061599731445 + mean=110.41701776258 + variance=411.382636894393""" + + self.run_rproj_test(method, statics) + + def test_lanczos(self): + """Testing method lanczos""" + ## Set up variables and validation values + method = "lanczos" + statics = """n=40585 + min=56.2350921630859 + max=156.066345214844 + mean=110.421826400841 + variance=411.6875834341575""" + + self.run_rproj_test(method, statics) + + def test_bilinear_f(self): + """Testing method bilinear_f""" + ## Set up variables and validation values + method = "bilinear_f" + statics = """n=40930 + min=55.5787925720215 + max=156.053298950195 + mean=110.376211041027 + variance=412.553041205029""" + + self.run_rproj_test(method, statics) + + def test_bicubic_f(self): + """Testing method bicubic_f""" + ## Set up variables and validation values + method = "bicubic_f" + statics = """n=40930 + min=55.5787925720215 + max=156.061599731445 + mean=110.375897704515 + variance=412.693308000461""" + + self.run_rproj_test(method, statics) + + def test_lanczos_f(self): + """Testing method lanczos_f""" + ## Set up variables and validation values + method = "lanczos_f" + statics = """n=40930 + min=55.5787925720215 + max=156.066345214844 + mean=110.375715222838 + variance=412.695433658258""" + + self.run_rproj_test(method, statics) + + +if __name__ == "__main__": + from grass.gunittest.main import test + + test() diff --git a/raster/r.report/testsuite/test_r_report.py b/raster/r.report/testsuite/test_r_report.py index 53e49fdc174..86a16c27adb 100644 --- a/raster/r.report/testsuite/test_r_report.py +++ b/raster/r.report/testsuite/test_r_report.py @@ -17,6 +17,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows class TestRasterreport(TestCase): @@ -294,6 +295,7 @@ def test_json(self): data = json.loads(module.outputs.stdout) self._assert_report_equal(reference, data) + @xfail_windows def test_json2(self): """Test JSON format with more options""" reference = { diff --git a/raster/r.resamp.filter/main.c b/raster/r.resamp.filter/main.c index b1f6ed3e530..e74f3598629 100644 --- a/raster/r.resamp.filter/main.c +++ b/raster/r.resamp.filter/main.c @@ -494,8 +494,8 @@ int main(int argc, char *argv[]) "threads setting.")); nprocs = 1; #endif - if (nprocs > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (nprocs > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active make.")); nprocs = 1; } if (parm.radius->answer) { diff --git a/raster/r.resamp.interp/main.c b/raster/r.resamp.interp/main.c index 734f3306bf8..2319400b0fc 100644 --- a/raster/r.resamp.interp/main.c +++ b/raster/r.resamp.interp/main.c @@ -132,8 +132,8 @@ int main(int argc, char *argv[]) "threads setting.")); threads = 1; #endif - if (threads > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (threads > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); threads = 1; } bufrows = atoi(memory->answer) * (((1 << 20) / sizeof(DCELL)) / dst_w.cols); diff --git a/raster/r.resamp.interp/r.resamp.interp.html b/raster/r.resamp.interp/r.resamp.interp.html index e4b77ac0d34..3c3eecc68a9 100644 --- a/raster/r.resamp.interp/r.resamp.interp.html +++ b/raster/r.resamp.interp/r.resamp.interp.html @@ -28,7 +28,7 @@

    NOTES

    Note that for bilinear, bicubic and lanczos interpolation, cells of the output raster that cannot be bounded by the appropriate number of input cell centers are set to NULL (NULL propagation). This could occur -due to the input cells being outside the current region, being NULL or MASKed. +due to the input cells being outside the current region, being NULL or masked.

    For longitude-latitude coordinate reference systems, diff --git a/raster/r.series/main.c b/raster/r.series/main.c index bfecbf117c0..ade93d8f185 100644 --- a/raster/r.series/main.c +++ b/raster/r.series/main.c @@ -227,8 +227,8 @@ int main(int argc, char *argv[]) "threads setting.")); nprocs = 1; #endif - if (nprocs > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (nprocs > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); nprocs = 1; } lo = -INFINITY; diff --git a/raster/r.sim/r.sim.sediment/Makefile b/raster/r.sim/r.sim.sediment/Makefile index 4bc07478ec9..13ca19d09dc 100644 --- a/raster/r.sim/r.sim.sediment/Makefile +++ b/raster/r.sim/r.sim.sediment/Makefile @@ -4,8 +4,8 @@ PGM=r.sim.sediment EXTRA_CLEAN_DIRS=doxygenhtml -LIBES = $(SIMLIB) $(GMATHLIB) $(GISLIB) $(OPENMP_LIBPATH) $(OPENMP_LIB) -DEPENDENCIES = $(SIMDEP) $(GMATHDEP) $(GISDEP) +LIBES = $(SIMLIB) $(GMATHLIB) $(GISLIB) $(RASTERLIB) $(OPENMP_LIBPATH) $(OPENMP_LIB) +DEPENDENCIES = $(SIMDEP) $(GMATHDEP) $(GISDEP) $(RASTERDEP) EXTRA_INC = $(OPENMP_INCPATH) $(VECT_INC) EXTRA_CFLAGS = -I ../simlib $(VECT_CFLAGS) $(OPENMP_CFLAGS) diff --git a/raster/r.sim/r.sim.sediment/main.c b/raster/r.sim/r.sim.sediment/main.c index fcdd9e98f89..d0197c2abb1 100644 --- a/raster/r.sim/r.sim.sediment/main.c +++ b/raster/r.sim/r.sim.sediment/main.c @@ -70,6 +70,7 @@ #endif #include #include +#include #include #include #include @@ -380,8 +381,8 @@ int main(int argc, char *argv[]) #else threads = 1; #endif - if (threads > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (threads > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); threads = 1; } G_message(_("Number of threads: %d"), threads); @@ -416,6 +417,8 @@ int main(int argc, char *argv[]) G_message(_("Using metric conversion factor %f, step=%f"), wp.conv, wp.step); + wp.observation = parm.observation->answer; + wp.logfile = parm.logfile->answer; init_library_globals(&wp); if ((wp.tc == NULL) && (wp.et == NULL) && (wp.conc == NULL) && diff --git a/raster/r.sim/r.sim.water/Makefile b/raster/r.sim/r.sim.water/Makefile index 36121ebf82e..47037823fae 100644 --- a/raster/r.sim/r.sim.water/Makefile +++ b/raster/r.sim/r.sim.water/Makefile @@ -4,8 +4,8 @@ PGM=r.sim.water EXTRA_CLEAN_DIRS=doxygenhtml -LIBES = $(SIMLIB) $(GMATHLIB) $(GISLIB) $(OPENMP_LIBPATH) $(OPENMP_LIB) -DEPENDENCIES = $(SIMDEP) $(GMATHDEP) $(GISDEP) +LIBES = $(SIMLIB) $(GMATHLIB) $(GISLIB) $(RASTERLIB) $(OPENMP_LIBPATH) $(OPENMP_LIB) +DEPENDENCIES = $(SIMDEP) $(GMATHDEP) $(GISDEP) $(RASTERDEP) EXTRA_INC = $(VECT_INC) $(OPENMP_INCPATH) EXTRA_CFLAGS = -I ../simlib $(VECT_CFLAGS) $(OPENMP_CFLAGS) diff --git a/raster/r.sim/r.sim.water/main.c b/raster/r.sim/r.sim.water/main.c index 3998e5524ac..209be3e33d9 100644 --- a/raster/r.sim/r.sim.water/main.c +++ b/raster/r.sim/r.sim.water/main.c @@ -77,6 +77,7 @@ #endif #include #include +#include #include #include #include @@ -219,7 +220,7 @@ int main(int argc, char *argv[]) parm.logfile->required = NO; parm.logfile->description = _("Name for sampling points output text file. For each observation " - "vector point the time series of sediment transport is stored."); + "vector point the time series of water discharge is stored."); parm.logfile->guisection = _("Output"); parm.nwalk = G_define_option(); @@ -407,8 +408,8 @@ int main(int argc, char *argv[]) #else threads = 1; #endif - if (threads > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (threads > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); threads = 1; } G_message(_("Number of threads: %d"), threads); @@ -524,6 +525,8 @@ int main(int argc, char *argv[]) G_message(_("Using metric conversion factor %f, step=%f"), wp.conv, wp.step); + wp.observation = parm.observation->answer; + wp.logfile = parm.logfile->answer; init_library_globals(&wp); if ((wp.depth == NULL) && (wp.disch == NULL) && (wp.err == NULL)) diff --git a/raster/r.sim/simlib/hydro.c b/raster/r.sim/simlib/hydro.c index 74145ec9bff..eb7649763e9 100644 --- a/raster/r.sim/simlib/hydro.c +++ b/raster/r.sim/simlib/hydro.c @@ -151,9 +151,6 @@ void main_loop(void) maxwa = maxwa / nblock; } - /* Create the observation points */ - create_observation_points(); - G_debug(2, " maxwa, nblock %d %d", maxwa, nblock); for (iblock = 1; iblock <= nblock; iblock++) { diff --git a/raster/r.slope.aspect/main.c b/raster/r.slope.aspect/main.c index 86b4d5f5607..d302e02b22c 100644 --- a/raster/r.slope.aspect/main.c +++ b/raster/r.slope.aspect/main.c @@ -305,8 +305,8 @@ int main(int argc, char *argv[]) "threads setting.")); nprocs = 1; #endif - if (nprocs > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (nprocs > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); nprocs = 1; } radians_to_degrees = 180.0 / M_PI; diff --git a/raster/r.stream.extract/r.stream.extract.html b/raster/r.stream.extract/r.stream.extract.html index e1c427599e8..22877936c93 100644 --- a/raster/r.stream.extract/r.stream.extract.html +++ b/raster/r.stream.extract/r.stream.extract.html @@ -126,7 +126,9 @@

    Defining a region of interest

    The stream extraction procedure can be restricted to a certain region of interest, e.g. a subbasin, by setting the computational region with -g.region and/or creating a MASK. Such region of interest should +g.region and/or creating a mask +with r.mask. +Such region of interest should be a complete catchment area, complete in the sense that the complete area upstream of an outlet point is included and buffered with at least one cell. diff --git a/raster/r.sun/main.c b/raster/r.sun/main.c index 9e45e184dac..e325cb637f0 100644 --- a/raster/r.sun/main.c +++ b/raster/r.sun/main.c @@ -591,8 +591,8 @@ int main(int argc, char *argv[]) #else threads = 1; #endif - if (threads > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (threads > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); threads = 1; } G_message(_("Number of threads <%d>"), threads); diff --git a/raster/r.terraflow/fill.cpp b/raster/r.terraflow/fill.cpp index ab1629a3b7f..c7b54cd0a47 100644 --- a/raster/r.terraflow/fill.cpp +++ b/raster/r.terraflow/fill.cpp @@ -518,7 +518,7 @@ void assignFinalDirections(AMI_STREAM *statstr, continue; } } -}; +} /* ********************************************************************** */ class directionElevationMerger { diff --git a/raster/r.terraflow/genericWindow.cpp b/raster/r.terraflow/genericWindow.cpp index 92b0852cd71..9b114773e2a 100644 --- a/raster/r.terraflow/genericWindow.cpp +++ b/raster/r.terraflow/genericWindow.cpp @@ -36,4 +36,4 @@ void fillPit(ElevationWindow &win) if (win.get(4) < min) { win.set(4, min); } -}; +} diff --git a/raster/r.terraflow/sweep.cpp b/raster/r.terraflow/sweep.cpp index 2f7fba8bb13..c98b844b016 100644 --- a/raster/r.terraflow/sweep.cpp +++ b/raster/r.terraflow/sweep.cpp @@ -65,7 +65,7 @@ sweepOutput::sweepOutput() #ifdef OUTPUT_TCI tci = (tci_type)nodataType::ELEVATION_NODATA; #endif -}; +} /* ------------------------------------------------------------ */ /* computes output parameters of cell (i,j) given the flow value, the diff --git a/raster/r.terraflow/weightWindow.cpp b/raster/r.terraflow/weightWindow.cpp index ccf55a82ca9..760dccc6b5c 100644 --- a/raster/r.terraflow/weightWindow.cpp +++ b/raster/r.terraflow/weightWindow.cpp @@ -229,7 +229,7 @@ void weightWindow::compute(const dimension_type i, const dimension_type j, cout << form("%3.2f ", weight.get(l)); cout << "]\n"; #endif -}; +} /* Find the dominant direction. Set corresponding weight to 1, and sets all other weights to 0. Set sumweight and sumcontour.*/ diff --git a/raster/r.thin/io.c b/raster/r.thin/io.c index d5ba76245c3..3b2d0bd8aa3 100644 --- a/raster/r.thin/io.c +++ b/raster/r.thin/io.c @@ -67,13 +67,17 @@ int put_a_row(int row, CELL *buf) static int read_row(int file, void *buf, int row, int buf_len) { - lseek(file, ((off_t)row) * buf_len, 0); + if (lseek(file, ((off_t)row) * buf_len, 0) == -1) { + G_fatal_error(_("Unable to seek: %s"), strerror(errno)); + } return (read(file, buf, buf_len) == buf_len); } static int write_row(int file, const void *buf, int row, int buf_len) { - lseek(file, ((off_t)row) * buf_len, 0); + if (lseek(file, ((off_t)row) * buf_len, 0) == -1) { + G_fatal_error(_("Unable to seek: %s"), strerror(errno)); + } return (write(file, buf, buf_len) == buf_len); } diff --git a/raster/r.topidx/arc_to_gridatb.py b/raster/r.topidx/arc_to_gridatb.py index 17e49365697..3eba7114430 100755 --- a/raster/r.topidx/arc_to_gridatb.py +++ b/raster/r.topidx/arc_to_gridatb.py @@ -9,9 +9,8 @@ def match(pattern, string): if m: match.value = m.group(1) return True - else: - match.value = None - return False + match.value = None + return False if len(sys.argv) != 3 or re.match("^-*help", sys.argv[1]): diff --git a/raster/r.topidx/r.topidx.html b/raster/r.topidx/r.topidx.html index 56dd001f20a..75938e6a231 100644 --- a/raster/r.topidx/r.topidx.html +++ b/raster/r.topidx/r.topidx.html @@ -10,12 +10,14 @@

    DESCRIPTION

    the local surface topographic slope (delta vertical) / (delta horizontal).
    -

    Input maps may have NULL values. For example, if you have a MASK for a -watershed (basin map from r.water.outlet), the following command will -create a masked elevation map (belev): +

    Input maps may have NULL values. For example, if you have a raster mask set +for a watershed (using basin map from r.water.outlet), the following +command will create a masked elevation map (belev): +

     r.mapcalc "belev = if(isnull(basin), basin, elev)"
     
    +

    r.stats -Anc prints out averaged statistics for topographic index. diff --git a/raster/r.univar/r.univar.html b/raster/r.univar/r.univar.html index 5220bc64a44..debde03a1d6 100644 --- a/raster/r.univar/r.univar.html +++ b/raster/r.univar/r.univar.html @@ -53,7 +53,7 @@

    PERFORMANCE

    r.univar supports parallel processing using OpenMP. The user can specify the number of threads to be used with the nprocs parameter. -However, parallelization is disabled when the MASK is set. +However, parallelization is disabled when the raster mask is set.

    Due to the differences in summation order, users may encounter small floating points diff --git a/raster/r.univar/r.univar_main.c b/raster/r.univar/r.univar_main.c index 84550a87347..e56301a1364 100644 --- a/raster/r.univar/r.univar_main.c +++ b/raster/r.univar/r.univar_main.c @@ -192,6 +192,10 @@ int main(int argc, char *argv[]) sscanf(param.nprocs->answer, "%d", &nprocs); if (nprocs < 1) G_fatal_error(_("<%d> is not valid number of nprocs."), nprocs); + if (nprocs > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); + nprocs = 1; + } #if defined(_OPENMP) omp_set_num_threads(nprocs); #else @@ -200,10 +204,6 @@ int main(int argc, char *argv[]) "threads setting.")); nprocs = 1; #endif - if (nprocs > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); - nprocs = 1; - } /* table field separator */ zone_info.sep = G_option_to_separator(param.separator); diff --git a/raster/r.viewshed/viewshed.cpp b/raster/r.viewshed/viewshed.cpp index 17ef21b7811..3ce07fa4652 100644 --- a/raster/r.viewshed/viewshed.cpp +++ b/raster/r.viewshed/viewshed.cpp @@ -261,6 +261,7 @@ MemoryVisibilityGrid *viewshed_in_memory(char *inputfname, GridHeader *hd, e.elev[0] = data[0][i]; e.elev[1] = data[1][i]; e.elev[2] = data[2][i]; + e.angle = -1.0; if (!is_nodata(visgrid->grid->hd, data[1][i]) && !is_point_outside_max_dist(*vp, *hd, sn.row, sn.col, @@ -499,6 +500,7 @@ IOVisibilityGrid *viewshed_external(char *inputfname, GridHeader *hd, e.elev[0] = data[0][i]; e.elev[1] = data[1][i]; e.elev[2] = data[2][i]; + e.angle = -1.0; if (!is_nodata(visgrid->hd, data[1][i]) && !is_point_outside_max_dist(*vp, *hd, sn.row, sn.col, viewOptions.maxDist)) { diff --git a/raster/r.what/testsuite/test_r_what.py b/raster/r.what/testsuite/test_r_what.py index fcc312e6284..68bfdeea376 100644 --- a/raster/r.what/testsuite/test_r_what.py +++ b/raster/r.what/testsuite/test_r_what.py @@ -510,7 +510,7 @@ def test_raster_what_csv(self): ) self.assertFileExists(filename="result.csv", msg="CSV file was not created") if os.path.isfile("result.csv"): - file = open("result.csv", "r") + file = open("result.csv") fileData = file.read() self.assertLooksLike( actual=fileData, diff --git a/raster3d/r3.in.lidar/main.c b/raster3d/r3.in.lidar/main.c index 6170a3f50ba..3cf91189d24 100644 --- a/raster3d/r3.in.lidar/main.c +++ b/raster3d/r3.in.lidar/main.c @@ -361,13 +361,12 @@ int main(int argc, char *argv[]) /* for the CRS info */ const char *projstr; - struct Cell_head current_region; - struct Cell_head file_region; - + struct Cell_head current_region = {0}; + struct Cell_head file_region = {0}; G_get_set_window(¤t_region); /* extent for all data */ - struct Cell_head data_region; + struct Cell_head data_region = {0}; long unsigned header_count = 0; int i; diff --git a/raster3d/r3.in.v5d/binio.c b/raster3d/r3.in.v5d/binio.c index f8582e97313..b47723a2929 100644 --- a/raster3d/r3.in.v5d/binio.c +++ b/raster3d/r3.in.v5d/binio.c @@ -147,7 +147,7 @@ static void if_to_c(long *t, const long *f) { if (*f != 0) { *t = (((*f & 0x8000000000000000) | - ((*f & 0x7f80000000000000) >> 7) + (16258 << 48)) | + ((*f & 0x7f80000000000000) >> 7) + (16258L << 48)) | (((*f & 0x007fffff00000000) >> 8) | (0x0000800000000000))); if ((*f << 1) == 0) *t = 0; @@ -160,7 +160,7 @@ static void if_to_c(long *t, const long *f) #define IF_TO_C(T, F) \ if (F != 0) { \ T = (((F & 0x8000000000000000) | \ - ((F & 0x7f80000000000000) >> 7) + (16258 << 48)) | \ + ((F & 0x7f80000000000000) >> 7) + (16258L << 48)) | \ (((F & 0x007fffff00000000) >> 8) | (0x0000800000000000))); \ if ((F << 1) == 0) \ T = 0; \ diff --git a/raster3d/r3.in.v5d/v5d.c b/raster3d/r3.in.v5d/v5d.c index 445d6f29b9f..54f75f2361a 100644 --- a/raster3d/r3.in.v5d/v5d.c +++ b/raster3d/r3.in.v5d/v5d.c @@ -63,6 +63,9 @@ #include #include #include +#include +#include + #include "binio.h" #include "v5d.h" #include "vis5d.h" @@ -1232,7 +1235,10 @@ static int read_comp_header(int f, v5dstruct *v) unsigned int id; /* reset file position to start of file */ - lseek(f, 0, SEEK_SET); + if (lseek(f, 0, SEEK_SET) == -1) { + G_warning(_("Unable to seek: %s"), strerror(errno)); + return 0; + } /* read file ID */ read_int4(f, (int *)&id); @@ -1334,8 +1340,8 @@ static int read_comp_header(int f, v5dstruct *v) /* skip ahead by 'gridsize' bytes */ if (lseek(f, gridsize, SEEK_CUR) == -1) { - printf("Error: Unexpected end of file, "); - printf("file may be corrupted.\n"); + G_warning(_("Error: Unexpected end of file, file may be " + "corrupted.")); return 0; } min = -(125.0 + gb) / ga; @@ -1478,7 +1484,10 @@ static int read_comp_grid(v5dstruct *v, int time, int var, float *ga, float *gb, /* move to position in file */ pos = grid_position(v, time, var); - lseek(f, pos, SEEK_SET); + if (lseek(f, pos, SEEK_SET) == -1) { + G_warning(_("Unable to seek: %s"), strerror(errno)); + return 0; + } if (v->FileFormat == 0x80808083) { /* read McIDAS grid and file numbers */ @@ -1551,7 +1560,13 @@ static int read_comp_grid(v5dstruct *v, int time, int var, float *ga, float *gb, */ static int read_v5d_header(v5dstruct *v) { -#define SKIP(N) lseek(f, N, SEEK_CUR) +#define SKIP(N) \ + do { \ + if (lseek(f, N, SEEK_CUR) == -1) { \ + G_warning(_("Unable to seek: %s"), strerror(errno)); \ + return 0; \ + } \ + } while (0) int end_of_header = 0; unsigned int id; int idlen, var, numargs; @@ -1870,13 +1885,19 @@ static int read_v5d_header(v5dstruct *v) case TAG_END: /* end of header */ end_of_header = 1; - lseek(f, length, SEEK_CUR); + if (lseek(f, length, SEEK_CUR) == -1) { + G_warning(_("Unable to seek: %s"), strerror(errno)); + return 0; + } break; default: /* unknown tag, skip to next tag */ printf("Unknown tag: %d length=%d\n", tag, length); - lseek(f, length, SEEK_CUR); + if (lseek(f, length, SEEK_CUR) == -1) { + G_warning(_("Unable to seek: %s"), strerror(errno)); + return 0; + } break; } } @@ -1966,7 +1987,10 @@ int v5dReadCompressedGrid(v5dstruct *v, int time, int var, float *ga, float *gb, /* move to position in file */ pos = grid_position(v, time, var); - lseek(v->FileDesc, pos, SEEK_SET); + if (lseek(v->FileDesc, pos, SEEK_SET) == -1) { + G_warning(_("Unable to seek: %s"), strerror(errno)); + return 0; + } /* read ga, gb arrays */ read_float4_array(v->FileDesc, ga, v->Nl[var]); @@ -2118,7 +2142,10 @@ static int write_v5d_header(v5dstruct *v) } /* set file pointer to start of file */ - lseek(f, 0, SEEK_SET); + if (lseek(f, 0, SEEK_SET) == -1) { + G_warning(_("Unable to seek: %s"), strerror(errno)); + return 0; + } v->CurPos = 0; /* @@ -2222,7 +2249,10 @@ static int write_v5d_header(v5dstruct *v) /* We're writing to a brand new file. Reserve 10000 bytes */ /* for future header growth. */ WRITE_TAG(v, TAG_END, 10000); - lseek(f, 10000, SEEK_CUR); + if (lseek(f, 10000, SEEK_CUR) == -1) { + G_warning(_("Unable to seek: %s"), strerror(errno)); + return 0; + } /* Let file pointer indicate where first grid is stored */ v->FirstGridPos = ltell(f); @@ -2336,7 +2366,7 @@ int v5dWriteCompressedGrid(const v5dstruct *v, int time, int var, pos = grid_position(v, time, var); if (lseek(v->FileDesc, pos, SEEK_SET) < 0) { /* lseek failed, return error */ - printf("Error in v5dWrite[Compressed]Grid: seek failed, disk full?\n"); + G_warning(_("Unable to seek: %s"), strerror(errno)); return 0; } @@ -2452,9 +2482,15 @@ int v5dCloseFile(v5dstruct *v) if (v->Mode == 'w') { /* rewrite header because writing grids updates the minval and */ /* maxval fields */ - lseek(v->FileDesc, 0, SEEK_SET); + if (lseek(v->FileDesc, 0, SEEK_SET) == -1) { + G_warning(_("Unable to seek: %s"), strerror(errno)); + return 0; + } status = write_v5d_header(v); - lseek(v->FileDesc, 0, SEEK_END); + if (lseek(v->FileDesc, 0, SEEK_END) == -1) { + G_warning(_("Unable to seek: %s"), strerror(errno)); + return 0; + } close(v->FileDesc); } else if (v->Mode == 'r') { diff --git a/raster3d/raster3dintro.html b/raster3d/raster3dintro.html index ac476b974b2..b51748b4dd8 100644 --- a/raster3d/raster3dintro.html +++ b/raster3d/raster3dintro.html @@ -115,7 +115,7 @@

    Conversion from 2D raster maps

    2D rasters are considered as slices in this case and merged into one 3D raster map (r.to.rast3). -

    3D region settings and 3D MASK

    +

    3D region settings and 3D mask

    GRASS GIS 3D raster map processing is always performed in the current 3D region settings (see g.region, -p3 flags), i.e. diff --git a/rpm/grass.spec b/rpm/grass.spec index a68453145bc..90c79bc939f 100644 --- a/rpm/grass.spec +++ b/rpm/grass.spec @@ -320,7 +320,7 @@ fi %{_docdir}/%{name}%{shortver} %files libs -%license AUTHORS COPYING GPL.TXT CHANGES +%license AUTHORS COPYING GPL.TXT %{_sysconfdir}/ld.so.conf.d/%{name}-%{_arch}.conf %{_libdir}/%{name}%{shortver}/lib/*.so %dir %{_libdir}/%{name}%{shortver}/driver diff --git a/scripts/d.correlate/d.correlate.py b/scripts/d.correlate/d.correlate.py index af681cce545..1068733a11b 100755 --- a/scripts/d.correlate/d.correlate.py +++ b/scripts/d.correlate/d.correlate.py @@ -73,7 +73,7 @@ def main(): gcore.run_command("r.stats", flags="cnA", input=(i, j), stdout=ofile) ofile.close() - ifile = open(tmpfile, "r") + ifile = open(tmpfile) first = True for line in ifile: f = line.rstrip("\r\n").split(" ") @@ -95,7 +95,7 @@ def main(): p = gcore.feed_command("d.graph", color=color) ofile = p.stdin - ifile = open(tmpfile, "r") + ifile = open(tmpfile) for line in ifile: f = line.rstrip("\r\n").split(" ") x = float(f[0]) diff --git a/scripts/d.frame/d.frame.py b/scripts/d.frame/d.frame.py index e9b44b21650..ff77316f0ec 100755 --- a/scripts/d.frame/d.frame.py +++ b/scripts/d.frame/d.frame.py @@ -91,7 +91,7 @@ def check_monitor(): def read_monitor_file(monitor, ftype="env"): mfile = check_monitor_file(monitor, ftype) try: - fd = open(mfile, "r") + fd = open(mfile) except OSError as e: fatal(_("Unable to get monitor info. %s"), e) diff --git a/scripts/d.polar/d.polar.py b/scripts/d.polar/d.polar.py index 4ef578d5676..d7e67486a0e 100755 --- a/scripts/d.polar/d.polar.py +++ b/scripts/d.polar/d.polar.py @@ -112,7 +112,7 @@ def plot_dgraph(): 50 * (1 + ring * math.sin(math.radians(i))), 50 * (1 + ring * math.cos(math.radians(i))), ) - for i in range(0, 361) + for i in range(361) ] # trend vector @@ -202,7 +202,6 @@ def plot_eps(psout): epsscale = 0.1 frameallowance = 1.1 halfframe = 3000 - center = (halfframe, halfframe) scale = halfframe / (outerradius * frameallowance) diagramlinewidth = halfframe / 400 @@ -211,11 +210,6 @@ def plot_eps(psout): diagramfontsize = halfframe / 20 halfframe_2 = halfframe * 2 - averagedirectioncolor = 1 # (blue) - diagramcolor = 4 # (red) - circlecolor = 2 # (green) - axescolor = 0 # (black) - northjustification = 2 eastjustification = 6 southjustification = 8 @@ -287,7 +281,6 @@ def plot_eps(psout): ) outf.write(s) - sublength = len(outercircle) - 2 (x, y) = outercircle[1] outf.write("%.2f %.2f moveto\n" % (x * scale + halfframe, y * scale + halfframe)) for x, y in outercircle[2:]: @@ -343,7 +336,6 @@ def plot_eps(psout): ) outf.write(s) - sublength = len(sine_cosine_replic) - 2 (x, y) = sine_cosine_replic[1] outf.write("%.2f %.2f moveto\n" % (x * scale + halfframe, y * scale + halfframe)) for x, y in sine_cosine_replic[2:]: @@ -369,7 +361,6 @@ def plot_eps(psout): s = t.substitute(DIAGRAMLINEWIDTH=diagramlinewidth) outf.write(s) - sublength = len(vector) - 2 (x, y) = vector[1] outf.write("%.2f %.2f moveto\n" % (x * scale + halfframe, y * scale + halfframe)) for x, y in vector[2:]: @@ -434,8 +425,8 @@ def main(): gcore.fatal( _( "EPS output file path <{}>, doesn't exists. " - "Set new output file path.".format(eps) - ) + "Set new output file path." + ).format(eps) ) else: eps = basename(eps, "eps") + ".eps" @@ -445,8 +436,8 @@ def main(): gcore.fatal( _( "option : <{}> exists. To overwrite, " - "use the --overwrite flag.".format(eps) - ) + "use the --overwrite flag." + ).format(eps) ) # check if we have xgraph (if no EPS output requested) @@ -521,7 +512,7 @@ def main(): outercircle = [] outercircle.append('"All Data incl. NULLs') scale = 1.0 * totalnumber / totalvalidnumber * maxradius - for i in range(0, 361): + for i in range(361): a = math.radians(i) x = math.cos(a) * scale y = math.sin(a) * scale diff --git a/scripts/db.univar/db.univar.py b/scripts/db.univar/db.univar.py index f941be42140..97dfbdb7dbe 100755 --- a/scripts/db.univar/db.univar.py +++ b/scripts/db.univar/db.univar.py @@ -77,7 +77,7 @@ def cleanup(): def sortfile(infile, outfile): - inf = open(infile, "r") + inf = open(infile) outf = open(outfile, "w") if gs.find_program("sort", "--help"): diff --git a/scripts/g.extension.all/g.extension.all.py b/scripts/g.extension.all/g.extension.all.py index 026589cca10..1b0a2a88108 100644 --- a/scripts/g.extension.all/g.extension.all.py +++ b/scripts/g.extension.all/g.extension.all.py @@ -64,7 +64,7 @@ def get_extensions(): return [] # read XML file - fo = open(fXML, "r") + fo = open(fXML) try: tree = ET.fromstring(fo.read()) except Exception as e: @@ -104,18 +104,18 @@ def download_modules_xml_file(url, response_format, *args, **kwargs): try: response = urlopen(url, *args, **kwargs) - if not response.code == 200: + if response.code != 200: index = HTTP_STATUS_CODES.index(response.code) desc = HTTP_STATUS_CODES[index].description gs.fatal( _( "Download file from <{url}>, " "return status code {code}, " - "{desc}".format( - url=url, - code=response.code, - desc=desc, - ), + "{desc}" + ).format( + url=url, + code=response.code, + desc=desc, ), ) if response_format not in response.getheader("Content-Type"): @@ -123,10 +123,10 @@ def download_modules_xml_file(url, response_format, *args, **kwargs): _( "Wrong file format downloaded. " "Check url <{url}>. Allowed file format is " - "{response_format}.".format( - url=url, - response_format=response_format, - ), + "{response_format}." + ).format( + url=url, + response_format=response_format, ), ) return response @@ -138,8 +138,8 @@ def download_modules_xml_file(url, response_format, *args, **kwargs): "The download of the modules.xml file " "from the server was not successful. " "File on the server <{url}> doesn't " - "exists.".format(url=url), - ), + "exists." + ).format(url=url), ) else: return download_modules_xml_file( @@ -148,11 +148,8 @@ def download_modules_xml_file(url, response_format, *args, **kwargs): ) except URLError: gs.fatal( - _( - "Download file from <{url}>, " - "failed. Check internet connection.".format( - url=url, - ), + _("Download file from <{url}>, failed. Check internet connection.").format( + url=url, ), ) @@ -199,9 +196,8 @@ def find_addon_name(addons): gs.warning( _( "The <{}> addon cannot be reinstalled. " - "Addon wasn't found among the official " - "addons.".format(addon) - ), + "Addon wasn't found among the official addons." + ).format(addon), ) return set(result) diff --git a/scripts/g.extension/g.extension.py b/scripts/g.extension/g.extension.py index 3b0c15c0bfc..194f498d49c 100644 --- a/scripts/g.extension/g.extension.py +++ b/scripts/g.extension/g.extension.py @@ -470,9 +470,10 @@ def replace_shebang_win(python_file): cur_dir = os.path.dirname(python_file) tmp_name = os.path.join(cur_dir, gs.tempname(12)) - with codecs.open(python_file, "r", encoding="utf8") as in_file, codecs.open( - tmp_name, "w", encoding="utf8" - ) as out_file: + with ( + codecs.open(python_file, "r", encoding="utf8") as in_file, + codecs.open(tmp_name, "w", encoding="utf8") as out_file, + ): for line in in_file: new_line = line.replace( "#!/usr/bin/env python\n", "#!/usr/bin/env python3\n" @@ -507,24 +508,23 @@ def get_version_branch(major_version): version_branch = f"grass{major_version}" if sys.platform == "win32": return version_branch - else: - branch = gs.Popen( - ["git", "ls-remote", "--heads", GIT_URL, f"refs/heads/{version_branch}"], - stdout=PIPE, - stderr=PIPE, - ) - branch, stderr = branch.communicate() - if stderr: - gs.fatal( - _( - "Failed to get branch from the Git repository <{repo_path}>.\n" - "{error}" - ).format( - repo_path=GIT_URL, - error=gs.decode(stderr), - ) + branch = gs.Popen( + ["git", "ls-remote", "--heads", GIT_URL, f"refs/heads/{version_branch}"], + stdout=PIPE, + stderr=PIPE, + ) + branch, stderr = branch.communicate() + if stderr: + gs.fatal( + _( + "Failed to get branch from the Git repository <{repo_path}>.\n" + "{error}" + ).format( + repo_path=GIT_URL, + error=gs.decode(stderr), ) - branch = gs.decode(branch) + ) + branch = gs.decode(branch) if version_branch not in branch: version_branch = "grass{}".format(int(major_version) - 1) return version_branch @@ -541,10 +541,8 @@ def get_default_branch(full_url): organization, repository = url_parts.path.split("/")[1:3] except URLError: gs.fatal( - _( - "Cannot retrieve organization and repository from URL: <{}>.".format( - full_url - ) + _("Cannot retrieve organization and repository from URL: <{}>.").format( + full_url ) ) # Construct API call and retrieve default branch @@ -583,10 +581,8 @@ def etree_fromurl(url): _( "Download file from <{url}>," " failed. File is not on the server or" - " check your internet connection.".format( - url=url, - ), - ), + " check your internet connection." + ).format(url=url), ) return ET.fromstring(file_.read()) @@ -2598,8 +2594,7 @@ def resolve_known_host_service(url, name, branch): ) gs.verbose(_("Will use the following URL for download: {0}").format(url)) return "remote_zip", url - else: - return None, None + return None, None def validate_url(url): @@ -2723,7 +2718,7 @@ def resolve_source_code(url=None, name=None, branch=None, fork=False): # Handle local URLs if os.path.isdir(url): return "dir", os.path.abspath(url) - elif os.path.exists(url): + if os.path.exists(url): if url.endswith(".zip"): return "zip", os.path.abspath(url) for suffix in extract_tar.supported_formats: @@ -2826,7 +2821,7 @@ def main(): xmlurl = resolve_xmlurl_prefix(original_url, source=source) list_available_extensions(xmlurl) return 0 - elif flags["a"]: + if flags["a"]: list_installed_extensions(toolboxes=flags["t"]) return 0 diff --git a/scripts/g.extension/testsuite/test_addons_modules.py b/scripts/g.extension/testsuite/test_addons_modules.py index c1cab5c954a..9b99e7ac2ae 100644 --- a/scripts/g.extension/testsuite/test_addons_modules.py +++ b/scripts/g.extension/testsuite/test_addons_modules.py @@ -15,7 +15,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test from grass.gunittest.gmodules import SimpleModule -from grass.gunittest.utils import silent_rmtree +from grass.gunittest.utils import silent_rmtree, xfail_windows from grass.script.utils import decode import os @@ -52,6 +52,7 @@ class TestModulesMetadata(TestCase): url = "file://" + os.path.abspath("data") + @xfail_windows def test_listing(self): """List individual extensions/modules/addons""" module = SimpleModule("g.extension", flags="l", url=self.url) @@ -90,6 +91,7 @@ def tearDown(self): """Remove created files""" silent_rmtree(self.install_prefix) + @xfail_windows def test_directory_install(self): """Test installing extension from directory""" self.assertModule( @@ -102,6 +104,7 @@ def test_directory_install(self): for file in self.files: self.assertFileExists(file) + @xfail_windows def test_targz_install(self): """Test installing extension from local .tar.gz""" self.assertModule( @@ -113,6 +116,7 @@ def test_targz_install(self): for file in self.files: self.assertFileExists(file) + @xfail_windows def test_remote_targz_without_dir_install(self): """Test installing extension from (remote) .tar.gz without main dir""" self.assertModule( @@ -125,6 +129,7 @@ def test_remote_targz_without_dir_install(self): for file in self.files: self.assertFileExists(file) + @xfail_windows def test_remote_zip_install(self): """Test installing extension from .zip specified by URL (local)""" self.assertModule( diff --git a/scripts/g.extension/testsuite/test_addons_toolboxes.py b/scripts/g.extension/testsuite/test_addons_toolboxes.py index 5cbc0454a41..17d7e4b5b74 100644 --- a/scripts/g.extension/testsuite/test_addons_toolboxes.py +++ b/scripts/g.extension/testsuite/test_addons_toolboxes.py @@ -15,9 +15,11 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows import os + FULL_TOOLBOXES_OUTPUT = """\ Hydrology (HY) * r.stream.basins @@ -39,6 +41,7 @@ class TestToolboxesMetadata(TestCase): url = "file://" + os.path.abspath("data") + @xfail_windows def test_listing(self): """List toolboxes and their content""" module = SimpleModule("g.extension", flags="lt", url=self.url) diff --git a/scripts/g.search.modules/g.search.modules.py b/scripts/g.search.modules/g.search.modules.py index 85247517898..5777b4bd033 100755 --- a/scripts/g.search.modules/g.search.modules.py +++ b/scripts/g.search.modules/g.search.modules.py @@ -66,6 +66,8 @@ import os import sys +from operator import itemgetter + from grass.script import core as grass from grass.exceptions import CalledModuleError @@ -182,8 +184,7 @@ def colored(pattern, attrs): if pattern: return text.replace(pattern, colored(pattern, attrs=attrs)) - else: - return colored(text, attrs=attrs) + return colored(text, attrs=attrs) def _search_module( @@ -199,7 +200,7 @@ def _search_module( WXGUIDIR = os.path.join(os.getenv("GISBASE"), "gui", "wxpython") filename = os.path.join(WXGUIDIR, "xml", "module_items.xml") - menudata_file = open(filename, "r") + menudata_file = open(filename) menudata = ET.parse(menudata_file) menudata_file.close() @@ -210,7 +211,7 @@ def _search_module( if os.getenv("GRASS_ADDON_BASE"): filename_addons = os.path.join(os.getenv("GRASS_ADDON_BASE"), "modules.xml") if os.path.isfile(filename_addons): - addon_menudata_file = open(filename_addons, "r") + addon_menudata_file = open(filename_addons) addon_menudata = ET.parse(addon_menudata_file) addon_menudata_file.close() addon_items = addon_menudata.findall("task") @@ -219,7 +220,7 @@ def _search_module( # add system-wide installed addons to modules list filename_addons_s = os.path.join(os.getenv("GISBASE"), "modules.xml") if os.path.isfile(filename_addons_s): - addon_menudata_file_s = open(filename_addons_s, "r") + addon_menudata_file_s = open(filename_addons_s) addon_menudata_s = ET.parse(addon_menudata_file_s) addon_menudata_file_s.close() addon_items_s = addon_menudata_s.findall("task") @@ -283,7 +284,7 @@ def _search_module( } ) - return sorted(found_modules, key=lambda k: k["name"]) + return sorted(found_modules, key=itemgetter("name")) def _basic_search(pattern, name, description, module_keywords) -> bool: @@ -311,10 +312,7 @@ def _exact_search(keyword, module_keywords): :param module_keywords: comma separated list of keywords """ module_keywords = module_keywords.split(",") - for current in module_keywords: - if keyword == current: - return True - return False + return keyword in module_keywords def _manpage_search(pattern, name): diff --git a/scripts/g.search.modules/testsuite/test_g_search_modules.py b/scripts/g.search.modules/testsuite/test_g_search_modules.py index d280ffc1441..75537eb8d78 100644 --- a/scripts/g.search.modules/testsuite/test_g_search_modules.py +++ b/scripts/g.search.modules/testsuite/test_g_search_modules.py @@ -15,6 +15,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows from grass.script.utils import decode import unittest @@ -65,6 +66,7 @@ def test_colored_terminal(self): stdout = decode(module.outputs.stdout).split() self.assertEqual(stdout[0], termcolor.colored("r.basins.fill", attrs=["bold"])) + @xfail_windows def test_manual_pages(self): module = SimpleModule("g.search.modules", keyword="kapri", flags="gm") self.assertModule(module) diff --git a/scripts/i.image.mosaic/i.image.mosaic.py b/scripts/i.image.mosaic/i.image.mosaic.py index df194c49c8f..fc342a3ed96 100755 --- a/scripts/i.image.mosaic/i.image.mosaic.py +++ b/scripts/i.image.mosaic/i.image.mosaic.py @@ -56,9 +56,8 @@ def get_limit(map): def make_expression(i, count): if i > count: return "null()" - else: - e = make_expression(i + 1, count) - return "if(isnull($image%d),%s,$image%d+$offset%d)" % (i, e, i, i) + e = make_expression(i + 1, count) + return "if(isnull($image%d),%s,$image%d+$offset%d)" % (i, e, i, i) def main(): diff --git a/scripts/i.oif/i.oif.py b/scripts/i.oif/i.oif.py index cfee7890120..0dabbe7cb38 100755 --- a/scripts/i.oif/i.oif.py +++ b/scripts/i.oif/i.oif.py @@ -47,7 +47,7 @@ def oifcalc(sdev, corr, k1, k2, k3): - grass.debug(_("Calculating OIF for combination: %s, %s, %s" % (k1, k2, k3)), 1) + grass.debug(_("Calculating OIF for combination: %s, %s, %s") % (k1, k2, k3), 1) # calculate SUM of Stddeviations: ssdev = [sdev[k1], sdev[k2], sdev[k3]] numer = sum(ssdev) @@ -63,7 +63,7 @@ def oifcalc(sdev, corr, k1, k2, k3): def perms(bands): n = len(bands) - for i in range(0, n - 2): + for i in range(n - 2): for j in range(i + 1, n - 1): for k in range(j + 1, n): yield (bands[i], bands[j], bands[k]) @@ -122,9 +122,7 @@ def main(): grass.message(_("Calculating Correlation Matrix...")) correlation = {} - s = grass.read_command( - "r.covar", flags="r", map=[band for band in bands], quiet=True - ) + s = grass.read_command("r.covar", flags="r", map=list(bands), quiet=True) # We need to skip the first line, since r.covar prints the number of values lines = s.splitlines() diff --git a/scripts/i.pansharpen/i.pansharpen.py b/scripts/i.pansharpen/i.pansharpen.py index f344c5ac7fd..bb271c07deb 100755 --- a/scripts/i.pansharpen/i.pansharpen.py +++ b/scripts/i.pansharpen/i.pansharpen.py @@ -402,7 +402,7 @@ def main(): gs.run_command("g.region", res=panres, align=pan) # Select sharpening method - gs.message(_("Performing pan sharpening with hi res pan image: %f" % panres)) + gs.message(_("Performing pan sharpening with hi res pan image: %f") % panres) if sharpen == "brovey": brovey(pan, ms1, ms2, ms3, out, pid, sproc) elif sharpen == "ihs": @@ -437,8 +437,8 @@ def main(): for ch in ["red", "green", "blue"]: gs.verbose(_("%s_%s") % (out, ch)) - gs.verbose(_("To visualize output, run: g.region -p raster=%s_red" % out)) - gs.verbose(_("d.rgb r=%s_red g=%s_green b=%s_blue" % (out, out, out))) + gs.verbose(_("To visualize output, run: g.region -p raster=%s_red") % out) + gs.verbose(_("d.rgb r=%s_red g=%s_green b=%s_blue") % (out, out, out)) gs.verbose( _("If desired, combine channels into a single RGB map with 'r.composite'.") ) @@ -749,7 +749,7 @@ def matchhist(original, target, matched): 0 # cumulative total of cells for sum of current and all lower grey values ) - for n in range(0, 256): + for n in range(256): if str(n) in stats_dict: num_cells = stats_dict[str(n)] else: diff --git a/scripts/i.spectral/i.spectral.py b/scripts/i.spectral/i.spectral.py index d40c1076169..171eac7359c 100755 --- a/scripts/i.spectral/i.spectral.py +++ b/scripts/i.spectral/i.spectral.py @@ -197,8 +197,8 @@ def draw_linegraph(what): gcore.fatal( _( "Supported monitor isn't running. Please launch one of the" - " monitors {}.".format(", ".join(supported_monitors)) - ) + " monitors {}." + ).format(", ".join(supported_monitors)) ) selected_monitor = gcore.read_command("d.mon", flags="p", quiet=True).replace( "\n", "" @@ -207,17 +207,15 @@ def draw_linegraph(what): gcore.fatal( _( "Supported monitor isn't selected. Please select one of the" - " monitors {}.".format(", ".join(supported_monitors)) - ) + " monitors {}." + ).format(", ".join(supported_monitors)) ) with open(gcore.parse_command("d.mon", flags="g", quiet=True)["env"]) as f: for line in f: if "GRASS_RENDER_FILE=" in line: gcore.info( - _( - "{} monitor is used, output file {}".format( - selected_monitor.capitalize(), line.split("=")[-1] - ) + _("{} monitor is used, output file {}").format( + selected_monitor.capitalize(), line.split("=")[-1] ) ) break diff --git a/scripts/i.tasscap/i.tasscap.py b/scripts/i.tasscap/i.tasscap.py index 4c68c234c73..dc767fd3f19 100755 --- a/scripts/i.tasscap/i.tasscap.py +++ b/scripts/i.tasscap/i.tasscap.py @@ -352,7 +352,7 @@ def main(): # assign "Data Description" field in all four component maps num_comp = len(parms[satellites.index(satellite)]) - for i in range(0, num_comp): + for i in range(num_comp): comp = names[i] gs.run_command( "r.support", diff --git a/scripts/r.in.wms/wms_base.py b/scripts/r.in.wms/wms_base.py index a14e15dc786..2d959289b23 100644 --- a/scripts/r.in.wms/wms_base.py +++ b/scripts/r.in.wms/wms_base.py @@ -78,10 +78,8 @@ def _initializeParameters(self, options, flags): self.params["password"] == "" and self.params["username"] ): gs.fatal( - _( - "Please insert both %s and %s parameters or none of them." - % ("password", "username") - ) + _("Please insert both %s and %s parameters or none of them.") + % ("password", "username") ) self.params["bgcolor"] = options["bgcolor"].strip() @@ -202,8 +200,8 @@ def _checkIgnoeredParams(self, options, flags, driver_props): _( "These parameter are ignored: %s\n\ %s driver does not support the parameters." - % (",".join(not_relevant_params), options["driver"]) ) + % (",".join(not_relevant_params), options["driver"]) ) not_relevant_flags = [] @@ -216,8 +214,8 @@ def _checkIgnoeredParams(self, options, flags, driver_props): _( "These flags are ignored: %s\n\ %s driver does not support the flags." - % (",".join(not_relevant_flags), options["driver"]) ) + % (",".join(not_relevant_flags), options["driver"]) ) def GetMap(self, options, flags): @@ -308,7 +306,7 @@ def GetCapabilities(self, options): Path(capfile_output).write_text(cap) return except OSError as error: - gs.fatal(_("Unable to open file '%s'.\n%s\n" % (capfile_output, error))) + gs.fatal(_("Unable to open file '%s'.\n%s\n") % (capfile_output, error)) # print to output print(cap) @@ -784,8 +782,7 @@ def GetSRSParamVal(srs): if srs in {84, 83, 27}: return "OGC:CRS{}".format(srs) - else: - return "EPSG:{}".format(srs) + return "EPSG:{}".format(srs) def GetEpsg(srs): diff --git a/scripts/r.in.wms/wms_cap_parsers.py b/scripts/r.in.wms/wms_cap_parsers.py index f9b0f7095fb..56b1d0ce48c 100644 --- a/scripts/r.in.wms/wms_cap_parsers.py +++ b/scripts/r.in.wms/wms_cap_parsers.py @@ -45,7 +45,7 @@ def __init__(self, cap_file): raise ParseError(_("Unable to parse XML file")) except OSError as error: raise ParseError( - _("Unable to open XML file '%s'.\n%s\n" % (cap_file, error)) + _("Unable to open XML file '%s'.\n%s\n") % (cap_file, error) ) else: try: @@ -131,7 +131,7 @@ def _checkFormats(self, capability): """!Check if format element is defined.""" request = self._find(capability, "Request") get_map = self._find(request, "GetMap") - formats = self._findall(get_map, "Format") + self._findall(get_map, "Format") def _checkLayerTree(self, parent_layer, first=True): """!Recursively check layer tree and manage inheritance in the tree""" diff --git a/scripts/r.in.wms/wms_drv.py b/scripts/r.in.wms/wms_drv.py index 1e7a90e9938..531112a1a6c 100644 --- a/scripts/r.in.wms/wms_drv.py +++ b/scripts/r.in.wms/wms_drv.py @@ -286,7 +286,7 @@ def _pct2rgb(self, src_filename, dst_filename): # open source file src_ds = gdal.Open(src_filename) if src_ds is None: - gs.fatal(_("Unable to open %s " % src_filename)) + gs.fatal(_("Unable to open %s ") % src_filename) src_band = src_ds.GetRasterBand(band_number) @@ -587,7 +587,7 @@ def _getQueryBbox(self, bbox, proj, srs_param, version): # CRS:84 and CRS:83 are exception (CRS:83 and CRS:27 need to be tested) if srs_param in {84, 83} or version != "1.3.0": return bbox - elif Srs(GetSRSParamVal(srs_param)).axisorder == "yx": + if Srs(GetSRSParamVal(srs_param)).axisorder == "yx": return self._flipBbox(bbox) return bbox @@ -736,9 +736,7 @@ def _findTileMats(self, tile_mats, region, bbox): best_diff = best_scale_den - scale_den mat_diff = mat_scale_den - scale_den - if (best_diff < mat_diff and mat_diff < 0) or ( - best_diff > mat_diff and best_diff > 0 - ): + if (best_diff < mat_diff < 0) or (best_diff > mat_diff and best_diff > 0): best_t_mat = t_mat best_scale_den = mat_scale_den @@ -1020,9 +1018,7 @@ def _parseTilePattern(self, group_t_patts, bbox, region): best_diff = best_res - res[comp_res] tile_diff = t_res[comp_res] - res[comp_res] - if (best_diff < tile_diff and tile_diff < 0) or ( - best_diff > tile_diff and best_diff > 0 - ): + if (best_diff < tile_diff < 0) or (best_diff > tile_diff and best_diff > 0): best_res = t_res[comp_res] best_patt = pattern diff --git a/scripts/r.in.wms/wms_gdal_drv.py b/scripts/r.in.wms/wms_gdal_drv.py index 6d30f5817f3..830be2b593e 100644 --- a/scripts/r.in.wms/wms_gdal_drv.py +++ b/scripts/r.in.wms/wms_gdal_drv.py @@ -60,7 +60,6 @@ def _createXML(self): gdal_wms = ET.Element("GDAL_WMS") service = ET.SubElement(gdal_wms, "Service") - name = ET.Element("name") service.set("name", "WMS") version = ET.SubElement(service, "Version") @@ -156,7 +155,7 @@ def _download(self): xml_file = self._createXML() # print xml file content for debug level 1 - file = open(xml_file, "r") + file = open(xml_file) gs.debug("WMS request XML:\n%s" % file.read(), 1) file.close() @@ -173,7 +172,7 @@ def _download(self): driver = gdal.GetDriverByName(self.gdal_drv_format) if driver is None: - gs.fatal(_("Unable to find %s driver" % format)) + gs.fatal(_("Unable to find %s driver") % self.gdal_drv_format) metadata = driver.GetMetadata() if ( diff --git a/scripts/r.out.xyz/r.out.xyz.html b/scripts/r.out.xyz/r.out.xyz.html index c9b2b6510be..e603c592e32 100644 --- a/scripts/r.out.xyz/r.out.xyz.html +++ b/scripts/r.out.xyz/r.out.xyz.html @@ -6,7 +6,7 @@

    DESCRIPTION

    NOTES

    This module will by default not export x,y coordinates for raster cells -containing a NULL value. This includes cells masked by a raster MASK. +containing a NULL value. This includes cells masked by a raster mask. Using the flag -i also these raster cells will be included in the exported data.

    diff --git a/scripts/r.pack/r.pack.py b/scripts/r.pack/r.pack.py index cd7d6c39282..5029f93c6d2 100644 --- a/scripts/r.pack/r.pack.py +++ b/scripts/r.pack/r.pack.py @@ -37,6 +37,8 @@ import atexit import tarfile +from pathlib import Path + from grass.script.utils import try_rmdir, try_remove from grass.script import core as grass @@ -80,7 +82,7 @@ def main(): grass.message(_("Packing <%s> to <%s>...") % (gfile["fullname"], outfile)) basedir = os.path.sep.join(os.path.normpath(gfile["file"]).split(os.path.sep)[:-2]) - olddir = os.getcwd() + olddir = Path.cwd() # copy elements info = grass.parse_command("r.info", flags="e", map=infile) @@ -93,7 +95,7 @@ def main(): if map_file["file"]: vrt = os.path.join(map_file["file"], "vrt") if os.path.exists(vrt): - with open(vrt, "r") as f: + with open(vrt) as f: for r in f: map, mapset = r.split("@") map_basedir = os.path.sep.join( @@ -180,7 +182,7 @@ def main(): os.chdir(olddir) - grass.verbose(_("Raster map saved to '%s'" % outfile)) + grass.verbose(_("Raster map saved to '%s'") % outfile) if __name__ == "__main__": diff --git a/scripts/r.semantic.label/r.semantic.label.py b/scripts/r.semantic.label/r.semantic.label.py index 53239772117..f3c26320ae3 100644 --- a/scripts/r.semantic.label/r.semantic.label.py +++ b/scripts/r.semantic.label/r.semantic.label.py @@ -62,7 +62,7 @@ def print_map_semantic_label(name, label_reader): label_reader.print_info(semantic_label=semantic_label) else: gs.info(_("No semantic label assigned to <{}>").format(name)) - except OpenError as e: + except OpenError: gs.error(_("Map <{}> not found").format(name)) @@ -94,7 +94,7 @@ def manage_map_semantic_label(name, semantic_label): except GrassError as e: gs.error(_("Unable to assign/dissociate semantic label. {}").format(e)) return 1 - except OpenError as e: + except OpenError: gs.error(_("Map <{}> not found in current mapset").format(name)) return 1 diff --git a/scripts/r.semantic.label/testsuite/test_r_semantic_label.py b/scripts/r.semantic.label/testsuite/test_r_semantic_label.py index b7456e22633..990954dbb5f 100644 --- a/scripts/r.semantic.label/testsuite/test_r_semantic_label.py +++ b/scripts/r.semantic.label/testsuite/test_r_semantic_label.py @@ -27,7 +27,7 @@ def read_semantic_label(self): return rast.info.semantic_label def test_semantic_label_assign_not_current_mapset(self): - if not self.mapset == "PERMANENT": + if self.mapset != "PERMANENT": self.mapset.name = "PERMANENT" a_map = self.mapset.glist(type="raster")[0] module = SimpleModule( diff --git a/scripts/r.tileset/r.tileset.py b/scripts/r.tileset/r.tileset.py index f5e7ab17b13..c3fba2c173e 100644 --- a/scripts/r.tileset/r.tileset.py +++ b/scripts/r.tileset/r.tileset.py @@ -246,16 +246,16 @@ def main(): _( "It is not possible to set 'maxcols=%s' and " "'overlap=%s'. Please set maxcols>overlap" - % (options["maxcols"], options["overlap"]) ) + % (options["maxcols"], options["overlap"]) ) elif max_rows == 0: gcore.fatal( _( "It is not possible to set 'maxrows=%s' and " "'overlap=%s'. Please set maxrows>overlap" - % (options["maxrows"], options["overlap"]) ) + % (options["maxrows"], options["overlap"]) ) # destination projection if not options["destproj"]: @@ -397,7 +397,7 @@ def main(): if errors_dest > 0: gcore.warning( - _("During computation %i tiles could not be created" % errors_dest) + _("During computation %i tiles could not be created") % errors_dest ) while xi < ximax: diff --git a/scripts/r.tileset/testsuite/test_r_tileset.py b/scripts/r.tileset/testsuite/test_r_tileset.py index 7f1c62ed1f5..cba9908d900 100644 --- a/scripts/r.tileset/testsuite/test_r_tileset.py +++ b/scripts/r.tileset/testsuite/test_r_tileset.py @@ -7,6 +7,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows from grass.script.utils import decode @@ -36,6 +37,7 @@ def tearDownClass(cls): """!Remove the temporary region""" cls.del_temp_region() + @xfail_windows def test_tiling(self): """Produce tiling test""" module = SimpleModule( diff --git a/scripts/r.unpack/r.unpack.py b/scripts/r.unpack/r.unpack.py index 053ac96988b..575d465ebb5 100644 --- a/scripts/r.unpack/r.unpack.py +++ b/scripts/r.unpack/r.unpack.py @@ -63,7 +63,7 @@ def main(): grass.debug("tmp_dir = {tmpdir}".format(tmpdir=tmp_dir)) if not os.path.exists(infile): - grass.fatal(_("File {name} not found.".format(name=infile))) + grass.fatal(_("File {name} not found.").format(name=infile)) gisenv = grass.gisenv() mset_dir = os.path.join( @@ -87,7 +87,7 @@ def main(): f = tar.extractfile("{}/{}".format(data_names[0], fname)) sys.stdout.write(f.read().decode()) except KeyError: - grass.fatal(_("Pack file unreadable: file '{}' missing".format(fname))) + grass.fatal(_("Pack file unreadable: file '{}' missing").format(fname)) tar.close() return 0 @@ -100,13 +100,11 @@ def main(): gfile = grass.find_file(name=map_name, element="cell", mapset=".") if gfile["file"]: if os.environ.get("GRASS_OVERWRITE", "0") != "1": - grass.fatal(_("Raster map <{name}> already exists".format(name=map_name))) + grass.fatal(_("Raster map <{name}> already exists").format(name=map_name)) else: grass.warning( - _( - "Raster map <{name}> already exists and will be overwritten".format( - name=map_name - ) + _("Raster map <{name}> already exists and will be overwritten").format( + name=map_name ) ) @@ -132,9 +130,10 @@ def main(): grass.fatal( _( "This GRASS GIS pack file contains vector data. Use " - "v.unpack to unpack <{name}>".format(name=map_name) - ) + "v.unpack to unpack <{name}>" + ).format(name=map_name) ) + else: grass.fatal(_("Pack file unreadable")) @@ -246,7 +245,7 @@ def main(): files = "\n".join(maps) Path(vrt_file).write_text(files) - grass.message(_("Raster map <{name}> unpacked".format(name=map_name))) + grass.message(_("Raster map <{name}> unpacked").format(name=map_name)) if __name__ == "__main__": diff --git a/scripts/v.centroids/testsuite/test_v_centroids.py b/scripts/v.centroids/testsuite/test_v_centroids.py index 4b0654748a5..a7f56464ef6 100644 --- a/scripts/v.centroids/testsuite/test_v_centroids.py +++ b/scripts/v.centroids/testsuite/test_v_centroids.py @@ -12,37 +12,47 @@ class TestVCentroids(TestCase): """Test v.centroids script""" - mapName = "busroute11" - outRouteMap = "busroute11_boundary" - fromType = "line" - toType = "boundary" - outAreaMap = "busroute11_area" + region_line = "region_line" + region_boundary = "region_boundary" + region_area = "region_area" + output = "output" @classmethod def setUpClass(cls): """Create an area from a closed line""" + cls.runModule("v.in.region", output=cls.region_line, type="line") + cls.runModule("v.in.region", output=cls.region_area, type="area") cls.runModule( "v.type", - input=cls.mapName, - output=cls.outRouteMap, - from_type=cls.fromType, - to_type=cls.toType, + input=cls.region_line, + output=cls.region_boundary, + from_type="line", + to_type="boundary", ) @classmethod def tearDownClass(cls): """Remove the generated maps""" cls.runModule( - "g.remove", flags="f", type="vector", name=(cls.outRouteMap, cls.outAreaMap) + "g.remove", + flags="f", + type="vector", + name=(cls.region_line, cls.region_area, cls.region_boundary), ) + def tearDown(self): + """Remove the generated maps""" + self.runModule("g.remove", flags="f", type="vector", name=self.output) + def test_area(self): """Adds missing centroids to closed boundaries test""" module = SimpleModule( - "v.centroids", input=self.outRouteMap, output=self.outAreaMap + "v.centroids", input=self.region_boundary, output=self.output ) self.assertModule(module) - self.assertVectorExists(self.outAreaMap) + self.assertVectorInfoEqualsVectorInfo( + self.output, self.region_area, precision=1e-6 + ) if __name__ == "__main__": diff --git a/scripts/v.centroids/v.centroids.html b/scripts/v.centroids/v.centroids.html index 2bebed24e97..b814b702bab 100644 --- a/scripts/v.centroids/v.centroids.html +++ b/scripts/v.centroids/v.centroids.html @@ -1,11 +1,13 @@

    DESCRIPTION

    -GRASS defines vector areas as composite entities consisting of a set of +In GRASS GIS, a centroid is a point within a closed ring of boundaries. +A vector area is defined as composite entity consisting of a set of closed boundaries and a centroid. The attribute information associated -with that area is linked to the centroid. The v.centroids module -adds centroids to closed boundaries in the input file and assigns a -category number to them. The starting value as well as the increment size -may be set using optional parameters. +with this area is linked to the centroid. + +The v.centroids module adds centroids to closed boundaries in +the input file and assigns a category number to them. The starting +value as well as the increment size may be set using optional parameters.

    Multiple attributes may be linked to a single vector entity through numbered fields referred to as layers. Refer to v.category for more details, as v.centroids is simply a frontend to that diff --git a/scripts/v.import/v.import.py b/scripts/v.import/v.import.py index 42e5952c76f..4f579c4bf45 100755 --- a/scripts/v.import/v.import.py +++ b/scripts/v.import/v.import.py @@ -257,8 +257,6 @@ def main(): f.write("GUI: text\n") f.close() - tgtsrs = gs.read_command("g.proj", flags="j", quiet=True) - # create temp location from input without import gs.verbose(_("Creating temporary project for <%s>...") % OGRdatasource) try: diff --git a/scripts/v.pack/v.pack.py b/scripts/v.pack/v.pack.py index cd8d96b86cd..4468c888bcb 100755 --- a/scripts/v.pack/v.pack.py +++ b/scripts/v.pack/v.pack.py @@ -38,6 +38,8 @@ import tarfile import atexit +from pathlib import Path + from grass.script.utils import try_rmdir, try_remove from grass.script import core as grass from grass.script import vector @@ -128,7 +130,7 @@ def main(): tar.add(path, "PROJ_" + support) tar.close() - grass.message(_("Pack file <%s> created") % os.path.join(os.getcwd(), outfile)) + grass.message(_("Pack file <%s> created") % Path(outfile).resolve()) if __name__ == "__main__": diff --git a/scripts/v.rast.stats/testsuite/test_v_rast_stats.py b/scripts/v.rast.stats/testsuite/test_v_rast_stats.py index ca3111d14d8..56acbce5964 100644 --- a/scripts/v.rast.stats/testsuite/test_v_rast_stats.py +++ b/scripts/v.rast.stats/testsuite/test_v_rast_stats.py @@ -5,6 +5,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows from grass.pygrass.vector import VectorTopo from grass.pygrass.vector.geometry import Line from grass.pygrass.vector.geometry import Boundary @@ -71,6 +72,7 @@ def setUp(self): vt.table.conn.commit() vt.close() + @xfail_windows def test_1(self): # Output of v.rast.stats univar_string = """cat|value|label|a_minimum|a_maximum|a_sum @@ -91,6 +93,7 @@ def test_1(self): self.runModule(v_db_select) self.assertLooksLike(univar_string, str(v_db_select.outputs.stdout)) + @xfail_windows def test_line_d(self): output_str = """cat|name|a_median|a_number|a_range 1|first|192|3|1 @@ -109,6 +112,7 @@ def test_line_d(self): self.runModule(v_db_select) self.assertLooksLike(output_str, str(v_db_select.outputs.stdout)) + @xfail_windows def test_line(self): output_str = """cat|name|a_median|a_number|a_range 1|first|192|5|2 @@ -128,6 +132,7 @@ def test_line(self): self.runModule(v_db_select) self.assertLooksLike(output_str, str(v_db_select.outputs.stdout)) + @xfail_windows def test_zone_all(self): # Output of v.rast.stats univar_string = """cat|value|label|a_number|a_null_cells|a_minimum|a_maximum|a_range|a_average|a_stddev|a_variance|a_coeff_var|a_sum|a_first_quartile|a_median|a_third_quartile|a_percentile_90 @@ -143,6 +148,7 @@ def test_zone_all(self): self.runModule(v_db_select) self.assertLooksLike(univar_string, str(v_db_select.outputs.stdout)) + @xfail_windows def test_small_area_with_centroid(self): # Output of v.rast.stats univar_string = """cat|name|a_number|a_null_cells|a_minimum|a_maximum|a_range|a_average|a_stddev|a_variance|a_coeff_var|a_sum|a_first_quartile|a_median|a_third_quartile|a_percentile_90 diff --git a/scripts/v.rast.stats/v.rast.stats.py b/scripts/v.rast.stats/v.rast.stats.py index 1e1451f6b84..803fc8691ad 100644 --- a/scripts/v.rast.stats/v.rast.stats.py +++ b/scripts/v.rast.stats/v.rast.stats.py @@ -143,10 +143,8 @@ def main(): gs.fatal( _( "Number of raster maps ({0}) different from \ - number of column prefixes ({1})".format( - len(rasters), len(colprefixes) - ) - ) + number of column prefixes ({1})" + ).format(len(rasters), len(colprefixes)) ) vector = vs[0] @@ -340,10 +338,8 @@ def get_nr_of_categories( gs.warning( _( "Not all vector categories converted to raster. \ - Converted {0} of {1}.".format( - number, vect_cats_n - ) - ) + Converted {0} of {1}." + ).format(number, vect_cats_n) ) return number diff --git a/scripts/v.report/v.report.py b/scripts/v.report/v.report.py index 8da23bbaf91..cec84582155 100755 --- a/scripts/v.report/v.report.py +++ b/scripts/v.report/v.report.py @@ -55,6 +55,8 @@ import sys import os +from operator import itemgetter + import grass.script as gs from grass.script.utils import separator, decode @@ -114,7 +116,7 @@ def main(): cols = decode(line).rstrip("\r\n").split("|") if catcol == -1: ncols = len(cols) - for i in range(0, ncols): + for i in range(ncols): if cols[i] == f["key"]: catcol = i break @@ -134,7 +136,7 @@ def main(): if p.returncode != 0: sys.exit(1) - records1.sort(key=lambda r: r[catcol]) + records1.sort(key=itemgetter(catcol)) if len(records1) == 0: try: @@ -216,9 +218,6 @@ def main(): if not flags["c"]: sys.stdout.write(fs.join(colnames + extracolnames) + "\n") - # make and print the table: - numcols = len(colnames) + len(extracolnames) - # calculate percents if requested if units == "percent" and option != "coor": # calculate total value diff --git a/scripts/v.to.lines/v.to.lines.py b/scripts/v.to.lines/v.to.lines.py index bfcb2e45bc2..0630ad86401 100644 --- a/scripts/v.to.lines/v.to.lines.py +++ b/scripts/v.to.lines/v.to.lines.py @@ -189,7 +189,7 @@ def main(): gs.fatal(_("Error removing table from layer 1")) # TODO: when this except is happaning, it seems that never, so it seems wrong except Exception: - gs.warning(_("No table for layer %d" % 1)) + gs.warning(_("No table for layer %d") % 1) try: gs.run_command( "v.category", diff --git a/scripts/v.unpack/v.unpack.py b/scripts/v.unpack/v.unpack.py index af430f98829..ea75d443b57 100644 --- a/scripts/v.unpack/v.unpack.py +++ b/scripts/v.unpack/v.unpack.py @@ -87,7 +87,7 @@ def main(): f = tar.extractfile(fname) sys.stdout.write(f.read().decode()) except KeyError: - grass.fatal(_("Pack file unreadable: file '{}' missing".format(fname))) + grass.fatal(_("Pack file unreadable: file '{}' missing").format(fname)) tar.close() return 0 @@ -139,8 +139,9 @@ def main(): grass.fatal( _( "This GRASS GIS pack file contains raster data. Use " - "r.unpack to unpack <%s>" % map_name + "r.unpack to unpack <%s>" ) + % map_name ) else: grass.fatal(_("Pack file unreadable")) @@ -215,13 +216,9 @@ def main(): # the db connection in the output mapset dbconn = grassdb.db_connection(force=True) todb = dbconn["database"] - # return all tables - list_fromtable = grass.read_command( - "db.tables", driver="sqlite", database=fromdb - ).splitlines() # return the list of old connection for extract layer number and key - dbln = open(os.path.join(new_dir, "dbln"), "r") + dbln = open(os.path.join(new_dir, "dbln")) dbnlist = dbln.readlines() dbln.close() # check if dbf or sqlite directory exists diff --git a/scripts/v.what.strds/v.what.strds.py b/scripts/v.what.strds/v.what.strds.py index 2bd6cd72131..8be00f3536d 100644 --- a/scripts/v.what.strds/v.what.strds.py +++ b/scripts/v.what.strds/v.what.strds.py @@ -169,13 +169,13 @@ def main(): "datasets must be equal\n<%(a)s> of type " "%(type_a)s do not match <%(b)s> of type " "%(type_b)s" - % { - "a": first_strds.get_id(), - "type_a": first_strds.get_temporal_type(), - "b": dataset.get_id(), - "type_b": dataset.get_temporal_type(), - } ) + % { + "a": first_strds.get_id(), + "type_a": first_strds.get_temporal_type(), + "b": dataset.get_id(), + "type_b": dataset.get_temporal_type(), + } ) mapmatrizes = tgis.sample_stds_by_stds_topology( @@ -225,9 +225,9 @@ def main(): pymap = Vector(output) try: pymap.open("r") - except: + except Exception: dbif.close() - gs.fatal(_("Unable to create vector map <%s>" % output)) + gs.fatal(_("Unable to create vector map <%s>") % output) if len(pymap.dblinks) == 0: try: @@ -235,7 +235,7 @@ def main(): gs.run_command("v.db.addtable", map=output) except CalledModuleError: dbif.close() - gs.fatal(_("Unable to add table <%s> to vector map <%s>" % output)) + gs.fatal(_("Unable to add table <%s> to vector map <%s>") % output) if pymap.is_open(): pymap.close() diff --git a/scripts/v.what.vect/testsuite/test_v_what_vect.py b/scripts/v.what.vect/testsuite/test_v_what_vect.py index 09ade33668f..2385a71c400 100644 --- a/scripts/v.what.vect/testsuite/test_v_what_vect.py +++ b/scripts/v.what.vect/testsuite/test_v_what_vect.py @@ -9,7 +9,6 @@ from grass.gunittest.gmodules import SimpleModule from grass.script.core import run_command -from grass.script.utils import decode class TestVWhatVect(TestCase): @@ -29,20 +28,20 @@ def tearDownClass(cls): def test_what_vect(self): """Uploads vector values""" - run_command("v.db.addcolumn", map=self.mapName, columns="urb_name varchar(25)") + run_command("v.db.addcolumn", map=self.mapName, columns="geology_cat integer") module = SimpleModule( "v.what.vect", map=self.mapName, - query_map="urbanarea", - column="urb_name", - query_column="NAME", + query_map="geology", + column="geology_cat", + query_column="cat", ) self.assertModule(module) - - m = SimpleModule("v.db.select", map=self.mapName) - self.assertModule(m) - self.assertRegex(decode(m.outputs.stdout), "urb_name") + minmax = "min=11\nmax=1810" + self.assertVectorFitsUnivar( + map=self.mapName, column="geology_cat", reference=minmax + ) if __name__ == "__main__": diff --git a/temporal/t.info/t.info.py b/temporal/t.info/t.info.py index 2f0b0d528ec..575446030a1 100755 --- a/temporal/t.info/t.info.py +++ b/temporal/t.info/t.info.py @@ -91,7 +91,7 @@ def main(): " +----------------------------------------------------------------------------+" # noqa: E501 ) return - elif system and not history: + if system and not history: print("dbmi_python_interface='" + str(dbif.get_dbmi().__name__) + "'") print("dbmi_string='" + str(tgis.get_tgis_database_string()) + "'") print("sql_template_path='" + str(tgis.get_sql_template_path()) + "'") diff --git a/temporal/t.rast.accdetect/t.rast.accdetect.py b/temporal/t.rast.accdetect/t.rast.accdetect.py index 887616f7a1c..1588b44d4b9 100644 --- a/temporal/t.rast.accdetect/t.rast.accdetect.py +++ b/temporal/t.rast.accdetect/t.rast.accdetect.py @@ -341,7 +341,7 @@ def main(): if len(input_maps) == 0: continue - gs.message(_("Processing cycle %s - %s" % (str(start), str(end)))) + gs.message(_("Processing cycle %s - %s") % (str(start), str(end))) count = compute_occurrence( occurrence_maps, diff --git a/temporal/t.rast.accumulate/t.rast.accumulate.py b/temporal/t.rast.accumulate/t.rast.accumulate.py index 3ad82fe9ed3..6fe067e02bc 100644 --- a/temporal/t.rast.accumulate/t.rast.accumulate.py +++ b/temporal/t.rast.accumulate/t.rast.accumulate.py @@ -323,7 +323,7 @@ def main(): where = "start_time >= '%s' AND start_time < '%s'" % (str(start), str(end)) input_maps = input_strds.get_registered_maps_as_objects(where=where, dbif=dbif) - gs.message(_("Processing cycle %s - %s" % (str(start), str(end)))) + gs.message(_("Processing cycle %s - %s") % (str(start), str(end))) if len(input_maps) == 0: continue @@ -483,7 +483,6 @@ def main(): if method: accmod.inputs["method"].value = method - print(accmod) accmod.run() if accmod.returncode != 0: diff --git a/temporal/t.rast.export/t.rast.export.py b/temporal/t.rast.export/t.rast.export.py index 675040bf5aa..fdf19541ee4 100755 --- a/temporal/t.rast.export/t.rast.export.py +++ b/temporal/t.rast.export/t.rast.export.py @@ -127,10 +127,10 @@ def main(): } if not directory or not os.path.exists(directory): - gs.fatal(_("Directory {} not found".format(directory))) + gs.fatal(_("Directory {} not found").format(directory)) if not os.access(directory, os.W_OK): - gs.fatal(_("Directory {} is not writable".format(directory))) + gs.fatal(_("Directory {} is not writable").format(directory)) if _type and _format in {"pack", "AAIGrid"}: gs.warning( diff --git a/temporal/t.rast.gapfill/t.rast.gapfill.py b/temporal/t.rast.gapfill/t.rast.gapfill.py index e2ffb149513..84395da6295 100755 --- a/temporal/t.rast.gapfill/t.rast.gapfill.py +++ b/temporal/t.rast.gapfill/t.rast.gapfill.py @@ -208,8 +208,9 @@ def main(): gs.fatal( _( "Map with name <%s> already exists. " - "Please use another base name." % (_id) + "Please use another base name." ) + % (_id) ) elif new_map.is_in_db(dbif): overwrite_flags[new_id] = True diff --git a/temporal/t.rast.gapfill/testsuite/test_gapfill.py b/temporal/t.rast.gapfill/testsuite/test_gapfill.py index 63cd2b83c26..7b083617d08 100644 --- a/temporal/t.rast.gapfill/testsuite/test_gapfill.py +++ b/temporal/t.rast.gapfill/testsuite/test_gapfill.py @@ -12,6 +12,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows class TestRasterToVector(TestCase): @@ -75,6 +76,7 @@ def tearDown(self): """Remove generated data""" self.runModule("t.remove", flags="df", type="strds", inputs="A") + @xfail_windows def test_simple_2procs(self): self.assertModule( "t.rast.gapfill", @@ -125,6 +127,7 @@ def test_simple_2procs(self): self.assertModule(rast_list) self.assertLooksLike(text, rast_list.outputs.stdout) + @xfail_windows def test_simple_where(self): self.assertModule( "t.rast.gapfill", @@ -173,6 +176,7 @@ def test_simple_where(self): self.assertModule(rast_list) self.assertLooksLike(text, rast_list.outputs.stdout) + @xfail_windows def test_simple_where_2(self): self.assertModule( "t.rast.gapfill", @@ -216,6 +220,7 @@ def test_simple_where_2(self): self.assertModule(rast_list) self.assertLooksLike(text, rast_list.outputs.stdout) + @xfail_windows def test_simple_empty(self): self.assertModule( "t.rast.gapfill", @@ -302,6 +307,7 @@ def test_simple_gran(self): self.assertModule(rast_list) self.assertLooksLike(text, rast_list.outputs.stdout) + @xfail_windows def test_simple_gran(self): self.assertModule( "t.rast.gapfill", diff --git a/temporal/t.rast.list/t.rast.list.py b/temporal/t.rast.list/t.rast.list.py index 651bc69b956..0209d0aeee6 100755 --- a/temporal/t.rast.list/t.rast.list.py +++ b/temporal/t.rast.list/t.rast.list.py @@ -108,7 +108,13 @@ def message_option_value_excludes_option_value( return _( "Combining {option_name}={option_value} and " "{excluded_option_name}={excluded_option_value} is not allowed. {reason}" - ).format(**locals()) + ).format( + option_name=option_name, + option_value=option_value, + excluded_option_name=excluded_option_name, + excluded_option_value=excluded_option_value, + reason=reason, + ) def message_option_value_excludes_option( @@ -117,13 +123,23 @@ def message_option_value_excludes_option( return _( "The option {excluded_option_name} is not allowed with " "{option_name}={option_value}. {reason}" - ).format(**locals()) + ).format( + excluded_option_name=excluded_option_name, + option_name=option_name, + option_value=option_value, + reason=reason, + ) def message_option_value_excludes_flag(option_name, option_value, flag_name, reason): return _( "The flag -{flag_name} is not allowed with {option_name}={option_value}." - " {reason}".format(**locals()) + " {reason}" + ).format( + flag_name=flag_name, + option_name=option_name, + option_value=option_value, + reason=reason, ) diff --git a/temporal/t.rast.list/tests/t_rast_list_test.py b/temporal/t.rast.list/tests/t_rast_list_test.py index fbc092175db..86e539467cd 100644 --- a/temporal/t.rast.list/tests/t_rast_list_test.py +++ b/temporal/t.rast.list/tests/t_rast_list_test.py @@ -83,7 +83,7 @@ def test_yaml(space_time_raster_dataset): @pytest.mark.needs_solo_run @pytest.mark.parametrize( - "separator,delimiter", [(None, ","), (",", ","), (";", ";"), ("tab", "\t")] + ("separator", "delimiter"), [(None, ","), (",", ","), (";", ";"), ("tab", "\t")] ) def test_csv(space_time_raster_dataset, separator, delimiter): """Check CSV can be parsed with different separators""" diff --git a/temporal/t.rast.out.vtk/t.rast.out.vtk.py b/temporal/t.rast.out.vtk/t.rast.out.vtk.py index a042168499a..876770e4c4e 100755 --- a/temporal/t.rast.out.vtk/t.rast.out.vtk.py +++ b/temporal/t.rast.out.vtk/t.rast.out.vtk.py @@ -160,7 +160,7 @@ def main(): overwrite=gs.overwrite(), ) except CalledModuleError: - gs.fatal(_("Unable to export raster map <%s>" % map_name)) + gs.fatal(_("Unable to export raster map <%s>") % map_name) count += 1 diff --git a/temporal/t.rast.series/t.rast.series.py b/temporal/t.rast.series/t.rast.series.py index 074f35a00a0..57907f463e4 100755 --- a/temporal/t.rast.series/t.rast.series.py +++ b/temporal/t.rast.series/t.rast.series.py @@ -149,8 +149,8 @@ def main(): gs.warning( _( "Processing over {} maps: activating -z flag of r.series which " - "slows down processing.".format(max_files_open) - ) + "slows down processing." + ).format(max_files_open) ) flag += "z" if nulls: diff --git a/temporal/t.rast.series/testsuite/test_series.py b/temporal/t.rast.series/testsuite/test_series.py index cfb17a338cd..99fe69d4352 100644 --- a/temporal/t.rast.series/testsuite/test_series.py +++ b/temporal/t.rast.series/testsuite/test_series.py @@ -14,6 +14,7 @@ import grass.temporal as tgis from grass.gunittest.case import TestCase from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows class TestSnapAbsoluteSTRDS(TestCase): @@ -146,6 +147,7 @@ def test_minimum_where(self): map="series_minimum_2", refmin=300, refmax=300, msg="Minimum must be 300" ) + @xfail_windows def test_quantile(self): self.assertModule( "t.rast.series", diff --git a/temporal/t.rast.to.rast3/t.rast.to.rast3.py b/temporal/t.rast.to.rast3/t.rast.to.rast3.py index e3bdd9567ad..7776d7426ee 100755 --- a/temporal/t.rast.to.rast3/t.rast.to.rast3.py +++ b/temporal/t.rast.to.rast3/t.rast.to.rast3.py @@ -162,7 +162,7 @@ def main(): overwrite=gs.overwrite(), ) except CalledModuleError: - gs.fatal(_("Unable to create 3D raster map <%s>" % output)) + gs.fatal(_("Unable to create 3D raster map <%s>") % output) gs.run_command("g.remove", flags="f", type="raster", name=null_map) diff --git a/temporal/t.rast.univar/testsuite/test_t_rast_univar.py b/temporal/t.rast.univar/testsuite/test_t_rast_univar.py index cfdfa78ab27..dca870d6a98 100644 --- a/temporal/t.rast.univar/testsuite/test_t_rast_univar.py +++ b/temporal/t.rast.univar/testsuite/test_t_rast_univar.py @@ -8,8 +8,10 @@ @author Soeren Gebbert """ +from pathlib import Path from grass.gunittest.case import TestCase from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows class TestRasterUnivar(TestCase): @@ -151,6 +153,7 @@ def tearDownClass(cls): cls.del_temp_region() + @xfail_windows def test_with_all_maps(self): t_rast_univar = SimpleModule( "t.rast.univar", @@ -176,6 +179,7 @@ def test_with_all_maps(self): res_line = res.split("|", 1)[1] self.assertLooksLike(ref_line, res_line) + @xfail_windows def test_with_subset_of_maps(self): t_rast_univar = SimpleModule( "t.rast.univar", @@ -200,6 +204,7 @@ def test_with_subset_of_maps(self): res_line = res.split("|", 1)[1] self.assertLooksLike(ref_line, res_line) + @xfail_windows def test_coarser_resolution(self): t_rast_univar = SimpleModule( "t.rast.univar", @@ -243,7 +248,7 @@ def test_subset_with_output(self): a_3@testing||2001-07-01 00:00:00|2001-10-01 00:00:00|300|300|300|300|0|0|0|2880000|0|9600|9600 a_4@testing||2001-10-01 00:00:00|2002-01-01 00:00:00|400|400|400|400|0|0|0|3840000|0|9600|9600 """ - univar_output = open("univar_output.txt", "r").read() + univar_output = Path("univar_output.txt").read_text() for ref, res in zip(univar_text.split("\n"), univar_output.split("\n")): if ref and res: @@ -269,7 +274,7 @@ def test_subset_with_extended_statistics_and_output(self): a_3@m2||2001-07-01 00:00:00|2001-10-01 00:00:00|300|300|300|300|0|0|0|2880000|0|9600|9600|300|300|300|300|300 a_4@m2||2001-10-01 00:00:00|2002-01-01 00:00:00|400|400|400|400|0|0|0|3840000|0|9600|9600|400|400|400|400|400 """ - univar_output = open("univar_output.txt", "r").read() + univar_output = Path("univar_output.txt").read_text() for ref, res in zip(univar_text.split("\n"), univar_output.split("\n")): if ref and res: @@ -292,7 +297,7 @@ def test_subset_with_extended_statistics_and_output(self): a_3@testing||2001-07-01 00:00:00|2001-10-01 00:00:00|300|300|300|300|0|0|0|2880000|0|9600|9600 a_4@testing||2001-10-01 00:00:00|2002-01-01 00:00:00|400|400|400|400|0|0|0|3840000|0|9600|9600 """ - univar_output = open("univar_output.txt", "r").read() + univar_output = Path("univar_output.txt").read_text() for ref, res in zip(univar_text.split("\n"), univar_output.split("\n")): if ref and res: @@ -315,6 +320,7 @@ def test_error_handling_no_input(self): # No input self.assertModuleFail("t.rast.univar", output="out.txt") + @xfail_windows def test_with_zones(self): """Test use of zones""" @@ -352,6 +358,7 @@ def test_with_zones(self): res_line = res.split("|", 1)[1] self.assertLooksLike(ref_line, res_line) + @xfail_windows def test_with_semantic_label(self): """Test semantic labels""" t_rast_univar = SimpleModule( @@ -378,6 +385,7 @@ def test_with_semantic_label(self): res_line = res.split("|", 1)[1] self.assertLooksLike(ref_line, res_line) + @xfail_windows def test_with_semantic_label_parallel(self): """Test semantic labels""" t_rast_univar = SimpleModule( @@ -405,6 +413,7 @@ def test_with_semantic_label_parallel(self): res_line = res.split("|", 1)[1] self.assertLooksLike(ref_line, res_line) + @xfail_windows def test_with_spatial_filter_intersects(self): """Test spatial filter overlaps""" t_rast_univar = SimpleModule( @@ -433,6 +442,7 @@ def test_with_spatial_filter_intersects(self): res_line = res.split("|", 1)[1] self.assertLooksLike(ref_line, res_line) + @xfail_windows def test_with_spatial_filter_contains(self): """Test spatial filter contains""" t_rast_univar = SimpleModule( @@ -459,6 +469,7 @@ def test_with_spatial_filter_contains(self): res_line = res.split("|", 1)[1] self.assertLooksLike(ref_line, res_line) + @xfail_windows def test_with_spatial_filter_is_contained(self): """Test spatial filter is_contained""" t_rast_univar = SimpleModule( diff --git a/temporal/t.rast.what/t.rast.what.py b/temporal/t.rast.what/t.rast.what.py index 9fa4ad5d793..b3cec73a538 100755 --- a/temporal/t.rast.what/t.rast.what.py +++ b/temporal/t.rast.what/t.rast.what.py @@ -387,9 +387,9 @@ def one_point_per_row_output( for count in range(len(output_files)): file_name = output_files[count] - gs.verbose(_("Transforming r.what output file %s" % (file_name))) + gs.verbose(_("Transforming r.what output file %s") % (file_name)) map_list = output_time_list[count] - in_file = open(file_name, "r") + in_file = open(file_name) for line in in_file: line = line.split(separator) if vcat: @@ -465,9 +465,8 @@ def one_point_per_col_output( first = True for count in range(len(output_files)): file_name = output_files[count] - gs.verbose(_("Transforming r.what output file %s" % (file_name))) - map_list = output_time_list[count] - in_file = open(file_name, "r") + gs.verbose(_("Transforming r.what output file %s") % (file_name)) + in_file = open(file_name) lines = in_file.readlines() matrix = [] @@ -564,7 +563,7 @@ def one_point_per_timerow_output( file_name = output_files[count] gs.verbose("Transforming r.what output file %s" % (file_name)) map_list = output_time_list[count] - in_file = open(file_name, "r") + in_file = open(file_name) if write_header: if first is True: @@ -608,7 +607,7 @@ def one_point_per_timerow_output( if write_header: out_file.write(header + "\n") - gs.verbose(_("Writing the output file <%s>" % (output))) + gs.verbose(_("Writing the output file <%s>") % (output)) for row in matrix: first = True for col in row: @@ -664,15 +663,13 @@ def process_loop( output_time_list.append(map_list) gs.verbose( - _( - "Process maps %(samp_start)i to %(samp_end)i (of %(total)i)" - % ( - { - "samp_start": count - len(map_names) + 1, - "samp_end": count, - "total": len(maps), - } - ) + _("Process maps %(samp_start)i to %(samp_end)i (of %(total)i)") + % ( + { + "samp_start": count - len(map_names) + 1, + "samp_end": count, + "total": len(maps), + } ) ) mod = copy.deepcopy(r_what) diff --git a/temporal/t.rast.what/testsuite/test_what.py b/temporal/t.rast.what/testsuite/test_what.py index 96432eff4e1..18c7af63807 100644 --- a/temporal/t.rast.what/testsuite/test_what.py +++ b/temporal/t.rast.what/testsuite/test_what.py @@ -10,6 +10,7 @@ from grass.gunittest.case import TestCase from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows class TestRasterWhat(TestCase): @@ -218,6 +219,7 @@ def test_timerow_output_coords(self): "out_timerow_coords.txt", "ca4ee0e7e4aaca170d6034e0d57d292d", text=True ) + @xfail_windows def test_row_stdout_where_parallel(self): t_rast_what = SimpleModule( "t.rast.what", @@ -245,6 +247,7 @@ def test_row_stdout_where_parallel(self): """ self.assertLooksLike(text, str(t_rast_what.outputs.stdout)) + @xfail_windows def test_row_stdout_where_parallel_cat(self): t_rast_what = SimpleModule( "t.rast.what", @@ -272,6 +275,7 @@ def test_row_stdout_where_parallel_cat(self): """ self.assertLooksLike(text, str(t_rast_what.outputs.stdout)) + @xfail_windows def test_row_stdout_where_parallel2(self): """Here without output definition, the default is used then""" @@ -385,6 +389,7 @@ def tearDownClass(cls): cls.runModule("t.remove", flags="df", type="strds", inputs="A") cls.del_temp_region() + @xfail_windows def test_null_value(self): """Test setting the null value""" diff --git a/temporal/t.rast3d.univar/testsuite/test_t_rast3d_univar.py b/temporal/t.rast3d.univar/testsuite/test_t_rast3d_univar.py index d34c1f253aa..4ca64e88442 100644 --- a/temporal/t.rast3d.univar/testsuite/test_t_rast3d_univar.py +++ b/temporal/t.rast3d.univar/testsuite/test_t_rast3d_univar.py @@ -8,8 +8,10 @@ @author Soeren Gebbert """ +from pathlib import Path from grass.gunittest.case import TestCase from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows class TestRasterUnivar(TestCase): @@ -57,6 +59,7 @@ def tearDownClass(cls): cls.runModule("g.remove", flags="f", type="raster_3d", name="zones") cls.del_temp_region() + @xfail_windows def test_with_all_maps(self): t_rast3d_univar = SimpleModule( "t.rast3d.univar", @@ -81,6 +84,7 @@ def test_with_all_maps(self): res_line = res.split("|", 1)[1] self.assertLooksLike(ref_line, res_line) + @xfail_windows def test_with_subset_of_maps(self): t_rast3d_univar = SimpleModule( "t.rast3d.univar", @@ -119,7 +123,7 @@ def test_subset_with_output(self): a_3@testing|2001-07-01 00:00:00|2001-10-01 00:00:00|300|300|300|300|0|0|0|144000000|0|480000|480000 a_4@testing|2001-10-01 00:00:00|2002-01-01 00:00:00|400|400|400|400|0|0|0|192000000|0|480000|480000 """ - univar_output = open("univar_output.txt", "r").read() + univar_output = Path("univar_output.txt").read_text() for ref, res in zip(univar_text.split("\n"), univar_output.split("\n")): if ref and res: @@ -142,7 +146,7 @@ def test_subset_with_output_no_header(self): a_3@testing|2001-07-01 00:00:00|2001-10-01 00:00:00|300|300|300|300|0|0|0|144000000|0|480000|480000 a_4@testing|2001-10-01 00:00:00|2002-01-01 00:00:00|400|400|400|400|0|0|0|192000000|0|480000|480000 """ - univar_output = open("univar_output.txt", "r").read() + univar_output = Path("univar_output.txt").read_text() for ref, res in zip(univar_text.split("\n"), univar_output.split("\n")): if ref and res: @@ -165,6 +169,7 @@ def test_error_handling_no_input(self): # No input self.assertModuleFail("t.rast3d.univar", output="out.txt") + @xfail_windows def test_with_zones(self): """Test use of zones""" @@ -202,6 +207,7 @@ def test_with_zones(self): res_line = res.split("|", 1)[1] self.assertLooksLike(ref_line, res_line) + @xfail_windows def test_with_zones_parallel(self): """Test use of zones""" diff --git a/temporal/t.remove/t.remove.py b/temporal/t.remove/t.remove.py index fd32f8972d5..91fa58dde7a 100755 --- a/temporal/t.remove/t.remove.py +++ b/temporal/t.remove/t.remove.py @@ -102,7 +102,7 @@ def main(): # Read the dataset list from file if file: - fd = open(file, "r") + fd = open(file) line = True while True: @@ -127,22 +127,25 @@ def main(): sp = tgis.open_old_stds(name, type, dbif) if not force: gs.message( - _("{stds}: {gid}".format(stds=sp.get_type().upper(), gid=sp.get_id())) + _("{stds}: {gid}").format(stds=sp.get_type().upper(), gid=sp.get_id()) ) if recursive or clean: if not force: if recursive: - msg = ( + msg = _( "The following maps of {stds} {gid} will be " "unregistered from temporal database:" ) elif clean: - msg = ( + msg = _( "The following maps of {stds} {gid} will be " "unregistered from temporal database and removed " "from spatial database:" ) - gs.message(_(msg.format(stds=sp.get_type(), gid=sp.get_id()))) + + if recursive or clean: + gs.message(msg.format(stds=sp.get_type(), gid=sp.get_id())) + maps = sp.get_registered_maps_as_objects(dbif=dbif) map_statement = "" count = 1 @@ -150,10 +153,10 @@ def main(): for map in maps: map.select(dbif) # We may have multiple layer for a single map, hence we need - # to avoid multiple deletation of the same map, + # to avoid multiple deletions of the same map, # but the database entries are still present and must be removed if not force: - gs.message(_("- %s" % map.get_name())) + gs.message(_("- %s") % map.get_name()) continue if clean and force: if map.get_name() not in name_list: @@ -190,8 +193,8 @@ def main(): gs.message( _( "Nothing removed. You must use the force flag (-{flag}) to actually " - "remove them.".format(flag="f") - ) + "remove them." + ).format(flag="f") ) else: # Execute the collected SQL statenents diff --git a/temporal/t.unregister/t.unregister.py b/temporal/t.unregister/t.unregister.py index e7e234320c0..b39b7b9819f 100755 --- a/temporal/t.unregister/t.unregister.py +++ b/temporal/t.unregister/t.unregister.py @@ -108,7 +108,7 @@ def main(): # Read the map list from file if file: - fd = open(file, "r") + fd = open(file) line = True while True: @@ -154,10 +154,8 @@ def main(): statement += map.delete(dbif=dbif, update=False, execute=False) else: gs.warning( - _( - "Unable to find %s map <%s> in temporal database" - % (map.get_type(), map.get_id()) - ) + _("Unable to find %s map <%s> in temporal database") + % (map.get_type(), map.get_id()) ) count += 1 @@ -170,7 +168,7 @@ def main(): # Update space time datasets if input: - gs.message(_("Unregister maps from space time dataset <%s>" % (input))) + gs.message(_("Unregister maps from space time dataset <%s>") % (input)) else: gs.message(_("Unregister maps from the temporal database")) diff --git a/temporal/t.vect.algebra/t.vect.algebra.py b/temporal/t.vect.algebra/t.vect.algebra.py index 5da83398404..852df8c3afe 100644 --- a/temporal/t.vect.algebra/t.vect.algebra.py +++ b/temporal/t.vect.algebra/t.vect.algebra.py @@ -64,7 +64,6 @@ def main(): expression = options["expression"] basename = options["basename"] spatial = flags["s"] - stdstype = "stvds" # Check for PLY istallation try: diff --git a/temporal/t.vect.observe.strds/t.vect.observe.strds.py b/temporal/t.vect.observe.strds/t.vect.observe.strds.py index 8b3850fb2ef..9c60a3d026c 100755 --- a/temporal/t.vect.observe.strds/t.vect.observe.strds.py +++ b/temporal/t.vect.observe.strds/t.vect.observe.strds.py @@ -152,13 +152,13 @@ def main(): "Temporal type of space time raster datasets must be equal\n" "<%(a)s> of type %(type_a)s do not match <%(b)s> of type " "%(type_b)s" - % { - "a": first_strds.get_id(), - "type_a": first_strds.get_temporal_type(), - "b": dataset.get_id(), - "type_b": dataset.get_temporal_type(), - } ) + % { + "a": first_strds.get_id(), + "type_a": first_strds.get_temporal_type(), + "b": dataset.get_id(), + "type_b": dataset.get_temporal_type(), + } ) mapmatrizes = tgis.sample_stds_by_stds_topology( diff --git a/testsuite/Makefile b/testsuite/Makefile deleted file mode 100644 index 7ed92b67442..00000000000 --- a/testsuite/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -MODULE_TOPDIR = .. - -SUBDIRS = \ - raster - -include $(MODULE_TOPDIR)/include/Make/Dir.make - -default: parsubdirs diff --git a/testsuite/README.md b/testsuite/README.md index 491fa4597af..36dda7d3da2 100644 --- a/testsuite/README.md +++ b/testsuite/README.md @@ -1,29 +1,39 @@ # Test suite -This directory contains scripts to check some functionality of GRASS GIS. +Tests are in directories `tests` and `testsuite` under each directory which has tests. +This directory contains additional scripts and information to test functionality +without a focus on a specific part of the code. -GRASS GIS testsuite documentation: +There are two testing mechanism in place, _pytest_ which is the modern way of testing +GRASS GIS. Tests using _pytest_ are written just as any other Python tests. -## Simple test data +In parallel, there is also custom unittest-based framework centered around +_grass.gunittest_ package. These tests run in the NC sample datasets and can be +executed using _pytest_ or directly. The unittest-based adds a number of custom +assert methods to accommodate different data and outputs typical in GRASS GIS. +_grass.gunittest_ documentation: + -Some tests may be launched in the location `../demolocation/`: +## Running tests + +Tests can be executed using _pytest_: ```bash -# create new mapset for test -grass ../demolocation/user1 -c -# run the test -make +# Setup the Python environment (if not set up already). +# Replace grass by path to the executable if not installed on path. +export PYTHONPATH=\$(grass --config python_path):\$PYTHONPATH +export LD_LIBRARY_PATH=\$(grass --config path)/lib:\$LD_LIBRARY_PATH +# Run the test. +pytest ``` -## Extended test data - -Most tests require the North Carolina Sample dataset, available from - +## Test data -## Notes +To test manually or to write tests, you may need to use the North Carolina +Sample dataset, available from +. -Since 2020: For a more advanced test suite, see - +## CI -Until 2019: For a more advanced test suite, see - +Most tests run in the CI. See the `.github` directory for details and +use it as a reference. diff --git a/testsuite/examples/test_framework_GRASS_GIS_with_NC.conf b/testsuite/examples/test_framework_GRASS_GIS_with_NC.conf deleted file mode 100644 index 6256108f6a8..00000000000 --- a/testsuite/examples/test_framework_GRASS_GIS_with_NC.conf +++ /dev/null @@ -1,29 +0,0 @@ -### CONFIGURATION -# -# name of binary: -GRASSBIN=grass -# source code directory as full path: -GRASSSRC="$(realpath ../../)" -# temporary grassdata directory -GRASSDATA="$HOME/grassdata" - -# leave 1 or more CPU free for other usage than testing -FREECPU=1 - -# Python binary to be used (python|python3) -PYTHON=python - -# here we suppose default compilation settings of GRASS GIS and no 'make install' -# may be no|yes -COMPILE="no" -# configure metascript with compiler flags: -CONFIGURE="${GRASSSRC}/conf_grass8.sh" - -# directory to store reports, e.g. in a subdirectory -REPORTS="testreports" - -# publish report on WWW Server (not needed for local tests) -# may be no|yes -PUBLISH="no" -# upload WWW dir on server for report publication (not used for local tests) -SERVERDIR="/var/www/html/grassgistestreports" diff --git a/testsuite/examples/test_framework_GRASS_GIS_with_NC.sh b/testsuite/examples/test_framework_GRASS_GIS_with_NC.sh deleted file mode 100755 index 808b4b9c716..00000000000 --- a/testsuite/examples/test_framework_GRASS_GIS_with_NC.sh +++ /dev/null @@ -1,144 +0,0 @@ -#!/bin/bash -############################################################################ -# -# MODULE: Example script to run testsuite -# AUTHOR(S): Markus Neteler, Sören Gebbert, Vaclav Petras -# PURPOSE: Test GRASS GIS using the test framework -# Documentation: -# https://trac.osgeo.org/grass/wiki/GSoC/2014/TestingFrameworkForGRASS -# https://grass.osgeo.org/grass-devel/manuals/libpython/gunittest_running_tests.html#example-bash-script-to-run-be-used-as-a-cron-job -# -# Data: -# We use the full NC dataset (nc_spm_full_v2_alpha.tar.gz) -# -# COPYRIGHT: (C) 2019-2021 by Markus Neteler, and the GRASS Development Team -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -############################################################################ - -### Fetch CONFIGURATION - -CONF="test_framework_GRASS_GIS_with_NC.conf" - -usage_msg(){ -echo "Usage: - $0 [conf_file] - -Example: - $0 ./${CONF} -" -} - -if [ ! -z "$1" ] ; then - case "$1" in - -h | --h | -help | --help) - usage_msg - exit 0 - ;; - *) - if [ -f ${1} ] ; then - CONF="$1" - else - echo "ERROR: $1 is not a file" - exit 1 - fi - ;; - esac -else - usage_msg - exit 0 -fi - -source ${CONF} - -######### nothing to change below - -set -e # fail fast - -# computer architecture: -ARCH=`${GRASSBIN} --config arch` - -# here we suppose default compilation settings of GRASS GIS and no make install -GRASSBIN="$GRASSSRC/bin.${ARCH}/${GRASSBIN}" -GRASSDIST="$GRASSSRC/dist.${ARCH}" - -# necessary hardcoded GRASS paths -GRASSDIST_PYTHON="$GRASSDIST/etc/python" -GRASS_MULTI_RUNNER="$GRASSSRC/python/grass/gunittest/multirunner.py" -GRASS_MULTI_REPORTER="$GRASSSRC/python/grass/gunittest/multireport.py" - -DATE_FLAGS="--utc +%Y-%m-%d-%H-%M" -NOW=$(date $DATE_FLAGS) - -# get number of processors of current machine -MYNPROC=`getconf _NPROCESSORS_ONLN` -# leave some free for other tasks -GCCTHREADS=`expr $MYNPROC - $FREECPU` -if [ $GCCTHREADS -lt 1 ] ; then - GCCTHREADS=1 -fi - -# contains last executed command stdout and stderr -# here were rely on reports being absolute -OUTPUT_LOGFILE="$REPORTS/output-$NOW.txt" - -# these are relative to REPORTS -CURRENT_REPORT_BASENAME="reports_for_date-" -FINAL_REPORT_DIR="summary_report" -CURRENT_REPORTS_DIR="$CURRENT_REPORT_BASENAME$NOW" -LOGFILE="$REPORTS/runs.log" - -mkdir -p $REPORTS/$CURRENT_REPORTS_DIR -mkdir -p $GRASSDATA - -# fetch sample data -SAMPLEDATA=nc_spm_full_v2alpha -(cd $GRASSDATA ; wget -c https://grass.osgeo.org/sampledata/north_carolina/$SAMPLEDATA.tar.gz ; tar xfz $SAMPLEDATA.tar.gz --strip-components 2) - -set -x - -echo "Testing of GRASS GIS started: $NOW" >> ${LOGFILE} - -if [ "$COMPILE" = "yes" ] ; then - ## compile current source code from scratch - cd $GRASSSRC - make distclean -j$GCCTHREADS - git pull - ./$CONFIGURE ... # configure meta script containing all the compiler flags - make -j$GCCTHREADS -fi - -# run tests for the current source code -cd $REPORTS/$CURRENT_REPORTS_DIR -$PYTHON $GRASS_MULTI_RUNNER \ - --grassbin $GRASSBIN \ - --grasssrc $GRASSSRC \ - --grassdata $GRASSDATA \ - --location $SAMPLEDATA --location-type nc # \ -# --location other_location --location-type other_type - -# create overall report of all so far executed tests -# the script depends on GRASS but just Python part is enough -export PYTHONPATH="$GRASSDIST_PYTHON:$PYTHONPATH" -$PYTHON $GRASS_MULTI_REPORTER --output $FINAL_REPORT_DIR \ - $CURRENT_REPORT_BASENAME*/* - -# publish on Web site -if [ "$PUBLISH" = "yes" ] ; then - ## although we cannot be sure the tests were executed was successfully - ## so publish or archive results - rsync -rtvu --delete $REPORTS/ $SERVERDIR -fi - -echo "Nightly ($NOW) GRASS GIS test finished: $(date $DATE_FLAGS)" >> ${LOGFILE} - -exit 0 diff --git a/testsuite/raster/Makefile b/testsuite/raster/Makefile deleted file mode 100644 index 21c1f8eb6c0..00000000000 --- a/testsuite/raster/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -all: - ./raster_md5test.sh - ./rmapcalc_test.sh diff --git a/testsuite/raster/README b/testsuite/raster/README deleted file mode 100644 index bc5b0940789..00000000000 --- a/testsuite/raster/README +++ /dev/null @@ -1 +0,0 @@ -Raster map tests go here diff --git a/testsuite/raster/rhemisphere.sh b/testsuite/raster/rhemisphere.sh deleted file mode 100755 index e312f7b36d1..00000000000 --- a/testsuite/raster/rhemisphere.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/sh - -# Markus Neteler, 2006 -# This program is free software under the GNU General Public -# License (>=v2). Read the file COPYING that comes with GRASS -# for details. -# Test cases for 2D raster data -# generate a hemisphere to test slope, aspect, curvatures - -# some definitions: -BOXLENGTH=1000 # side length of test area -RADIUS=500 # half BOXLENGTH - -############ - -if [ -z "$GISBASE" ] ; then - echo "You must be in GRASS GIS to run this program." >&2 - exit 1 -fi - -# some functions - keep order here -TMP="disk.$$" - -cleanup() -{ - echo "Removing temporary map" - g.remove --q -f type=raster name=$TMP > /dev/null -} - -######################## - -g.region n=$BOXLENGTH s=0 w=0 e=$BOXLENGTH -p res=1 - -X="(col() - $RADIUS)" -Y="($RADIUS - row())" -r="sqrt($X^2 + $Y^2)" - -#Mask out unwanted parts (check for <= ??): -r.mapcalc "$TMP = if($r<$RADIUS,$r,null())" - -ALPHA="acos ($TMP/$RADIUS)" -HEIGHT="$RADIUS * sin($ALPHA)" - - -r.mapcalc "hemisphere = $HEIGHT" -cleanup -g.message "Generated raster map " -#echo "Now generate aspect + slope on " diff --git a/testsuite/raster/raster_md5test.sh b/testsuite/raster_md5test.sh similarity index 67% rename from testsuite/raster/raster_md5test.sh rename to testsuite/raster_md5test.sh index 0bda0c3428c..b3281d4c505 100755 --- a/testsuite/raster/raster_md5test.sh +++ b/testsuite/raster_md5test.sh @@ -14,19 +14,23 @@ if [ -z "$GISBASE" ] ; then fi #### check if we have sed -if [ ! -x "`which sed`" ] ; then +if [ ! -x "$(which sed)" ] ; then echo "$PROG: sed required, please install first" 1>&2 exit 1 fi -#### check if we have md5sum -if [ ! -x "`which md5sum`" ] ; then - echo "$PROG: md5sum required, please install first" 1>&2 - exit 1 +#### check if we have md5sum or md5 +if [ -x "$(which md5sum)" ] ; then + MD5="md5sum | cut -d' ' -f1" +elif [ -x "$(which md5)" ] ; then + MD5="md5 -q" +else + echo "$PROG: md5sum or md5 required, please install first" 1>&2 + exit 1 fi #### check if we have cut -if [ ! -x "`which cut`" ] ; then +if [ ! -x "$(which cut)" ] ; then echo "$PROG: cut required, please install first" 1>&2 exit 1 fi @@ -38,47 +42,47 @@ export LC_NUMERIC=C # enforce ZLIB export GRASS_COMPRESSOR=ZLIB -eval `g.gisenv` -: ${GISBASE?} ${GISDBASE?} ${LOCATION_NAME?} ${MAPSET?} +eval "$(g.gisenv)" +: "${GISBASE?}" "${GISDBASE?}" "${LOCATION_NAME?}" "${MAPSET?}" MAPSET_PATH=$GISDBASE/$LOCATION_NAME/$MAPSET # some definitions PIXEL=3 PID=$$ -TMPNAME="`echo ${PID}_tmp_testmap | sed 's+\.+_+g'`" +TMPNAME=$(echo ${PID}_tmp_testmap | sed 's+\.+_+g') # some functions - keep order here cleanup() { echo "Removing temporary map" - g.remove -f type=raster name=$TMPNAME > /dev/null + g.remove -f type=raster name="$TMPNAME" > /dev/null } # check if a MASK is already present: -MASKTMP=mask.$TMPNAME -USERMASK=usermask_${MASKTMP} -if test -f $MAPSET_PATH/cell/MASK +MASKTMP="mask.${TMPNAME}" +USERMASK="usermask_${MASKTMP}" +if test -f "${MAPSET_PATH}/cell/MASK" then echo "A user raster mask (MASK) is present. Saving it..." - g.rename raster=MASK,$USERMASK > /dev/null + g.rename raster=MASK,"$USERMASK" > /dev/null fi finalcleanup() { echo "Restoring user region" - g.region region=$TMPNAME - g.remove -f type=region name=$TMPNAME > /dev/null + g.region region="$TMPNAME" + g.remove -f type=region name="$TMPNAME" > /dev/null #restore user mask if present: - if test -f $MAPSET_PATH/cell/$USERMASK ; then + if test -f "${MAPSET_PATH}/cell/${USERMASK}" ; then echo "Restoring user MASK" g.remove -f type=raster name=MASK > /dev/null - g.rename raster=$USERMASK,MASK > /dev/null + g.rename raster="$USERMASK",MASK > /dev/null fi } check_exit_status() { - if [ $1 -ne 0 ] ; then + if [ "$1" -ne 0 ] ; then echo "An error occurred." cleanup ; finalcleanup exit 1 @@ -106,7 +110,7 @@ check_md5sum() } echo "Saving current & setting test region." -g.region save=$TMPNAME +g.region save="$TMPNAME" check_exit_status $? g.region s=0 n=$PIXEL w=0 e=$PIXEL res=1 tbres=1 check_exit_status $? @@ -118,8 +122,8 @@ r.mapcalc "$TMPNAME = 1" check_exit_status $? echo "MD5 checksum on output of INT/CELL test." -MD5="`r.out.ascii $TMPNAME precision=15 | md5sum | cut -d' ' -f1`" -check_md5sum "549e7dabe70df893803690571d2e1503" "$MD5" +SUM=$(r.out.ascii "$TMPNAME" precision=15 | eval "$MD5") +check_md5sum "549e7dabe70df893803690571d2e1503" "$SUM" cleanup echo "INT/CELL md5sum test successful" @@ -132,8 +136,8 @@ r.mapcalc "$TMPNAME = $VALUE" check_exit_status $? echo "MD5 checksum on output of FLOAT/FCELL test." -MD5="`r.out.ascii $TMPNAME precision=15 | md5sum | cut -d' ' -f1`" -check_md5sum "379f3d880b6d509051af6b4ccf470762" "$MD5" +SUM=$(r.out.ascii "$TMPNAME" precision=15 | eval "$MD5") +check_md5sum "379f3d880b6d509051af6b4ccf470762" "$SUM" cleanup echo "FLOAT/FCELL md5sum test successful" diff --git a/testsuite/vector/v.in.gps_test.sh b/testsuite/vector/v.in.gps_test.sh deleted file mode 100755 index 62b2f5b651c..00000000000 --- a/testsuite/vector/v.in.gps_test.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/sh -# v.in.garmin and v.in.gpsbabel test script -# by Hamish Bowman 18 May 2007 ; public domain -# assumes downloading from a garmin on port /dev/gps - -for PGM in garmin gpsbabel ; do - for DO_PTS in pts lines ; do - for TASK in w t r ; do - if [ $TASK = w ] && [ $DO_PTS = "lines" ] ; then - continue - fi - if [ $DO_PTS = "pts" ] ; then - PTFLAG="-p" - else - PTFLAG="" - fi - MAPNAME="test_${PGM}_${TASK}_${DO_PTS}_$$" - echo "-- Running [v.in.$PGM] for [$TASK] download as [$DO_PTS] into <$MAPNAME> --" - v.in.$PGM -$TASK $PTFLAG out="$MAPNAME" - if [ $? -ne 0 ] ; then - exit 1 - fi - awk 'BEGIN {printf("\n\n\n\n")}' - done - done -done diff --git a/utils/coverage_mapper.py b/utils/coverage_mapper.py index 9a2f1389781..88fa30f9b54 100644 --- a/utils/coverage_mapper.py +++ b/utils/coverage_mapper.py @@ -22,12 +22,14 @@ def map_scripts_paths(old_path): if INITIAL_GISBASE is None or INITIAL_PWD is None: return old_path p = Path(old_path) + extension = ".py" + p_name = p.stem if p.suffix == extension else p.name temporal_base = Path(INITIAL_GISBASE) / "scripts" / "t.*" base = Path(INITIAL_GISBASE) / "scripts" / "*" if p.match(str(temporal_base)): - return str(Path(INITIAL_PWD) / "temporal" / (p.name) / (p.name)) + ".py" + return str(Path(INITIAL_PWD) / "temporal" / (p_name) / (p_name)) + extension if p.match(str(base)): - return str(Path(INITIAL_PWD) / "scripts" / (p.name) / (p.name)) + ".py" + return str(Path(INITIAL_PWD) / "scripts" / (p_name) / (p_name)) + extension return old_path diff --git a/utils/g.html2man/g.html2man.py b/utils/g.html2man/g.html2man.py index 498ce34dfe1..58ffb2f7bca 100755 --- a/utils/g.html2man/g.html2man.py +++ b/utils/g.html2man/g.html2man.py @@ -17,12 +17,10 @@ def fix(content): tag, attrs, body = content if tag == "div" and ("class", "toc") in attrs: return None - else: - return (tag, attrs, fix(body)) - elif isinstance(content, list): + return (tag, attrs, fix(body)) + if isinstance(content, list): return [fixed for item in content for fixed in [fix(item)] if fixed is not None] - else: - return content + return content def main(): diff --git a/utils/g.html2man/ggroff.py b/utils/g.html2man/ggroff.py index 49c16f19f44..e62c5ec2b1c 100644 --- a/utils/g.html2man/ggroff.py +++ b/utils/g.html2man/ggroff.py @@ -253,8 +253,7 @@ def pp_text(self, content): for line in lines: self.pp_text(line) return - else: - content = lines[0] + content = lines[0] if self.at_bol and not self.get("preformat"): content = self.strip_re.sub("", content) self.pp_string(content) diff --git a/utils/g.html2man/ghtml.py b/utils/g.html2man/ghtml.py index eabb494198d..4b30950ff0e 100644 --- a/utils/g.html2man/ghtml.py +++ b/utils/g.html2man/ghtml.py @@ -95,7 +95,7 @@ def setify(d): - return dict([(key, frozenset(val)) for key, val in d.items()]) + return {key: frozenset(val) for key, val in d.items()} def omit(allowed, tags): @@ -225,8 +225,7 @@ def __init__(self, entities=None): def top(self): if self.tag_stack == []: return None - else: - return self.tag_stack[-1][0] + return self.tag_stack[-1][0] def pop(self): self.excluded = self.excluded_stack.pop() diff --git a/utils/g.html2man/rest.py b/utils/g.html2man/rest.py index 2df87db8e27..c320f18e397 100644 --- a/utils/g.html2man/rest.py +++ b/utils/g.html2man/rest.py @@ -1,4 +1,5 @@ import sys +from operator import itemgetter def match(node, tag, attr=None, val=None): @@ -26,8 +27,7 @@ def find(node, tag, attr=None, val=None): raise ValueError("child not found") -def children(node): - return node[2] +children = itemgetter(2) def text(node): diff --git a/utils/generate_release_notes.py b/utils/generate_release_notes.py index 3cfffe77bd2..c8a22b01d86 100755 --- a/utils/generate_release_notes.py +++ b/utils/generate_release_notes.py @@ -97,9 +97,7 @@ def print_category(category, changes, file=None): # Relies on author being specified as username. if " " in author: author = author.split(" ", maxsplit=1)[0] - if author.startswith("@"): - # We expect that to be always the case, but we test anyway. - author = author[1:] + author = author.removeprefix("@") if author in known_bot_names or author.endswith("[bot]"): hidden.append(item) elif len(visible) > max_section_length: @@ -229,7 +227,7 @@ def notes_from_gh_api(start_tag, end_tag, branch, categories, exclude): raw_changes = lines[start_whats_changed + 1 : end_whats_changed] changes = [] for change in raw_changes: - if change.startswith("* ") or change.startswith("- "): + if change.startswith(("* ", "- ")): changes.append(change[2:]) else: changes.append(change) diff --git a/utils/gitlog2changelog.py b/utils/gitlog2changelog.py index 2626321d6fb..5ad459aa2b1 100755 --- a/utils/gitlog2changelog.py +++ b/utils/gitlog2changelog.py @@ -66,8 +66,8 @@ author = authorList[1] author = author[0 : len(author) - 1] authorFound = True - except: - print("Could not parse authorList = '%s'" % (line)) + except Exception as e: + print(f"Could not parse authorList = '{line}'. Error: {e!s}") # Match the date line elif line.startswith("Date:"): @@ -76,16 +76,14 @@ date = dateList[1] date = date[0 : len(date) - 1] dateFound = True - except: - print("Could not parse dateList = '%s'" % (line)) - # The Fossil-IDs are ignored: - elif line.startswith(" Fossil-ID:") or line.startswith(" [[SVN:"): - continue - # The svn-id lines are ignored - elif " git-svn-id:" in line: - continue - # The sign off line is ignored too - elif "Signed-off-by" in line: + except Exception as e: + print(f"Could not parse dateList = '{line}'. Error: {e!s}") + # The Fossil-IDs, svn-id, ad sign off lines are ignored: + elif ( + line.startswith((" Fossil-ID:", " [[SVN:")) + or " git-svn-id:" in line + or "Signed-off-by" in line + ): continue # Extract the actual commit message for this commit elif authorFound & dateFound & messageFound is False: diff --git a/utils/mkhtml.py b/utils/mkhtml.py index 210e83b3fd6..39a5e6e26eb 100644 --- a/utils/mkhtml.py +++ b/utils/mkhtml.py @@ -159,17 +159,16 @@ def download_git_commit(url, response_format, *args, **kwargs): """ try: response = urlopen(url, *args, **kwargs) - if not response.code == 200: + if response.code != 200: index = HTTP_STATUS_CODES.index(response.code) desc = HTTP_STATUS_CODES[index].description gs.fatal( _( - "Download commit from <{url}>, return status code " - "{code}, {desc}".format( - url=url, - code=response.code, - desc=desc, - ), + "Download commit from <{url}>, return status code {code}, {desc}" + ).format( + url=url, + code=response.code, + desc=desc, ), ) if response_format not in response.getheader("Content-Type"): @@ -177,10 +176,10 @@ def download_git_commit(url, response_format, *args, **kwargs): _( "Wrong downloaded commit file format. " "Check url <{url}>. Allowed file format is " - "{response_format}.".format( - url=url, - response_format=response_format, - ), + "{response_format}." + ).format( + url=url, + response_format=response_format, ), ) return response @@ -190,16 +189,16 @@ def download_git_commit(url, response_format, *args, **kwargs): "The download of the commit from the GitHub API " "server wasn't successful, <{}>. Commit and commit " "date will not be included in the <{}> addon html manual " - "page.".format(err.msg, pgm) - ), + "page." + ).format(err.msg, pgm), ) except URLError: gs.warning( _( "Download file from <{url}>, failed. Check internet " "connection. Commit and commit date will not be included " - "in the <{pgm}> addon manual page.".format(url=url, pgm=pgm) - ), + "in the <{pgm}> addon manual page." + ).format(url=url, pgm=pgm), ) @@ -367,7 +366,7 @@ def has_src_code_git(src_dir, is_addon): if core module or addon source code has Git """ - actual_dir = os.getcwd() + actual_dir = Path.cwd() if is_addon: os.chdir(src_dir) else: @@ -407,15 +406,14 @@ def get_last_git_commit(src_dir, addon_path, is_addon): commit=process_result.stdout.decode(), src_dir=src_dir, ) - elif gs: + if gs: # Addons installation return get_git_commit_from_rest_api_for_addon_repo( addon_path=addon_path, src_dir=src_dir, ) # During GRASS GIS compilation from source code without Git - else: - return get_git_commit_from_file(src_dir=src_dir) + return get_git_commit_from_file(src_dir=src_dir) html_page_footer_pages_path = os.getenv("HTML_PAGE_FOOTER_PAGES_PATH") or "" @@ -850,10 +848,9 @@ def to_title(name): """Convert name of command class/family to form suitable for title""" if name == "raster3d": return "3D raster" - elif name == "postscript": + if name == "postscript": return "PostScript" - else: - return name.capitalize() + return name.capitalize() index_titles = {} diff --git a/vector/Makefile b/vector/Makefile index f195ce3aafb..7244ac59af5 100644 --- a/vector/Makefile +++ b/vector/Makefile @@ -102,7 +102,6 @@ SUBDIRS = \ v.out.ogr \ v.in.ogr \ v.external \ - v.in.dwg \ v.in.lidar \ v.external.out diff --git a/vector/v.cluster/main.c b/vector/v.cluster/main.c index c3f95e78778..49c7535beca 100644 --- a/vector/v.cluster/main.c +++ b/vector/v.cluster/main.c @@ -286,7 +286,6 @@ int main(int argc, char *argv[]) mean = sum / n; sd = sqrt(sumsq / n - mean * mean); - eps = mean + 1.644854 * sd; /* 90% CI */ eps = mean + 2.575829 * sd; /* 99% CI */ if (eps > max) @@ -493,7 +492,6 @@ int main(int argc, char *argv[]) mean = sum / n; sd = sqrt(sumsq / n - mean * mean); - eps = mean + 1.644854 * sd; /* 90% CI */ eps = mean + 2.575829 * sd; /* 99% CI */ if (eps > max) diff --git a/vector/v.colors/read_rgb.c b/vector/v.colors/read_rgb.c index 99aa054138d..c6e762ca0af 100644 --- a/vector/v.colors/read_rgb.c +++ b/vector/v.colors/read_rgb.c @@ -64,4 +64,5 @@ void rgb2colr(struct Map_info *Map, int layer, const char *rgb_column, G_warning(_("%d invalid RGB color values skipped"), nskipped); db_close_database_shutdown_driver(driver); + Vect_destroy_field_info(fi); } diff --git a/vector/v.colors/scan_attr.c b/vector/v.colors/scan_attr.c index 18c51635f81..e805cd74a7f 100644 --- a/vector/v.colors/scan_attr.c +++ b/vector/v.colors/scan_attr.c @@ -42,6 +42,8 @@ int scan_attr(struct Map_info *Map, int layer, const char *column_name, &cvarr); if (nrec < 1) { G_important_message(_("No data selected")); + Vect_destroy_field_info(fi); + db_close_database(driver); return 0; } @@ -100,6 +102,7 @@ int scan_attr(struct Map_info *Map, int layer, const char *column_name, } db_close_database(driver); + Vect_destroy_field_info(fi); return is_fp; } diff --git a/vector/v.external/list.c b/vector/v.external/list.c index 900aede55ab..6c94ea69deb 100644 --- a/vector/v.external/list.c +++ b/vector/v.external/list.c @@ -64,7 +64,8 @@ char **format_list(int *count, size_t *len) } /* order formats by name */ - qsort(list, *count, sizeof(char *), cmp); + if (list) + qsort(list, *count, sizeof(char *), cmp); #endif #if defined HAVE_POSTGRES && !defined HAVE_OGR list = G_realloc(list, ((*count) + 1) * sizeof(char *)); diff --git a/vector/v.generalize/displacement.c b/vector/v.generalize/displacement.c index bc7a3f15170..a4d599080e4 100644 --- a/vector/v.generalize/displacement.c +++ b/vector/v.generalize/displacement.c @@ -310,6 +310,8 @@ int snakes_displacement(struct Map_info *In, struct Map_info *Out, matrix_free(&fy); matrix_free(&dx_old); matrix_free(&dy_old); + Vect_destroy_cats_struct(Cats); + Vect_destroy_line_struct(Points); return 0; } diff --git a/vector/v.generalize/smoothing.c b/vector/v.generalize/smoothing.c index d5a817f8f2f..0b5d9a5e12f 100644 --- a/vector/v.generalize/smoothing.c +++ b/vector/v.generalize/smoothing.c @@ -422,6 +422,7 @@ int hermite(struct line_pnts *Points, double step, double angle_thresh, angle_thresh *= M_PI / 180.0; head.next = NULL; + head.p.x = head.p.y = head.p.z = 0.0; point = last = &head; if (!is_loop) { diff --git a/vector/v.in.dwg/Makefile b/vector/v.in.dwg/Makefile deleted file mode 100644 index c5c30c1dde7..00000000000 --- a/vector/v.in.dwg/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -MODULE_TOPDIR = ../.. - -PGM=v.in.dwg -ADINIT = $(ETC)/adinit.dat -ADINITSRC := $(shell echo $(OPENDWGINCPATH) | cut -b3- )/adinit/adinit.dat - -DEPENDENCIES = $(VECTORDEP) $(DBMIDEP) $(GISDEP) -LIBES = $(VECTORLIB) $(DBMILIB) $(GISLIB) $(OPENDWGLIBPATH) $(OPENDWGLIB) -EXTRA_INC = $(VECT_INC) $(OPENDWGINCPATH) -EXTRA_CFLAGS = $(VECT_CFLAGS) - -include $(MODULE_TOPDIR)/include/Make/Module.make - -ifneq ($(USE_OPENDWG),) -default: check - $(MAKE) cmd $(ADINIT) -endif - -check: -ifneq ($(strip $(MINGW)),) - cat WARNING -else - cat WARNING >/dev/tty -endif - @read IN ." diff --git a/vector/v.in.dwg/entity.c b/vector/v.in.dwg/entity.c deleted file mode 100644 index c70bc308fe0..00000000000 --- a/vector/v.in.dwg/entity.c +++ /dev/null @@ -1,540 +0,0 @@ -/* ************************************************************** - * - * MODULE: v.in.dwg - * - * AUTHOR(S): Radim Blazek - * - * PURPOSE: Import of DWG/DXF files - * - * COPYRIGHT: (C) 2001 by the GRASS Development Team - * - * This program is free software under the - * GNU General Public License (>=v2). - * Read the file COPYING that comes with GRASS - * for details. - * - * In addition, as a special exception, Radim Blazek gives permission - * to link the code of this program with the OpenDWG libraries (or with - * modified versions of the OpenDWG libraries that use the same license - * as OpenDWG libraries), and distribute linked combinations including the two. - * You must obey the GNU General Public License in all respects for all - * of the code used other than. If you modify this file, you may extend - * this exception to your version of the file, but you are not obligated - * to do so. If you do not wish to do so, delete this exception statement - * from your version. - * - * **************************************************************/ - -/* Documentation: - * http://www.opendwg.org - * -> OpenDWG Toolkit Reference - * - * Unsupported entities must be added in wrentity() - * - * TODO: 3rd dimension is not functional for CIRCLE and ARC - * -> required updated of transformation in INSERT - * (how to do that??) - */ - -#define AD_PROTOTYPES -#define AD_VM_PC - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ad2.h" -#include "global.h" - -#define exampleprintf printf -#define LOCPI M_PI - -char buf[1000]; -char buf2[1000]; - -void getEntTypeName(PAD_ENT_HDR adenhd, char *name) -{ - switch (adenhd->enttype) { - case AD_ENT_LINE: - strcpy(name, "LINE"); - break; - case AD_ENT_POINT: - strcpy(name, "POINT"); - break; - case AD_ENT_CIRCLE: - strcpy(name, "CIRCLE"); - break; - case AD_ENT_SHAPE: - strcpy(name, "SHAPE"); - break; - case AD_ENT_ELLIPSE: - strcpy(name, "ELLIPSE"); - break; - case AD_ENT_SPLINE: - strcpy(name, "SPLINE"); - break; - case AD_ENT_TEXT: - strcpy(name, "TEXT"); - break; - case AD_ENT_ARC: - strcpy(name, "ARC"); - break; - case AD_ENT_TRACE: - strcpy(name, "TRACE"); - break; - case AD_ENT_SOLID: - strcpy(name, "SOLID"); - break; - case AD_ENT_BLOCK: - strcpy(name, "BLOCK"); - break; - case AD_ENT_ENDBLK: - strcpy(name, "ENDBLK"); - break; - case AD_ENT_INSERT: - strcpy(name, "INSERT"); - break; - case AD_ENT_ATTDEF: - strcpy(name, "ATTDEF"); - break; - case AD_ENT_ATTRIB: - strcpy(name, "ATTRIB"); - break; - case AD_ENT_SEQEND: - strcpy(name, "SEQEND"); - break; - case AD_ENT_POLYLINE: - strcpy(name, "POLYLINE"); - break; - case AD_ENT_VERTEX: - strcpy(name, "VERTEX"); - break; - case AD_ENT_LINE3D: - strcpy(name, "3DLINE"); - break; - case AD_ENT_FACE3D: - strcpy(name, "3DFACE"); - break; - case AD_ENT_DIMENSION: - strcpy(name, "DIMENSION"); - break; - case AD_ENT_VIEWPORT: - strcpy(name, "VIEWPORT"); - break; - case AD_ENT_SOLID3D: - strcpy(name, "SOLID3D"); - break; - case AD_ENT_RAY: - strcpy(name, "RAY"); - break; - case AD_ENT_XLINE: - strcpy(name, "XLINE"); - break; - case AD_ENT_MTEXT: - strcpy(name, "MTEXT"); - break; - case AD_ENT_LEADER: - strcpy(name, "LEADER"); - break; - case AD_ENT_TOLERANCE: - strcpy(name, "TOLERANCE"); - break; - case AD_ENT_MLINE: - strcpy(name, "MLINE"); - break; - case AD_ENT_BODY: - strcpy(name, "BODY"); - break; - case AD_ENT_REGION: - strcpy(name, "REGION"); - break; - default: - if (adenhd->enttype == adOle2frameEnttype(dwghandle)) - strcpy(name, "OLE2FRAME"); - else if (adenhd->enttype == adLwplineEnttype(dwghandle)) - strcpy(name, "LWPOLYLINE"); - else if (adenhd->enttype == adHatchEnttype(dwghandle)) - strcpy(name, "HATCH"); - else if (adenhd->enttype == adImageEnttype(dwghandle)) - strcpy(name, "IMAGE"); - else if (adenhd->enttype == adArcAlignedTextEnttype(dwghandle)) - strcpy(name, "ArcAlignedText"); - else if (adenhd->enttype == adWipeoutEnttype(dwghandle)) - strcpy(name, "Wipeout"); - else if (adenhd->enttype == adRtextEnttype(dwghandle)) - strcpy(name, "Rtext"); - else { /* regular proxy */ - - G_debug(3, "adenhd->enttype: %d", adenhd->enttype); - strcpy(name, "Proxy"); - } - break; - } -} - -int write_line(PAD_ENT_HDR adenhd, int type, int level) -{ - int i, l; - double x, y, z, r, ang; - - adSeekLayer(dwghandle, adenhd->entlayerobjhandle, Layer); - - /* Transformation, go up through all levels of transformation */ - /* not sure what is the right order of transformation */ - for (l = level; l >= 0; l--) { - for (i = 0; i < Points->n_points; i++) { - /* scale */ - x = Points->x[i] * Trans[l].xscale; - y = Points->y[i] * Trans[l].yscale; - z = Points->z[i] * Trans[l].zscale; - /* rotate */ - r = sqrt(x * x + y * y); - ang = atan2(y, x) + Trans[l].rotang; - x = r * cos(ang); - y = r * sin(ang); - /* move */ - x += Trans[l].dx; - y += Trans[l].dy; - z += Trans[l].dz; - Points->x[i] = x; - Points->y[i] = y; - Points->z[i] = z; - } - } - - Vect_reset_cats(Cats); - Vect_cat_set(Cats, 1, cat); - Vect_write_line(&Map, type, Points, Cats); - - /* Cat */ - sprintf(buf, "insert into %s values ( %d", Fi->table, cat); - db_set_string(&sql, buf); - - /* Entity name */ - getEntTypeName(adenhd, buf2); - sprintf(buf, ", '%s'", buf2); - db_append_string(&sql, buf); - - /* Color */ - sprintf(buf, ", %d", adenhd->entcolor); - db_append_string(&sql, buf); - - /* Weight */ - sprintf(buf, ", %d", adenhd->lineweight); - db_append_string(&sql, buf); - - /* Layer name */ - if (!Layer->purgedflag && Layer->name != NULL) { - db_set_string(&str, Layer->name); - db_double_quote_string(&str); - sprintf(buf, ", '%s'", db_get_string(&str)); - } - else { - sprintf(buf, ", ''"); - } - db_append_string(&sql, buf); - - /* Block name */ - if (Block != NULL) { - db_set_string(&str, Block); - db_double_quote_string(&str); - } - else { - db_set_string(&str, ""); - } - sprintf(buf, ", '%s'", db_get_string(&str)); - db_append_string(&sql, buf); - - /* Text */ - if (Txt != NULL) { - db_set_string(&str, Txt); - db_double_quote_string(&str); - } - else { - db_set_string(&str, ""); - } - sprintf(buf, ", '%s'", db_get_string(&str)); - db_append_string(&sql, buf); - - db_append_string(&sql, ")"); - G_debug(3, db_get_string(&sql)); - - if (db_execute_immediate(driver, &sql) != DB_OK) { - db_close_database(driver); - db_shutdown_driver(driver); - G_fatal_error("Cannot insert new row: %s", db_get_string(&sql)); - } - - cat++; - return 0; -} - -/* Returns 1 if element has geometry and may be written to vector */ -int is_low_level(PAD_ENT_HDR adenhd) -{ - if (adenhd->enttype == AD_ENT_BLOCK || adenhd->enttype == AD_ENT_ENDBLK || - adenhd->enttype == AD_ENT_SEQEND || adenhd->enttype == AD_ENT_INSERT) { - return 0; - } - return 1; -} - -void wrentity(PAD_ENT_HDR adenhd, PAD_ENT aden, int level, AD_VMADDR entlist, - int circle_as_point) -{ - short ret; - PAD_BLOB_CTRL bcptr; - PAD_ENT_HDR adenhd2; - PAD_ENT aden2; - OdaLong il; - double tempdouble[3], tempbulge, tempwidth[3]; - double x, y, z, ang; - PAD_BLKH adblkh; - int layer_found = 1; - - if (is_low_level(adenhd)) - n_elements++; - - /* Check layer name */ - if (layers_opt->answers) { - int i = 0; - - adSeekLayer(dwghandle, adenhd->entlayerobjhandle, Layer); - - layer_found = 0; - if (!Layer->purgedflag) { - while (layers_opt->answers[i]) { - if (strcmp(Layer->name, layers_opt->answers[i]) == 0) { - layer_found = 1; - break; - } - i++; - } - } - - if ((!invert_flag->answer && !layer_found) || - (invert_flag->answer && layer_found)) { - if (is_low_level(adenhd)) - n_skipped++; - if (adenhd->enttype != AD_ENT_INSERT && - adenhd->enttype != AD_ENT_POLYLINE) - return; - } - } - - getEntTypeName(adenhd, buf); - G_debug(1, "Entity: %s", buf); - - Txt = NULL; - adenhd2 = (PAD_ENT_HDR)G_malloc(sizeof(AD_ENT_HDR)); - aden2 = (PAD_ENT)G_malloc(sizeof(AD_ENT)); - adblkh = (PAD_BLKH)G_malloc(sizeof(AD_BLKH)); - Vect_reset_line(Points); - - /* Check space for lower level */ - if (level + 1 == atrans) { - atrans += 10; - Trans = (TRANS *)G_realloc(Trans, atrans * sizeof(TRANS)); - } - - switch (adenhd->enttype) { - case AD_ENT_LINE: - Vect_append_point(Points, aden->line.pt0[0], aden->line.pt0[1], - aden->line.pt0[2]); - Vect_append_point(Points, aden->line.pt1[0], aden->line.pt1[1], - aden->line.pt1[2]); - write_line(adenhd, GV_LINE, level); - break; - - case AD_ENT_FACE3D: - Vect_append_point(Points, aden->face3d.pt0[0], aden->face3d.pt0[1], - aden->face3d.pt0[2]); - Vect_append_point(Points, aden->face3d.pt1[0], aden->face3d.pt1[1], - aden->face3d.pt1[2]); - Vect_append_point(Points, aden->face3d.pt2[0], aden->face3d.pt2[1], - aden->face3d.pt2[2]); - Vect_append_point(Points, aden->face3d.pt3[0], aden->face3d.pt3[1], - aden->face3d.pt3[2]); - write_line(adenhd, GV_FACE, level); - break; - - case AD_ENT_SOLID: - Vect_append_point(Points, aden->solid.pt0[0], aden->solid.pt0[1], - aden->solid.pt0[2]); - Vect_append_point(Points, aden->solid.pt1[0], aden->solid.pt1[1], - aden->solid.pt1[2]); - Vect_append_point(Points, aden->solid.pt2[0], aden->solid.pt2[1], - aden->solid.pt2[2]); - Vect_append_point(Points, aden->solid.pt3[0], aden->solid.pt3[1], - aden->solid.pt3[2]); - write_line(adenhd, GV_FACE, level); - break; - - case AD_ENT_TEXT: - Txt = aden->text.textstr; - Vect_append_point(Points, aden->text.pt0[0], aden->text.pt0[1], - aden->line.pt0[2]); - write_line(adenhd, GV_POINT, level); - break; - - case AD_ENT_POINT: - Vect_append_point(Points, aden->point.pt0[0], aden->point.pt0[1], - aden->line.pt0[2]); - write_line(adenhd, GV_POINT, level); - break; - - case AD_ENT_ARC: - for (ang = aden->arc.stang; ang < aden->arc.endang; - ang += 2 * LOCPI / 360) { - x = aden->arc.pt0[0] + aden->arc.radius * cos(ang); - y = aden->arc.pt0[1] + aden->arc.radius * sin(ang); - z = aden->arc.pt0[2]; - Vect_append_point(Points, x, y, z); - } - x = aden->arc.pt0[0] + aden->arc.radius * cos(aden->arc.endang); - y = aden->arc.pt0[1] + aden->arc.radius * sin(aden->arc.endang); - z = aden->arc.pt0[2]; - Vect_append_point(Points, x, y, z); - write_line(adenhd, GV_LINE, level); - break; - - case AD_ENT_CIRCLE: - if (circle_as_point) { - Vect_append_point(Points, aden->circle.pt0[0], aden->circle.pt0[1], - aden->circle.pt0[3]); - write_line(adenhd, GV_POINT, level); - } - else { - for (ang = 0; ang < 2 * LOCPI; ang += 2 * LOCPI / 360) { - x = aden->circle.pt0[0] + aden->circle.radius * cos(ang); - y = aden->circle.pt0[1] + aden->circle.radius * sin(ang); - z = aden->circle.pt0[3]; - Vect_append_point(Points, x, y, z); - } - Vect_append_point(Points, Points->x[0], Points->y[0], Points->z[0]); - write_line(adenhd, GV_LINE, level); - } - break; - - /* BLOCK starts block of entities but makes no transformation - is it - * right ? - * -> do nothing just warn for xref */ - case AD_ENT_BLOCK: - if (aden->block.xrefpath[0]) { - G_warning("External reference for block not supported.\n xref: %s", - aden->block.xrefpath); - } - Block = G_store(aden->block.name2); - break; - - case AD_ENT_ENDBLK: /* endblk - no data */ - G_free(Block); - Block = NULL; - break; - - case AD_ENT_INSERT: /* insert */ - /* get transformation */ - /* TODO: fix rotation for CIRCLE and ARC */ - G_debug(3, " x,y,z: %f, %f, %f", aden->insert.pt0[0], - aden->insert.pt0[1], aden->insert.pt0[2]); - G_debug(3, " xscale, yscale, zscale: %f, %f, %f", aden->insert.xscale, - aden->insert.yscale, aden->insert.zscale); - G_debug(3, " rotang: %f", aden->insert.rotang); - G_debug(3, " ncols, nrows: %d, %d", aden->insert.numcols, - aden->insert.numrows); - G_debug(3, " coldist, rowdist: %f, %f", aden->insert.coldist, - aden->insert.rowdist); - - /* write block entities */ - adSeekBlockheader(dwghandle, aden->insert.blockheaderobjhandle, adblkh); - if (!adblkh->purgedflag) { - adStartEntityGet(adblkh->entitylist); - while (1) { - ret = adGetEntity(adblkh->entitylist, adenhd2, aden2); - if (adenhd2->enttype == AD_ENT_ENDBLK) - break; - if (ret) { - /* Set transformation for lower level */ - Trans[level + 1].dx = aden->insert.pt0[0]; - Trans[level + 1].dy = aden->insert.pt0[1]; - Trans[level + 1].dz = aden->insert.pt0[2]; - Trans[level + 1].xscale = aden->insert.xscale; - Trans[level + 1].yscale = aden->insert.yscale; - Trans[level + 1].zscale = aden->insert.zscale; - Trans[level + 1].rotang = aden->insert.rotang; - wrentity(adenhd2, aden2, level + 1, adblkh->entitylist, - circle_as_point); - } - } - } - break; - - case AD_ENT_SEQEND: /* seqend */ - break; - - case AD_ENT_POLYLINE: - while (1) { - ret = adGetEntity(entlist, adenhd2, aden2); - if (ret != 1) { - G_warning("Cannot get entity: %d: %s.", adError(), - adErrorStr(adError())); - break; - } - - if (adenhd2->enttype == AD_ENT_SEQEND) - break; - if (adenhd2->enttype != AD_ENT_VERTEX) { - getEntTypeName(adenhd2, buf); - G_warning("Expected VERTEX got %s in POLYLINE -> skip", buf); - } - else { - Vect_append_point(Points, aden2->vertex.pt0[0], - aden2->vertex.pt0[1], aden2->vertex.pt0[2]); - } - }; - if ((!invert_flag->answer && layer_found) || - (invert_flag->answer && !layer_found)) - write_line(adenhd, GV_LINE, level); - break; - - default: - if (adenhd->enttype == adLwplineEnttype(dwghandle)) { - G_debug(3, "Npoints: %ld\n", aden->lwpline.numpoints); - bcptr = adStartBlobRead(aden->lwpline.ldblob); - for (il = 0; il < aden->lwpline.numpoints; il++) { - adReadBlob2Double(bcptr, tempdouble); - Vect_append_point(Points, tempdouble[0], tempdouble[1], - tempdouble[2]); - tempbulge = tempwidth[0] = tempwidth[1] = tempwidth[2] = 0.0; - if (aden->lwpline.flag & AD_LWPLINE_HAS_BULGES) { - adReadBlobDouble(bcptr, &tempbulge); - } - if (aden->lwpline.flag & AD_LWPLINE_HAS_WIDTHS) { - adReadBlob2Double(bcptr, tempwidth); - } - } - G_debug(3, "flag = %d", aden->lwpline.flag); - if (aden->lwpline.flag & AD_LWPLINE_IS_CLOSED) { - G_debug(3, " -> is closed"); - Vect_append_point(Points, Points->x[0], Points->y[0], - Points->z[0]); - } - write_line(adenhd, GV_LINE, level); - adEndBlobRead(bcptr); - } - else { - getEntTypeName(adenhd, buf); - G_warning("%s entity not supported", buf); - } - break; - - } /* end of switch */ - - G_free(aden2); - G_free(adenhd2); -} diff --git a/vector/v.in.dwg/global.h b/vector/v.in.dwg/global.h deleted file mode 100644 index 39e46f17856..00000000000 --- a/vector/v.in.dwg/global.h +++ /dev/null @@ -1,59 +0,0 @@ -/* ************************************************************** - * - * MODULE: v.in.dwg - * - * AUTHOR(S): Radim Blazek - * - * PURPOSE: Import of DWG/DXF files - * - * COPYRIGHT: (C) 2001 by the GRASS Development Team - * - * This program is free software under the - * GNU General Public License (>=v2). - * Read the file COPYING that comes with GRASS - * for details. - * - * In addition, as a special exception, Radim Blazek gives permission - * to link the code of this program with the OpenDWG libraries (or with - * modified versions of the OpenDWG libraries that use the same license - * as OpenDWG libraries), and distribute linked combinations including the two. - * You must obey the GNU General Public License in all respects for all - * of the code used other than. If you modify this file, you may extend - * this exception to your version of the file, but you are not obligated - * to do so. If you do not wish to do so, delete this exception statement - * from your version. - * - * **************************************************************/ - -/* transformation, first level is 0 ( called from main ) and transformation - * for this level is 0,0,0, 1,1,1, 0 so that no transformation is done on first - * level (not effective but better readable?) */ -typedef struct { - double dx, dy, dz; - double xscale, yscale, zscale; - double rotang; -} TRANS; - -extern int cat; -extern int - n_elements; /* number of processed elements (only low level elements) */ -extern int - n_skipped; /* number of skipped low level elements (different layer name) */ -extern struct Map_info Map; -extern dbDriver *driver; -extern dbString sql; -extern dbString str; -extern struct line_pnts *Points; -extern struct line_cats *Cats; -extern PAD_LAY Layer; -extern char *Txt; -extern char *Block; -extern struct field_info *Fi; -extern AD_DB_HANDLE dwghandle; -extern TRANS *Trans; /* transformation */ -extern int atrans; /* number of allocated levels */ -extern struct Option *layers_opt; -extern struct Flag *invert_flag; - -void wrentity(PAD_ENT_HDR adenhd, PAD_ENT aden, int level, AD_VMADDR entlist, - int circle_as_point); diff --git a/vector/v.in.dwg/main.c b/vector/v.in.dwg/main.c deleted file mode 100644 index e21602ecb90..00000000000 --- a/vector/v.in.dwg/main.c +++ /dev/null @@ -1,291 +0,0 @@ -/* ************************************************************** - * - * MODULE: v.in.dwg - * - * AUTHOR(S): Radim Blazek - * - * PURPOSE: Import of DWG/DXF files - * - * COPYRIGHT: (C) 2001-2008 by the GRASS Development Team - * - * This program is free software under the - * GNU General Public License (>=v2). - * Read the file COPYING that comes with GRASS - * for details. - * - * In addition, as a special exception, Radim Blazek gives permission - * to link the code of this program with the OpenDWG libraries (or with - * modified versions of the OpenDWG libraries that use the same license - * as OpenDWG libraries), and distribute linked combinations including the two. - * You must obey the GNU General Public License in all respects for all - * of the code used other than. If you modify this file, you may extend - * this exception to your version of the file, but you are not obligated - * to do so. If you do not wish to do so, delete this exception statement - * from your version. - * - * **************************************************************/ -#define AD_PROTOTYPES -#define AD_VM_PC -#define OD_GENERIC_READ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ad2.h" -#include "io/odio.h" -#include "global.h" - -int cat; -int n_elements; /* number of processed elements (only low level elements) */ -int n_skipped; /* number of skipped low level elements (different layer name) */ -struct Map_info Map; -dbDriver *driver; -dbString sql; -dbString str; -struct line_pnts *Points; -struct line_cats *Cats; -PAD_LAY Layer; -char *Txt; -char *Block; -struct field_info *Fi; -AD_DB_HANDLE dwghandle; -TRANS *Trans; /* transformation */ -int atrans; /* number of allocated levels */ -struct Option *layers_opt; -struct Flag *invert_flag; - -int main(int argc, char *argv[]) -{ - struct GModule *module; - struct Option *out_opt, *in_opt; - struct Flag *z_flag, *circle_flag, *l_flag, *int_flag; - char buf[2000]; - - /* DWG */ - char path[2000]; - short initerror, entset, retval; - AD_OBJHANDLE pspace, mspace; - PAD_ENT_HDR adenhd; - PAD_ENT aden; - AD_VMADDR entlist; - - G_gisinit(argv[0]); - - module = G_define_module(); - G_add_keyword(_("vector")); - G_add_keyword(_("import")); - module->description = _("Converts DWG/DXF to GRASS vector map"); - - in_opt = G_define_standard_option(G_OPT_F_INPUT); - in_opt->description = _("Name of DWG or DXF file"); - - out_opt = G_define_standard_option(G_OPT_V_OUTPUT); - out_opt->required = YES; - - layers_opt = G_define_option(); - layers_opt->key = "layers"; - layers_opt->type = TYPE_STRING; - layers_opt->required = NO; - layers_opt->multiple = YES; - layers_opt->description = _("List of layers to import"); - - invert_flag = G_define_flag(); - invert_flag->key = 'i'; - invert_flag->description = - _("Invert selection by layers (don't import layers in list)"); - - z_flag = G_define_flag(); - z_flag->key = 'z'; - z_flag->description = _("Create 3D vector map"); - - circle_flag = G_define_flag(); - circle_flag->key = 'c'; - circle_flag->description = _("Write circles as points (centre)"); - - l_flag = G_define_flag(); - l_flag->key = 'l'; - l_flag->description = _("List available layers and exit"); - - int_flag = G_define_flag(); - int_flag->key = 'n'; - int_flag->description = _("Use numeric type for attribute \"layer\""); - - if (G_parser(argc, argv)) - exit(EXIT_FAILURE); - - db_init_string(&sql); - db_init_string(&str); - adenhd = (PAD_ENT_HDR)G_malloc(sizeof(AD_ENT_HDR)); - aden = (PAD_ENT)G_malloc(sizeof(AD_ENT)); - Layer = (PAD_LAY)G_malloc(sizeof(AD_LAY)); - Points = Vect_new_line_struct(); - Cats = Vect_new_cats_struct(); - Block = NULL; - - atrans = 20; /* nested, recursive levels */ - Trans = (TRANS *)G_malloc(atrans * sizeof(TRANS)); - - /* Init OpenDWG */ - sprintf(path, "%s/etc/adinit.dat", G_gisbase()); - if (!adInitAd2(path, &initerror)) { - sprintf(buf, _("Unable to initialize OpenDWG Toolkit, error: %d: %s."), - initerror, adErrorStr(initerror)); - if (initerror == AD_UNABLE_TO_OPEN_INIT_FILE) - sprintf(buf, _("%s Cannot open %s"), buf, path); - G_fatal_error(buf); - } - adSetupDwgRead(); - adSetupDxfRead(); - - /* Open input file */ - if ((dwghandle = adLoadFile(in_opt->answer, AD_PRELOAD_ALL, 1)) == NULL) { - G_fatal_error(_("Unable to open input file <%s>. Error %d: %s"), - in_opt->answer, adError(), adErrorStr(adError())); - } - - if (l_flag->answer) { /* List layers */ - PAD_TB adtb; - AD_DWGHDR adhd; - int i; - char on, frozen, vpfrozen, locked; - - adtb = (PAD_TB)G_malloc(sizeof(AD_TB)); - - G_debug(2, "%d layers", (int)adNumLayers(dwghandle)); - adReadHeaderBlock(dwghandle, &adhd); - adStartLayerGet(dwghandle); - - fprintf(stdout, "%d layers:\n", (int)adNumLayers(dwghandle)); - for (i = 0; i < (int)adNumLayers(dwghandle); i++) { - adGetLayer(dwghandle, &(adtb->lay)); - if (!adtb->lay.purgedflag) { - fprintf(stdout, "%s COLOR %d, ", adtb->lay.name, - adtb->lay.color); - } - adGetLayerState(dwghandle, adtb->lay.objhandle, &on, &frozen, - &vpfrozen, &locked); - if (on) - fprintf(stdout, "ON, "); - else - fprintf(stdout, "OFF, "); - if (frozen) - fprintf(stdout, "FROZEN, "); - else - fprintf(stdout, "THAWED, "); - if (vpfrozen) - fprintf(stdout, "VPFROZEN, "); - else - fprintf(stdout, "VPTHAWED, "); - if (locked) - fprintf(stdout, "LOCKED\n"); - else - fprintf(stdout, "UNLOCKED\n"); - } - adCloseFile(dwghandle); - adCloseAd2(); - exit(EXIT_SUCCESS); - } - - /* open output vector */ - if (Vect_open_new(&Map, out_opt->answer, z_flag->answer) < 0) - G_fatal_error(_("Unable to create vector map <%s>"), out_opt->answer); - - Vect_hist_command(&Map); - - /* Add DB link */ - Fi = Vect_default_field_info(&Map, 1, NULL, GV_1TABLE); - Vect_map_add_dblink(&Map, 1, NULL, Fi->table, GV_KEY_COLUMN, Fi->database, - Fi->driver); - - driver = db_start_driver_open_database(Fi->driver, - Vect_subst_var(Fi->database, &Map)); - if (driver == NULL) { - G_fatal_error(_("Unable to open database <%s> by driver <%s>"), - Vect_subst_var(Fi->database, &Map), Fi->driver); - } - db_set_error_handler_driver(driver); - - db_begin_transaction(driver); - - /* Create table */ - if (int_flag->answer) { /* List layers */ - sprintf(buf, - "create table %s ( cat integer, entity_name varchar(20), color " - "int, weight int, " - "layer real, block varchar(100), txt varchar(100) )", - Fi->table); - } - else { - sprintf(buf, - "create table %s ( cat integer, entity_name varchar(20), color " - "int, weight int, " - "layer varchar(100), block varchar(100), txt varchar(100) )", - Fi->table); - } - db_set_string(&sql, buf); - G_debug(3, db_get_string(&sql)); - - if (db_execute_immediate(driver, &sql) != DB_OK) { - db_close_database(driver); - db_shutdown_driver(driver); - G_fatal_error(_("Unable to create table: '%s'"), db_get_string(&sql)); - } - - if (db_create_index2(driver, Fi->table, GV_KEY_COLUMN) != DB_OK) - G_warning(_("Unable to create index for table <%s>, key <%s>"), - Fi->table, GV_KEY_COLUMN); - - if (db_grant_on_table(driver, Fi->table, DB_PRIV_SELECT, - DB_GROUP | DB_PUBLIC) != DB_OK) - G_fatal_error(_("Unable to grant privileges on table <%s>"), Fi->table); - - cat = 1; - n_elements = n_skipped = 0; - /* Write each entity. Some entities may be composed by other entities (like - * INSERT or BLOCK) */ - /* Set transformation for first (index 0) level */ - Trans[0].dx = Trans[0].dy = Trans[0].dz = 0; - Trans[0].xscale = Trans[0].yscale = Trans[0].zscale = 1; - Trans[0].rotang = 0; - if (adGetBlockHandle(dwghandle, pspace, AD_PAPERSPACE_HANDLE)) { - entlist = adEntityList(dwghandle, pspace); - adStartEntityGet(entlist); - for (entset = 0; entset < 2; entset++) { - do { - if (!(retval = adGetEntity(entlist, adenhd, aden))) - continue; - wrentity(adenhd, aden, 0, entlist, circle_flag->answer); - } while (retval == 1); - if (entset == 0) { - if (adGetBlockHandle(dwghandle, mspace, AD_MODELSPACE_HANDLE)) { - entlist = adEntityList(dwghandle, mspace); - adStartEntityGet(entlist); - } - } - } - } - - db_commit_transaction(driver); - db_close_database_shutdown_driver(driver); - - adCloseFile(dwghandle); - adCloseAd2(); - - Vect_build(&Map, stderr); - Vect_close(&Map); - - if (n_skipped > 0) - G_message(_("%d elements skipped (layer name was not in list)"), - n_skipped); - - G_done_msg(_("%d elements processed"), n_elements); - - exit(EXIT_SUCCESS); -} diff --git a/vector/v.in.dwg/v.in.dwg.html b/vector/v.in.dwg/v.in.dwg.html deleted file mode 100644 index 60f00966f9d..00000000000 --- a/vector/v.in.dwg/v.in.dwg.html +++ /dev/null @@ -1,32 +0,0 @@ -

    DESCRIPTION

    - -v.in.dwg imports DWG/DXF file into GRASS. - -

    EXAMPLE

    - -
    -v.in.dwg input=map.dwg output=map
    -
    - -

    NOTES

    - -v.in.dwg requires OpenDWG toolkit. To get this toolkit you must become at -least "Associate Member" of OpenDWG Alliance (http://www.opendesign.com/). -

    The toolkit, for example ad27linx.tar, unpack in a directory -(e.g. /home/usr1/opendwg27) and use the related configure options -to tell GRASS about it: - -

    -   ./configure \
    -   ... \
    -   --with-opendwg \
    -   --with-opendwg-includes=/home/usr1/opendwg27 \
    -   --with-opendwg-libs=/home/usr1/opendwg27
    -
    - -Then you can compile this module. -

    Not all entity types are supported (warning printed). - -

    AUTHOR

    - -Radim Blazek, ITC-Irst, Trento, Italy diff --git a/vector/v.kernel/main.c b/vector/v.kernel/main.c index 96198a4d8f7..c1e7f77a36a 100644 --- a/vector/v.kernel/main.c +++ b/vector/v.kernel/main.c @@ -769,7 +769,9 @@ double compute_all_net_distances(struct Map_info *In, struct Map_info *Net, G_debug(3, " kk = %d", kk); } } - + Vect_destroy_line_struct(APoints); + Vect_destroy_line_struct(BPoints); + Vect_destroy_boxlist(List); return (kk); } diff --git a/vector/v.net.timetable/main.c b/vector/v.net.timetable/main.c index 5fb382009bb..424d8a851bd 100644 --- a/vector/v.net.timetable/main.c +++ b/vector/v.net.timetable/main.c @@ -176,9 +176,7 @@ void write_subroute(struct segment *seg, struct line_pnts *line, int line_id) struct line_cats *Cats; struct ilist *list; - Points = Vect_new_line_struct(); Cats = Vect_new_cats_struct(); - list = Vect_new_list(); r = seg->route; Vect_cat_set(Cats, 2, line_id); @@ -188,6 +186,9 @@ void write_subroute(struct segment *seg, struct line_pnts *line, int line_id) return; } + Points = Vect_new_line_struct(); + list = Vect_new_list(); + for (i = 0; i < nnodes; i++) edges[i] = 0; for (i = 0; i < lines[r]->n_values; i++) diff --git a/vector/v.out.lidar/testsuite/test_v_out_lidar.py b/vector/v.out.lidar/testsuite/test_v_out_lidar.py index 9be4f57d3b6..613cb14b61a 100644 --- a/vector/v.out.lidar/testsuite/test_v_out_lidar.py +++ b/vector/v.out.lidar/testsuite/test_v_out_lidar.py @@ -12,6 +12,7 @@ import os from grass.gunittest.case import TestCase from grass.gunittest.main import test +from grass.gunittest.utils import xfail_windows class BasicTest(TestCase): @@ -60,6 +61,7 @@ def test_module_runs_output_created(self): self.assertModule("v.out.lidar", input=self.vector_points, output=self.las_file) self.assertFileExists(self.las_file) + @xfail_windows def test_output_identical(self): """Test to see if the standard outputs are created diff --git a/vector/v.out.ogr/list.c b/vector/v.out.ogr/list.c index 0df74cf5dac..2b80111de3e 100644 --- a/vector/v.out.ogr/list.c +++ b/vector/v.out.ogr/list.c @@ -43,7 +43,8 @@ char *OGR_list_write_drivers(void) len += strlen(buf) + 1; /* + ',' */ } - qsort(list, count, sizeof(char *), cmp); + if (list) + qsort(list, count, sizeof(char *), cmp); if (len > 0) { ret = G_malloc((len + 1) * sizeof(char)); /* \0 */ diff --git a/vector/v.out.svg/main.c b/vector/v.out.svg/main.c index 4c99d148d04..4d29f845b29 100644 --- a/vector/v.out.svg/main.c +++ b/vector/v.out.svg/main.c @@ -25,7 +25,7 @@ #define SVG_NS "http://www.w3.org/2000/svg" #define XLINK_NS "http://www.w3.org/1999/xlink" -#define GRASS_NS "http:/grass.itc.it/2006/gg" +#define GRASS_NS "http://grass.itc.it/2006/gg" #define RADIUS_SCALE .003 #define WIDTH_SCALE .001 #define G_Areas "G_Areas" diff --git a/vector/v.overlay/v.overlay.html b/vector/v.overlay/v.overlay.html index 2b2a35be8c8..0077f2915f5 100644 --- a/vector/v.overlay/v.overlay.html +++ b/vector/v.overlay/v.overlay.html @@ -97,7 +97,7 @@

    AND operator

    v.overlay with AND operator
    -Figure: v.overlay with AND operator (selected polygons in grey color) +Figure: v.overlay with AND operator (selected polygons in yellow color)

    OR operator

    @@ -113,7 +113,7 @@

    OR operator

    v.overlay with OR operator
    -Figure: v.overlay with OR operator (selected polygons in grey color) +Figure: v.overlay with OR operator (selected polygons in yellow color)

    XOR operator

    @@ -129,7 +129,7 @@

    XOR operator

    v.overlay with XOR operator
    -Figure: v.overlay with XOR operator (selected polygons in grey color) +Figure: v.overlay with XOR operator (selected polygons in yellow color)

    NOT operator

    @@ -145,7 +145,7 @@

    NOT operator

    v.overlay with NOT operator
    -Figure: v.overlay with NOT operator (selected polygon in grey color) +Figure: v.overlay with NOT operator (selected polygon in yellow color)

    Overlay operations: AND, OR, NOT, XOR

    diff --git a/vector/v.overlay/v_overlay_op_and.png b/vector/v.overlay/v_overlay_op_and.png index 3d4bb3a07ff..c545f2140ad 100644 Binary files a/vector/v.overlay/v_overlay_op_and.png and b/vector/v.overlay/v_overlay_op_and.png differ diff --git a/vector/v.overlay/v_overlay_op_not.png b/vector/v.overlay/v_overlay_op_not.png index ac7eb441bbc..2c903f22d60 100644 Binary files a/vector/v.overlay/v_overlay_op_not.png and b/vector/v.overlay/v_overlay_op_not.png differ diff --git a/vector/v.overlay/v_overlay_op_or.png b/vector/v.overlay/v_overlay_op_or.png index c19bd32ce9f..bbde7b06eb1 100644 Binary files a/vector/v.overlay/v_overlay_op_or.png and b/vector/v.overlay/v_overlay_op_or.png differ diff --git a/vector/v.overlay/v_overlay_op_xor.png b/vector/v.overlay/v_overlay_op_xor.png index 446624f36ec..bf5bd5b8e45 100644 Binary files a/vector/v.overlay/v_overlay_op_xor.png and b/vector/v.overlay/v_overlay_op_xor.png differ diff --git a/vector/v.reclass/reclass.c b/vector/v.reclass/reclass.c index 5af40e5473e..4300f4216ff 100644 --- a/vector/v.reclass/reclass.c +++ b/vector/v.reclass/reclass.c @@ -79,6 +79,9 @@ int reclass(struct Map_info *In, struct Map_info *Out, int type, int field, G_warning("For %d elements requested negative category (ignored, no " "category in output)", negative); + Vect_destroy_cats_struct(Cats); + Vect_destroy_cats_struct(NewCats); + Vect_destroy_line_struct(Points); return (rclelem); } diff --git a/vector/v.rectify/main.c b/vector/v.rectify/main.c index b02630c88ae..86999d6286d 100644 --- a/vector/v.rectify/main.c +++ b/vector/v.rectify/main.c @@ -126,7 +126,9 @@ int main(int argc, char *argv[]) if (grp->answer) { G_strip(grp->answer); - strcpy(group, grp->answer); + if (G_strlcpy(group, grp->answer, sizeof(group)) >= sizeof(group)) { + G_fatal_error(_("Group name <%s> is too long"), grp->answer); + } } else group[0] = '\0'; diff --git a/vector/v.select/testsuite/test_v_select.py b/vector/v.select/testsuite/test_v_select.py index c74cdb53761..b8564505a6a 100644 --- a/vector/v.select/testsuite/test_v_select.py +++ b/vector/v.select/testsuite/test_v_select.py @@ -13,22 +13,9 @@ class TestRasterReport(TestCase): - binput = "bridges" + binput = "zipcodes" ainput = "geology" output = "testvselect" - overlap = "geonames_wake" - disjoint = "schools_wake" - equals = "streets_wake" - touches = "zipcodes_wake" - within = "geonames_wake" - - @classmethod - def setUpClass(cls): - cls.use_temp_region() - - @classmethod - def tearDownClass(cls): - cls.del_temp_region() def tearDown(cls): cls.runModule("g.remove", type="vector", flags="f", name=cls.output) @@ -42,8 +29,8 @@ def test_opo(self): output=self.output, operator="overlap", ) - topology = {"points": 1088, "lines": 0, "areas": 0} - self.assertVectorFitsTopoInfo(self.overlap, topology) + topology = {"areas": 97} + self.assertVectorFitsTopoInfo(self.output, topology) def test_opd(self): """Testign operator disjoint""" @@ -54,8 +41,8 @@ def test_opd(self): output=self.output, operator="disjoint", ) - topology = {"points": 167, "lines": 0, "areas": 0} - self.assertVectorFitsTopoInfo(self.disjoint, topology) + topology = {"areas": 1770} + self.assertVectorFitsTopoInfo(self.output, topology) def test_ope(self): """Testing operator equals""" @@ -66,8 +53,7 @@ def test_ope(self): output=self.output, operator="equals", ) - topology = {"points": 0, "lines": 49746, "areas": 0} - self.assertVectorFitsTopoInfo(self.equals, topology) + self.assertVectorDoesNotExist(self.output) def test_opt(self): """Testing operator touches""" @@ -78,8 +64,7 @@ def test_opt(self): output=self.output, operator="touches", ) - topology = {"points": 0, "lines": 0, "areas": 48} - self.assertVectorFitsTopoInfo(self.touches, topology) + self.assertVectorDoesNotExist(self.output) def test_opw(self): """Testing operator within""" @@ -90,8 +75,8 @@ def test_opw(self): output=self.output, operator="within", ) - topology = {"points": 1088, "lines": 0, "areas": 0} - self.assertVectorFitsTopoInfo(self.within, topology) + topology = {"areas": 17} + self.assertVectorFitsTopoInfo(self.output, topology) if __name__ == "__main__": diff --git a/vector/v.surf.rst/Makefile b/vector/v.surf.rst/Makefile index 3b5d8eca836..414ebbd85a0 100644 --- a/vector/v.surf.rst/Makefile +++ b/vector/v.surf.rst/Makefile @@ -4,9 +4,9 @@ PGM=v.surf.rst EXTRA_CLEAN_DIRS=doxygenhtml -LIBES = $(INTERPFLLIB) $(QTREELIB) $(INTERPDATALIB) $(GMATHLIB) $(VECTORLIB) $(DBMILIB) $(GISLIB) $(MATHLIB) +LIBES = $(INTERPFLLIB) $(QTREELIB) $(INTERPDATALIB) $(GMATHLIB) $(RASTERLIB) $(VECTORLIB) $(DBMILIB) $(GISLIB) $(MATHLIB) EXTRA_LIBS = $(OPENMP_LIBPATH) $(OPENMP_LIB) -DEPENDENCIES = $(INTERPFLDEP) $(QTREEDEP) $(INTERPDATADEP) $(GMATHDEP) $(VECTORDEP) $(DBMIDEP) $(GISDEP) +DEPENDENCIES = $(INTERPFLDEP) $(QTREEDEP) $(INTERPDATADEP) $(GMATHDEP) $(RASTERDEP) $(VECTORDEP) $(DBMIDEP) $(GISDEP) EXTRA_INC = $(VECT_INC) $(OPENMP_INCPATH) EXTRA_CFLAGS = $(VECT_CFLAGS) $(OPENMP_CFLAGS) diff --git a/vector/v.surf.rst/main.c b/vector/v.surf.rst/main.c index c4581737eed..7b42e269d0f 100644 --- a/vector/v.surf.rst/main.c +++ b/vector/v.surf.rst/main.c @@ -33,6 +33,7 @@ #include #include +#include #include #include #include @@ -419,8 +420,8 @@ int main(int argc, char *argv[]) G_warning(_("GRASS GIS is not compiled with OpenMP support, parallel " "computation is disabled.")); #endif - if (threads > 1 && G_find_raster("MASK", G_mapset()) != NULL) { - G_warning(_("Parallel processing disabled due to active MASK.")); + if (threads > 1 && Rast_mask_is_present()) { + G_warning(_("Parallel processing disabled due to active mask.")); threads = 1; } if (devi) { diff --git a/vector/v.to.3d/trans2.c b/vector/v.to.3d/trans2.c index 1680d950117..c4bde9b3888 100644 --- a/vector/v.to.3d/trans2.c +++ b/vector/v.to.3d/trans2.c @@ -73,6 +73,7 @@ void trans2d(struct Map_info *In, struct Map_info *Out, int type, double height, G_debug(3, "%d records selected", cvarr.n_values); db_close_database_shutdown_driver(driver); + Vect_destroy_field_info(Fi); } G_message(_("Transforming features...")); diff --git a/vector/v.to.db/areas.c b/vector/v.to.db/areas.c index 0977890276e..232cc4894d6 100644 --- a/vector/v.to.db/areas.c +++ b/vector/v.to.db/areas.c @@ -2,6 +2,7 @@ #include #include #include +#include #include "global.h" @@ -111,5 +112,6 @@ int read_areas(struct Map_info *Map) G_percent(area_num, nareas, 2); } + Vect_destroy_cats_struct(Cats); return 0; } diff --git a/vector/v.to.db/update.c b/vector/v.to.db/update.c index dd63ef78d35..972fd6be93e 100644 --- a/vector/v.to.db/update.c +++ b/vector/v.to.db/update.c @@ -3,6 +3,7 @@ #include #include #include +#include #include "global.h" static int srch(const void *, const void *); @@ -297,6 +298,8 @@ int update(struct Map_info *Map) db_close_database_shutdown_driver(driver); db_free_string(&stmt); + Vect_destroy_field_info(Fi); + Vect_destroy_field_info(qFi); return 0; } diff --git a/vector/v.transform/main.c b/vector/v.transform/main.c index 400cd3ded91..06a7d105881 100644 --- a/vector/v.transform/main.c +++ b/vector/v.transform/main.c @@ -188,8 +188,17 @@ int main(int argc, char *argv[]) if (G_parser(argc, argv)) exit(EXIT_FAILURE); - strcpy(Current.name, vold->answer); - strcpy(Trans.name, vnew->answer); + if (G_strlcpy(Current.name, vold->answer, sizeof(Current.name)) >= + sizeof(Current.name)) { + G_fatal_error(_("Input vector map name <%s> is too long"), + vold->answer); + } + + if (G_strlcpy(Trans.name, vnew->answer, sizeof(Trans.name)) >= + sizeof(Trans.name)) { + G_fatal_error(_("Output vector map name <%s> is too long"), + vnew->answer); + } Vect_check_input_output_name(vold->answer, vnew->answer, G_FATAL_EXIT); diff --git a/vector/v.type/v.type.html b/vector/v.type/v.type.html index 8e6d5806db8..124f8f39fe0 100644 --- a/vector/v.type/v.type.html +++ b/vector/v.type/v.type.html @@ -2,6 +2,27 @@

    DESCRIPTION

    v.type changes the type of geometry primitives. +

    +The following vector object types are defined in GRASS GIS: + +

      +
    • point: a point;
    • +
    • line: a directed sequence of connected vertices with two endpoints called nodes;
    • +
    • boundary: the border line describing an area;
    • +
    • centroid: a point within a closed ring of boundaries;
    • +
    • area: the topological composition of a closed ring of boundaries and a centroid;
    • +
    • face: a 3D area;
    • +
    • kernel: a 3D centroid in a volume (not yet implemented);
    • +
    • volume: a 3D corpus, the topological composition of faces and kernel (not yet implemented).
    • +
    +

    +Lines and boundaries can be composed of multiple vertices. +

    +Area topology also holds information about isles. These isles are located +within that area, not touching the boundaries of the outer area. Isles +are holes inside the area, and can consist of one or more areas. They are +used internally to maintain correct topology for areas. +

    EXAMPLES

    Convert lines to area boundaries
    diff --git a/vector/v.univar/testsuite/test_v_univar.py b/vector/v.univar/testsuite/test_v_univar.py index 766871d951c..e5fc2685cac 100644 --- a/vector/v.univar/testsuite/test_v_univar.py +++ b/vector/v.univar/testsuite/test_v_univar.py @@ -15,9 +15,11 @@ from grass.gunittest.case import TestCase from grass.gunittest.main import test from grass.gunittest.gmodules import SimpleModule +from grass.gunittest.utils import xfail_windows class TestProfiling(TestCase): + @xfail_windows def test_flagg(self): """Testing flag g with map lakes""" output_str = """n=15279 @@ -40,6 +42,7 @@ def test_flagg(self): v_univar.run() self.assertLooksLike(actual=v_univar.outputs.stdout, reference=output_str) + @xfail_windows def test_flage(self): """Testing flag e with map geology""" output_str = """number of features with non NULL attribute: 1832 @@ -68,6 +71,7 @@ def test_flage(self): v_univar.run() self.assertLooksLike(actual=v_univar.outputs.stdout, reference=output_str) + @xfail_windows def test_flagw(self): """Testing flag w with map lakes""" output_str = """number of features with non NULL attribute: 15279 @@ -83,6 +87,7 @@ def test_flagw(self): v_univar.run() self.assertLooksLike(actual=v_univar.outputs.stdout, reference=output_str) + @xfail_windows def test_flagd(self): """Testing flag d with map hospitals""" univar_string = """number of primitives: 160 diff --git a/vector/v.vol.rst/user1.c b/vector/v.vol.rst/user1.c index f47324dff36..6a1c2f441e6 100644 --- a/vector/v.vol.rst/user1.c +++ b/vector/v.vol.rst/user1.c @@ -220,6 +220,7 @@ int INPUT(struct Map_info *In, char *column, char *scol, char *wheresql) if (a < 0) { G_warning(_("Can't insert %lf,%lf,%lf,%lf,%lf a=%d"), x, y, z, w, sm, a); + Vect_destroy_field_info(Fi); return -1; } @@ -322,6 +323,7 @@ int INPUT(struct Map_info *In, char *column, char *scol, char *wheresql) } else { fprintf(stderr, "ERROR: zero points in the given region!\n"); + Vect_destroy_field_info(Fi); return -1; } } @@ -332,6 +334,7 @@ int INPUT(struct Map_info *In, char *column, char *scol, char *wheresql) KMIN, KMAX); fprintf(stderr, "for smooth connection of segments, npmin > segmax " "(see manual) \n"); + Vect_destroy_field_info(Fi); return -1; } @@ -382,6 +385,7 @@ int INPUT(struct Map_info *In, char *column, char *scol, char *wheresql) } G_message(_("Bitmap mask created")); } + Vect_destroy_field_info(Fi); return 1; } diff --git a/vector/v.vol.rst/user2.c b/vector/v.vol.rst/user2.c index 64f7b4a67f2..49a36d39175 100644 --- a/vector/v.vol.rst/user2.c +++ b/vector/v.vol.rst/user2.c @@ -92,6 +92,7 @@ int interp_call(struct octtree *root, struct octtree *tree) int skip_index, segtest; double xx, yy, zz /*, ww */; + skip_point.x = skip_point.y = skip_point.z = skip_point.w = 0.0; if (tree == NULL) return -1; if (tree->data == NULL)
    FailedPercent successful