code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import logging
import os
import socket
import zope.component
from certbot import interfaces
from certbot import util
try:
import psutil
USE_PSUTIL = True
except ImportError:
USE_PSUTIL = False
logger = logging.getLogger(__name__)
RENEWER_EXTRA_MSG = (
" For automated renewal, you may want to use a ... | certbot/plugins/util.py | import logging
import os
import socket
import zope.component
from certbot import interfaces
from certbot import util
try:
import psutil
USE_PSUTIL = True
except ImportError:
USE_PSUTIL = False
logger = logging.getLogger(__name__)
RENEWER_EXTRA_MSG = (
" For automated renewal, you may want to use a ... | 0.480722 | 0.146087 |
from datetime import datetime
from dateutil.relativedelta import relativedelta
from decimal import Decimal
STEPDOWN_MONTH = 6 # Assume children graduate high shcool in June
STEPDOWN_DAY = 30 # Last day before child support reduces is last day of month
def stepdown(children: list, initial_payment_amount: Decimal, nu... | csutils/stepdown.py | from datetime import datetime
from dateutil.relativedelta import relativedelta
from decimal import Decimal
STEPDOWN_MONTH = 6 # Assume children graduate high shcool in June
STEPDOWN_DAY = 30 # Last day before child support reduces is last day of month
def stepdown(children: list, initial_payment_amount: Decimal, nu... | 0.810929 | 0.396243 |
from __future__ import division, absolute_import, print_function
try: unicode
except NameError: unicode = str
from warnings import warn
from statsmodels.compat.collections import OrderedDict
import numpy as np
import pandas as pd
from statsmodels.regression.linear_model import OLS
from statsmodels.tools.data import ... | statsmodels/regression/recursive_ls.py | from __future__ import division, absolute_import, print_function
try: unicode
except NameError: unicode = str
from warnings import warn
from statsmodels.compat.collections import OrderedDict
import numpy as np
import pandas as pd
from statsmodels.regression.linear_model import OLS
from statsmodels.tools.data import ... | 0.923589 | 0.454654 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'SpringCloudAppIdentity',
'SpringCloudAppPersistentDisk',
'SpringCloudServiceConfigServerGitSetting',
'SpringCloudService... | sdk/python/pulumi_azure/appplatform/outputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'SpringCloudAppIdentity',
'SpringCloudAppPersistentDisk',
'SpringCloudServiceConfigServerGitSetting',
'SpringCloudService... | 0.840062 | 0.064065 |
from alibabacloud.client import AlibabaCloudClient
from alibabacloud.request import APIRequest
from alibabacloud.utils.parameter_validation import verify_params
class MoPenClient(AlibabaCloudClient):
def __init__(self, client_config, credentials_provider=None, retry_policy=None,
endpoint_resolv... | alibabacloud/clients/mopen_20180211.py |
from alibabacloud.client import AlibabaCloudClient
from alibabacloud.request import APIRequest
from alibabacloud.utils.parameter_validation import verify_params
class MoPenClient(AlibabaCloudClient):
def __init__(self, client_config, credentials_provider=None, retry_policy=None,
endpoint_resolv... | 0.561816 | 0.106505 |
import os
import sys
import glob
import jinja2
import codecs
import markdown
from bin.jinja_setup import setup_jinja
from bin.markdown_jinja import MarkdownJinja
from frontend.digital_land_frontend.filters import organisation_mapper
from frontmatter import Frontmatter
docs = "docs/"
def render(path, template, **... | render.py |
import os
import sys
import glob
import jinja2
import codecs
import markdown
from bin.jinja_setup import setup_jinja
from bin.markdown_jinja import MarkdownJinja
from frontend.digital_land_frontend.filters import organisation_mapper
from frontmatter import Frontmatter
docs = "docs/"
def render(path, template, **... | 0.341802 | 0.110663 |
from oslo_utils import uuidutils
from wsme import exc
from wsme.rest import json as wsme_json
from wsme import types as wsme_types
from octavia.api.v2.types import pool as pool_type
from octavia.common import constants
from octavia.tests.unit.api.common import base
class TestSessionPersistence(object):
... | zuul.d/octavia/tests/unit/api/v2/types/test_pools.py |
from oslo_utils import uuidutils
from wsme import exc
from wsme.rest import json as wsme_json
from wsme import types as wsme_types
from octavia.api.v2.types import pool as pool_type
from octavia.common import constants
from octavia.tests.unit.api.common import base
class TestSessionPersistence(object):
... | 0.411584 | 0.179028 |
import argparse
import re
import jvmtunerInterface
from jvmtunerInterface import JvmFlagsTunerInterface
argparser = argparse.ArgumentParser(parents=[jvmtunerInterface.argparser])
argparser.add_argument(
'--jvm_spec_startup', default='java -jar SPECjvm2008.jar {source} -ikv -crf false --jvmArgs "{Opt_flags}"',
hel... | Hotspot_JVM_Tuner/src/specjvmTuner.py | import argparse
import re
import jvmtunerInterface
from jvmtunerInterface import JvmFlagsTunerInterface
argparser = argparse.ArgumentParser(parents=[jvmtunerInterface.argparser])
argparser.add_argument(
'--jvm_spec_startup', default='java -jar SPECjvm2008.jar {source} -ikv -crf false --jvmArgs "{Opt_flags}"',
hel... | 0.276984 | 0.065755 |
from collections import defaultdict
from flask import request
from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms.fields.core import UnboundField
from wtforms.form import FormMeta
from eNMS import app
from eNMS.database import db
from eNMS.forms.fields import (
BooleanField,
DictF... | eNMS/forms/__init__.py | from collections import defaultdict
from flask import request
from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms.fields.core import UnboundField
from wtforms.form import FormMeta
from eNMS import app
from eNMS.database import db
from eNMS.forms.fields import (
BooleanField,
DictF... | 0.480722 | 0.09739 |
from f5.bigip.resource import Collection as BigIpCollection
from f5.bigip.resource import HTTPError
from f5.bigip.resource import OrganizingCollection as BigIpOrganizingCollection
from f5.bigip.resource import PathElement as BigIpPathElement
from f5.bigip.resource import Resource as BigIpResource
from f5.bigip.resourc... | f5/bigiq/resource.py |
from f5.bigip.resource import Collection as BigIpCollection
from f5.bigip.resource import HTTPError
from f5.bigip.resource import OrganizingCollection as BigIpOrganizingCollection
from f5.bigip.resource import PathElement as BigIpPathElement
from f5.bigip.resource import Resource as BigIpResource
from f5.bigip.resourc... | 0.833968 | 0.154983 |
import mock
from mangum import Mangum
def test_websocket_close(tmp_path, mock_ws_connect_event, mock_ws_send_event) -> None:
dsn = f"sqlite://{tmp_path}/mangum.sqlite3"
async def app(scope, receive, send):
if scope["type"] == "websocket":
while True:
message = await rece... | tests/test_websockets.py | import mock
from mangum import Mangum
def test_websocket_close(tmp_path, mock_ws_connect_event, mock_ws_send_event) -> None:
dsn = f"sqlite://{tmp_path}/mangum.sqlite3"
async def app(scope, receive, send):
if scope["type"] == "websocket":
while True:
message = await rece... | 0.394667 | 0.196325 |
"""Class to interface with an Experiment"""
from typing import List
import numpy as np
from mtenv.utils.types import ObsType
from mtrl.agent import utils as agent_utils
from mtrl.env.vec_env import VecEnv # type: ignore[attr-defined]
from mtrl.experiment import multitask
from mtrl.utils.types import ConfigType, Ten... | src/mtrl/experiment/dmcontrol.py | """Class to interface with an Experiment"""
from typing import List
import numpy as np
from mtenv.utils.types import ObsType
from mtrl.agent import utils as agent_utils
from mtrl.env.vec_env import VecEnv # type: ignore[attr-defined]
from mtrl.experiment import multitask
from mtrl.utils.types import ConfigType, Ten... | 0.926761 | 0.538862 |
# Copyright (c) 2016 by University of Kassel and Fraunhofer Institute for Wind Energy and Energy
# System Technology (IWES), Kassel. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import pandapower as pp
def panda_four_load_branch():
"""
... | pandapower/networks/simple_pandapower_test_networks.py |
# Copyright (c) 2016 by University of Kassel and Fraunhofer Institute for Wind Energy and Energy
# System Technology (IWES), Kassel. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import pandapower as pp
def panda_four_load_branch():
"""
... | 0.847005 | 0.246737 |
expected_output={
'crypto_eng': {
'crypto_engine': 'Software Crypto Engine',
'crypto_engine_num': 1,
'dh_in_free': 41008,
'dh_in_freeing': 0,
'dh_in_use': 0
},
'crypto_... | src/genie/libs/parser/iosxe/tests/ShowCryptoEliAll/cli/equal/golden_output_expected.py | expected_output={
'crypto_eng': {
'crypto_engine': 'Software Crypto Engine',
'crypto_engine_num': 1,
'dh_in_free': 41008,
'dh_in_freeing': 0,
'dh_in_use': 0
},
'crypto_... | 0.498291 | 0.236593 |
from __future__ import print_function
from __future__ import division
import os
import time
from signal import SIGTERM, SIGKILL
from accelerator.compat import PY3
from accelerator.status import children, statmsg_endwait
from accelerator.build import JobError
valid_fds = []
def update_valid_fds():
# Collect all v... | accelerator/dispatch.py |
from __future__ import print_function
from __future__ import division
import os
import time
from signal import SIGTERM, SIGKILL
from accelerator.compat import PY3
from accelerator.status import children, statmsg_endwait
from accelerator.build import JobError
valid_fds = []
def update_valid_fds():
# Collect all v... | 0.290578 | 0.100084 |
from .markuputils import attribute_escape, html_escape, xml_escape
from .robottypes import is_string
from .robotio import file_writer
class _MarkupWriter(object):
def __init__(self, output, write_empty=True):
"""
:param output: Either an opened, file like object, or a path to the
des... | new/Lib/robot/utils/markupwriters.py |
from .markuputils import attribute_escape, html_escape, xml_escape
from .robottypes import is_string
from .robotio import file_writer
class _MarkupWriter(object):
def __init__(self, output, write_empty=True):
"""
:param output: Either an opened, file like object, or a path to the
des... | 0.757077 | 0.142024 |
import torch
import logging
from torch import nn
from transformers import CLIPModel
from .utils import assign_layer_ids
from ..constants import (
IMAGE, IMAGE_VALID_NUM, TEXT_TOKEN_IDS,
TEXT_VALID_LENGTH, LABEL, LOGITS, FEATURES, AUTOMM
)
from typing import Optional
from .utils import init_weights
logger = log... | text/src/autogluon/text/automm/models/clip.py | import torch
import logging
from torch import nn
from transformers import CLIPModel
from .utils import assign_layer_ids
from ..constants import (
IMAGE, IMAGE_VALID_NUM, TEXT_TOKEN_IDS,
TEXT_VALID_LENGTH, LABEL, LOGITS, FEATURES, AUTOMM
)
from typing import Optional
from .utils import init_weights
logger = log... | 0.922308 | 0.423756 |
import os.path
import requests
from bs4 import BeautifulSoup
import sys
if sys.version_info[0] != 3:
print('''\t--------------------------------------\n\t\tREQUIRED PYTHON 3.x\n\t\tinstall and try: python3
fb.py\n\t--------------------------------------''')
sys.exit()
PASSWORD_FILE = "<PASSWORD... | fb-1.py | import os.path
import requests
from bs4 import BeautifulSoup
import sys
if sys.version_info[0] != 3:
print('''\t--------------------------------------\n\t\tREQUIRED PYTHON 3.x\n\t\tinstall and try: python3
fb.py\n\t--------------------------------------''')
sys.exit()
PASSWORD_FILE = "<PASSWORD... | 0.087815 | 0.071494 |
from datetime import datetime, tzinfo
from enum import Enum
import re
from typing import Any, Optional
from .string_validator import StringValidator
from validataclass.exceptions import InvalidDateTimeError, InvalidValidatorOptionException, DateTimeRangeError
from validataclass.helpers.datetime_range import BaseDateTi... | src/validataclass/validators/datetime_validator.py | from datetime import datetime, tzinfo
from enum import Enum
import re
from typing import Any, Optional
from .string_validator import StringValidator
from validataclass.exceptions import InvalidDateTimeError, InvalidValidatorOptionException, DateTimeRangeError
from validataclass.helpers.datetime_range import BaseDateTi... | 0.937009 | 0.674456 |
from copy import deepcopy
import dateutil.parser
import json
import os
import unittest
from cloudcafe.images.common.types import (
ImageContainerFormat, ImageDiskFormat, ImageStatus, ImageVisibility)
from cloudcafe.images.v2.models.image import Image
class TestImage(unittest.TestCase):
@classmethod
def ... | metatests/cloudcafe/images/v2_0/models/image_test.py | from copy import deepcopy
import dateutil.parser
import json
import os
import unittest
from cloudcafe.images.common.types import (
ImageContainerFormat, ImageDiskFormat, ImageStatus, ImageVisibility)
from cloudcafe.images.v2.models.image import Image
class TestImage(unittest.TestCase):
@classmethod
def ... | 0.568416 | 0.268213 |
import PyQt5
# local import
from mw4.base.indiClass import IndiClass
class SettIndi(object):
"""
the main window class handles the main menu as well as the show and no show part of
any other window. all necessary processing for functions of that gui will be linked
to this class. therefore window class... | mw4/gui/mainWmixin/tabSettIndi.py | import PyQt5
# local import
from mw4.base.indiClass import IndiClass
class SettIndi(object):
"""
the main window class handles the main menu as well as the show and no show part of
any other window. all necessary processing for functions of that gui will be linked
to this class. therefore window class... | 0.383757 | 0.175821 |
date = '16/03/2020'
data = {
'LVMH': [298, 150e9, 'Consumer goods'] ,
'L\'OREAL': [208, 116e9, 'Consumer goods'],
'SANOFI' : [77.0, 96.0e9, 'Health care'],
'AIRBUS' : [69, 54.0e9, 'Industrials'],
'TOTAL' : [24.3, 63.3e9, 'Oil and gas'],
'HERMES' : [548, 57.9e9, 'Consumer goods'],
'KERING' :... | catbars/cac40.py | date = '16/03/2020'
data = {
'LVMH': [298, 150e9, 'Consumer goods'] ,
'L\'OREAL': [208, 116e9, 'Consumer goods'],
'SANOFI' : [77.0, 96.0e9, 'Health care'],
'AIRBUS' : [69, 54.0e9, 'Industrials'],
'TOTAL' : [24.3, 63.3e9, 'Oil and gas'],
'HERMES' : [548, 57.9e9, 'Consumer goods'],
'KERING' :... | 0.331661 | 0.338282 |
import torch
from torch.optim import Adam
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
import os
from utils.preprocess import timit_dataloader, dataloader
from sklearn.metrics import accuracy_score
from gender_detector.model import Model
device = torch.device('cuda' if torch.cuda.is_avai... | gender_detector/train.py | import torch
from torch.optim import Adam
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
import os
from utils.preprocess import timit_dataloader, dataloader
from sklearn.metrics import accuracy_score
from gender_detector.model import Model
device = torch.device('cuda' if torch.cuda.is_avai... | 0.540439 | 0.303113 |
from __future__ import annotations
from unittest.mock import patch
from homeassistant import config_entries
from homeassistant.components.sensibo.const import DOMAIN
from homeassistant.components.sensibo.util import NoUsernameError
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import Ho... | tests/components/sensibo/test_init.py | from __future__ import annotations
from unittest.mock import patch
from homeassistant import config_entries
from homeassistant.components.sensibo.const import DOMAIN
from homeassistant.components.sensibo.util import NoUsernameError
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import Ho... | 0.724968 | 0.227523 |
import __main__ as main
import sys
import geopandas as gpd
import pandas as pd
import numpy as np
if not hasattr(main, '__file__'):
argv = ['code', 'data/processed/geo/tiles.shp',
'data/processed/census/oa_tile_reference.csv',
'data/raw/census/engwal_OA_lsoa.csv',
'data/raw/cens... | src/data/census/tile_age.py | import __main__ as main
import sys
import geopandas as gpd
import pandas as pd
import numpy as np
if not hasattr(main, '__file__'):
argv = ['code', 'data/processed/geo/tiles.shp',
'data/processed/census/oa_tile_reference.csv',
'data/raw/census/engwal_OA_lsoa.csv',
'data/raw/cens... | 0.260484 | 0.245051 |
import ray
import json
import os
import logging
import argparse
import psutil
import tqdm
import arxiv_library.io_pkg.targz as io_targz
import arxiv_library.io_pkg.metadata as io_metadata
import arxiv_library.extraction.comments as comments
import arxiv_library.extraction.imports as imports
import arxiv_library.extract... | arxiv_library/pipeline.py | import ray
import json
import os
import logging
import argparse
import psutil
import tqdm
import arxiv_library.io_pkg.targz as io_targz
import arxiv_library.io_pkg.metadata as io_metadata
import arxiv_library.extraction.comments as comments
import arxiv_library.extraction.imports as imports
import arxiv_library.extract... | 0.361503 | 0.163579 |
import datetime
import typing
class ArticleField:
"""The `ArticleField` class for the Advanced Requirements."""
def __init__(self, field_type: typing.Type[typing.Any]):
pass
class Article:
"""The `Article` class you need to write for the qualifier."""
def __init__(self, title: str, author:... | qualifier.py | import datetime
import typing
class ArticleField:
"""The `ArticleField` class for the Advanced Requirements."""
def __init__(self, field_type: typing.Type[typing.Any]):
pass
class Article:
"""The `Article` class you need to write for the qualifier."""
def __init__(self, title: str, author:... | 0.777638 | 0.259518 |
import uuid
from django.test import TestCase
from unittest.mock import patch
from corehq.apps.domain.shortcuts import create_domain
from corehq.apps.linked_domain.models import DomainLink
from corehq.apps.linked_domain.tests.test_linked_apps import BaseLinkedDomainTest
from corehq.apps.linked_domain.updates import up... | corehq/apps/linked_domain/tests/test_update_roles.py | import uuid
from django.test import TestCase
from unittest.mock import patch
from corehq.apps.domain.shortcuts import create_domain
from corehq.apps.linked_domain.models import DomainLink
from corehq.apps.linked_domain.tests.test_linked_apps import BaseLinkedDomainTest
from corehq.apps.linked_domain.updates import up... | 0.556882 | 0.304352 |
from unittest import TestCase
import os
from conf_publisher.page_maker import make_page, make_pages
from conf_publisher.confluence import Page
from conf_publisher.config import ConfigLoader, ConfigDumper
class FakeConfluencePageManager(object):
def __init__(self, initial_pages=None):
if initial_pages is... | tests/test_page_maker.py | from unittest import TestCase
import os
from conf_publisher.page_maker import make_page, make_pages
from conf_publisher.confluence import Page
from conf_publisher.config import ConfigLoader, ConfigDumper
class FakeConfluencePageManager(object):
def __init__(self, initial_pages=None):
if initial_pages is... | 0.536313 | 0.192672 |
__all__ = ['A', 'B', 'Transform', 'compose', 'ItemList', 'ResizeTransform', 'ImageItemList', 'group_by', 'Matcher',
'map_group', 'SplitData']
# Cell
from solutions.lesson1 import *
from solutions.lesson2 import *
from solutions.lesson3 import *
from typing import List, Sequence, TypeVar, Generic, Callable,... | solutions/solutions/lesson4.py |
__all__ = ['A', 'B', 'Transform', 'compose', 'ItemList', 'ResizeTransform', 'ImageItemList', 'group_by', 'Matcher',
'map_group', 'SplitData']
# Cell
from solutions.lesson1 import *
from solutions.lesson2 import *
from solutions.lesson3 import *
from typing import List, Sequence, TypeVar, Generic, Callable,... | 0.89154 | 0.461502 |
import json
from datetime import datetime, timedelta
from app import db, LOGGER
from app.utils.testing import ApiTestCase
from app.outcome.models import Outcome, Status
from app.outcome.repository import OutcomeRepository as outcome_repository
class OutcomeApiTest(ApiTestCase):
def seed_static_data(self):
... | api/app/outcome/tests.py | import json
from datetime import datetime, timedelta
from app import db, LOGGER
from app.utils.testing import ApiTestCase
from app.outcome.models import Outcome, Status
from app.outcome.repository import OutcomeRepository as outcome_repository
class OutcomeApiTest(ApiTestCase):
def seed_static_data(self):
... | 0.524151 | 0.155046 |
### Import required python modules
import logging
from gevent import monkey; monkey.patch_all()
import platform
import os
from os import listdir, stat, makedirs, mkdir, walk, remove, pardir
from os.path import isdir, isfile, join, splitext, getmtime, basename, normpath, exists, expanduser, split, dirname, getsize, ab... | src/pysoda/prepare_metadata.py |
### Import required python modules
import logging
from gevent import monkey; monkey.patch_all()
import platform
import os
from os import listdir, stat, makedirs, mkdir, walk, remove, pardir
from os.path import isdir, isfile, join, splitext, getmtime, basename, normpath, exists, expanduser, split, dirname, getsize, ab... | 0.311951 | 0.114839 |
from azurelinuxagent.common.exception import ProtocolError
import azurelinuxagent.common.logger as logger
# pylint: disable=W0105
"""
Base class for data contracts between guest and host and utilities to manipulate the properties in those contracts
"""
# pylint: enable=W0105
class DataContract(object):
pass
... | azurelinuxagent/common/datacontract.py |
from azurelinuxagent.common.exception import ProtocolError
import azurelinuxagent.common.logger as logger
# pylint: disable=W0105
"""
Base class for data contracts between guest and host and utilities to manipulate the properties in those contracts
"""
# pylint: enable=W0105
class DataContract(object):
pass
... | 0.416797 | 0.319679 |
import csv
import json
import os
from pathlib import Path
import pytest
import yaml
from jinja2 import Template
# -------------------------------------
# Execute once at session start
# -------------------------------------
def omit_hints(data):
"""Set values encapsulated with <> to None in a dict"""
if i... | .github/workflows/data-check/conftest.py |
import csv
import json
import os
from pathlib import Path
import pytest
import yaml
from jinja2 import Template
# -------------------------------------
# Execute once at session start
# -------------------------------------
def omit_hints(data):
"""Set values encapsulated with <> to None in a dict"""
if i... | 0.453746 | 0.352202 |
from __future__ import print_function
import os
import sys
from six.moves import configparser
from chromite.lib import boto_compat
from chromite.lib import cros_test_lib
from chromite.lib import osutils
assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
class FixBotoCertsTest(cros_test_lib.Tem... | lib/boto_compat_unittest.py | from __future__ import print_function
import os
import sys
from six.moves import configparser
from chromite.lib import boto_compat
from chromite.lib import cros_test_lib
from chromite.lib import osutils
assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
class FixBotoCertsTest(cros_test_lib.Tem... | 0.400163 | 0.201695 |
import os
import unittest2 as unittest
import tempfile
import rdflib
import shutil
from osp.core.ontology.installation import OntologyInstallationManager, \
pico_migrate
from osp.core.ontology.namespace_registry import NamespaceRegistry
FILES = [
os.path.join(os.path.dirname(os.path.abspath(__file__)),
... | tests/test_installation.py | import os
import unittest2 as unittest
import tempfile
import rdflib
import shutil
from osp.core.ontology.installation import OntologyInstallationManager, \
pico_migrate
from osp.core.ontology.namespace_registry import NamespaceRegistry
FILES = [
os.path.join(os.path.dirname(os.path.abspath(__file__)),
... | 0.378459 | 0.462655 |
import os
import pytest
from orco import builder, attach_object, attach_file, attach_directory, attach_text
def test_blob_validate_name(env):
@builder()
def bb(x):
with pytest.raises(Exception, match="has to be a string"):
attach_object(123, 1)
with pytest.raises(Exception, match... | tests/test_blobs.py | import os
import pytest
from orco import builder, attach_object, attach_file, attach_directory, attach_text
def test_blob_validate_name(env):
@builder()
def bb(x):
with pytest.raises(Exception, match="has to be a string"):
attach_object(123, 1)
with pytest.raises(Exception, match... | 0.57821 | 0.581897 |
import os
from proboscis import SkipTest
import six
import time as timer
from trove.common import cfg
from trove.common import exception
from trove.common.utils import poll_until
from trove.tests.scenario.helpers.test_helper import DataType
from trove.tests.scenario.runners.test_runners import TestRunner
from trove.... | trove/tests/scenario/runners/cluster_actions_runners.py |
import os
from proboscis import SkipTest
import six
import time as timer
from trove.common import cfg
from trove.common import exception
from trove.common.utils import poll_until
from trove.tests.scenario.helpers.test_helper import DataType
from trove.tests.scenario.runners.test_runners import TestRunner
from trove.... | 0.541894 | 0.340787 |
import numpy as np
import os
import csv
import sys
import MySQLdb
import scipy.stats as stats
from collections import defaultdict
import scipy as sp
from scipy import stats
from sklearn.externals import joblib
from sklearn import metrics
from sklearn import ensemble
from sklearn import linear_model
from sklearn import ... | src/train_collapse_stroke_classifier_both.py | import numpy as np
import os
import csv
import sys
import MySQLdb
import scipy.stats as stats
from collections import defaultdict
import scipy as sp
from scipy import stats
from sklearn.externals import joblib
from sklearn import metrics
from sklearn import ensemble
from sklearn import linear_model
from sklearn import ... | 0.069101 | 0.136983 |
from .helpers import *
from .coefficient_array import CoefficientArray, PwCoeffs
from .py_sirius import *
from .py_sirius import K_point_set, Density
from .logger import Logger
from .operators import S_operator
import numpy as np
from numpy import array, zeros
__all__ = ["ot", "baarman", "bands", "edft"]
class Occupa... | python_module/sirius/__init__.py | from .helpers import *
from .coefficient_array import CoefficientArray, PwCoeffs
from .py_sirius import *
from .py_sirius import K_point_set, Density
from .logger import Logger
from .operators import S_operator
import numpy as np
from numpy import array, zeros
__all__ = ["ot", "baarman", "bands", "edft"]
class Occupa... | 0.558086 | 0.159872 |
from query_engine.sage_engine import SageEngine
from query_engine.iterators.scan import ScanIterator
from query_engine.iterators.filter import FilterIterator
from query_engine.iterators.projection import ProjectionIterator
from query_engine.iterators.loader import load
from database.hdt_file_connector import HDTFileCon... | tests/iterators/filter_iterator_test.py | from query_engine.sage_engine import SageEngine
from query_engine.iterators.scan import ScanIterator
from query_engine.iterators.filter import FilterIterator
from query_engine.iterators.projection import ProjectionIterator
from query_engine.iterators.loader import load
from database.hdt_file_connector import HDTFileCon... | 0.654784 | 0.344554 |
import requests
import pytest
from suite.resources_utils import ensure_connection_to_public_endpoint, create_items_from_yaml, create_example_app, \
wait_until_all_pods_are_ready, ensure_response_from_backend, create_namespace_with_name_from_yaml, delete_namespace
from suite.yaml_utils import get_first_ingress_host... | tests/suite/test_watch_namespace.py | import requests
import pytest
from suite.resources_utils import ensure_connection_to_public_endpoint, create_items_from_yaml, create_example_app, \
wait_until_all_pods_are_ready, ensure_response_from_backend, create_namespace_with_name_from_yaml, delete_namespace
from suite.yaml_utils import get_first_ingress_host... | 0.591841 | 0.341775 |
from typing import Any, Dict
from peekingduck.pipeline.nodes.abstract_node import AbstractNode
from peekingduck.pipeline.nodes.model.hrnetv1 import hrnet_model
class Node(AbstractNode):
"""Initializes and uses HRNet model to infer poses from detected bboxes.
Note that HRNet must be used in conjunction with a... | peekingduck/pipeline/nodes/model/hrnet.py | from typing import Any, Dict
from peekingduck.pipeline.nodes.abstract_node import AbstractNode
from peekingduck.pipeline.nodes.model.hrnetv1 import hrnet_model
class Node(AbstractNode):
"""Initializes and uses HRNet model to infer poses from detected bboxes.
Note that HRNet must be used in conjunction with a... | 0.946026 | 0.535706 |
import sys
sys.path.insert(1, "../..")
# ------------------------------------------------
import logging
from slack_sdk.web.async_client import AsyncSlackResponse, AsyncWebClient
from slack_bolt.async_app import AsyncApp, AsyncAck
logging.basicConfig(level=logging.DEBUG)
# export SLACK_SIGNING_SECRET=***
# export ... | examples/workflow_steps/async_steps_from_apps_primitive.py | import sys
sys.path.insert(1, "../..")
# ------------------------------------------------
import logging
from slack_sdk.web.async_client import AsyncSlackResponse, AsyncWebClient
from slack_bolt.async_app import AsyncApp, AsyncAck
logging.basicConfig(level=logging.DEBUG)
# export SLACK_SIGNING_SECRET=***
# export ... | 0.374791 | 0.284793 |
import unittest
from typing import Any, List, Tuple
from unittest.mock import MagicMock, mock_open, patch
from nix_review.cli import main
from .cli_mocks import (
CliTestCase,
IgnoreArgument,
Mock,
MockCompletedProcess,
build_cmds,
read_asset,
)
def borg_eval_cmds() -> List[Tuple[Any, Any]]:... | nix_review/tests/test_pr_borg_eval.py | import unittest
from typing import Any, List, Tuple
from unittest.mock import MagicMock, mock_open, patch
from nix_review.cli import main
from .cli_mocks import (
CliTestCase,
IgnoreArgument,
Mock,
MockCompletedProcess,
build_cmds,
read_asset,
)
def borg_eval_cmds() -> List[Tuple[Any, Any]]:... | 0.672117 | 0.286543 |
from templates import diag
import os, time
import func
class diag_troubleshooting_f2f_worker(diag):
page = "Troubleshooting.F2F Worker"
title = "Debug F2F Worker Connections"
isFirewall = True
isManagement = False
isClusterXL = False
minVersion = 8020
content = ['This command enables:', 'e... | troubleshooting.py |
from templates import diag
import os, time
import func
class diag_troubleshooting_f2f_worker(diag):
page = "Troubleshooting.F2F Worker"
title = "Debug F2F Worker Connections"
isFirewall = True
isManagement = False
isClusterXL = False
minVersion = 8020
content = ['This command enables:', 'e... | 0.137605 | 0.122156 |
import random
from catch.filter.base_filter import BaseFilter
from catch import probe
__author__ = '<NAME> <<EMAIL>>'
class NExpansionFilter(BaseFilter):
"""Filter that expands 'N' bases within probes.
"""
def __init__(self, limit_n_expansion_randomly=3):
"""
Args:
limit_n_e... | catch/filter/n_expansion_filter.py | import random
from catch.filter.base_filter import BaseFilter
from catch import probe
__author__ = '<NAME> <<EMAIL>>'
class NExpansionFilter(BaseFilter):
"""Filter that expands 'N' bases within probes.
"""
def __init__(self, limit_n_expansion_randomly=3):
"""
Args:
limit_n_e... | 0.458106 | 0.175786 |
from app import db
from flask import current_app, g
from app.youtube_money_calculator.models import Channel, Video
from googleapiclient.discovery import build
class ChannelService:
def fetch(channel_id):
try:
youtube = get_youtube_service()
response = youtube\
.chan... | backend/app/youtube_money_calculator/services.py | from app import db
from flask import current_app, g
from app.youtube_money_calculator.models import Channel, Video
from googleapiclient.discovery import build
class ChannelService:
def fetch(channel_id):
try:
youtube = get_youtube_service()
response = youtube\
.chan... | 0.188997 | 0.098555 |
from abc import ABCMeta, abstractmethod
from asyncio import StreamWriter, Task
from typing import Optional, Tuple
from meltano.core.logging.utils import SubprocessOutputWriter
class IOBlock(metaclass=ABCMeta):
"""The IOBlock interface is a basic block that Consumes, Produces, or Consume and Produces (Transforms)... | src/meltano/core/block/ioblock.py | from abc import ABCMeta, abstractmethod
from asyncio import StreamWriter, Task
from typing import Optional, Tuple
from meltano.core.logging.utils import SubprocessOutputWriter
class IOBlock(metaclass=ABCMeta):
"""The IOBlock interface is a basic block that Consumes, Produces, or Consume and Produces (Transforms)... | 0.942042 | 0.262186 |
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.uni... | report.py | from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.uni... | 0.743727 | 0.108945 |
import contextlib
import os
import textwrap
from mock import Mock, call, patch
from pystachio import Empty
from apache.aurora.client.api import SchedulerProxy
from apache.aurora.client.cli import EXIT_OK
from apache.aurora.client.cli.jobs import DiffCommand
from apache.aurora.client.cli.options import TaskInstanceKe... | Chapter4/Aurora/src/test/python/apache/aurora/client/cli/test_diff.py |
import contextlib
import os
import textwrap
from mock import Mock, call, patch
from pystachio import Empty
from apache.aurora.client.api import SchedulerProxy
from apache.aurora.client.cli import EXIT_OK
from apache.aurora.client.cli.jobs import DiffCommand
from apache.aurora.client.cli.options import TaskInstanceKe... | 0.543833 | 0.094052 |
# Standard libraries. Should not fail.
import sys
import json
import textwrap
from argparse import Action
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
# Required 3rd-party libraries.
try:
from requests_html import HTMLSession
from tabulate import tabulate
from colorama im... | tpsp/__init__.py |
# Standard libraries. Should not fail.
import sys
import json
import textwrap
from argparse import Action
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
# Required 3rd-party libraries.
try:
from requests_html import HTMLSession
from tabulate import tabulate
from colorama im... | 0.406509 | 0.130009 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tempfile
from absl import app
from absl import flags
import apache_beam as beam
import tensorflow.compat.v1 as tf
import tensorflow_transform as tft
import tensorflow_transform.beam as tft_beam
from tenso... | third_party/tensorflow-text/src/tools/wordpiece_vocab/generate_vocab.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tempfile
from absl import app
from absl import flags
import apache_beam as beam
import tensorflow.compat.v1 as tf
import tensorflow_transform as tft
import tensorflow_transform.beam as tft_beam
from tenso... | 0.887741 | 0.169234 |
import datetime
import typing
from datetime import date
from typing import List, Optional
from ninja import Field, Schema
from pydantic import EmailStr
from share import choices, states
class OrganizationSummary(Schema):
id: int
type: str
name: str
city: choices.Cities
class DonationCreation(Schem... | share/schemas.py | import datetime
import typing
from datetime import date
from typing import List, Optional
from ninja import Field, Schema
from pydantic import EmailStr
from share import choices, states
class OrganizationSummary(Schema):
id: int
type: str
name: str
city: choices.Cities
class DonationCreation(Schem... | 0.772058 | 0.229508 |
import functools
import hashlib
import os
from django import http
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.db.transaction import non_atomic_requests
from django.shortcuts import get_object_or_404, redirect
from django.views.decor... | src/olympia/bandwagon/views.py | import functools
import hashlib
import os
from django import http
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.db.models import Q
from django.db.transaction import non_atomic_requests
from django.shortcuts import get_object_or_404, redirect
from django.views.decor... | 0.399929 | 0.056888 |
"""Wrapper around yamllint that supports YAML embedded in Ansible modules."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ast
import json
import os
import re
import sys
import yaml
from yaml.resolver import Resolver
from yaml.constructor import SafeConstructor
from y... | venv/lib/python3.6/site-packages/ansible_test/_data/sanity/yamllint/yamllinter.py | """Wrapper around yamllint that supports YAML embedded in Ansible modules."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import ast
import json
import os
import re
import sys
import yaml
from yaml.resolver import Resolver
from yaml.constructor import SafeConstructor
from y... | 0.543833 | 0.167729 |
from __future__ import annotations
import logging
import os
import platform
import shutil
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generator, Optional, Tuple, Union, cast
from ..compat import cached_property
if TYPE_CHECKING:
from urllib.error import URLError
from runway._l... | runway/env_mgr/__init__.py | from __future__ import annotations
import logging
import os
import platform
import shutil
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generator, Optional, Tuple, Union, cast
from ..compat import cached_property
if TYPE_CHECKING:
from urllib.error import URLError
from runway._l... | 0.805976 | 0.13012 |
import spot
import buddy
match_strings = [('is_buchi', 'is_co_buchi'),
('is_generalized_buchi', 'is_generalized_co_buchi'),
('is_all', 'is_none'),
('is_all', 'is_all'),
('is_buchi', 'is_all')]
# existential and universal are dual
# deterministic is ... | lib/spot-2.8.1/tests/python/dualize.py |
import spot
import buddy
match_strings = [('is_buchi', 'is_co_buchi'),
('is_generalized_buchi', 'is_generalized_co_buchi'),
('is_all', 'is_none'),
('is_all', 'is_all'),
('is_buchi', 'is_all')]
# existential and universal are dual
# deterministic is ... | 0.453504 | 0.585457 |
from dataclasses import dataclass
from sqlalchemy import Column
from ..model import db
@dataclass
class PlaceDAO(db.Model):
__tablename__ = 'place'
__table_args__ = {'extend_existing': True}
id: int
place_num: int
place_name: str
content_id: int
sigungu_code: int
addr: str
lat: f... | camping_server1/app/main/model/place_dao.py | from dataclasses import dataclass
from sqlalchemy import Column
from ..model import db
@dataclass
class PlaceDAO(db.Model):
__tablename__ = 'place'
__table_args__ = {'extend_existing': True}
id: int
place_num: int
place_name: str
content_id: int
sigungu_code: int
addr: str
lat: f... | 0.588298 | 0.111145 |
"""Test that the debug commands work."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from ctools.pysc2 import maps
from ctools.pysc2 import run_configs
from ctools.pysc2.lib import units
from s2clientprotocol import c... | ctools/pysc2/tests/debug_test.py | """Test that the debug commands work."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from ctools.pysc2 import maps
from ctools.pysc2 import run_configs
from ctools.pysc2.lib import units
from s2clientprotocol import c... | 0.78233 | 0.332635 |
import itertools
import os
from absl.testing import parameterized
import tensorflow as tf
from official.core import exp_factory
from official.core import task_factory
from official.projects.edgetpu.vision.serving import export_util
def _build_experiment_model(experiment_type):
"""Builds model from experiment type... | official/projects/edgetpu/vision/serving/export_tflite_test.py | import itertools
import os
from absl.testing import parameterized
import tensorflow as tf
from official.core import exp_factory
from official.core import task_factory
from official.projects.edgetpu.vision.serving import export_util
def _build_experiment_model(experiment_type):
"""Builds model from experiment type... | 0.693992 | 0.282753 |
import hashlib
import logging
from typing import Optional, Union
import github
import gitlab
from ogr.abstract import CommitStatus, GitProject
from ogr.services.gitlab import GitlabProject
from ogr.services.pagure import PagureProject
logger = logging.getLogger(__name__)
class StatusReporter:
def __init__(
... | packit_service/worker/reporting.py |
import hashlib
import logging
from typing import Optional, Union
import github
import gitlab
from ogr.abstract import CommitStatus, GitProject
from ogr.services.gitlab import GitlabProject
from ogr.services.pagure import PagureProject
logger = logging.getLogger(__name__)
class StatusReporter:
def __init__(
... | 0.766774 | 0.135604 |
import logging
from inspect import currentframe
from boto.connection import AWSAuthConnection, AWSQueryConnection
from wrapt import wrap_function_wrapper
from opentelemetry.instrumentation.boto.version import __version__
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.instru... | instrumentation/opentelemetry-instrumentation-boto/src/opentelemetry/instrumentation/boto/__init__.py | import logging
from inspect import currentframe
from boto.connection import AWSAuthConnection, AWSQueryConnection
from wrapt import wrap_function_wrapper
from opentelemetry.instrumentation.boto.version import __version__
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.instru... | 0.69035 | 0.149531 |
import logging
import os
import re
import socket
import time
from abc import ABCMeta, abstractmethod
from contextlib import contextmanager
from datetime import datetime
from importlib import import_module
from inspect import getmembers
import requests
logging.basicConfig(level=logging.WARN)
LOG = logging.getLogger(__... | setup/terraform/resources/labs/__init__.py | import logging
import os
import re
import socket
import time
from abc import ABCMeta, abstractmethod
from contextlib import contextmanager
from datetime import datetime
from importlib import import_module
from inspect import getmembers
import requests
logging.basicConfig(level=logging.WARN)
LOG = logging.getLogger(__... | 0.415492 | 0.054575 |
from ...UI.Base import Document
from ...UI.Elements import div,img,label,radio
from ...Core.DataTypes.UI import EventListener
from ...UI.CustomElements import AspectRatioPreservedContainer
class CreateGame(Document):
Name = "Pong/Arcade/CreateGame"
StyleSheet = "Styles/Arcade/CreateGame.json"
ResourceKey =... | Client/App/Views/Arcade/CreateGame.py | from ...UI.Base import Document
from ...UI.Elements import div,img,label,radio
from ...Core.DataTypes.UI import EventListener
from ...UI.CustomElements import AspectRatioPreservedContainer
class CreateGame(Document):
Name = "Pong/Arcade/CreateGame"
StyleSheet = "Styles/Arcade/CreateGame.json"
ResourceKey =... | 0.349422 | 0.064153 |
import subprocess
from pyroute2 import IPDB
def get_default_iface_name():
ip = IPDB()
interface_name = ip.interfaces[ip.routes['default']['oif']].get('ifname')
ip.release()
return interface_name
def iptables_version():
iptables_proc = subprocess.Popen(['iptables', '-L'], stderr=subprocess.PIPE,... | platform_agent/cmd/iptables.py | import subprocess
from pyroute2 import IPDB
def get_default_iface_name():
ip = IPDB()
interface_name = ip.interfaces[ip.routes['default']['oif']].get('ifname')
ip.release()
return interface_name
def iptables_version():
iptables_proc = subprocess.Popen(['iptables', '-L'], stderr=subprocess.PIPE,... | 0.206494 | 0.067547 |
from oslotest import mockpatch
from tempest.lib import exceptions as lib_exc
from tempest.lib.services.compute import security_groups_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services.compute import base
class TestSecurityGroupsClient(base.BaseComputeServiceTest):
FAKE_SEC... | tempest/tests/lib/services/compute/test_security_groups_client.py |
from oslotest import mockpatch
from tempest.lib import exceptions as lib_exc
from tempest.lib.services.compute import security_groups_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services.compute import base
class TestSecurityGroupsClient(base.BaseComputeServiceTest):
FAKE_SEC... | 0.510985 | 0.188137 |
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
class QT:
"""
Generate an instance of the Quantum Teleportation Protocol.
Attributes
----------
msg : List of Statevectors
The strand of 1-qubit state vectors that is intended to be sent
barriers : bool
C... | QT/quantum_teleportation.py | from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
class QT:
"""
Generate an instance of the Quantum Teleportation Protocol.
Attributes
----------
msg : List of Statevectors
The strand of 1-qubit state vectors that is intended to be sent
barriers : bool
C... | 0.865437 | 0.730855 |
import responses
import pytest
import re
from freezegun import freeze_time
from app import app, settings
from fastapi.testclient import TestClient
from idunn.datasources.wikipedia import WikipediaSession
from idunn.utils.redis import RedisWrapper
from .utils import override_settings
from .test_api_with_wiki import mock... | tests/test_rate_limiter.py | import responses
import pytest
import re
from freezegun import freeze_time
from app import app, settings
from fastapi.testclient import TestClient
from idunn.datasources.wikipedia import WikipediaSession
from idunn.utils.redis import RedisWrapper
from .utils import override_settings
from .test_api_with_wiki import mock... | 0.609524 | 0.406037 |
from .helper_utilities import unflatten_state
from .env import GridWorldMDP
import numpy as np
class GridWorldPlotter(object):
def __init__(self, grid_size, has_absorbing_state=True):
"""
Utility to plot gridworlds
:param grid_size: size of the gridworld
:param has_absorbing_state: ... | emdp/gridworld/plotting.py | from .helper_utilities import unflatten_state
from .env import GridWorldMDP
import numpy as np
class GridWorldPlotter(object):
def __init__(self, grid_size, has_absorbing_state=True):
"""
Utility to plot gridworlds
:param grid_size: size of the gridworld
:param has_absorbing_state: ... | 0.74826 | 0.663056 |
import unittest
from garminworkouts.models.power import Power
class PowerTestCase(unittest.TestCase):
def test_valid_power_to_watts_conversion(self):
ftp = 200
diff = 0
valid_powers = [
("0", 0),
("0%", 0),
("10", 20),
("10%", 20),
... | tests/models/test_power.py | import unittest
from garminworkouts.models.power import Power
class PowerTestCase(unittest.TestCase):
def test_valid_power_to_watts_conversion(self):
ftp = 200
diff = 0
valid_powers = [
("0", 0),
("0%", 0),
("10", 20),
("10%", 20),
... | 0.542379 | 0.628151 |
from progressivis.table.table import Table
from progressivis.table.constant import Constant
from progressivis import Print
from progressivis.stats import RandomTable
from progressivis.table.bisectmod import Bisect
from progressivis.core.bitmap import bitmap
from progressivis.table.hist_index import HistogramIndex
from... | tests/test_03_bisect.py | from progressivis.table.table import Table
from progressivis.table.constant import Constant
from progressivis import Print
from progressivis.stats import RandomTable
from progressivis.table.bisectmod import Bisect
from progressivis.core.bitmap import bitmap
from progressivis.table.hist_index import HistogramIndex
from... | 0.38827 | 0.490968 |
from __future__ import annotations
from dataclasses import dataclass
from functools import partial
from homeassistant.components.sensor import (
STATE_CLASS_MEASUREMENT,
STATE_CLASS_TOTAL_INCREASING,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from hom... | homeassistant/components/rainmachine/sensor.py | from __future__ import annotations
from dataclasses import dataclass
from functools import partial
from homeassistant.components.sensor import (
STATE_CLASS_MEASUREMENT,
STATE_CLASS_TOTAL_INCREASING,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from hom... | 0.749362 | 0.081923 |
import os
import sys
import numpy as np
from rednose.helpers import TEMPLATE_DIR, load_code, write_code
from rednose.helpers.sympy_helpers import quat_matrix_l, rot_matrix
def sane(track):
img_pos = track[1:, 2:4]
diffs_x = abs(img_pos[1:, 0] - img_pos[:-1, 0])
diffs_y = abs(img_pos[1:, 1] - img_pos[:-1, 1])... | rednose/helpers/feature_handler.py |
import os
import sys
import numpy as np
from rednose.helpers import TEMPLATE_DIR, load_code, write_code
from rednose.helpers.sympy_helpers import quat_matrix_l, rot_matrix
def sane(track):
img_pos = track[1:, 2:4]
diffs_x = abs(img_pos[1:, 0] - img_pos[:-1, 0])
diffs_y = abs(img_pos[1:, 1] - img_pos[:-1, 1])... | 0.315103 | 0.372791 |
from __future__ import division
import time
import Adafruit_PCA9685
import RPi.GPIO as GPIO
from Adafruit_GPIO import I2C
import rospy
from geometry_msgs.msg import Twist
# sudo apt install RPi.GPIO
# pip install adafruit-pca9685
# pip install adafruit-gpio
class SunFounder:
# STEERING
# used for the DRIVE_T... | terabot_drive/src/base_control.py | from __future__ import division
import time
import Adafruit_PCA9685
import RPi.GPIO as GPIO
from Adafruit_GPIO import I2C
import rospy
from geometry_msgs.msg import Twist
# sudo apt install RPi.GPIO
# pip install adafruit-pca9685
# pip install adafruit-gpio
class SunFounder:
# STEERING
# used for the DRIVE_T... | 0.610918 | 0.155976 |
from peas.server.outbound_message import NodeType
from peas.server.server import ssl_context_for_server
from peas.types.peer_info import PeerInfo
from tests.block_tools import create_block_tools
from peas.util.ints import uint16
from peas.util.ws_message import create_payload
from tests.core.node_height import node_hei... | tests/core/daemon/test_daemon.py | from peas.server.outbound_message import NodeType
from peas.server.server import ssl_context_for_server
from peas.types.peer_info import PeerInfo
from tests.block_tools import create_block_tools
from peas.util.ints import uint16
from peas.util.ws_message import create_payload
from tests.core.node_height import node_hei... | 0.366476 | 0.349699 |
import unittest
import numpy as np
import SimpleITK as sitk
from deliravision.utils.image_ops import bounding_box, \
calculate_origin_offset, max_energy_slice, \
sitk_copy_metadata, sitk_new_blank_image, \
sitk_resample_to_image, sitk_resample_to_shape, sitk_resample_to_spacing
class ImageOpTest(unittest.... | tests/utils/image_ops.py | import unittest
import numpy as np
import SimpleITK as sitk
from deliravision.utils.image_ops import bounding_box, \
calculate_origin_offset, max_energy_slice, \
sitk_copy_metadata, sitk_new_blank_image, \
sitk_resample_to_image, sitk_resample_to_shape, sitk_resample_to_spacing
class ImageOpTest(unittest.... | 0.665193 | 0.717829 |
import pytest
from weasyprint.formatting_structure import boxes
from .testing_utils import assert_no_logs, render_pages
def outer_area(box):
"""Return the (x, y, w, h) rectangle for the outer area of a box."""
return (box.position_x, box.position_y,
box.margin_width(), box.margin_height())
@ass... | tests/test_float.py | import pytest
from weasyprint.formatting_structure import boxes
from .testing_utils import assert_no_logs, render_pages
def outer_area(box):
"""Return the (x, y, w, h) rectangle for the outer area of a box."""
return (box.position_x, box.position_y,
box.margin_width(), box.margin_height())
@ass... | 0.785267 | 0.517876 |
import io
import os
import time
import logging
import urllib.parse
import json
import boto3
from botocore.exceptions import ClientError
# FalconPy SDK - Auth, Sample Uploads and Quick Scan
from falconpy import OAuth2, SampleUploads, QuickScan # pylint: disable=E0401
from functions import generate_manifest, send_to_sec... | s3-bucket-protection/lambda/lambda_function.py | import io
import os
import time
import logging
import urllib.parse
import json
import boto3
from botocore.exceptions import ClientError
# FalconPy SDK - Auth, Sample Uploads and Quick Scan
from falconpy import OAuth2, SampleUploads, QuickScan # pylint: disable=E0401
from functions import generate_manifest, send_to_sec... | 0.36693 | 0.064653 |
import cv2
import numpy as np
from utils import ShapeDetector
from vision.msg import VisionMessage
offset = 15
class ImageTracker:
def __init__(self, segm_limits, kernel):
self.shape_detector = ShapeDetector()
self.kernel = kernel
self.frame = None
self.vision_msg = VisionMessage()... | image_tracker.py | import cv2
import numpy as np
from utils import ShapeDetector
from vision.msg import VisionMessage
offset = 15
class ImageTracker:
def __init__(self, segm_limits, kernel):
self.shape_detector = ShapeDetector()
self.kernel = kernel
self.frame = None
self.vision_msg = VisionMessage()... | 0.203312 | 0.217576 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import Optional, TYPE_CHECKING
from cdm.enums import CdmObjectType
from cdm.utilities import ResolveOptions, logger
from cdm.enums import CdmLogCode
... | objectModel/Python/cdm/objectmodel/cdm_trait_group_def.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
from typing import Optional, TYPE_CHECKING
from cdm.enums import CdmObjectType
from cdm.utilities import ResolveOptions, logger
from cdm.enums import CdmLogCode
... | 0.914549 | 0.11694 |
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from urllib.parse import urlencode
from urllib.request import urlopen
from django.core.urlresolvers import reverse
from django.conf import settings as project_settings
from .base import BackendBase
class PaypalBackend(Backe... | payments/backends/paypal.py | from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _
from urllib.parse import urlencode
from urllib.request import urlopen
from django.core.urlresolvers import reverse
from django.conf import settings as project_settings
from .base import BackendBase
class PaypalBackend(Backe... | 0.41052 | 0.077274 |
import pytest
from cuppak.component.abstract_frame import AbstractFrame
from cuppak.dto import *
##SET UP
class ConcreteAbstractFrame(AbstractFrame):
def __init__(self, window, columns, rows, **kw):
super().__init__(window, columns, rows, **kw)
def change_child_state(self, state):
super().ch... | cuppak/tests/component/abstract_frame_test.py | import pytest
from cuppak.component.abstract_frame import AbstractFrame
from cuppak.dto import *
##SET UP
class ConcreteAbstractFrame(AbstractFrame):
def __init__(self, window, columns, rows, **kw):
super().__init__(window, columns, rows, **kw)
def change_child_state(self, state):
super().ch... | 0.524395 | 0.584568 |
from twisted.internet import defer, reactor
from zope.interface import implements, classProvides
from automatron.backend.plugin import IAutomatronPluginFactory
from automatron.controller.client import IAutomatronSignedOnHandler, IAutomatronChannelJoinedHandler,\
IAutomatronChannelLeftHandler, IAutomatronChannelKic... | twisted/plugins/automatron_auto_join.py | from twisted.internet import defer, reactor
from zope.interface import implements, classProvides
from automatron.backend.plugin import IAutomatronPluginFactory
from automatron.controller.client import IAutomatronSignedOnHandler, IAutomatronChannelJoinedHandler,\
IAutomatronChannelLeftHandler, IAutomatronChannelKic... | 0.720172 | 0.08698 |
from etcdb import OperationalError, __version__
from etcdb.resultset import Column
from etcdb.sqlparser.parser import SQLParserError
class EtcdbFunction(object):
"""EtcdbFunction represents an SQL function.
:param function_name: python function that implements SQL function.
:type function_name: callable
... | etcdb/eval_expr.py | from etcdb import OperationalError, __version__
from etcdb.resultset import Column
from etcdb.sqlparser.parser import SQLParserError
class EtcdbFunction(object):
"""EtcdbFunction represents an SQL function.
:param function_name: python function that implements SQL function.
:type function_name: callable
... | 0.76856 | 0.439988 |
from direct.distributed.DistributedObjectGlobalAI import DistributedObjectGlobalAI
from direct.directnotify import DirectNotifyGlobal
from toontown.chat.ChatGlobals import *
from otp.distributed import OtpDoGlobals
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.MsgTypes import *
from time ... | otp/chat/ChatAgentAI.py | from direct.distributed.DistributedObjectGlobalAI import DistributedObjectGlobalAI
from direct.directnotify import DirectNotifyGlobal
from toontown.chat.ChatGlobals import *
from otp.distributed import OtpDoGlobals
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.MsgTypes import *
from time ... | 0.507568 | 0.051893 |
from datetime import datetime
import itertools
import netaddr
from neutron_lib.agent import topics
from neutron_lib.api.definitions import portbindings_extended as pb_ext
from neutron_lib.callbacks import events as callback_events
from neutron_lib.callbacks import registry
from neutron_lib.callbacks import resources ... | neutron/agent/rpc.py |
from datetime import datetime
import itertools
import netaddr
from neutron_lib.agent import topics
from neutron_lib.api.definitions import portbindings_extended as pb_ext
from neutron_lib.callbacks import events as callback_events
from neutron_lib.callbacks import registry
from neutron_lib.callbacks import resources ... | 0.782164 | 0.097519 |
import ast
from typing import Optional
from gaphas.canvas import Canvas
from gaphas.item import NW, Element
from gaphas.item import Line as _Line
from gaphas.util import path_ellipse
class SimpleItem:
"""
Marker for simple (non-Presentation) diagram items.
"""
canvas: Optional[Canvas]
def save(... | gaphor/diagram/general/simpleitem.py | import ast
from typing import Optional
from gaphas.canvas import Canvas
from gaphas.item import NW, Element
from gaphas.item import Line as _Line
from gaphas.util import path_ellipse
class SimpleItem:
"""
Marker for simple (non-Presentation) diagram items.
"""
canvas: Optional[Canvas]
def save(... | 0.807574 | 0.292772 |
from LTO.Transactions.SetScript import SetScript
from LTO.Accounts.AccountFactoryED25519 import AccountED25519 as AccountFactory
from time import time
from unittest import mock
class TestSetScript:
ACCOUNT_SEED = "df3dd6d884714288a39af0bd973a1771c9f00f168cf040d6abb6a50dd5e055d8"
account = AccountFactory('T')... | tests/Transactions/SetScriptTest.py | from LTO.Transactions.SetScript import SetScript
from LTO.Accounts.AccountFactoryED25519 import AccountED25519 as AccountFactory
from time import time
from unittest import mock
class TestSetScript:
ACCOUNT_SEED = "df3dd6d884714288a39af0bd973a1771c9f00f168cf040d6abb6a50dd5e055d8"
account = AccountFactory('T')... | 0.572245 | 0.437403 |
# 実行方法
# python python_crawler_final_bs4.py
import re
import time
from typing import Iterator
import requests
from pymongo import MongoClient
from urllib.parse import urljoin
from bs4 import BeautifulSoup
def main():
"""
クローラーのメインの処理。
"""
client = MongoClient('localhost', 27017) # ローカルホストのMongoDBに接... | crawling_scraping/crawler/python_crawler_final_bs4.py |
# 実行方法
# python python_crawler_final_bs4.py
import re
import time
from typing import Iterator
import requests
from pymongo import MongoClient
from urllib.parse import urljoin
from bs4 import BeautifulSoup
def main():
"""
クローラーのメインの処理。
"""
client = MongoClient('localhost', 27017) # ローカルホストのMongoDBに接... | 0.41182 | 0.210604 |
import itertools
import logging
from cookiecutter.exceptions import CookiecutterException
from cookiecutter.main import cookiecutter
from samcli.local.common.runtime_template import RUNTIME_DEP_TEMPLATE_MAPPING
from samcli.local.init.exceptions import GenerateProjectFailedError
LOG = logging.getLogger(__name__)
de... | samcli/local/init/__init__.py | import itertools
import logging
from cookiecutter.exceptions import CookiecutterException
from cookiecutter.main import cookiecutter
from samcli.local.common.runtime_template import RUNTIME_DEP_TEMPLATE_MAPPING
from samcli.local.init.exceptions import GenerateProjectFailedError
LOG = logging.getLogger(__name__)
de... | 0.580471 | 0.128143 |
import json
import os
from types import SimpleNamespace
import pytest
from golem.execution_runner import execution_runner as exc_runner
from golem.core import test
from golem.core import test_data
from golem.core import environment_manager
from golem.core import utils
from golem.core import settings_manager
from gole... | tests/execution_runner/execution_runner_test.py | import json
import os
from types import SimpleNamespace
import pytest
from golem.execution_runner import execution_runner as exc_runner
from golem.core import test
from golem.core import test_data
from golem.core import environment_manager
from golem.core import utils
from golem.core import settings_manager
from gole... | 0.49707 | 0.33334 |
import csv
import re
import os
from pyaedt.generic.general_methods import aedt_exception_handler, generate_unique_name, is_ironpython
from pyaedt.application.Analysis import Analysis
from pyaedt.modeler.Model3D import Modeler3D
from pyaedt.modules.MeshIcepak import IcepakMesh
if is_ironpython:
from pyaedt.modules... | pyaedt/application/AnalysisIcepak.py | import csv
import re
import os
from pyaedt.generic.general_methods import aedt_exception_handler, generate_unique_name, is_ironpython
from pyaedt.application.Analysis import Analysis
from pyaedt.modeler.Model3D import Modeler3D
from pyaedt.modules.MeshIcepak import IcepakMesh
if is_ironpython:
from pyaedt.modules... | 0.809276 | 0.354391 |
import numpy as np
from ..normalizations import minmax_normalization
from ..distance_metrics import euclidean
from .mcda_method import MCDA_method
class TOPSIS(MCDA_method):
def __init__(self, normalization_method = minmax_normalization, distance_metric = euclidean):
"""
Create the TOPSIS method o... | src/pyrepo_mcda/mcda_methods/topsis.py | import numpy as np
from ..normalizations import minmax_normalization
from ..distance_metrics import euclidean
from .mcda_method import MCDA_method
class TOPSIS(MCDA_method):
def __init__(self, normalization_method = minmax_normalization, distance_metric = euclidean):
"""
Create the TOPSIS method o... | 0.93485 | 0.695907 |
import unittest
from nose import SkipTest
import rx
asyncio = rx.config['asyncio']
if asyncio is None:
raise SkipTest("asyncio not available")
Future = rx.config['Future']
from rx import Observable
class TestFromFuture(unittest.TestCase):
def test_future_success(self):
loop = asyncio.get_event_loop(... | tests/test_observable/py3_fromfuture.py | import unittest
from nose import SkipTest
import rx
asyncio = rx.config['asyncio']
if asyncio is None:
raise SkipTest("asyncio not available")
Future = rx.config['Future']
from rx import Observable
class TestFromFuture(unittest.TestCase):
def test_future_success(self):
loop = asyncio.get_event_loop(... | 0.439026 | 0.318287 |
import argparse
import os
import sys
import json
import time
import humanize
import fnmatch
import hashlib
from pathlib import Path
IGNORED_FILES = [
".submit.timestamp",
".user_assignment_access.json"
]
with open(Path(__file__).resolve().parent / "lichen_config.json") as lichen_config_file:
LICHEN_CONFIG... | bin/concatenate_all.py | import argparse
import os
import sys
import json
import time
import humanize
import fnmatch
import hashlib
from pathlib import Path
IGNORED_FILES = [
".submit.timestamp",
".user_assignment_access.json"
]
with open(Path(__file__).resolve().parent / "lichen_config.json") as lichen_config_file:
LICHEN_CONFIG... | 0.335351 | 0.113432 |
"""thor_layer"""
import numpy as np
import mindspore.common.dtype as mstype
from mindspore._checkparam import check_bool, check_int_positive
from mindspore.common.initializer import TruncatedNormal, initializer
from mindspore.common.parameter import Parameter
from mindspore.common.tensor import Tensor
from mindspore.nn... | model_zoo/official/nlp/bert_thor/src/thor_layer.py | """thor_layer"""
import numpy as np
import mindspore.common.dtype as mstype
from mindspore._checkparam import check_bool, check_int_positive
from mindspore.common.initializer import TruncatedNormal, initializer
from mindspore.common.parameter import Parameter
from mindspore.common.tensor import Tensor
from mindspore.nn... | 0.893522 | 0.584597 |
import socket
from time import sleep
import sys
import pickle
from threading import Thread
from manualreview import rawscriptsmenu
import hashlib
from manualreview import videoscriptcore
import datetime
from manualreview import publishmenu
from manualreview import settings
from PyQt5 import QtWidgets
import... | YouTube Bot Client/manualreview/client.py | import socket
from time import sleep
import sys
import pickle
from threading import Thread
from manualreview import rawscriptsmenu
import hashlib
from manualreview import videoscriptcore
import datetime
from manualreview import publishmenu
from manualreview import settings
from PyQt5 import QtWidgets
import... | 0.091696 | 0.050471 |
import sys
import logging
import numpy as np
import pandas as pnd
from shapely.geometry import LineString
import orangery.ops.geometry as og
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class Change:
""" An analysis of the change between two Section objects.
Parameters
... | orangery/core/change.py | import sys
import logging
import numpy as np
import pandas as pnd
from shapely.geometry import LineString
import orangery.ops.geometry as og
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class Change:
""" An analysis of the change between two Section objects.
Parameters
... | 0.58166 | 0.337217 |
import argparse
import logging
import pickle
import os
import sys
from pathlib import Path
import numpy as np
import _init_paths # noqa: F401
from utils.logging import setup_logging
def main():
# Use first line of file docstring as description if it exists.
parser = argparse.ArgumentParser(
descrip... | tools/one_off/list_video_mistake_types.py | import argparse
import logging
import pickle
import os
import sys
from pathlib import Path
import numpy as np
import _init_paths # noqa: F401
from utils.logging import setup_logging
def main():
# Use first line of file docstring as description if it exists.
parser = argparse.ArgumentParser(
descrip... | 0.456894 | 0.227942 |