repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
grimmer0125/StrEnum | strenum/mixins.py | <reponame>grimmer0125/StrEnum
class Comparable:
"""Customise how your Enum acts when compared to other objects.
Your Enum must implement a ``_cmp_values`` method which takes the Enum
member's value and the other value and manipulates them into the actual
values that can be compared.
A case-insensi... |
grimmer0125/StrEnum | tests/test_strenum_casefold.py | <reponame>grimmer0125/StrEnum
# pylint:disable=missing-docstring,invalid-name
from enum import auto
from strenum import LowercaseStrEnum, UppercaseStrEnum
def test_lowercase_auto():
class BeamType(LowercaseStrEnum):
START = auto()
STOP = auto()
PARTIAL = auto()
assert BeamType.START =... |
grimmer0125/StrEnum | strenum/__init__.py | <reponame>grimmer0125/StrEnum<gh_stars>1-10
import enum
from ._version import get_versions
from ._name_mangler import _NameMangler
__version__ = get_versions()["version"]
__version_info__ = tuple(int(n) for n in __version__.partition("+")[0].split("."))
del get_versions
_name_mangler = _NameMangler()
# The first arg... |
lotzk/stringfuzz | stringfuzz/generator.py | import re
from stringfuzz.constants import SMT_20, SMT_20_STRING, SMT_25_STRING
from stringfuzz.scanner import scan, ALPHABET, WHITESPACE
from stringfuzz.ast import *
__all__ = [
'generate',
'generate_file',
'NotSupported',
]
# exceptions
class NotSupported(ValueError):
def __init__(self, e, language... |
lotzk/stringfuzz | stringfuzz/scanner.py | <filename>stringfuzz/scanner.py
import re
import string
from stringfuzz.constants import *
__all__ = [
'scan',
'scan_file',
'ScanningError',
'ALPHABET',
'WHITESPACE',
]
# data structures
class ScanningError(ValueError):
pass
class Token(object):
def __init__(self, name, value, position)... |
fossabot/auto-tag | auto_tag/constants.py | #!/usr/bin/env python3
"""
Constants used in the AutoTag project
"""
MAJOR = 100
MINOR = 10
PATCH = 1
CHANGE_TYPE_PAIRS = (
(MAJOR, 'MAJOR'),
(MINOR, 'MINOR'),
(PATCH, 'PATCH'),
)
CHANGE_TYPES = {value: name for value, name in CHANGE_TYPE_PAIRS}
CHANGE_TYPES_REVERSE = {name: value for value, name in CHANG... |
fossabot/auto-tag | setup.py | <gh_stars>0
#!/usr/bin/env python3
"""
Setup file for the package.
"""
import os
import pathlib
from setuptools import setup, find_packages
# The directory containing this file
HERE = os.path.abspath(pathlib.Path(__file__).parent)
# The text of the README file
README = open(
os.path.join(HERE, 'README.md'),
... |
fossabot/auto-tag | auto_tag/core.py | #!/usr/bin/env python3
"""
Automatically tags branches base on commit message
"""
import logging
import semantic_version
import git
from auto_tag import constants
from auto_tag import git_custom_env
class AutoTag():
"""Class wrapper for auto-tag functionality."""
def __init__(self, repo, branch, upstream_... |
fossabot/auto-tag | auto_tag/cli.py | <reponame>fossabot/auto-tag
#!/usr/bin/env python3
"""
CLI parser for auto-tag.
"""
import logging
import argparse
def get_parser():
"""Return the argument parser setup."""
parser = argparse.ArgumentParser(
description='Tag branch based on commit messages')
parser.add_argument('-b', '--branch', ty... |
fossabot/auto-tag | auto_tag/detectors.py | <reponame>fossabot/auto-tag
#!/usr/bin/env python3
"""
Change type detectors.
Parses a configuration with what type of change do you want to produce.
"""
import abc
import logging
import re
import six
from auto_tag import constants
from auto_tag import exception
@six.add_metaclass(abc.ABCMeta)
class BaseDetector():... |
fossabot/auto-tag | auto_tag/tests/conftest.py | #!/usr/bin/env python3
"""
Fixtures used to test AutoTag module.
"""
import os
import git
import pytest
from auto_tag import detectors_config
@pytest.fixture
def simple_repo(tmpdir):
"""Return a simple repository with 3 basic commits and no tags."""
bare_repo_path = os.path.join(tmpdir, 'bare-repo')
bar... |
fossabot/auto-tag | auto_tag/detectors_config.py | <gh_stars>0
#!/usr/bin/env python3
"""
Prepare Detectors based on a file config.
"""
import logging
import io
import yaml
from auto_tag import exception
from auto_tag import detectors
from auto_tag import constants
# pylint:disable=too-few-public-methods
class DetectorsConfig():
"""Handles instantiation of det... |
fossabot/auto-tag | auto_tag/tests/test_core.py | <filename>auto_tag/tests/test_core.py
#!/usr/bin/env python3
"""
Test simple flows of the AutoTag application
"""
import os
import git
import pytest
from auto_tag import core
# pylint:disable=invalid-name
TEST_DATA_SIMPLE_TAG_PATCH_BUMP = [
('0.0.1', '0.0.2'),
('0.1.1', '0.1.2'),
('1.0.1', '1.0.2'),
]
T... |
fossabot/auto-tag | auto_tag/tests/test_detectors_config.py | <reponame>fossabot/auto-tag
#!/usr/bin/env python3
"""
Test simple flows of the AutoTag application
"""
import os
from auto_tag import detectors_config
from auto_tag import detectors
# pylint:disable=invalid-name
def test_detector_config():
"""Test to see if the factory returns what we expect."""
path_to_fil... |
clee088/Character-Distribution | distribution.py | <filename>distribution.py
"""
distribution.py
Author: <NAME>
Credit: https://developers.google.com/edu/python/sorting
Assignment:
Write and submit a Python program (distribution.py) that computes and displays
the distribution of characters in a given sample of text.
Output of your program should look like this:
Pl... |
danielrjiang/Ax | ax/modelbridge/tests/test_log_transform.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
from copy import deepcopy
from ax.core.observation import ObservationFeatures
from ax.core.parameter import ChoiceParameter, ParameterType, RangeParameter
from ax.core.search_space import SearchSpace
from ax.mod... |
danielrjiang/Ax | ax/modelbridge/tests/test_search_space_to_choice_transform.py | <reponame>danielrjiang/Ax
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from copy import deepcopy
from ax.core.arm import Arm
from ax.core.observation import ObservationFeatures
from ax.core.parameter import (
ChoiceParameter,
FixedParameter,
ParameterType,... |
danielrjiang/Ax | ax/service/tests/test_storage_utils.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from ax.service.utils.storage import (
load_experiment,
load_experiment_and_generation_strategy,
save_experiment,
save_experiment_and_generation_strategy,
)
from ax.storage.sqa_store.db import init_test_engin... |
danielrjiang/Ax | ax/modelbridge/transforms/ordered_choice_encode.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from typing import Dict, List, Optional
from ax.core.observation import ObservationData, ObservationFeatures
from ax.core.parameter import ChoiceParameter, Parameter, ParameterType, RangeParameter
from ax.core.search_space ... |
danielrjiang/Ax | ax/plot/table_view.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
import pandas as pd
import plotly.graph_objs as go
from ax.core.data import Data
from ax.core.experiment import Experiment
from ax.modelbridge.factory import get_empirical_bayes_thompson, get_thompson
from ax.pl... |
danielrjiang/Ax | ax/modelbridge/numpy.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from typing import List
from ax.modelbridge.array import ArrayModelBridge
from ax.models.numpy_base import NumpyModel
# pyre-fixme[13]: Attribute `model` is never initialized.
# pyre-fixme[13]: Attribute `outcomes` is nev... |
danielrjiang/Ax | ax/modelbridge/modelbridge_utils.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from typing import Callable, Dict, List, MutableMapping, Optional, Tuple
import numpy as np
from ax.core.batch_trial import BatchTrial
from ax.core.experiment import Experiment
from ax.core.observation import ObservationFea... |
danielrjiang/Ax | ax/benchmark/tests/test_benchmark.py | <reponame>danielrjiang/Ax
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from ax.benchmark.benchmark import full_benchmark_run
from ax.benchmark.benchmark_problem import BenchmarkProblem, SimpleBenchmarkProblem
from ax.core.experiment import Experiment
from ax.modelbridg... |
danielrjiang/Ax | ax/service/tests/test_instantiation_utils.py | <reponame>danielrjiang/Ax<gh_stars>0
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from ax.core.parameter import ParameterType, RangeParameter
from ax.service.utils.instantiation import (
_get_parameter_type,
constraint_from_str,
outcome_constraint_from_str,... |
danielrjiang/Ax | ax/benchmark/benchmark.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from types import FunctionType
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
from ax.benchmark import utils
from ax.benchmark.benchmark_problem import BenchmarkProblem, SimpleBenchmarkProblem
from... |
danielrjiang/Ax | ax/core/batch_trial.py | <gh_stars>0
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import OrderedDict, defaultdict
from datetime import datetime
from typing import (
TYPE_CHECKING,
DefaultDict,
Dict,
List,
MutableMapping,
NamedTuple,
Optional,
Un... |
danielrjiang/Ax | ax/modelbridge/tests/test_torch_modelbridge.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from unittest import mock
import numpy as np
import torch
from ax.modelbridge.torch import TorchModelBridge
from ax.models.torch_base import TorchModel
from ax.utils.common.testutils import TestCase
class TorchModelBridge... |
danielrjiang/Ax | ax/models/tests/test_full_factorial.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
from ax.models.discrete.full_factorial import FullFactorialGenerator
from ax.utils.common.testutils import TestCase
class FullFactorialGeneratorTest(TestCase):
def testFullFactorial(self):
g... |
danielrjiang/Ax | ax/modelbridge/generation_strategy.py | <reponame>danielrjiang/Ax
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from inspect import signature
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Type, Union
from ax.core.base import Base
from ax.core.data import Data
from ax.core.experiment imp... |
danielrjiang/Ax | ax/modelbridge/array.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
import numpy as np
from ax.core.objective import Objective, ScalarizedObjective
from ax.core.observation import ObservationData, ObservationFeatures
from ax... |
danielrjiang/Ax | ax/utils/testing/modeling_stubs.py | <filename>ax/utils/testing/modeling_stubs.py<gh_stars>0
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from typing import List, Optional, Type
import numpy as np
from ax.core.experiment import Experiment
from ax.core.observation import Observation, ObservationData, Obse... |
danielrjiang/Ax | ax/models/tests/test_torch.py | <reponame>danielrjiang/Ax
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
from ax.models.torch.utils import normalize_indices
from ax.models.torch_base import TorchModel
from ax.utils.common.testutils import TestCase
class TorchModelTest(TestCase):
... |
danielrjiang/Ax | ax/modelbridge/__init__.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# flake8: noqa F401
from ax.modelbridge import transforms
from ax.modelbridge.base import ModelBridge
from ax.modelbridge.factory import (
Models,
get_factorial,
get_GPEI,
get_sobol,
get_thompson,
get_... |
danielrjiang/Ax | ax/modelbridge/tests/test_discrete_modelbridge.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from unittest import mock
import numpy as np
from ax.core.metric import Metric
from ax.core.objective import Objective
from ax.core.observation import Observation, ObservationData, ObservationFeatures
from ax.core.optimizat... |
bwilson3853/astr302-bayuw | trash/jan23.py | #!/Users/bayuwilson/anaconda3/bin/python
import functools
import sys
def juric_func(*arg):
return functools.reduce(lambda x,y:float(x)*float(y),arg)
juric_func(sys.argv[1:])
#print(sys.argv)
|
bwilson3853/astr302-bayuw | trash/hw3/visutils.py | <reponame>bwilson3853/astr302-bayuw<gh_stars>0
from utils import *
from ipywidgets import interact
def load_and_prepare_cmd(filename,verbose=False): # (g, gr) = load_and_prepare_cmd('fieldA.csv')
"""
Loads in data. Returns pandas Series of g-r and r respectively.
"""
FIELD = pd.read_csv("fieldA.csv")
... |
oopt-goldstone/mgmt | src/north/cli/gscli/onlp.py | <filename>src/north/cli/gscli/onlp.py
import sys
import os
from .base import InvalidInput
import libyang as ly
import sysrepo as sr
from .common import sysrepo_wrap
from tabulate import tabulate
import logging
from natsort import natsorted
logger = logging.getLogger(__name__)
stdout = logging.getLogger("stdout")
stde... |
oopt-goldstone/mgmt | tools/mk_quilt_patch.py | #!/usr/bin/env python
import argparse
import subprocess
from git import Repo
import os
import sys
import gitdb
import time
def run(args, cwd=None):
print(f'cmd: {args}, cwd: {cwd}')
subprocess.run(args, cwd=cwd)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--submodule')
par... |
oopt-goldstone/mgmt | src/north/cli/gscli/sonic_cli.py | <gh_stars>0
import sys
import os
import re
import logging
from .base import InvalidInput, Completer
from .cli import GSObject as Object
import libyang as ly
import sysrepo as sr
from prompt_toolkit.document import Document
from prompt_toolkit.completion import (
WordCompleter,
Completion,
NestedCompleter,... |
oopt-goldstone/mgmt | src/north/snmp/src/gs_ax_impl/main.py | """
SNMP subagent entrypoint.
"""
import asyncio
import functools
import os
import signal
import argparse
import logging
import ax_interface
from .mibs.ietf import rfc1213
DEFAULT_UPDATE_FREQUENCY = 5
logger = logging.getLogger(__name__)
class GoldstoneMIB(
rfc1213.InterfacesMIB,
rfc1213.SystemMIB,
):
... |
oopt-goldstone/mgmt | src/south/onlp/setup.py | import setuptools
setuptools.setup(
name="gsonlp",
version="0.1.0",
# install_requires=['sysrepo'],
description="Goldstone Python ONLP south daemon",
url="https://github.com/microsonic/goldstone-mgmt",
python_requires=">=3.7",
entry_points={
"console_scripts": [
"... |
oopt-goldstone/mgmt | src/south/tai/gstai/main.py | <reponame>oopt-goldstone/mgmt
import sysrepo
import logging
import taish
import asyncio
import argparse
import json
import signal
import struct
import base64
import re
import libyang
import traceback
from aiohttp import web
# TODO improve taish library
TAI_STATUS_ITEM_ALREADY_EXISTS = -6
TAI_STATUS_FAILURE = -1
clas... |
oopt-goldstone/mgmt | src/north/cli/gscli/tai_cli.py | <reponame>oopt-goldstone/mgmt
from .tai import Transponder, human_freq, to_human
from .base import InvalidInput, Completer, Command
from .cli import GSObject as Object
from .cli import ShowCommand
from prompt_toolkit.completion import WordCompleter, NestedCompleter
from .common import sysrepo_wrap, print_tabular
import... |
oopt-goldstone/mgmt | src/xlate/openconfig/gsopenconfig/platform.py | import logging
logger = logging.getLogger(__name__)
class PlatformServer(object):
def __init__(self, conn):
self.conn = conn
self.sess = self.conn.start_session()
def stop(self):
self.sess.stop()
def oper_cb(self, sess, xpath, req_xpath, parent, priv):
self.sess.switch_d... |
oopt-goldstone/mgmt | src/xlate/openconfig/gsopenconfig/interface.py | <gh_stars>1-10
import logging
logger = logging.getLogger(__name__)
class InterfaceServer(object):
def __init__(self, conn):
self.conn = conn
self.sess = self.conn.start_session()
def stop(self):
self.sess.stop()
def oper_cb(self, sess, xpath, req_xpath, parent, priv):
se... |
oopt-goldstone/mgmt | src/xlate/openconfig/setup.py | import setuptools
with open("requirements.txt", "r") as f:
install_requires = f.read().split()
setuptools.setup(
name="gsopenconfig",
version="0.1.0",
install_requires=install_requires,
description="Goldstone OpenConfig translator",
url="https://github.com/microsonic/goldstone-mgmt",
pytho... |
oopt-goldstone/mgmt | src/south/sonic/gssonic/k8s_api.py | import datetime
import io
import re
import os
import logging
import asyncio
import json
import kubernetes as k
import kubernetes_asyncio as k_async
from jinja2 import Template
USONIC_DEPLOYMENTS = os.getenv(
"USONIC_DEPLOYMENTS",
"usonic-core,usonic-bcm,usonic-port,usonic-neighbor,usonic-mgrd,usonic-teamd",
... |
oopt-goldstone/mgmt | src/north/cli/gscli/system_cli.py | <filename>src/north/cli/gscli/system_cli.py
from .cli import GSObject as Object
from .base import InvalidInput, Completer
from .system import AAA, TACACS, Mgmtif
from prompt_toolkit.document import Document
from prompt_toolkit.completion import WordCompleter, Completion, NestedCompleter
from .common import sysrepo_wrap... |
oopt-goldstone/mgmt | src/north/cli/gscli/common.py | import sys
import os
import json
import logging
import libyang as ly
import sysrepo as sr
from sysrepo.session import DATASTORE_VALUES
from tabulate import tabulate
from .base import InvalidInput, LockedError
logger = logging.getLogger(__name__)
stdout = logging.getLogger("stdout")
stderr = logging.getLogger("stderr"... |
oopt-goldstone/mgmt | src/south/system/gssystem/system.py | <reponame>oopt-goldstone/mgmt
import dbus
import logging
import json
import sysrepo
import os
VERSION_FILE = os.getenv(
"GOLDSTONE_VERSION_FILE", "/etc/goldstone/loader/versions.json"
)
logger = logging.getLogger(__name__)
class SystemServer:
def __init__(self, conn):
self.sess = conn.start_session(... |
oopt-goldstone/mgmt | src/north/snmp/src/ax_interface/agent.py | import asyncio
from .mib import MIBTable, MIBMeta
from .socket_io import SocketManager
# how long to wait before forcibly killing background task(s) during the shutdown procedure.
BACKGROUND_WAIT_TIMEOUT = 10 # seconds
class Agent:
def __init__(self, mib_cls, update_frequency, loop, ax_socket_path):
if... |
oopt-goldstone/mgmt | src/north/cli/gscli/tai.py | import re
import base64
import struct
import sysrepo as sr
import libyang as ly
import logging
from tabulate import tabulate
from .common import sysrepo_wrap, print_tabular
from .base import InvalidInput
from natsort import natsorted
_FREQ_RE = re.compile(r".+[kmgt]?hz$")
logger = logging.getLogger(__name__)
stdout =... |
oopt-goldstone/mgmt | src/north/snmp/setup.py | <reponame>oopt-goldstone/mgmt
import setuptools
setuptools.setup(
name="gssnmp",
version="0.1.0",
install_requires=["prompt_toolkit", "tabulate", "python_arptable"],
description="Goldstone SNMP AgentX",
url="https://github.com/microsonic/goldstone-mgmt",
python_requires=">=3.7",
entry_point... |
oopt-goldstone/mgmt | src/south/system/gssystem/mgmtif.py | <reponame>oopt-goldstone/mgmt
import pyroute2
import sysrepo
import logging
from pyroute2.netlink.rtnl import ndmsg
import os
import re
# This hardcoding has to be removed once ENV
# is added in system file for gssystem-south
MGMT_INTF_NAMES = os.getenv("GS_MGMT_INTFS", "eth0").split(",")
MAX_PREFIX_LENGTH = 32
DEFAUL... |
oopt-goldstone/mgmt | src/south/system/gssystem/k8s.py | <reponame>oopt-goldstone/mgmt
import dbus
from kubernetes_asyncio import config, client
import asyncio
import os
import logging
import os.path
import pyroute2
KUBECONFIG = os.getenv("KUBECONFIG", "/etc/rancher/k3s/k3s.yaml")
K8S_SERVICE = os.getenv("K8S_SERVICE", "k3s.service")
SERVICE_CIDR = os.getenv("SERVICE_CIDR",... |
oopt-goldstone/mgmt | src/north/cli/gscli/base.py | <filename>src/north/cli/gscli/base.py
from prompt_toolkit.document import Document
from prompt_toolkit.completion import (
Completion,
WordCompleter,
FuzzyWordCompleter,
NestedCompleter,
DummyCompleter,
FuzzyCompleter,
)
from prompt_toolkit.completion import Completer as PromptCompleter
from pro... |
oopt-goldstone/mgmt | src/north/cli/gscli/sonic.py | <gh_stars>0
import sys
import os
import libyang as ly
from tabulate import tabulate
import json
import sysrepo as sr
from .common import sysrepo_wrap, print_tabular
from prompt_toolkit.completion import WordCompleter
from .base import InvalidInput
from natsort import natsorted
import logging
logger = logging.getLo... |
oopt-goldstone/mgmt | src/north/cli/gscli/system.py | <gh_stars>0
import sysrepo as sr
from tabulate import tabulate
from .common import sysrepo_wrap, print_tabular
from natsort import natsorted
import json
import re
import logging
logger = logging.getLogger(__name__)
stdout = logging.getLogger("stdout")
stderr = logging.getLogger("stderr")
class Mgmtif(object):
X... |
oopt-goldstone/mgmt | src/south/notif/gsnotif/main.py | <filename>src/south/notif/gsnotif/main.py
import sysrepo
import libyang
import logging
import asyncio
import argparse
import json
import signal
import struct
import base64
import os
from aiohttp import web
from libyang import SNode
logger = logging.getLogger(__name__)
class Server(object):
def __init__(self):
... |
oopt-goldstone/mgmt | src/south/onlp/gsonlp/main.py | import sysrepo
import logging
import asyncio
import argparse
import signal
import ctypes
import onlp.onlp
import json
import re
from pathlib import Path
libonlp = onlp.onlp.libonlp
class InvalidXPath(Exception):
pass
logger = logging.getLogger(__name__)
STATUS_UNPLUGGED = 0
STATUS_ACO_PRESENT = 1 << 0
STATUS_... |
oopt-goldstone/mgmt | src/north/cli/gscli/main.py | <reponame>oopt-goldstone/mgmt<gh_stars>0
#!/usr/bin/env python
import sysrepo as sr
import argparse
from prompt_toolkit import PromptSession
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.completion import (
Completer,
NestedCompleter,
FuzzyWordCompleter,
)
from prompt_toolkit imp... |
oopt-goldstone/mgmt | src/north/cli/gscli/cli.py | <reponame>oopt-goldstone/mgmt<gh_stars>0
import sys
import os
import sysrepo
from tabulate import tabulate
from .sonic import Sonic
from .tai import Transponder
from .system import System, TACACS, AAA, Mgmtif
from .onlp import Component
import json
import libyang as ly
import sysrepo as sr
from sysrepo.session import D... |
IBMPredictiveAnalytics/GATHERMD | src/GATHERMD.py | #/***********************************************************************
# * Licensed Materials - Property of IBM
# *
# * IBM SPSS Products: Statistics Common
# *
# * (C) Copyright IBM Corp. 1989, 2020
# *
# * US Government Users Restricted Rights - Use, duplication or disclosure
# * restricted by GSA ADP Schedule Co... |
danrugeles/cay | cay.py | import numpy as np
from scipy.special import gammaln
from aux import addrandomtopic,dictionate
import time
data=np.array([[0,0],
[0,1],
[1,0],
[1,1],
[0,1],
[2,2],
[2,1],
[1,2],
[0,1],
[1,1],
[0,1],
[2,3],
[3,3],
[3,2],
... |
danrugeles/cay | aux.py | <filename>aux.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This code is available under the MIT License.
# (c)2015 <NAME>
# daniel007[at]e.ntu.edu.sg / Nanyang Technological University
import math
import numpy as np
from random import randint,seed
__author__ = "<NAME>"
__copyright__ = "Copyright 2015, Auxili... |
mrowlingfox/kk | src/main/python/kk/kube_objects.py | <reponame>mrowlingfox/kk<filename>src/main/python/kk/kube_objects.py
from kubernetes import config, client, watch
import time
import json
import pickle
import pydash as _
from kk.utils import Utils
# import only system from os
from os import system, name
class KubeObjects:
all_nodes = []
all_pods = []
... |
mrowlingfox/kk | src/main/python/kk/utils.py | <reponame>mrowlingfox/kk<filename>src/main/python/kk/utils.py
import os
import logging
from time import time, ctime
from os import system, name
import pydash as _
import json
import jsonpickle
from json import JSONEncoder
class Utils:
@staticmethod
def clear():
# for windows
if name == 'nt':... |
mrowlingfox/kk | run.py | <reponame>mrowlingfox/kk<gh_stars>1-10
#!/usr/bin/env python
#shortcut to quickly try and test without doing full pyb (TODO: learn some python testcase! probably best do it with testcases)
import sys
import logging
import pydash as _
sys.path.append('src/main/python')
from kk.kube_objects import KubeObjects
from ... |
mrowlingfox/kk | build.py | # -*- coding: utf-8 -*-
from pybuilder.core import use_plugin, init
import glob
import os
import shutil
import logging
from pybuilder.core import use_plugin, init, Author, task
from pybuilder.utils import assert_can_execute
use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.distutils")
nam... |
CommonGarden/CommonGarden-IoT | ai/classifier/camera.py | import picamera
camera = picamera.PiCamera()
def capture(file_name='img.jpg'):
camera.capture(file_name)
def capture_sequence(base_name='img'):
'''Capture a sequence of images'''
i = 0
while True:
file_name = base_name + '_' + str(i) + '.jpg'
key = raw_input("Press Enter to take pict... |
LegubeDNAREPAIR/LoopExtrusion | script/4Cseq/demultiplex.py | import itertools
import gzip
import HTSeq
import argparse
def main():
"""Script to demultiplex a fastq single end library.
The fastq file specified in --fastq is demultiplexed
using the sequences provided in the barcode fasta file (--barcode)."""
parser = argparse.ArgumentParser(description='Demultiplex a fas... |
JiscRDSS/rdss-terraform-standards-checker | terrachecker/terrachecker.py | #!/usr/bin/env python
import argparse
import sys
from terrachecker.terraform_checker import TerraformChecker
def main():
"""Script entrypoint."""
args = parse_args()
checker = TerraformChecker(args.terraform_path)
if not checker.is_valid():
for error in checker.validation_errors:
... |
JiscRDSS/rdss-terraform-standards-checker | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='terrachecker',
version='0.0.5',
description='Terraform checker.',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/JiscRDSS/rdss-terraform-standards-checker',
packages=find_packages(),
inclu... |
JiscRDSS/rdss-terraform-standards-checker | tests/test_terraform_checker.py | import pytest
from terrachecker.terraform_checker import TerraformChecker
class TestTerraformChecker(object):
"""Test the Terraform checker module."""
def test_ensure_trailing_slash_adds_slash(self):
"""Ensure the trailing slash function adds a slash."""
root = 'something/test'
check... |
JiscRDSS/rdss-terraform-standards-checker | terrachecker/terraform_checker.py | import os
import hcl
class TerraformChecker(object):
"""Terraform checker."""
tf_file_paths = []
validation_errors = []
def __init__(self, root_path):
"""Read the Terraform configs from the provided path."""
self.validation_errors = []
self.tf_file_paths = self._get_tf_file_p... |
arrieta/shldn | shldn/leonard.py | <filename>shldn/leonard.py
"""
Leonard always DRIVES Sheldon (this module is the __main__ driver for Sheldon)
"""
import argparse
import sys
import os
try:
from cooper import Sheldon
except:
from .cooper import Sheldon
# Extensions for python source files
EXTENSIONS = [".py", ".mpy"]
def parse_commandline():... |
arrieta/shldn | shldn/cooper.py | """Sheldon helps you find the divisions in your Python code.
"""
import ast
try:
from visitors.divisitor import DivVisitor
except:
from .visitors.divisitor import DivVisitor
# based on div tuple in divisitor module
LINENO = 0
NUMERATOR = 1
DENOMINATOR = 2
# Constant for readable output
TABSIZE = 4
class Sh... |
arrieta/shldn | shldn/tests/test.py | <filename>shldn/tests/test.py
import unittest
from shldn.cooper import Sheldon
class TestSheldon(unittest.TestCase):
def test_basic(self):
"""Input file with basic integer division"""
obj = Sheldon("test-data/div.py")
obj.analyze()
expected = [(1, "Name", "Attribute")]
s... |
arrieta/shldn | shldn/__init__.py | __version_info__ = (1, 2, 1)
__version__ = "{0}.{1}.{2}".format(*__version_info__)
|
arrieta/shldn | shldn/tests/test-data/intdiv.py |
def intdiv(a, b):
return a // b
if __name__ == "__main__":
print("Hi, I can calculate the integer division of two numers")
a = int(input("a = "))
b = int(input("b = "))
print(f"a // b = {intdiv(a, b)}")
print("Bye!")
|
arrieta/shldn | shldn/tests/test-data/helloworld.py | <reponame>arrieta/shldn<filename>shldn/tests/test-data/helloworld.py
if __name__== "__main__":
print("Hello World!")
1/2 |
arrieta/shldn | shldn/visitors/divisitor.py | <reponame>arrieta/shldn
"""
Division visitor for Python 3 AST tools
"""
import ast
class DivVisitor(ast.NodeVisitor):
"""Traverse the AST collecting all divisions."""
def __init__(self):
super().__init__()
self._acc = []
@property
def divs(self):
return self._acc
class _D... |
torbjomg/pwa_flask_app | migrations/versions/e6e803f959af_.py | <filename>migrations/versions/e6e803f959af_.py
"""empty message
Revision ID: e6e803f959af
Revises: <PASSWORD>
Create Date: 2020-04-13 15:45:04.192069
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e6e803f959af'
down_revision = '<PASSWORD>'
branc... |
torbjomg/pwa_flask_app | app/utils.py | <gh_stars>0
# -*- coding: utf-8 -*-
"""Helper utilities and decorators."""
from flask import flash
from app.plan.models import Plan
from app.task.models import Task
from essential_generators import DocumentGenerator
from uuid import uuid4
GEN = DocumentGenerator()
def flash_errors(form, category="warning"):
"""Fl... |
torbjomg/pwa_flask_app | app/app.py | <filename>app/app.py<gh_stars>0
import logging
import sys
from flask import Flask, render_template
from app import public, user, plan, task
from app.plan.models import Plan
from app.task.models import Task
from app.extensions import (
bcrypt,
csrf_protect,
login_manager,
db,
migra... |
torbjomg/pwa_flask_app | app/user/views.py | """User views."""
from flask import Blueprint, render_template, request, jsonify
from flask_login import login_required, login_user, logout_user, current_user
from app.extensions import login_manager, csrf_protect, db
from app.plan.models import Plan
from app.task.models import Task
blueprint = Blueprint("user"... |
torbjomg/pwa_flask_app | app/task/models.py | <gh_stars>0
import datetime as datetime
from app.database import (
Column,
Model,
db,
relationship,
)
class Task(Model):
__tablename__ = "task"
user_id = Column(db.Integer, db.ForeignKey('users.id'))
plan = Column(db.Integer, db.ForeignKey('plan.id'))
name = Column(db.Stri... |
torbjomg/pwa_flask_app | migrations/versions/5bed454c783d_.py | <reponame>torbjomg/pwa_flask_app<gh_stars>0
"""empty message
Revision ID: 5bed454c783d
Revises: e<PASSWORD>
Create Date: 2020-04-13 15:51:39.083447
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5bed454c783d'
down_revision = 'e<PASSWORD>'
branch... |
torbjomg/pwa_flask_app | app/plan/views.py | <reponame>torbjomg/pwa_flask_app
from flask import (
Blueprint,
current_app,
render_template,
redirect,
request,
jsonify,
)
from sqlalchemy.exc import IntegrityError
from flask_login import (
login_required,
login_user,
logout_user,
current_user,
)
from app... |
torbjomg/pwa_flask_app | migrations/versions/0c89b9c0a9cd_.py | """empty message
Revision ID: 0c89b9c0a9cd
Revises: <KEY>
Create Date: 2020-04-07 16:43:07.842078
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0c89b9c0a9cd'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
... |
torbjomg/pwa_flask_app | app/task/views.py | from flask import (
Blueprint,
current_app,
render_template,
redirect,
request,
jsonify,
)
from flask_login import (
login_required,
login_user,
logout_user,
current_user,
)
from app.extensions import login_manager, csrf_protect, db
blueprint = Blueprint("t... |
neelkamath/hackerrank-solutions | src/Practice/Algorithms/Greedy/Minimum Absolute Difference in an Array.py | <gh_stars>0
#!/bin/python3
import math
import os
import random
import re
import sys
def minimumAbsoluteDifference(arr):
arr.sort()
minimum = 1e9
for index, num in enumerate(arr[:len(arr) - 1]):
newMin = abs(num - arr[index + 1])
if newMin < minimum:
minimum = newMin
return... |
neelkamath/hackerrank-solutions | src/Practice/Python/Basic Data Types/Find the Runner-Up Score!.py | input() # Discard number of elements.
print(sorted({int(score) for score in input().split()})[-2])
|
neelkamath/hackerrank-solutions | src/Practice/Python/Basic Data Types/Nested Lists.py | <filename>src/Practice/Python/Basic Data Types/Nested Lists.py
students = []
for _ in range(int(input())):
students.append([input(), float(input())])
lowest = min([student[1] for student in students])
students = [student for student in students if student[1] != lowest]
second_lowest = min([student[1] for student in... |
neelkamath/hackerrank-solutions | src/Practice/Python/Introduction/Python If-Else.py | #!/bin/python3
N = int(input())
if N % 2 == 1:
print('Weird')
else:
if N in range(2, 6):
print('Not Weird')
if N in range(6, 21):
print('Weird')
if N > 20:
print('Not Weird')
|
neelkamath/hackerrank-solutions | src/Practice/Python/Sets/Set .discard(), .remove() & .pop().py | <filename>src/Practice/Python/Sets/Set .discard(), .remove() & .pop().py
n = int(input())
s = set(map(int, input().split()))
N = int(input())
for _ in range(N):
data = input().split(' ')
if data[0] == 'pop':
s.pop()
elif data[0] == 'remove':
s.remove(int(data[1]))
elif data[0] == 'discar... |
neelkamath/hackerrank-solutions | src/Practice/Python/Introduction/Loops.py | if __name__ == '__main__':
n = int(input())
for num in range(n):
print(num * num)
|
puntofisso/wardle | qgis/centroids-constituencies.py | import geopandas as gpd
# GeoDataFrame creation
file = 'constituencies.shp'
poly = gpd.read_file(file)
points = poly.copy()
# change the geometry
# points.geometry = points['geometry'].centroid
points.to_crs(epsg=4326, inplace=True)
# same crs #points.crs =poly.crs
# print(points['geometry'])
for index, row in points.... |
puntofisso/wardle | qgis/centroids_LA.py | import geopandas as gpd
# GeoDataFrame creation
file = 'LAD_MAY_2021_UK_BFE_V2.shp'
poly = gpd.read_file(file)
points = poly.copy()
# change the geometry
points.geometry = points['geometry'].centroid
points.to_crs(epsg=4326, inplace=True)
# same crs #points.crs =poly.crs
# print(points['geometry'])
print("laid|laname|... |
puntofisso/wardle | qgis/centroids-wards.py | <gh_stars>0
import geopandas as gpd
# GeoDataFrame creation
file = 'wardsjoined.shp'
poly = gpd.read_file(file)
points = poly.copy()
# change the geometry
points.geometry = points['geometry'].centroid
points.to_crs(epsg=4326, inplace=True)
# same crs #points.crs =poly.crs
# print(points['geometry'])
print("wardid|ward... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.