text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
import math
import time
from typing import Optional
from tqdm import tqdm as tqdm
"""
Build a super dumb iterator wrapper which then returns a progress, this should be kinda splitted
first we need an object which remains alive the whole time where the logic and the variables are set to know
where the progress should ... | danihae/bio-image-unet | bio_image_unet/progress/progressnotifier.py | .py | 44f8eb09a21aa3ba | 7.42 | 6 |
import os
import subprocess
try:
subprocess.call(["md5sum", "--help"], stdout=subprocess.DEVNULL)
except FileNotFoundError:
raise Exception # md5sum not found. Are you using Linux?
def md5sum(filename):
"""
returns the md5sum of a file, along with its filename, e.g.:
0df61fe4ddf4455ba4d4e3c15abfabe2 predic... | danihae/bio-image-unet | bio_image_unet/siam_unet/helpers/__md5sum__.py | .py | e2c4db7d666e8ab6 | 7.42 | 6 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import math
def create_pixel_value_histogram(input_tifs, frames_per_hist=100, bin_width=8):
"""Creates a histogram for the pixel values in a tif file
Args:
input_tifs (str path to .tif files): input
frames_per_hist (int, optional): number of frames t... | danihae/bio-image-unet | bio_image_unet/siam_unet/helpers/create_pixel_value_histogram.py | .py | d6aebf820e32905b | 7.42 | 6 |
import cv2 # type: ignore
import numpy as np
def extract_frame_of_movie(tiff_movie, frame_number, output_file):
"""Extract a certain frame of tiff_movie, and write it into a separate file. Used for testing find_frame_of_image
Args:
tiff_movie (str): path to input
frame_number (int): which frame to extract
Rai... | danihae/bio-image-unet | bio_image_unet/siam_unet/helpers/extract_frame_of_movie.py | .py | 98dc8498007cd157 | 7.42 | 6 |
import cv2 # type: ignore
import numpy as np
import time
import tifffile
from tifffile import TiffFile
import os
def find_frame_of_image(query_image, search_space=[], save_machine_readable_output=True, machine_readable_output_filename='search_result_mr.txt'):
"""Finds the frame number of query_image within search_... | danihae/bio-image-unet | bio_image_unet/siam_unet/helpers/find_frame_of_image.py | .py | c78f870ffd7f39c2 | 7.42 | 6 |
import cv2
import numpy as np
import tifffile
import os
import glob
from scipy.ndimage import geometric_transform
import tifffile
import glob
import numpy as np
import matplotlib.pyplot as plt
def generate_coupled_image(movie, frame, output):
"""
Generates an image from the previous frame of the given frame a... | danihae/bio-image-unet | bio_image_unet/siam_unet/helpers/generate_siam_unet_input_imgs.py | .py | bcfc1305f474b8a0 | 7.42 | 6 |
import tifffile
from tifffile import TiffFile
def fetch_frame(tif_file):
"""Returns a generator of frames in a tif file
Args:
tif_file (str): path to the tif file of concern
Yields:
numpy ndarray: A matrix representing a frame in the image. Should be two dimensional if the input is graysc... | danihae/bio-image-unet | bio_image_unet/siam_unet/helpers/low_mem_tif_utils.py | .py | e726e9d906bd15d8 | 7.42 | 6 |
import cv2
from os import listdir
from os.path import isfile, join
import numpy as np
def threshold_images(in_path, out_path):
"""
Performs the threshold function on all the images in the folder `in_path` and outputs them in `out_path`
Params:
in_path: folder of source images
out_path: fold... | danihae/bio-image-unet | bio_image_unet/siam_unet/helpers/threshold_images.py | .py | df038581650b2787 | 7.42 | 6 |
import cv2
import os
os.nice(20)
import subprocess
import numpy as np
import tifffile
from skimage import morphology
import platform
if platform.system() != 'Linux':
raise Exception # this script is designed to use Linux bash commands. Please use Linux
try:
subprocess.run(["ffmpeg"], stdout=subprocess.DEVNUL... | danihae/bio-image-unet | bio_image_unet/siam_unet/helpers/tif_to_mp4.py | .py | fb9c93c108ecec6b | 7.42 | 6 |
import torch
from torch import nn
import torch.nn.functional as F
import logging
class Siam_UNet(nn.Module):
"""
Siamese U-Net model for image segmentation.
Parameters
----------
n_filter : int, optional
Number of filters in the convolutional layers (default is 32).
mode : str, option... | danihae/bio-image-unet | bio_image_unet/siam_unet/siam_unet.py | .py | 3857bc529b36e62e | 7.42 | 6 |
import torch
from torch import nn
class BabyUnet(nn.Module):
"""
Neural network for semantic image segmentation U-Net (PyTorch), with only three max-pooling layers
Reference: Falk, T. et al. U-Net: deep learning for cell counting, detection, and morphometry. Nat Methods 16,
67–70 (2019).
Paramet... | danihae/bio-image-unet | bio_image_unet/unet/baby_unet.py | .py | 2475fef1e0291548 | 7.42 | 6 |
import glob
import os
from typing import Union
import tifffile
import torch.optim as optim
from torch.utils.data import DataLoader, random_split
from tqdm import tqdm
from .unet3d import UNet3D
from .losses import *
from .predict import Predict
from ..utils import init_weights, get_device
class Trainer:
"""
... | danihae/bio-image-unet | bio_image_unet/unet3d/train.py | .py | 598b862b8486e2a2 | 7.42 | 6 |
import torch
from torch import nn
import torch.nn.functional as F
class UNet3D(nn.Module):
"""
Neural network for time-consistent segmentation or volume segmentation,
adapted from Li, X. et al. Real-time denoising enables high-sensitivity fluorescence time-lapse imaging
beyond the shot-noise limit. Na... | danihae/bio-image-unet | bio_image_unet/unet3d/unet3d.py | .py | 15d514a4a0b0fad0 | 7.42 | 6 |
import unittest
import azure.functions as func
from FunctionProjTest import response_text_processing
class TestFunction(unittest.TestCase):
def test_my_function(self):
# Construct a mock HTTP request.
req = func.HttpRequest(
method='GET',
body=None,
url='/api/H... | pyladiesams/azure-functions-beginner-mar2020 | solutions/part2_azure_functions/tests/test_response_text_processing.py | .py | 46da42dae8f7e3cd | 7.02 | 10 |
"""Contains compilation steps for compiling a LaTeX document.
Each compilation step must have the following signature:
.. code-block::
def compilation_step(path_to_tex: Path, path_to_document: Path):
...
A compilation step constructor must yield a function with this signature.
"""
from __future__ impo... | pytask-dev/pytask-latex | src/pytask_latex/compilation_steps.py | .py | 93d543d81aa06e92 | 7.5 | 9 |
"""Configuration file for pytest."""
from __future__ import annotations
import os
import shutil
import sys
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from click.testing import CliRunner
from pytask import storage
if TYPE_CHECKING:
from collectio... | pytask-dev/pytask-latex | tests/conftest.py | .py | c756337c733e3682 | 8 | 9 |
from __future__ import annotations
import textwrap
from pathlib import Path
from typing import cast
import pytest
from pytask import ExitCode
from pytask import Mark
from pytask import Skipped
from pytask import Task
from pytask import build
from pytask import cli
from pytask_latex.execute import pytask_execute_task... | pytask-dev/pytask-latex | tests/test_execute.py | .py | df2d587a389acb65 | 7 | 9 |
"""Contains test which ensure that the plugin works with pytask-parallel."""
from __future__ import annotations
import os
import textwrap
import pytest
from pytask import ExitCode
from pytask import cli
from tests.conftest import needs_latexmk
from tests.conftest import skip_on_github_actions_with_win
try:
imp... | pytask-dev/pytask-latex | tests/test_parallel.py | .py | 3af3185bf1ab321b | 7 | 9 |
import click
class RequiredIfNotEmpty(click.Option):
def __init__(self, *args, **kwargs):
self.required_if_not_empty = kwargs.pop("required_if_empty")
if not self.required_if_not_empty:
raise ValueError(
'"required_if_not_empty" argument is required for "RequiredIfNotE... | druids/developers-chamber | developers_chamber/click/options.py | .py | e2ae1d4cc9680bf0 | 7.52 | 10 |
import json
import os
from pathlib import Path
import yaml
from dotenv import load_dotenv
from developers_chamber.click.options import (
ContainerCommandType,
ContainerDirToCopyType,
ContainerEnvironment,
)
CONFIG_DIR_NAME = ".pydev"
DOTENV_SUFFIXES = (".conf",)
JSON_SUFFIXES = (".json",)
YAML_SUFFIXES =... | druids/developers-chamber | developers_chamber/config.py | .py | d2627a8c6f2fd2e8 | 7.52 | 10 |
import logging
import os
import re
import subprocess
import sys
import click
from click import ClickException
from developers_chamber.utils import MIGRATIONS_PATTERN, RepoMixin
LOGGER = logging.getLogger()
class QAError(Exception):
"""
Generic QA exception that also carries command output.
"""
def... | druids/developers-chamber | developers_chamber/qa/base.py | .py | 483f679003f699c8 | 7.52 | 10 |
import click
from click.formatting import HelpFormatter
from gettext import gettext as _
from developers_chamber.click.alias import AliasCommand
class FullHelpGroup(click.Group):
def format_commands(self, ctx, formatter) -> None:
"""Extra format methods for multi methods that adds all the commands
... | druids/developers-chamber | developers_chamber/scripts/__init__.py | .py | 735d7053ec42556f | 7.52 | 10 |
import click
from developers_chamber.click.options import RequiredIfNotEmpty
from developers_chamber.docker_utils import login_client as login_client_func
from developers_chamber.docker_utils import push_image as push_image_func
from developers_chamber.docker_utils import tag as tag_func
from developers_chamber.script... | druids/developers-chamber | developers_chamber/scripts/docker.py | .py | aa1b329c9154da92 | 7.52 | 10 |
import click
from developers_chamber.scripts import cli
from developers_chamber.slack_utils import (
upload_new_migration as upload_new_migration_func,
)
from developers_chamber.utils import MIGRATIONS_PATTERN
TARGET_BRANCH = "master"
@cli.group()
def slack():
"""Helpers for Slack management."""
@slack.c... | druids/developers-chamber | developers_chamber/scripts/slack.py | .py | f60335cda609cd2e | 7.52 | 10 |
import logging
import os
import re
import subprocess
import sys
from click import ClickException
LOGGER = logging.getLogger()
MIGRATIONS_PATTERN = r"migrations\/([^\/]+)\.py$"
def call_command(command, quiet=False, env=None):
env = {} if env is None else env
try:
if not quiet:
LOGGER.inf... | druids/developers-chamber | developers_chamber/utils.py | .py | 3de9f9c40ebb829c | 7.52 | 10 |
import json
import os
import pytest
@pytest.fixture(autouse=True)
def restore_environ():
"""
Keep the environment of one test out of the others.
Loading a configuration writes arbitrary variables into ``os.environ``, which monkeypatch
cannot undo because it does not know about them.
"""
orig... | druids/developers-chamber | tests/conftest.py | .py | 9945387acf8b52b8 | 8.02 | 10 |
#!/usr/bin/env python
"""
ezgooey.logging
---------------
Copyright (c) 2020 Adam Twardoch <adam+github@twardoch.com>
MIT license. Python 3.8+
Sets up a simple colorful logger,
compatible with Gooey's richtext control
## Simple usage
### Import and initialize in one place
```python
import ezgooey.logging as loggin... | twardoch/ezgooey | ezgooey/logging.py | .py | 7491cd0066debe02 | 7.5 | 9 |
#!/usr/bin/env python3
import os
import re
from setuptools import find_packages, setup
NAME = "ezgooey"
readme_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md")
with open(readme_file) as f:
readme = f.read()
def get_version(*args):
# Try to import version from version.py first
... | twardoch/ezgooey | setup.py | .py | 45be89082d9e4806 | 7.5 | 9 |
# this_file: tests/conftest.py
"""Pytest configuration and fixtures for ezgooey tests."""
import os
import sys
import pytest
from unittest.mock import patch
# Add parent directory to path for all tests
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
@pytest.fixture(autouse=True)
def ... | twardoch/ezgooey | tests/conftest.py | .py | 0f8d19caad81c168 | 8 | 9 |
#!/usr/bin/env python3
# this_file: tests/test_ez.py
"""Tests for ezgooey.ez module."""
import os
import sys
import unittest
from unittest.mock import patch, MagicMock
import argparse
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ezgooey.ez import... | twardoch/ezgooey | tests/test_ez.py | .py | 83b9ed3c7643ea91 | 7 | 9 |
#!/usr/bin/env python3
# this_file: tests/test_integration.py
"""Integration tests for ezgooey package."""
import os
import sys
import unittest
from unittest.mock import patch, MagicMock
import tempfile
import subprocess
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath... | twardoch/ezgooey | tests/test_integration.py | .py | 2a3d1bf2d77d5621 | 8 | 9 |
#!/usr/bin/env python3
# this_file: tests/test_logging.py
"""Tests for ezgooey.logging module."""
import os
import sys
import unittest
from unittest.mock import patch, MagicMock
import logging as std_logging
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))... | twardoch/ezgooey | tests/test_logging.py | .py | b194e09618f3428c | 8 | 9 |
#!/usr/bin/env python3
# this_file: tests/test_version.py
"""Tests for version management functionality."""
import os
import sys
import tempfile
import unittest
from unittest.mock import patch, MagicMock
import subprocess
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspat... | twardoch/ezgooey | tests/test_version.py | .py | 0572bce275063022 | 8 | 9 |
#!/usr/bin/env python3
# this_file: version.py
"""
Version management utilities for ezgooey.
Provides git-tag-based semantic versioning.
"""
import os
import re
import subprocess
from typing import Optional
def get_git_tag_version() -> Optional[str]:
"""Get the latest git tag version."""
try:
# Get t... | twardoch/ezgooey | version.py | .py | 2bbab67c563c1181 | 7.5 | 9 |
# Copyright 2007 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the... | kkujansuu/gramps | addons/Fulltext/whoosh/analysis/acore.py | .py | 5747e1b082d85853 | 7.5 | 9 |
# coding=utf-8
# Copyright 2007 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of co... | kkujansuu/gramps | addons/Fulltext/whoosh/analysis/filters.py | .py | af5197eb6f093d11 | 7.5 | 9 |
# Copyright 2007 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the... | kkujansuu/gramps | addons/Fulltext/whoosh/analysis/morph.py | .py | ad83b4d3e6571f8a | 7.5 | 9 |
# Copyright 2007 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the... | kkujansuu/gramps | addons/Fulltext/whoosh/analysis/tokenizers.py | .py | 7c6561c017ec80fd | 7.5 | 9 |
# Copyright 2012 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the... | kkujansuu/gramps | addons/Fulltext/whoosh/automata/nfa.py | .py | 6e218753d8827778 | 7.5 | 9 |
import array, sys
# Run time aliasing of Python2/3 differences
def htmlescape(s, quote=True):
# this is html.escape reimplemented with cgi.escape,
# so it works for python 2.x, 3.0 and 3.1
import cgi
s = cgi.escape(s, quote)
if quote:
# python 3.2 also replaces the single quotes:
... | kkujansuu/gramps | addons/Fulltext/whoosh/compat.py | .py | 182ed3023bc833bf | 7.5 | 9 |
# pylint: disable=django-not-configured
"""
This package contains checks for edx repo standards
"""
import codecs
import glob
import os
from configparser import ConfigParser
import dockerfile
import pytest
__version__ = "3.0.0"
def parse_config_file(path):
"""
Get the parsed content of an INI-style config... | openedx/edx-repo-health | repo_health/__init__.py | .py | 25a076dca97d1486 | 7.45 | 7 |
"""
Checks to identify whether the Dependabot file exists and which ecosystems are covered under Dependabot
"""
import os
from collections import OrderedDict
import pytest
import yaml
from pytest_repo_health import add_key_to_metadata, health_metadata
from repo_health import get_file_content
module_dict_key = "depen... | openedx/edx-repo-health | repo_health/check_dependabot.py | .py | 6b7be5d2aa759d81 | 7.45 | 7 |
"""
Checks repository open dependabot alert and collects metrics.
"""
import logging
import os
import pytest
import requests
from pytest_repo_health import health_metadata
from .utils import github_org_repo
logger = logging.getLogger(__name__)
MODULE_DICT_KEY = "dependabot_alerts"
def get_github_dependabot_api_re... | openedx/edx-repo-health | repo_health/check_dependabot_alerts.py | .py | a17751f8239705db | 7.45 | 7 |
"""
contains check that reads/parses dependencies of a repo
"""
import copy
import json
import logging
import os
import re
from abc import ABC, abstractmethod
from pathlib import Path
import pytest
from pytest_repo_health import health_metadata
from repo_health import get_file_content, get_file_lines
logger = loggi... | openedx/edx-repo-health | repo_health/check_dependencies.py | .py | 6389f71761b64191 | 7.45 | 7 |
"""
contains check that reads/parses dependencies of a repo
"""
import csv
import json
import logging
import os
import re
import tempfile
from pathlib import Path
import pytest
import requests
from packaging.version import InvalidVersion, parse
from pytest_repo_health import health_metadata
from repo_health import ... | openedx/edx-repo-health | repo_health/check_django_dependencies_compatibility.py | .py | 8d8553e919d685b5 | 7.45 | 7 |
"""
Contains the check to check the Django support releases
"""
import pytest
from pytest_repo_health import health_metadata
from .utils import find_django_version_in_setup_py_classifier, get_default_branch, get_release_tags, is_django_package
MODULE_DICT_KEY = "django"
@pytest.fixture(name='repo_release_tags')
def... | openedx/edx-repo-health | repo_health/check_django_support_releases.py | .py | 72b7dde130631d78 | 7.45 | 7 |
"""
Check some details of Read The Docs integration.
"""
import json
import logging
import os.path
import re
import pytest
import requests
import yaml
from pytest_repo_health import health_metadata
from repo_health import fixture_readme, get_file_content # pylint: disable=unused-import
logger = logging.getLogger(__... | openedx/edx-repo-health | repo_health/check_docs.py | .py | a806c469e629b7e1 | 7.45 | 7 |
"""
Checks repository is on github actions workflow and tests are enabled.
"""
import json
import logging
import os
import pytest
import requests
from pytest_repo_health import add_key_to_metadata
from .utils import github_org_repo
logger = logging.getLogger(__name__)
module_dict_key = "github_actions"
# Active wo... | openedx/edx-repo-health | repo_health/check_github_integration.py | .py | 0242676898bfdbae | 7.45 | 7 |
"""
Checks to see if Makefile follows standards
"""
import os
import re
import pytest
from pytest_repo_health import health_metadata
from repo_health import get_file_content
module_dict_key = "makefile"
output_keys = {
"upgrade": "target that upgrades our dependencies to newer released versions",
"test": "ta... | openedx/edx-repo-health | repo_health/check_makefile.py | .py | 6cc470dee75a0aac | 7.45 | 7 |
"""
Checks package published name on npm.
"""
import json
import os
import pytest
from pytest_repo_health import health_metadata
from repo_health import get_file_content
module_dict_key = "npm_package"
def get_dependencies(repo_path):
"""
entry point to read parse and read dependencies
@param repo_path:
... | openedx/edx-repo-health | repo_health/check_npm_package.py | .py | de290ef90e2b5456 | 7.45 | 7 |
"""
Checks to fetch repository ownership information from the Google Sheets speadsheet.
"""
import json
import logging
import os
import gspread
import pytest
import yaml
from pytest_repo_health import health_metadata
from .utils import github_org_repo
logger = logging.getLogger(__name__)
MODULE_DICT_KEY = "ownershi... | openedx/edx-repo-health | repo_health/check_ownership.py | .py | 6dfdb78b65b49958 | 7.45 | 7 |
"""
Counts the python dependencies which are pinned
"""
import os
import pytest
from repo_health import get_file_content
module_dict_key = "pinned_python_dependencies"
def get_dependencies_count(repo_path, file_name):
"""
entry point to read requirements from constraints and common-constraints
@param rep... | openedx/edx-repo-health | repo_health/check_pinned_python_dependencies.py | .py | c9a33f5d8b9bbe6c | 7.45 | 7 |
"""
Contains the checks to check the python support releases
"""
import pytest
from pytest_repo_health import health_metadata
from .utils import find_python_version_in_config_files, get_default_branch, get_release_tags
MODULE_DICT_KEY = "python"
@pytest.fixture(name='repo_release_tags')
def fixture_repo_release_tag... | openedx/edx-repo-health | repo_health/check_python_support_releases.py | .py | cef1bf83f3bc8f8e | 7.45 | 7 |
"""
Check some details in the readme file.
"""
import re
import urllib.parse
import pytest
import requests
from pytest_repo_health import health_metadata
from repo_health import fixture_readme # pylint:disable=unused-import
module_dict_key = "readme"
# Good things should be there, and are True if they are present... | openedx/edx-repo-health | repo_health/check_readme.py | .py | 18ed83ead8b5f7db | 7.45 | 7 |
"""
Applying the following checks:
Does any of the following readthedocs config file exists:
- readthedocs.yml
- readthedocs.yaml
- .readthedocs.yml
- .readthedocs.yaml
What is the name of file and version
"""
import os
from collections import OrderedDict
import pytest
import yaml
from pytest_repo_health import ad... | openedx/edx-repo-health | repo_health/check_readthedocs_config.py | .py | ff3a30fb6ea40bac | 7.45 | 7 |
"""
Checks whether repo requires some libraries
"""
import glob
import os
import re
import pytest
from pytest_repo_health import health_metadata
from repo_health import get_file_lines
module_dict_key = "requires"
@pytest.fixture(name='req_lines')
def fixture_req_lines(repo_path):
"""
Fixture containing th... | openedx/edx-repo-health | repo_health/check_requirements.py | .py | 0f5b84d1f93a9f9f | 7.45 | 7 |
"""
Checks tox.ini format
"""
import os
import pytest
from pytest_repo_health import add_key_to_metadata, health_metadata
from repo_health import get_file_content
module_dict_key = "tox_ini"
@pytest.fixture(name='tox_ini')
def fixture_tox_ini(repo_path):
"""Fixture containing the text content of tox.ini"""
... | openedx/edx-repo-health | repo_health/check_tox_ini.py | .py | fccb7ee61b66f3a1 | 7.45 | 7 |
"""
Utility Functions
"""
import functools
import operator
import os
import re
import subprocess
from datetime import datetime
import toml
from repo_health import get_file_content
GITHUB_DATETIME_FMT = "%Y-%m-%dT%H:%M:%SZ"
URL_PATTERN = r"github.com[/:](?P<org_name>[^/]+)/(?P<repo_name>[^/]+).git"
def file_exists(... | openedx/edx-repo-health | repo_health/utils.py | .py | 735c505e2a0b5ad1 | 7.45 | 7 |
"""
utils used to create dashboard
"""
import csv
import datetime
import html
import os
import re
import sqlite3
def _parse_timestamp_date(value):
"""Parse a CSV TIMESTAMP cell (date or datetime) into a date; None on failure."""
text = str(value).strip()
if not text:
return None
try:
r... | openedx/edx-repo-health | repo_health_dashboard/utils/utils.py | .py | 49e28b98f37498dc | 7.45 | 7 |
#!/usr/bin/env python
"""
This script prints to the console a repository health dashboard derived from SQL queries against the SQLite output
option of a set of repository health data. It currently consists mainly of:
1) Detected issues which likely require maintenance work to address, in roughly the order that the 2U... | openedx/edx-repo-health | scripts/console_dashboard.py | .py | 74823e5ad8ef469d | 7.45 | 7 |
"""Test suite for dependabot alerts check"""
import json
import os
from unittest import mock
from repo_health.check_dependabot_alerts import MODULE_DICT_KEY, check_dependabot_alert_stats
class MockResponse:
"""
Class to hold mock responses from api call
"""
def __init__(self, response, status_code):
... | openedx/edx-repo-health | tests/test_check_dependabot_alerts.py | .py | 9a0a5cd11251798f | 7.95 | 7 |
"""Test checks for GitHub integrations."""
import json
import os
from unittest import mock
from repo_health.check_github_integration import check_github_actions_integration, module_dict_key
class MockResponse:
"""Mock response for a GitHub call."""
def __init__(self, content, status_code):
self.con... | openedx/edx-repo-health | tests/test_check_github_integration.py | .py | bb0b9be1f56b4214 | 7.95 | 7 |
import argparse
import re
from openbabel import openbabel, pybel
openbabel.obErrorLog.StopLogging()
def parse_command_line():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', required=True, help='Input file name')
parser.add_argument('-o', '--output', required=True, help='Output fi... | RECETOX/galaxytools | tools/filter_compounds/filter_compounds.py | .py | 04134cf244bbe4b7 | 7.6 | 15 |
import argparse
import itertools
import os
from matchms import Metadata
from matchms.exporting import save_as_msp
from matchms.importing import load_from_msp
Metadata.set_key_replacements({})
def make_outdir(outdir: str):
"""Create destination directory.
Args:
outdir (str): Path to destination dire... | RECETOX/galaxytools | tools/matchms/matchms_split.py | .py | 646f9112fabc66ca | 7.6 | 15 |
#!/usr/bin/env python3
"""Hierarchical proportional block assignment.
Samples are split into blocks of size m (the last block may be smaller).
Balancing is done by levels:
1. Factor 1 is matched proportionally in every block.
2. Within each factor-1 slice, factor 2 is matched proportionally.
3. The same logic is appli... | RECETOX/galaxytools | tools/misc/stratified_block_randomization.py | .py | a5142208792ea44e | 7.6 | 15 |
import argparse
from typing import Tuple
import numpy as np
import pandas as pd
class LoadDataAction(argparse.Action):
"""
Custom argparse action to load data from a file into a pandas DataFrame.
Supports CSV, TSV, and Parquet file formats.
"""
def __call__(
self,
parser: argpars... | RECETOX/galaxytools | tools/misc/target_screen.py | .py | 208533d5ea3056bd | 7.6 | 15 |
import argparse
import pandas as pd
from openbabel import openbabel, pybel
openbabel.obErrorLog.SetOutputLevel(1) # 0: suppress warnings; 1: warnings
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('-iformat', '--input_format', help='Input file format')
... | RECETOX/galaxytools | tools/rem_complex/rem_complex.py | .py | 11760278cc952cd1 | 7.6 | 15 |
import argparse
from collections import defaultdict
from typing import Tuple
import pandas as pd
def parse_arguments() -> argparse.Namespace:
"""Parses command-line arguments.
Returns:
argparse.Namespace: Namespace with argument values as attributes.
"""
parser = argparse.ArgumentParser(desc... | RECETOX/galaxytools | tools/rename_annotated_feature/rename_annotated_feature.py | .py | b3d0e512eafe4c99 | 7.6 | 15 |
#!/usr/bin/env python
import argparse
import sys
from matchms.importing import load_from_mgf, load_from_msp
from spec2vec import SpectrumDocument
from spec2vec.model_building import train_new_word2vec_model
from spec2vec.serialization import export_model
def read_spectra(spectra_file, file_format):
if file_form... | RECETOX/galaxytools | tools/spec2vec/spec2vec_training_wrapper.py | .py | 81480ec8fae693c6 | 7.1 | 15 |
import argparse
import logging
from typing import Tuple
import pandas as pd
from utils import KeyValuePairsAction, LoadDataAction, StoreOutputAction
def rename_columns(df: pd.DataFrame, rename_dict: dict):
"""
Rename columns in the dataframe based on the provided dictionary.
Parameters:
df (pd.DataF... | RECETOX/galaxytools | tools/tables/table_pandas_rename_column.py | .py | bc7095af756cef9a | 7.6 | 15 |
import argparse
import logging
import re
from typing import List, Tuple
import pandas as pd
from utils import LoadDataAction, SplitColumnIndicesAction, StoreOutputAction
def rename_columns(
df: pd.DataFrame, columns: List[int], regex_check: str, regex_replace: str
) -> pd.DataFrame:
"""
Rename columns i... | RECETOX/galaxytools | tools/tables/table_pandas_rename_columns_regex.py | .py | c8fc1dfc887eedd3 | 7.6 | 15 |
from airflow import DAG
from ewah.constants import EWAHConstants as EC
from ewah.utils.airflow_utils import datetime_utcnow_with_tz
from ewah.operators.base import EWAHBaseOperator
from ewah.uploaders import get_uploader
from collections.abc import Iterable
from copy import deepcopy
from croniter import croniter
from... | Gemma-Analytics/ewah | ewah/dag_factories/dag_factory_atomic.py | .py | 8bcd237cab3f1756 | 7.57 | 13 |
from airflow import DAG
from airflow.sensors.external_task import ExternalTaskSensor
from airflow.operators.bash import BashOperator
from ewah.constants import EWAHConstants as EC
from ewah.uploaders.bigquery import BigqueryOperator
from ewah.uploaders.snowflake import SnowflakeOperator
from ewah.utils.airflow_utils i... | Gemma-Analytics/ewah | ewah/dag_factories/dag_factory_idempotent.py | .py | 8c29748b9a8dbe8e | 7.57 | 13 |
"""This data loading strategy is a mix of full refresh and incremental.
It has two DAGs like the incremental strategy, but no Reset.
Both DAGs have a schedule interval.
There is a Full Refresh DAG and an Incremental DAG.
The Full Refresh DAG runs with a longer periodicity, e.g. 1 day or 1 week.
The Incremental DAG the... | Gemma-Analytics/ewah | ewah/dag_factories/dag_factory_mixed.py | .py | 83424441f012cc26 | 7.57 | 13 |
from ewah.hooks.base import EWAHBaseHook
import requests
class EWAHAirflowHook(EWAHBaseHook):
"""Get Airflow Metadata from an Airflow installation via the stable API."""
_ATTR_RELABEL = {
"url": "host",
"user": "login",
}
conn_name_attr = "ewah_airflow_conn_id"
default_conn_name... | Gemma-Analytics/ewah | ewah/hooks/airflow.py | .py | 876365800d74eb40 | 7.57 | 13 |
from ewah.hooks.base import EWAHBaseHook
from ewah.constants import EWAHConstants as EC
# from datetime import datetime, date, timedelta
import pendulum
import requests
import gzip
import json
import time
class EWAHAmazonAdsHook(EWAHBaseHook):
"""
Implements the Amazon Ads API.
"""
_ENDPOINTS_ADS_AP... | Gemma-Analytics/ewah | ewah/hooks/amazon_ads.py | .py | fb3588ec458565c0 | 7.57 | 13 |
from airflow.hooks.base import BaseHook
from airflow.models.connection import Connection
from airflow.providers_manager import ProvidersManager
from airflow.utils.module_loading import import_string
from typing import Type, Optional
class EWAHConnection(Connection):
"""Extension of airflow's native Connection.""... | Gemma-Analytics/ewah | ewah/hooks/base.py | .py | 32b1fa89dbc8036d | 7.57 | 13 |
from ewah.hooks.base import EWAHBaseHook
class EWAHdbtEnvVarHook(EWAHBaseHook):
"""
Very simple hook to show a custom connection type in Airflow.
Not used for data loading.
Use it to create environment variable secrets using Airflow connections
which are then used in dbt runs. Usage may be extende... | Gemma-Analytics/ewah | ewah/hooks/dbt_env_var.py | .py | 5c7e362f3dadc696 | 7.57 | 13 |
from ewah.constants import EWAHConstants as EC
from ewah.hooks.base import EWAHBaseHook
from google.cloud import storage
from google.oauth2 import service_account
import avro.schema
import json
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter
from io import BytesIO... | Gemma-Analytics/ewah | ewah/hooks/google_cloud_storage.py | .py | 2553aff0f1622d54 | 7.57 | 13 |
from ewah.hooks.sql_base import EWAHSQLBaseHook
from typing import Optional, List, Union
# cx_Oracle is optional - only available on amd64 (no ARM64 binaries)
try:
import cx_Oracle
CX_ORACLE_AVAILABLE = True
except ImportError:
cx_Oracle = None
CX_ORACLE_AVAILABLE = False
class EWAHOracleSQLOperato... | Gemma-Analytics/ewah | ewah/hooks/oracle.py | .py | a53e4493c2b516a5 | 7.57 | 13 |
from __future__ import annotations
import json
import subprocess
from copy import deepcopy
from pathlib import Path
from tempfile import TemporaryDirectory
from importlib_resources import files as resource_file
from jsonschema import validate
from lxml.etree import (
Element,
ElementTree,
fromstring,
)
fr... | antarctica/metadata-library | src/bas_metadata_library/__init__.py | .py | 037999cdb8cd0494 | 7.57 | 13 |
from __future__ import annotations
import json
from copy import deepcopy
from pathlib import Path
from importlib_resources import files as resource_file
from lxml.etree import Element, fromstring
from bas_metadata_library import MetadataRecord as _MetadataRecord
from bas_metadata_library import MetadataRecordConfig ... | antarctica/metadata-library | src/bas_metadata_library/standards/iso_19115_2/__init__.py | .py | e7e49b292e0a4fed | 7.57 | 13 |
import json
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from typing import Final, Optional, TypeVar
import cattrs
TAdministrationMetadata = TypeVar("TAdministration", bound="AdministrationMetadata")
@dataclass
class Permission:
"""
Access permission.
Represe... | antarctica/metadata-library | src/bas_metadata_library/standards/magic_administration/v1/__init__.py | .py | fc3e99321b4a296b | 7.57 | 13 |
import json
from typing import Optional
from jwskate import JweCompact, Jwk, JwtSigner
from bas_metadata_library.standards.magic_administration.v1 import AdministrationMetadata
class AdministrationMetadataSubjectMismatchError(Exception):
"""Raised when administration metadata does not relate to discovery metada... | antarctica/metadata-library | src/bas_metadata_library/standards/magic_administration/v1/utils.py | .py | ffe948e259e7ff93 | 7.57 | 13 |
from __future__ import annotations
import json
from pathlib import Path
from flask import Flask, Response, current_app, jsonify
from flask.testing import FlaskClient
from importlib_resources import files as resource_file
from jsonref import JsonRef
from jsonschema.validators import validate
from bas_metadata_library... | antarctica/metadata-library | tests/app.py | .py | 93ef2d04ed53563c | 8.07 | 13 |
import json
import pickle
from copy import deepcopy
from datetime import datetime, timezone
from http import HTTPStatus
from pathlib import Path
from typing import Callable, Optional
import cattrs
import pytest
from flask.testing import FlaskClient
from jsonschema.exceptions import ValidationError
from lxml.etree impo... | antarctica/metadata-library | tests/bas_metadata_library_tests/test_profile_magic_administration_v1.py | .py | 1644c00a35d6295b | 7.07 | 13 |
from copy import deepcopy
from http import HTTPStatus
from pathlib import Path
from typing import Callable
import pytest
from flask.testing import FlaskClient
from jsonschema.exceptions import ValidationError
from lxml.etree import tostring, ElementTree
from bas_metadata_library.standards.iso_19115_2 import (
Met... | antarctica/metadata-library | tests/bas_metadata_library_tests/test_profile_magic_discovery_v2.py | .py | 98c1bae523434f2c | 8.07 | 13 |
from functools import lru_cache
from typing import Callable, Optional, Union
import pytest
from _pytest.fixtures import FixtureRequest
from _pytest.monkeypatch import MonkeyPatch
from flask import Flask
from flask.testing import FlaskClient
from lxml import etree
from lxml.etree import ElementTree, fromstring
from ba... | antarctica/metadata-library | tests/conftest.py | .py | 3a645c06ec4b216b | 8.07 | 13 |
from jwskate import Jwk
from bas_metadata_library.standards.magic_administration.v1.utils import AdministrationKeys
def make_keys() -> None:
"""
Generate new test keys.
Note: This should not be needed again but is retained to allow keys to be rotated.
"""
signing_key_private = Jwk.generate(alg="... | antarctica/metadata-library | tests/resources/keys/__init__.py | .py | c7dc9775300a2192 | 8.07 | 13 |
import click
from ..blueprints import select_blueprint_kind
@click.group()
def blueprint():
pass
@blueprint.command()
@click.argument("file_path", type=click.Path(exists=True))
def validate(file_path):
"""
Validate a blueprint file.
"""
try:
model, data = select_blueprint_kind(file_pa... | etive-io/asimov | asimov/cli/blueprint.py | .py | 78f0017213c6ea4e | 7.45 | 7 |
import click
import os
from asimov import config
@click.group()
def configuration():
"""Group for all of the configuration-related command line stuff."""
pass
@configuration.command()
@click.option("--key", "-k", "key", default=None, help="Show a specific key")
def show(key):
"""Show all configuration v... | etive-io/asimov | asimov/cli/configuration.py | .py | 0f02e952de02e93f | 7.45 | 7 |
import json
from math import floor
import click
@click.option("--event", "event", default=None, help="The event which will be updated")
@click.option("--json", "json_data", default=None)
@click.command(help="Add data from the configurator.")
def configurator(event, json_data=None):
"""
Add data from the PECon... | etive-io/asimov | asimov/cli/data.py | .py | 898191772845b388 | 7.45 | 7 |
import json
import os
from math import floor
import click
from asimov import config
from asimov import current_ledger as ledger
from asimov.utils import update
from asimov.event import Event
@click.group()
def event():
"""
Commands to handle events & collections.
"""
pass
@click.option(
"--old... | etive-io/asimov | asimov/cli/event.py | .py | 111bb76a276caced | 7.45 | 7 |
from copy import copy
import click
import yaml
from asimov import config
from asimov import current_ledger as ledger
from asimov.event import Production
from asimov.storage import Store
@click.group()
def production():
"""
Commands to handle productions.
"""
pass
@click.argument("pipeline")
@clic... | etive-io/asimov | asimov/cli/production.py | .py | 83d54547d969e669 | 7.45 | 7 |
"""
zProject management tools.
"""
try:
import ConfigParser as configparser
except ImportError:
import configparser
import os
import shutil
import getpass
import click
from asimov import config, storage, logger, LOGGER_LEVEL
from asimov.ledger import Ledger
logger = logger.getChild("cli").getChild("project... | etive-io/asimov | asimov/cli/project.py | .py | 9ffceb405ff1c776 | 7.45 | 7 |
"""
Code for interacting with the condor scheduler.
An important function of asimov is interaction with condor schedulers in order to track the status of running jobs.
In order to improve performance the code caches results from the query to the scheduler.
Note: This module now uses the asimov.scheduler module inter... | etive-io/asimov | asimov/condor.py | .py | b09502fd0caa4a34 | 7.45 | 7 |
"""
Asimov databse interface
------------------------
This module implements the asimov database and its interfaces.
Note that this approach to the database is a departure from what I set
up initially for the database backed logger, and I think it would be
better to use a document database going forward.
Implementat... | etive-io/asimov | asimov/database.py | .py | 00d96829f59a6471 | 7.45 | 7 |
"""
Handle run configuration files.
This module provides a minimal wrapper around a pipeline's ini-style
run configuration file, used to locate and validate the file without
asimov needing to understand its pipeline-specific contents.
"""
from configparser import ConfigParser
class RunConfiguration(object):
"""... | etive-io/asimov | asimov/ini.py | .py | 231404041739eef4 | 7.45 | 7 |
"""
Code for the project ledger.
"""
import yaml
import os
import shutil
from functools import reduce
import asimov
import asimov.database
from asimov import config
from asimov.analysis import ProjectAnalysis
from asimov.event import Event, Production
from asimov.utils import update, set_directory
class Ledger:
... | etive-io/asimov | asimov/ledger.py | .py | 9d73eadeb2df19fd | 7.45 | 7 |
import json
import requests
from . import config
class Mattermost(object):
def __init__(self, url=None):
if not url:
self.url = config.get("mattermost", "webhook_url")
else:
self.url = url
def send_message(self, message, channel=None):
"""
Send a mess... | etive-io/asimov | asimov/mattermost.py | .py | 2e9f96c304c9a2be | 7.45 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.