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 yaml
from apricot import TestWithServers
from command_utils import CommandFailure
from server_utils import ServerFailed
class ConfigGenerateRun(TestWithServers):
"""JIRA ID: DAOS-5986
Verify dmg config generate by running daos_server with generated config
file.
:avocado: recursive
"""
... | src/tests/ftest/control/config_generate_run.py | import yaml
from apricot import TestWithServers
from command_utils import CommandFailure
from server_utils import ServerFailed
class ConfigGenerateRun(TestWithServers):
"""JIRA ID: DAOS-5986
Verify dmg config generate by running daos_server with generated config
file.
:avocado: recursive
"""
... | 0.379378 | 0.157105 |
import numpy as np
import Robustness as Robust
def angle_normalization_0_2pi(angle):
"""Automatically normalize angle value(s) to the range of 0-2pi.
This function relies on modular arithmetic.
Parameters
----------
angle : array_like
The angles to be converted
Returns... | Codebase/Active_Codebase/Backend/astronomical_coordinates.py | import numpy as np
import Robustness as Robust
def angle_normalization_0_2pi(angle):
"""Automatically normalize angle value(s) to the range of 0-2pi.
This function relies on modular arithmetic.
Parameters
----------
angle : array_like
The angles to be converted
Returns... | 0.899519 | 0.674231 |
from flask import Blueprint, request, current_app
from apps.autotest.business.monkey import (
MonkeyBusiness, MonkeyDeviceStatusBusiness, MonkeyErrorLogBusiness,
MonkeyPackageBusiness, MonkeyReportBusiness, MonkeyDeviceUsingBusiness,
)
from apps.autotest.extentions import parse_list_args2, parse_list_args, val... | apps/autotest/views/monkey.py | from flask import Blueprint, request, current_app
from apps.autotest.business.monkey import (
MonkeyBusiness, MonkeyDeviceStatusBusiness, MonkeyErrorLogBusiness,
MonkeyPackageBusiness, MonkeyReportBusiness, MonkeyDeviceUsingBusiness,
)
from apps.autotest.extentions import parse_list_args2, parse_list_args, val... | 0.351534 | 0.188604 |
#!pip install --upgrade plotly
import plotly.graph_objs as go
import statsmodels.api as sm
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
def plot_data(data, **kwargs):
title = kwargs.get('title')
xlabel = kwargs.get('xlabel... | plotly_utils/__init__.py |
#!pip install --upgrade plotly
import plotly.graph_objs as go
import statsmodels.api as sm
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
def plot_data(data, **kwargs):
title = kwargs.get('title')
xlabel = kwargs.get('xlabel... | 0.482917 | 0.486149 |
from collections import defaultdict
import sys, os
class nd_node(object):
''' directionless (non-directed) node'''
def __init__(self, name):
self.name = name
self.neighbors = []
class Topology(object):
def __init__(self):
self.num_nodes = 0
self.vertices = []
self... | system_model/topology.py | from collections import defaultdict
import sys, os
class nd_node(object):
''' directionless (non-directed) node'''
def __init__(self, name):
self.name = name
self.neighbors = []
class Topology(object):
def __init__(self):
self.num_nodes = 0
self.vertices = []
self... | 0.350533 | 0.181662 |
import errno
import logging
import select
from . import dirwatch_base
from treadmill.syscall import inotify
_LOGGER = logging.getLogger(__name__)
class LinuxDirWatcher(dirwatch_base.DirWatcher):
"""Linux directory watcher implementation."""
__slots__ = (
'inotify',
'poll'
)
def _... | treadmill/dirwatch/linux_dirwatch.py |
import errno
import logging
import select
from . import dirwatch_base
from treadmill.syscall import inotify
_LOGGER = logging.getLogger(__name__)
class LinuxDirWatcher(dirwatch_base.DirWatcher):
"""Linux directory watcher implementation."""
__slots__ = (
'inotify',
'poll'
)
def _... | 0.635675 | 0.104523 |
from ..resources.tokens.token_types import TokenType, Token
from string import ascii_letters
KEYWORDS = ['define', 'object', 'cls', 'if', 'elif', 'else', 'and', 'or', 'not', 'for', 'while', 'return']
LETTERS_DIGITS = ascii_letters + '0123456789'
class Lexer:
"""
The class for the lexer of the language.
... | language/lexer/lexer.py | from ..resources.tokens.token_types import TokenType, Token
from string import ascii_letters
KEYWORDS = ['define', 'object', 'cls', 'if', 'elif', 'else', 'and', 'or', 'not', 'for', 'while', 'return']
LETTERS_DIGITS = ascii_letters + '0123456789'
class Lexer:
"""
The class for the lexer of the language.
... | 0.427755 | 0.305102 |
from sense_hat import SenseHat
from time import sleep, time
from multiprocessing import Process
from pubnub.pubnub import PubNub, SubscribeListener, SubscribeCallback, PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.exceptions import PubNubException
import uuid, os, pyrebase, pubnub, sy... | Sensor/ReadSensorData.py | from sense_hat import SenseHat
from time import sleep, time
from multiprocessing import Process
from pubnub.pubnub import PubNub, SubscribeListener, SubscribeCallback, PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.exceptions import PubNubException
import uuid, os, pyrebase, pubnub, sy... | 0.330795 | 0.179351 |
from threading import Semaphore
from uuid import uuid4
from eventsourcing.persistence import (
AggregateRecorder,
ApplicationRecorder,
ProcessRecorder,
StoredEvent,
Tracking,
)
from eventsourcing.tests.persistence import (
AggregateRecorderTestCase,
ApplicationRecorderTestCase,
ProcessR... | tests/test_recorders.py | from threading import Semaphore
from uuid import uuid4
from eventsourcing.persistence import (
AggregateRecorder,
ApplicationRecorder,
ProcessRecorder,
StoredEvent,
Tracking,
)
from eventsourcing.tests.persistence import (
AggregateRecorderTestCase,
ApplicationRecorderTestCase,
ProcessR... | 0.498779 | 0.357483 |
from decimal import Decimal as PyDecimal # Qt 5.12 also exports Decimal
import os
import re
import shutil
import threading
import urllib
from .address import Address
from . import bitcoin
from . import networks
from .util import format_satoshis_plain
DEFAULT_EXPLORER = "Blockchair.com"
mainnet_block_explorers = {... | lib/web.py |
from decimal import Decimal as PyDecimal # Qt 5.12 also exports Decimal
import os
import re
import shutil
import threading
import urllib
from .address import Address
from . import bitcoin
from . import networks
from .util import format_satoshis_plain
DEFAULT_EXPLORER = "Blockchair.com"
mainnet_block_explorers = {... | 0.465873 | 0.21034 |
from lib.instance_generation.chen_grossmann_miller_generator import generate_chen_grossmann_miller_instances
from lib.instance_generation.grossmann_random_generator import generate_grossmann_random_instances
from lib.instance_generation.large_scale_instance_generator import generate_large_scale_instances
from lib.insta... | main.py | from lib.instance_generation.chen_grossmann_miller_generator import generate_chen_grossmann_miller_instances
from lib.instance_generation.grossmann_random_generator import generate_grossmann_random_instances
from lib.instance_generation.large_scale_instance_generator import generate_large_scale_instances
from lib.insta... | 0.314156 | 0.066297 |
import sys
from collections import OrderedDict
import numpy as np
from holoviews.core.data import Interface, DictInterface, MultiInterface
from holoviews.core.data.interface import DataError
from holoviews.core.data.spatialpandas import to_geom_dict
from holoviews.core.dimension import OrderedDict as cyODict, dimensio... | geoviews/data/geom_dict.py | import sys
from collections import OrderedDict
import numpy as np
from holoviews.core.data import Interface, DictInterface, MultiInterface
from holoviews.core.data.interface import DataError
from holoviews.core.data.spatialpandas import to_geom_dict
from holoviews.core.dimension import OrderedDict as cyODict, dimensio... | 0.536556 | 0.497986 |
import os.path
import shlex
from typing import List, Tuple, cast
from moulin.utils import create_stamp_name
from yaml.nodes import MappingNode, SequenceNode
from moulin import yaml_helpers as yh
from moulin import ninja_syntax
def get_builder(conf: MappingNode, name: str, build_dir: str, src_stamps: List[str],
... | moulin/builders/yocto.py | import os.path
import shlex
from typing import List, Tuple, cast
from moulin.utils import create_stamp_name
from yaml.nodes import MappingNode, SequenceNode
from moulin import yaml_helpers as yh
from moulin import ninja_syntax
def get_builder(conf: MappingNode, name: str, build_dir: str, src_stamps: List[str],
... | 0.770292 | 0.15034 |
import json
from alipay.aop.api.constant.ParamConstants import *
class SceneExtParam(object):
def __init__(self):
self._apply_reason = None
self._contract_no = None
self._discountamt = None
self._firstpayamt = None
self._interestrate = None
self._lastpayamt = None... | alipay/aop/api/domain/SceneExtParam.py | import json
from alipay.aop.api.constant.ParamConstants import *
class SceneExtParam(object):
def __init__(self):
self._apply_reason = None
self._contract_no = None
self._discountamt = None
self._firstpayamt = None
self._interestrate = None
self._lastpayamt = None... | 0.517083 | 0.216198 |
from contextlib import contextmanager
from .utils.debug import debug_if_needed, NO_EXC_INFO
from .utils.exception_mark import mark_exception, get_exception_mark
from .utils.traceback_proxy import create_traceback_proxy
from . import hooks as trigger_hook
from . import exceptions
from ._compat import PY2, PYPY
from .ctx... | slash/exception_handling.py | from contextlib import contextmanager
from .utils.debug import debug_if_needed, NO_EXC_INFO
from .utils.exception_mark import mark_exception, get_exception_mark
from .utils.traceback_proxy import create_traceback_proxy
from . import hooks as trigger_hook
from . import exceptions
from ._compat import PY2, PYPY
from .ctx... | 0.458591 | 0.101012 |
from kivy.graphics import *
from kivy.graphics.instructions import *
from .gobject import GObject
def same_side(p1, p2, a, b):
"""
Checks whether two points are on the same side of a line segment.
:param p1: A point represented as a 2-element sequence of numbers
:type p1: ``list`` or ``tuple``
... | bracket/game2d/gpath.py | from kivy.graphics import *
from kivy.graphics.instructions import *
from .gobject import GObject
def same_side(p1, p2, a, b):
"""
Checks whether two points are on the same side of a line segment.
:param p1: A point represented as a 2-element sequence of numbers
:type p1: ``list`` or ``tuple``
... | 0.91791 | 0.750004 |
import operator
from nuitka.PythonVersions import python_version
binary_operator_functions = {
"Add": operator.add,
"Sub": operator.sub,
"Pow": operator.pow,
"Mult": operator.mul,
"FloorDiv": operator.floordiv,
"TrueDiv": operator.truediv,
"Mod": operator.mod,
"LShift": operator.lshift... | nuitka/PythonOperators.py | import operator
from nuitka.PythonVersions import python_version
binary_operator_functions = {
"Add": operator.add,
"Sub": operator.sub,
"Pow": operator.pow,
"Mult": operator.mul,
"FloorDiv": operator.floordiv,
"TrueDiv": operator.truediv,
"Mod": operator.mod,
"LShift": operator.lshift... | 0.572603 | 0.387459 |
from unittest import TestCase, mock
import logging
from data_vault import get_synced_params
from helper import KeeperApiHelper
from keepercommander.commands import folder
from keepercommander.error import CommandError
class TestFolder(TestCase):
def setUp(self):
self.communicate_mock = mock.patch('keeper... | unit-tests/test_command_folder.py | from unittest import TestCase, mock
import logging
from data_vault import get_synced_params
from helper import KeeperApiHelper
from keepercommander.commands import folder
from keepercommander.error import CommandError
class TestFolder(TestCase):
def setUp(self):
self.communicate_mock = mock.patch('keeper... | 0.530236 | 0.370282 |
import pytest
import torch
import torchcde
@pytest.mark.parametrize("backend, method, kwargs", (('torchdiffeq', 'rk4', {"options": {"step_size": 1.0}}),
('torchdiffeq', 'dopri5', {}),
('torchsde', 'midpoint', {"d... | test/test_cdeint.py | import pytest
import torch
import torchcde
@pytest.mark.parametrize("backend, method, kwargs", (('torchdiffeq', 'rk4', {"options": {"step_size": 1.0}}),
('torchdiffeq', 'dopri5', {}),
('torchsde', 'midpoint', {"d... | 0.863837 | 0.711675 |
from math import pi, sin
from pysph.sph.equation import Equation
# constants
M_PI = pi
class SummationDensity(Equation):
r"""**Summation density with volume summation**
In addition to the standard summation density, the number density
for the particle is also computed. The number density is important
... | pysph/sph/wc/transport_velocity.py | from math import pi, sin
from pysph.sph.equation import Equation
# constants
M_PI = pi
class SummationDensity(Equation):
r"""**Summation density with volume summation**
In addition to the standard summation density, the number density
for the particle is also computed. The number density is important
... | 0.909068 | 0.75199 |
from datetime import timedelta
from typing import List, Tuple
from celery.app import shared_task
from django.db.models import Count
from django.utils.timezone import now
from posthog.models import Team
from posthog.models.event import Event
from posthog.models.event_definition import EventDefinition
from posthog.mode... | posthog/tasks/calculate_event_property_usage.py | from datetime import timedelta
from typing import List, Tuple
from celery.app import shared_task
from django.db.models import Count
from django.utils.timezone import now
from posthog.models import Team
from posthog.models.event import Event
from posthog.models.event_definition import EventDefinition
from posthog.mode... | 0.536556 | 0.172416 |
import re
from flask import (
render_template,
redirect,
url_for,
flash,
current_app,
Blueprint,
request,
)
from flask_login import login_user
from slurk.extensions.login import login_manager
from slurk.models import User, Token
from .forms import LoginForm
import slurk.views.login.events... | slurk/views/login/__init__.py | import re
from flask import (
render_template,
redirect,
url_for,
flash,
current_app,
Blueprint,
request,
)
from flask_login import login_user
from slurk.extensions.login import login_manager
from slurk.models import User, Token
from .forms import LoginForm
import slurk.views.login.events... | 0.398172 | 0.05549 |
from flask import Flask, request, redirect, render_template, session, flash
from mysqlconnection import MySQLConnector
import datetime
import re
import md5 # imports the md5 module to generate a hash
app = Flask(__name__)
app.secret_key = "ThisIsSecret!"
mysql = MySQLConnector(app,'login_registration_db')
EMAIL_REGEX... | Python/FlaskMySQL/LoginAndRegistration/server.py | from flask import Flask, request, redirect, render_template, session, flash
from mysqlconnection import MySQLConnector
import datetime
import re
import md5 # imports the md5 module to generate a hash
app = Flask(__name__)
app.secret_key = "ThisIsSecret!"
mysql = MySQLConnector(app,'login_registration_db')
EMAIL_REGEX... | 0.350533 | 0.05498 |
"""Utility functions for managing the underling Git repository."""
import os
import sys
from contextlib import contextmanager
from email.utils import formatdate
import click
import git
from git import Actor
from renku import errors
from renku.version import __version__
GIT_KEY = 'renku.git'
COMMITTER = Actor(
'... | renku/cli/_git.py | """Utility functions for managing the underling Git repository."""
import os
import sys
from contextlib import contextmanager
from email.utils import formatdate
import click
import git
from git import Actor
from renku import errors
from renku.version import __version__
GIT_KEY = 'renku.git'
COMMITTER = Actor(
'... | 0.400984 | 0.207415 |
""" Primary Backup Logic"""
import json
import sys
import time
import datetime
import logging
import argparse
import subprocess
from datetime import date
from settings import settings
from googleapiclient import discovery
from kubernetes_client import k8s_control
from googleapiclient.errors import HttpError
from oaut... | backup/backup-disks.py |
""" Primary Backup Logic"""
import json
import sys
import time
import datetime
import logging
import argparse
import subprocess
from datetime import date
from settings import settings
from googleapiclient import discovery
from kubernetes_client import k8s_control
from googleapiclient.errors import HttpError
from oaut... | 0.353094 | 0.134037 |
import logging
import os
import tempfile
import time
# 3rd party
import yaml
from config import _windows_commondata_path, get_confd_path, JMX_VERSION
from util import yDumper
from utils.pidfile import PidFile
from utils.platform import Platform
# JMXFetch java version
JMX_FETCH_JAR_NAME = "jmxfetch-{ver}-jar-with-de... | utils/jmx.py | import logging
import os
import tempfile
import time
# 3rd party
import yaml
from config import _windows_commondata_path, get_confd_path, JMX_VERSION
from util import yDumper
from utils.pidfile import PidFile
from utils.platform import Platform
# JMXFetch java version
JMX_FETCH_JAR_NAME = "jmxfetch-{ver}-jar-with-de... | 0.328422 | 0.059976 |
import random as r
# Some basic values related to ABC:
# Song number
X='1' # First song, increase this to make an opus
# Title
T="Beginnings" # Song title
# Key
keys=['C','C# ','D','D# ','E','F','F# ','G','G# ','A','A# ','B']
K=r.choice(keys) # Random key, they're all the same mostly
K='C'
# and will only be used at th... | Beginnings.py | import random as r
# Some basic values related to ABC:
# Song number
X='1' # First song, increase this to make an opus
# Title
T="Beginnings" # Song title
# Key
keys=['C','C# ','D','D# ','E','F','F# ','G','G# ','A','A# ','B']
K=r.choice(keys) # Random key, they're all the same mostly
K='C'
# and will only be used at th... | 0.322526 | 0.305568 |
import re, os
def to_tag(item):
"""
take any string and convert it to an acceptable tag
tags should not contain spaces or special characters
numbers, lowercase letters only
underscores can be used, but they will be converted to spaces in some cases
"""
item = item.lower()
#get rid of t... | moments/tag.py | import re, os
def to_tag(item):
"""
take any string and convert it to an acceptable tag
tags should not contain spaces or special characters
numbers, lowercase letters only
underscores can be used, but they will be converted to spaces in some cases
"""
item = item.lower()
#get rid of t... | 0.45181 | 0.167372 |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
SECRET_KEY = '<KEY>'
INSTALLED_APPS = [
# API (v1)
'v1.accounts.apps.AccountsConfig',
'v1.credits.apps.CreditsConfig',
'v1.filters.apps.FiltersConfig',
'v1.posts.apps.PostsConfig',
... | app/config/settings/base.py | import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
SECRET_KEY = '<KEY>'
INSTALLED_APPS = [
# API (v1)
'v1.accounts.apps.AccountsConfig',
'v1.credits.apps.CreditsConfig',
'v1.filters.apps.FiltersConfig',
'v1.posts.apps.PostsConfig',
... | 0.358129 | 0.072341 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from gst_file import gst_file_loader
from draw_utils import draw_ped
# EXAMPLE 3.2.1 | Apply Contour Based Visual Inspection Engine for Video Stream
# Uncomment this if using OpenGL for image rendering
window_name_1 = "Detected Object"
window_name_2 = "D... | pertemuan_13/contour_based_video_stream_opengl.py | import cv2
import numpy as np
import matplotlib.pyplot as plt
from gst_file import gst_file_loader
from draw_utils import draw_ped
# EXAMPLE 3.2.1 | Apply Contour Based Visual Inspection Engine for Video Stream
# Uncomment this if using OpenGL for image rendering
window_name_1 = "Detected Object"
window_name_2 = "D... | 0.475362 | 0.423398 |
# encoding: UTF-8
import difflib
import pytest
import sys
from functools import partial
if sys.version_info[0] <= 2:
from pathlib2 import Path
else:
from pathlib import Path
FORCE_REGEN = False
@pytest.fixture
def original_datadir(request):
# Method from: https://github.com/gabrielcnr/pytest-datadir
... | python/helpers/pydev/pydev_tests_python/regression_check.py |
# encoding: UTF-8
import difflib
import pytest
import sys
from functools import partial
if sys.version_info[0] <= 2:
from pathlib2 import Path
else:
from pathlib import Path
FORCE_REGEN = False
@pytest.fixture
def original_datadir(request):
# Method from: https://github.com/gabrielcnr/pytest-datadir
... | 0.540924 | 0.557062 |
import collections.abc
import pytest
from kopf.reactor.causation import ResourceChangingCause, ResourceWatchingCause
from kopf.structs.handlers import Activity
# Used in the tests. Must be global-scoped, or its qualname will be affected.
def some_fn():
pass
def test_generic_registry_via_iter(
generic_... | tests/registries/legacy-2/test_legacy2_registering.py | import collections.abc
import pytest
from kopf.reactor.causation import ResourceChangingCause, ResourceWatchingCause
from kopf.structs.handlers import Activity
# Used in the tests. Must be global-scoped, or its qualname will be affected.
def some_fn():
pass
def test_generic_registry_via_iter(
generic_... | 0.741487 | 0.409339 |
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import ARRAY, TSVECTOR
from sqlalchemy.ext.declarative import declared_attr
from webservices import docs
from .base import db, BaseModel
class CandidateSearch(BaseModel):
__tablename__ = 'ofec_candidate_fulltext_mv'
id = db.Column(db.String)
n... | webservices/common/models/candidates.py | import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import ARRAY, TSVECTOR
from sqlalchemy.ext.declarative import declared_attr
from webservices import docs
from .base import db, BaseModel
class CandidateSearch(BaseModel):
__tablename__ = 'ofec_candidate_fulltext_mv'
id = db.Column(db.String)
n... | 0.407098 | 0.11479 |
import pathlib
import re
import sys
from distutils.command.build_ext import build_ext
from distutils.errors import (
CCompilerError,
DistutilsExecError,
DistutilsPlatformError,
)
from setuptools import Extension, setup
if sys.version_info < (3, 5, 3):
raise RuntimeError("hyper_internal_service 3.x req... | setup.py | import pathlib
import re
import sys
from distutils.command.build_ext import build_ext
from distutils.errors import (
CCompilerError,
DistutilsExecError,
DistutilsPlatformError,
)
from setuptools import Extension, setup
if sys.version_info < (3, 5, 3):
raise RuntimeError("hyper_internal_service 3.x req... | 0.253306 | 0.064535 |
import datetime, os
import tensorflow as tf
import numpy as np
import pprint
from tensorflow.python.ops.nn import rnn_cell, dynamic_rnn
try:
# Python 2 compat
import cPickle as pickle
except ImportError:
import pickle
pp = pprint.PrettyPrinter()
class TextLSTM(object):
def __init__(self, config, sess,... | hlstm.py | import datetime, os
import tensorflow as tf
import numpy as np
import pprint
from tensorflow.python.ops.nn import rnn_cell, dynamic_rnn
try:
# Python 2 compat
import cPickle as pickle
except ImportError:
import pickle
pp = pprint.PrettyPrinter()
class TextLSTM(object):
def __init__(self, config, sess,... | 0.667256 | 0.192995 |
from spack import *
class GmapGsnap(AutotoolsPackage):
"""GMAP: A Genomic Mapping and Alignment Program for
mRNA and EST Sequences, and GSNAP: Genomic Short-read
Nucleotide Alignment Program"""
homepage = "http://research-pub.gene.com/gmap/"
url = "http://research-pub.gene.com/gmap/sr... | var/spack/repos/builtin/packages/gmap-gsnap/package.py |
from spack import *
class GmapGsnap(AutotoolsPackage):
"""GMAP: A Genomic Mapping and Alignment Program for
mRNA and EST Sequences, and GSNAP: Genomic Short-read
Nucleotide Alignment Program"""
homepage = "http://research-pub.gene.com/gmap/"
url = "http://research-pub.gene.com/gmap/sr... | 0.455199 | 0.386185 |
from selenium import webdriver
import time, unittest, config
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
class test_dataverse(unittest.TestCase):
def setUp(self):
if (config.local):
self.wd = webdriver.Firefox()
... | tests/test_dataverse.py | from selenium import webdriver
import time, unittest, config
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
class test_dataverse(unittest.TestCase):
def setUp(self):
if (config.local):
self.wd = webdriver.Firefox()
... | 0.216923 | 0.050144 |
import re
import html
import logging
from datetime import datetime, timedelta
from typing import List
import pytz
from twitter import Twitter
from twitter import OAuth
from twitter import oauth_dance
from slackbot.utils.secrets import Secrets
class TwitterApi(object):
"""
Connect to Twitter and query for ... | slackbot/utils/twitter_api.py | import re
import html
import logging
from datetime import datetime, timedelta
from typing import List
import pytz
from twitter import Twitter
from twitter import OAuth
from twitter import oauth_dance
from slackbot.utils.secrets import Secrets
class TwitterApi(object):
"""
Connect to Twitter and query for ... | 0.649579 | 0.09795 |
import logging
from pathlib import Path
import icat
import icat.config
logging.basicConfig(level=logging.INFO)
config = icat.config.Config(ids="mandatory")
config.add_variable('investigation', ("investigation",),
dict(help="name and optionally visit id "
"(separated by a... | doc/examples/addfile.py |
import logging
from pathlib import Path
import icat
import icat.config
logging.basicConfig(level=logging.INFO)
config = icat.config.Config(ids="mandatory")
config.add_variable('investigation', ("investigation",),
dict(help="name and optionally visit id "
"(separated by a... | 0.392686 | 0.240184 |
from .SB_Test_runner import get_test_dict
import numpy as np
import pandas as pd
import pickle
import requests
from io import BytesIO
from zipfile import ZipFile
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVe... | BIAS/SB_Toolbox.py | from .SB_Test_runner import get_test_dict
import numpy as np
import pandas as pd
import pickle
import requests
from io import BytesIO
from zipfile import ZipFile
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVe... | 0.641422 | 0.441071 |
import numpy as np
import napari
def test_view_image(qtbot):
"""Test adding image."""
np.random.seed(0)
data = np.random.random((10, 15))
viewer = napari.view_image(data)
view = viewer.window.qt_viewer
qtbot.addWidget(view)
assert np.all(viewer.layers[0].data == data)
assert len(vi... | napari/tests/test_napari.py | import numpy as np
import napari
def test_view_image(qtbot):
"""Test adding image."""
np.random.seed(0)
data = np.random.random((10, 15))
viewer = napari.view_image(data)
view = viewer.window.qt_viewer
qtbot.addWidget(view)
assert np.all(viewer.layers[0].data == data)
assert len(vi... | 0.852675 | 0.872728 |
import os
import re
from defusedxml.minidom import parseString
import pydot
# List of colours
# http://wingraphviz.sourceforge.net/wingraphviz/language/colorname.htm
class VizOozie(object):
"""VizOozie is an Oozie workflow visualization tool
Found at https://github.com/iprovalo/vizoozie modified for ibis use... | ibis/utilities/vizoozie.py | import os
import re
from defusedxml.minidom import parseString
import pydot
# List of colours
# http://wingraphviz.sourceforge.net/wingraphviz/language/colorname.htm
class VizOozie(object):
"""VizOozie is an Oozie workflow visualization tool
Found at https://github.com/iprovalo/vizoozie modified for ibis use... | 0.452536 | 0.095687 |
import pytest
from linkedlist import LinkedList
class TestLinkedList:
def test_init(self):
'''There are no front or back in a newly initialized list'''
ll = LinkedList()
assert ll.front == None
assert ll.back == None
def test_add_to_empty_list(self):
'''
Adding... | tests/test_linkedlist.py | import pytest
from linkedlist import LinkedList
class TestLinkedList:
def test_init(self):
'''There are no front or back in a newly initialized list'''
ll = LinkedList()
assert ll.front == None
assert ll.back == None
def test_add_to_empty_list(self):
'''
Adding... | 0.774157 | 0.605187 |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from google.colab import drive
drive.mount('/content/gdrive')
data = pd.read_csv("gdrive/My Drive/Colab Notebooks/FeatureEngineering/train_date.csv")
data.head()
# Outliers according to the quantiles + 1.5 IQR
sns.catplot(x... | FeatureEngineeringPy_DataScience/demo156_outliers_detection_localoutlierfactor.py | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from google.colab import drive
drive.mount('/content/gdrive')
data = pd.read_csv("gdrive/My Drive/Colab Notebooks/FeatureEngineering/train_date.csv")
data.head()
# Outliers according to the quantiles + 1.5 IQR
sns.catplot(x... | 0.46223 | 0.421492 |
import os
from collections.abc import Mapping
from contextlib import contextmanager
from glob import glob
from json import dumps, loads
from json.decoder import JSONDecodeError
from sys import argv, stderr
from time import time
from typing import Any
from urllib.parse import urlparse
import yaml
from django.conf impor... | authentik/lib/config.py | import os
from collections.abc import Mapping
from contextlib import contextmanager
from glob import glob
from json import dumps, loads
from json.decoder import JSONDecodeError
from sys import argv, stderr
from time import time
from typing import Any
from urllib.parse import urlparse
import yaml
from django.conf impor... | 0.55254 | 0.110495 |
"""Canonicalizes break statements by de-sugaring into a control boolean."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.autograph.pyct import anno
from tensorflow.contrib.autograph.pyct import templates
from tensorflow.contrib.au... | tensorflow/contrib/autograph/converters/break_statements.py | """Canonicalizes break statements by de-sugaring into a control boolean."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.autograph.pyct import anno
from tensorflow.contrib.autograph.pyct import templates
from tensorflow.contrib.au... | 0.891593 | 0.206594 |
import streamlit as st
def write():
with st.spinner("Loading Credits ..."):
st.write(
"""
# Credits
This project was possible thanks to the data provided by the
[COVID-19 Data Repository by the Center for Systems Science and Enginee... | src/pages/credits.py | import streamlit as st
def write():
with st.spinner("Loading Credits ..."):
st.write(
"""
# Credits
This project was possible thanks to the data provided by the
[COVID-19 Data Repository by the Center for Systems Science and Enginee... | 0.418103 | 0.574096 |
import pytest
import inspect
import pyhf
modifiers_to_test = [
"histosys",
"normfactor",
"normsys",
"shapefactor",
"shapesys",
"staterror",
]
modifier_pdf_types = ["normal", None, "normal", None, "poisson", "normal"]
# we make sure we can import all of our pre-defined modifiers correctly
@pyt... | tests/test_modifiers.py | import pytest
import inspect
import pyhf
modifiers_to_test = [
"histosys",
"normfactor",
"normsys",
"shapefactor",
"shapesys",
"staterror",
]
modifier_pdf_types = ["normal", None, "normal", None, "poisson", "normal"]
# we make sure we can import all of our pre-defined modifiers correctly
@pyt... | 0.551815 | 0.567038 |
__author__ = 'Administrator'
from wjBlog.blog.default import views
def fun_template():
'''
default 模板的 方法控制器
'''
funMap={}
funMap['404']=(views.page404,('/404.html',))
funMap['index']=(views.index,('/index.html',))
funMap['blogAdmin']=(views.blogAdmin,('/admindefault.html',))
funMap['ma... | data/train/python/d52258bea3734ef7a71653c7cdbdaad97c34eef4funmap.py | __author__ = 'Administrator'
from wjBlog.blog.default import views
def fun_template():
'''
default 模板的 方法控制器
'''
funMap={}
funMap['404']=(views.page404,('/404.html',))
funMap['index']=(views.index,('/index.html',))
funMap['blogAdmin']=(views.blogAdmin,('/admindefault.html',))
funMap['ma... | 0.158891 | 0.038107 |
import sys, os, tempfile, rtf2xml.copy, rtf2xml.field_strings, re
class FieldsSmall:
"""
=================
Purpose
=================
Write tags for bookmarks, index and toc entry fields in a tokenized file.
This module does not handle toc or index tables. (This module won't be any
use to use to you unless you us... | WorkingDirectory/DaisyPipeline/transformers/ca_cnib_rtf2dtbook/rtf2xml-py/rtf2xml/fields_small.py |
import sys, os, tempfile, rtf2xml.copy, rtf2xml.field_strings, re
class FieldsSmall:
"""
=================
Purpose
=================
Write tags for bookmarks, index and toc entry fields in a tokenized file.
This module does not handle toc or index tables. (This module won't be any
use to use to you unless you us... | 0.378115 | 0.230714 |
from .geom_abline import geom_abline
from .geom_area import geom_area
from .geom_bar import geom_bar
from .geom_bin2d import geom_bin2d
from .geom_blank import geom_blank
from .geom_boxplot import geom_boxplot
from .geom_col import geom_col
from .geom_count import geom_count
from .geom_crossbar import geom_crossbar
fro... | fairmodels/plotnine/geoms/__init__.py | from .geom_abline import geom_abline
from .geom_area import geom_area
from .geom_bar import geom_bar
from .geom_bin2d import geom_bin2d
from .geom_blank import geom_blank
from .geom_boxplot import geom_boxplot
from .geom_col import geom_col
from .geom_count import geom_count
from .geom_crossbar import geom_crossbar
fro... | 0.526099 | 0.404507 |
import errno
import logging
import socket
import ssl
from .. import compat
from .. import connection
from .. import exceptions
try:
SOL_TCP = socket.SOL_TCP
except AttributeError:
SOL_TCP = 6
if compat.PY2:
_SOCKET_ERROR = socket.error
else:
# socket.error was deprecated and replaced by OSError in p... | aio_pika/pika/adapters/base_connection.py | import errno
import logging
import socket
import ssl
from .. import compat
from .. import connection
from .. import exceptions
try:
SOL_TCP = socket.SOL_TCP
except AttributeError:
SOL_TCP = 6
if compat.PY2:
_SOCKET_ERROR = socket.error
else:
# socket.error was deprecated and replaced by OSError in p... | 0.541409 | 0.128963 |
import os
import sys
import numpy as np
import tensorflow as tf
import matplotlib
matplotlib.use('GTK3Cairo')
import matplotlib.pyplot as plt
from util.seq2seq import Seq2SeqEvaluator
from util.loader import unknown_tokens, load_data
from util.general_utils import get_minibatches
from model import initialize
def sho... | deep/run_pca.py | import os
import sys
import numpy as np
import tensorflow as tf
import matplotlib
matplotlib.use('GTK3Cairo')
import matplotlib.pyplot as plt
from util.seq2seq import Seq2SeqEvaluator
from util.loader import unknown_tokens, load_data
from util.general_utils import get_minibatches
from model import initialize
def sho... | 0.341473 | 0.38266 |
import osbrain
from osbrain import run_nameserver
from osbrain import run_agent
import mabs.ka.ka_s.stochastic as stochastic
import mabs.bb.blackboard_optimization as bb_opt
from mabs.utils.problem import BenchmarkProblem
import numpy as np
import time
def test_init():
try:
ns = run_nameserver()
except... | test/test_kas_stochastic.py | import osbrain
from osbrain import run_nameserver
from osbrain import run_agent
import mabs.ka.ka_s.stochastic as stochastic
import mabs.bb.blackboard_optimization as bb_opt
from mabs.utils.problem import BenchmarkProblem
import numpy as np
import time
def test_init():
try:
ns = run_nameserver()
except... | 0.399577 | 0.350144 |
from flask import Flask, request, render_template
import RPi.GPIO as GPIO
import threading
from time import gmtime, strftime
from bluetooth import *
from pushbullet import Pushbullet
import os
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(2, GPIO.OUT)
auth = "74:A5:28:FA:51:B7"
... | main.py | from flask import Flask, request, render_template
import RPi.GPIO as GPIO
import threading
from time import gmtime, strftime
from bluetooth import *
from pushbullet import Pushbullet
import os
app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(3, GPIO.OUT)
GPIO.setup(2, GPIO.OUT)
auth = "74:A5:28:FA:51:B7"
... | 0.197987 | 0.076132 |
import operator
from rpython.rlib.rarithmetic import ovfcheck
from rpython.tool.sourcetools import func_renamer
from pypy.interpreter.pyframe import PyFrame
from pypy.interpreter.error import oefmt
from pypy.objspace.std.intobject import W_IntObject
from pypy.objspace.std.listobject import W_ListObject
class BaseF... | pypy/objspace/std/frame.py |
import operator
from rpython.rlib.rarithmetic import ovfcheck
from rpython.tool.sourcetools import func_renamer
from pypy.interpreter.pyframe import PyFrame
from pypy.interpreter.error import oefmt
from pypy.objspace.std.intobject import W_IntObject
from pypy.objspace.std.listobject import W_ListObject
class BaseF... | 0.499512 | 0.1382 |
"""Idempotence Command Module."""
import re
import click
from molecule import logger
from molecule import util
from molecule.command import base
LOG = logger.get_logger(__name__)
class Idempotence(base.Base):
"""
Runs the converge step a second time. If no tasks will be marked as changed \
the scenari... | molecule/command/idempotence.py | """Idempotence Command Module."""
import re
import click
from molecule import logger
from molecule import util
from molecule.command import base
LOG = logger.get_logger(__name__)
class Idempotence(base.Base):
"""
Runs the converge step a second time. If no tasks will be marked as changed \
the scenari... | 0.755997 | 0.28259 |
from flask import *
from libs.rcon import MCRcon
import os
import json
import sqlite3
import logging
import time
import hmac
import base64
def gettime():
t = ''
localtime = time.localtime(time.time())
if localtime.tm_mon<10:
t = str(localtime.tm_year)+'0'+str(localtime.tm_mon)+str(localtime.tm_mday... | advanced-edition/server/server.py | from flask import *
from libs.rcon import MCRcon
import os
import json
import sqlite3
import logging
import time
import hmac
import base64
def gettime():
t = ''
localtime = time.localtime(time.time())
if localtime.tm_mon<10:
t = str(localtime.tm_year)+'0'+str(localtime.tm_mon)+str(localtime.tm_mday... | 0.202759 | 0.06165 |
import argparse, sys, os, gzip
from shutil import rmtree, copy
from multiprocessing import cpu_count, Pool
from tempfile import mkdtemp, gettempdir
from seqtools.format.fasta import FASTAData
from seqtools.format.gpd import GPDStream
from seqtools.cli.utilities.fastq_to_salmon_quant import external_cmd as salmon
from s... | seqtools/cli/utilities/iterate_salmon.py | import argparse, sys, os, gzip
from shutil import rmtree, copy
from multiprocessing import cpu_count, Pool
from tempfile import mkdtemp, gettempdir
from seqtools.format.fasta import FASTAData
from seqtools.format.gpd import GPDStream
from seqtools.cli.utilities.fastq_to_salmon_quant import external_cmd as salmon
from s... | 0.127816 | 0.214157 |
from coati.win32 import copy, execute_commandbar
from coati import utils, excel, powerpoint
import time
import logging
import re
import abc
class AbstractResource():
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def merge(self, slide):
pass
class Chart(AbstractResource):
def __init__(self... | coati/resources.py | from coati.win32 import copy, execute_commandbar
from coati import utils, excel, powerpoint
import time
import logging
import re
import abc
class AbstractResource():
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def merge(self, slide):
pass
class Chart(AbstractResource):
def __init__(self... | 0.38943 | 0.136436 |
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from PIL import Image
import json
def main():
# get arguments from command line... | predict.py | import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from PIL import Image
import json
def main():
# get arguments from command line... | 0.880707 | 0.492737 |
import numpy as np
from openvino.tools.pot.graph import node_utils as nu
from openvino.tools.pot.graph.model_utils import get_nodes_by_type
from openvino.tools.pot.graph.special_operations import OPERATIONS_WITH_WEIGHTS
from openvino.tools.pot.utils.logger import get_logger
logger = get_logger(__name__)
def check... | tools/pot/openvino/tools/pot/algorithms/sparsity/default/utils.py |
import numpy as np
from openvino.tools.pot.graph import node_utils as nu
from openvino.tools.pot.graph.model_utils import get_nodes_by_type
from openvino.tools.pot.graph.special_operations import OPERATIONS_WITH_WEIGHTS
from openvino.tools.pot.utils.logger import get_logger
logger = get_logger(__name__)
def check... | 0.698432 | 0.384739 |
from math import ceil
import torch
import torch.nn as nn
import torch.nn.functional as F
from deep_architect.helpers.pytorch_support import siso_pytorch_module
def calculate_same_padding(h_in, w_in, stride, filter_size):
h_out = ceil(float(h_in) / float(stride))
w_out = ceil(float(w_in) / float(stride))
... | deep_architect/contrib/deep_learning_backend/pytorch_ops.py | from math import ceil
import torch
import torch.nn as nn
import torch.nn.functional as F
from deep_architect.helpers.pytorch_support import siso_pytorch_module
def calculate_same_padding(h_in, w_in, stride, filter_size):
h_out = ceil(float(h_in) / float(stride))
w_out = ceil(float(w_in) / float(stride))
... | 0.861363 | 0.419945 |
import boto.glacier
import boto3
import sure # noqa # pylint: disable=unused-import
import pytest
from moto import mock_glacier_deprecated, mock_glacier
from moto.core import ACCOUNT_ID
from uuid import uuid4
# Has boto3 equivalent
@mock_glacier_deprecated
def test_create_vault():
conn = boto.glaci... | tests/test_glacier/test_glacier_vaults.py | import boto.glacier
import boto3
import sure # noqa # pylint: disable=unused-import
import pytest
from moto import mock_glacier_deprecated, mock_glacier
from moto.core import ACCOUNT_ID
from uuid import uuid4
# Has boto3 equivalent
@mock_glacier_deprecated
def test_create_vault():
conn = boto.glaci... | 0.373533 | 0.174094 |
import socket
from vnc_api.gen.resource_client import Alarm
from vnc_api.gen.resource_xsd import IdPermsType, AlarmExpression, \
AlarmAndList, AlarmOrList
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from config_handler import ConfigHandler
from opserver_util import camel_case_to_hyphen, inverse_dict... | src/opserver/alarmgen_config_handler.py |
import socket
from vnc_api.gen.resource_client import Alarm
from vnc_api.gen.resource_xsd import IdPermsType, AlarmExpression, \
AlarmAndList, AlarmOrList
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from config_handler import ConfigHandler
from opserver_util import camel_case_to_hyphen, inverse_dict... | 0.327561 | 0.039676 |
import sys
import os.path
import numpy as nmp
from solver import *
save_path = '../results'
def unit_tests_1():
print('Running Tests 1\n\n')
for w, unit_lambda in enumerate(['0', '0.25', '0.5', '0.9'], 1):
for w2, unit_alpha in enumerate(['0'], 1):
for w3, unit_N in enumerate(['500', '1... | Projects/Project5/src/testing.py |
import sys
import os.path
import numpy as nmp
from solver import *
save_path = '../results'
def unit_tests_1():
print('Running Tests 1\n\n')
for w, unit_lambda in enumerate(['0', '0.25', '0.5', '0.9'], 1):
for w2, unit_alpha in enumerate(['0'], 1):
for w3, unit_N in enumerate(['500', '1... | 0.294824 | 0.318962 |
import asyncio
import logging
import os
import signal
from typing import (
AsyncIterable,
AsyncIterator,
Awaitable,
Callable,
Tuple,
)
from async_generator import asynccontextmanager
from async_timeout import timeout
class AsyncProcessRunner():
logger = logging.getLogger("trinity.tools.async_... | trinity/tools/async_process_runner.py | import asyncio
import logging
import os
import signal
from typing import (
AsyncIterable,
AsyncIterator,
Awaitable,
Callable,
Tuple,
)
from async_generator import asynccontextmanager
from async_timeout import timeout
class AsyncProcessRunner():
logger = logging.getLogger("trinity.tools.async_... | 0.570571 | 0.094052 |
import pprint
import re # noqa: F401
import six
from cons3rt.configuration import Configuration
__author__ = 'Jackpine Technologies Corporation'
__copyright__ = 'Copyright 2020, Jackpine Technologies Corporation'
__license__ = 'Apache 2.0',
__version__ = '1.0.0'
__maintainer__ = 'API Support'
__email__ = '<EMAIL>'
... | cons3rt/models/v_cloud_cloud.py | import pprint
import re # noqa: F401
import six
from cons3rt.configuration import Configuration
__author__ = 'Jackpine Technologies Corporation'
__copyright__ = 'Copyright 2020, Jackpine Technologies Corporation'
__license__ = 'Apache 2.0',
__version__ = '1.0.0'
__maintainer__ = 'API Support'
__email__ = '<EMAIL>'
... | 0.631367 | 0.070977 |
from flask import Flask
from flask_restplus import Api, Resource, fields
from marshmallow import Schema, fields as ma_fields, post_load
import requests
import json
import re
app = Flask(__name__) #instantiate flask app
api = Api(app) #instantiate api
# get API key from local text file
with open("API_Key.tx... | server/main/app.py | from flask import Flask
from flask_restplus import Api, Resource, fields
from marshmallow import Schema, fields as ma_fields, post_load
import requests
import json
import re
app = Flask(__name__) #instantiate flask app
api = Api(app) #instantiate api
# get API key from local text file
with open("API_Key.tx... | 0.36977 | 0.080394 |
from brewtils.errors import ModelValidationError
from brewtils.models import Operation, Resolvable
from brewtils.schema_parser import SchemaParser
from tornado.escape import json_decode
from beer_garden.api.http.base_handler import BaseHandler
class FileChunkAPI(BaseHandler):
async def get(self):
"""
... | src/app/beer_garden/api/http/handlers/vbeta/chunk.py |
from brewtils.errors import ModelValidationError
from brewtils.models import Operation, Resolvable
from brewtils.schema_parser import SchemaParser
from tornado.escape import json_decode
from beer_garden.api.http.base_handler import BaseHandler
class FileChunkAPI(BaseHandler):
async def get(self):
"""
... | 0.763836 | 0.17676 |
__author__ = 'yanqiong'
import json
import logging
import os
import jwt
import requests
from shinny_structlog import ShinnyLoggerAdapter
import tqsdk
class TqAuth(object):
"""信易用户认证类"""
def __init__(self, user_name: str = "", password: str = ""):
"""
创建信易用户认证类
Args:
us... | tqsdk/auth.py | __author__ = 'yanqiong'
import json
import logging
import os
import jwt
import requests
from shinny_structlog import ShinnyLoggerAdapter
import tqsdk
class TqAuth(object):
"""信易用户认证类"""
def __init__(self, user_name: str = "", password: str = ""):
"""
创建信易用户认证类
Args:
us... | 0.344664 | 0.07989 |
import ubelt as ub
import netharn as nh
class Failpoint(Exception):
pass
class MyHarn(nh.FitHarn):
def _run_epoch(harn, loader, tag, learn=False):
if harn.epoch == harn.failpoint:
raise Failpoint
# Overload run_epoch to do nothing
epoch_metrics = {'loss': 3}
retur... | tests/test_restart_lr.py | import ubelt as ub
import netharn as nh
class Failpoint(Exception):
pass
class MyHarn(nh.FitHarn):
def _run_epoch(harn, loader, tag, learn=False):
if harn.epoch == harn.failpoint:
raise Failpoint
# Overload run_epoch to do nothing
epoch_metrics = {'loss': 3}
retur... | 0.603581 | 0.246618 |
from pathlib import Path
import tempfile
import os
import shutil
import platform
import numpy as np
import math
import bpy
import hdusd
# saving current process id
PID = os.getpid()
OS = platform.system()
IS_WIN = OS == 'Windows'
IS_MAC = OS == 'Darwin'
IS_LINUX = OS == 'Linux'
BLENDER_VERSION = f'{bpy.app.version... | src/hdusd/utils/__init__.py | from pathlib import Path
import tempfile
import os
import shutil
import platform
import numpy as np
import math
import bpy
import hdusd
# saving current process id
PID = os.getpid()
OS = platform.system()
IS_WIN = OS == 'Windows'
IS_MAC = OS == 'Darwin'
IS_LINUX = OS == 'Linux'
BLENDER_VERSION = f'{bpy.app.version... | 0.452536 | 0.103295 |
# Generate highway shields as SVG files in symbols/shields.
from __future__ import print_function
import copy, lxml.etree, math, os
from generate_road_colours import load_settings, generate_colours
def main():
settings = load_settings()
colours = generate_colours(settings, 'shield')
namespace = 'http:/... | scripts/generate_shields.py |
# Generate highway shields as SVG files in symbols/shields.
from __future__ import print_function
import copy, lxml.etree, math, os
from generate_road_colours import load_settings, generate_colours
def main():
settings = load_settings()
colours = generate_colours(settings, 'shield')
namespace = 'http:/... | 0.422981 | 0.082771 |
import sys
import IPO
import random
#objectiveType = 'weights'
#objectiveType = 'random'
#objectiveType = '0/1-random'
objectiveType = '0/-1-random'
objectiveZeroProbability = 0.5
N = 10000
V = range(10)
E = [ (i,j) for i in xrange(len(V)) for j in xrange(i+1,len(V)) ]
# Write LP.
fileName = '/tmp/ipo.lp'
lpData ... | examples/matching-dominant.py |
import sys
import IPO
import random
#objectiveType = 'weights'
#objectiveType = 'random'
#objectiveType = '0/1-random'
objectiveType = '0/-1-random'
objectiveZeroProbability = 0.5
N = 10000
V = range(10)
E = [ (i,j) for i in xrange(len(V)) for j in xrange(i+1,len(V)) ]
# Write LP.
fileName = '/tmp/ipo.lp'
lpData ... | 0.173044 | 0.197309 |
import logging
import pytest
import annif.backend
import annif.corpus
from annif.exception import NotSupportedException
fasttext = pytest.importorskip("annif.backend.fasttext")
def test_fasttext_default_params(project):
fasttext_type = annif.backend.get_backend("fasttext")
fasttext = fasttext_type(
... | tests/test_backend_fasttext.py |
import logging
import pytest
import annif.backend
import annif.corpus
from annif.exception import NotSupportedException
fasttext = pytest.importorskip("annif.backend.fasttext")
def test_fasttext_default_params(project):
fasttext_type = annif.backend.get_backend("fasttext")
fasttext = fasttext_type(
... | 0.547222 | 0.163245 |
import torch
from torchvision import datasets, transforms
import numpy as np
import math
from utils.metrics import plot_roc
from utils.metrics import get_summary_statistics
from utils.datasets import GaussianNoiseDataset
from utils.datasets import UniformNoiseDataset
from utils import Progbar
torch.manual_seed(1)
... | test_cifar.py |
import torch
from torchvision import datasets, transforms
import numpy as np
import math
from utils.metrics import plot_roc
from utils.metrics import get_summary_statistics
from utils.datasets import GaussianNoiseDataset
from utils.datasets import UniformNoiseDataset
from utils import Progbar
torch.manual_seed(1)
... | 0.906891 | 0.647687 |
"""Ernie model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import json
import logging
import paddle.fluid as fluid
import six
from nets.common.transformer_encoder impor... | ST_DM/KDD2021-MSTPAC/code/MST-PAC/nets/common/ernie_encoder.py | """Ernie model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import json
import logging
import paddle.fluid as fluid
import six
from nets.common.transformer_encoder impor... | 0.807802 | 0.089813 |
__author__ = "<NAME>"
import unittest,redis,config
import lib.common as common
import lib.cidoc_crm as cidoc_crm
import lib.namespaces as ns
redis_server = redis.StrictRedis(host=config.REDIS_HOST,
port=config.REDIS_PORT,
db=config.REDIS_TEST_DB)
clas... | tests/test_cidoc_crm.py | __author__ = "<NAME>"
import unittest,redis,config
import lib.common as common
import lib.cidoc_crm as cidoc_crm
import lib.namespaces as ns
redis_server = redis.StrictRedis(host=config.REDIS_HOST,
port=config.REDIS_PORT,
db=config.REDIS_TEST_DB)
clas... | 0.433742 | 0.281751 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = [
'GetObjectVersionsResult',
'AwaitableGetObjectVersionsResult',
'get_object_versions',
]
@pulumi.outpu... | sdk/python/pulumi_oci/objectstorage/get_object_versions.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = [
'GetObjectVersionsResult',
'AwaitableGetObjectVersionsResult',
'get_object_versions',
]
@pulumi.outpu... | 0.850251 | 0.143608 |
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.climate import (
ClimateDevice, PLATFORM_SCHEMA, STATE_HEAT, STATE_OFF,
STATE_AUTO, SUPPORT_AUX_HEAT, SUPPORT_OPERATION_MODE,
SUPPORT_TARGET_TEMPERATURE)
from homeassistant.const import (
TEMP_CELSIUS, ... | homeassistant/components/climate/ephember.py | import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.climate import (
ClimateDevice, PLATFORM_SCHEMA, STATE_HEAT, STATE_OFF,
STATE_AUTO, SUPPORT_AUX_HEAT, SUPPORT_OPERATION_MODE,
SUPPORT_TARGET_TEMPERATURE)
from homeassistant.const import (
TEMP_CELSIUS, ... | 0.811303 | 0.15633 |
import heapq
import os
import platform
import random
import signal
import subprocess
# Base dir of the build products for Release and Debug.
OUT_DIR = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..', 'out'))
def list_processes_linux():
"""Returns list of tuples (pid, command) of proc... | tools/testrunner/testproc/util.py |
import heapq
import os
import platform
import random
import signal
import subprocess
# Base dir of the build products for Release and Debug.
OUT_DIR = os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..', 'out'))
def list_processes_linux():
"""Returns list of tuples (pid, command) of proc... | 0.565539 | 0.150153 |
import os
import time
import unittest
from tests import *
from floating_ip_tests import *
from mx_test import *
from tcutils.contrailtestrunner import ContrailHTMLTestRunner
if __name__ == "__main__":
os.environ['SCRIPT_TS'] = time.strftime("%Y%m%d%H%M%S")
x = TestSanityFixture()
x.setUp()
x.inputs.ge... | scripts/floating_ip_tests_suite.py | import os
import time
import unittest
from tests import *
from floating_ip_tests import *
from mx_test import *
from tcutils.contrailtestrunner import ContrailHTMLTestRunner
if __name__ == "__main__":
os.environ['SCRIPT_TS'] = time.strftime("%Y%m%d%H%M%S")
x = TestSanityFixture()
x.setUp()
x.inputs.ge... | 0.254972 | 0.32861 |
import json
import gc
import pytest
import vanilla
import vanilla.http
# TODO: remove
import logging
logging.basicConfig()
class TestHTTP(object):
def test_get_body(self):
h = vanilla.Hub()
serve = h.http.listen()
@h.spawn
def _():
conn = serve.recv()
... | tests/unit/test_http.py | import json
import gc
import pytest
import vanilla
import vanilla.http
# TODO: remove
import logging
logging.basicConfig()
class TestHTTP(object):
def test_get_body(self):
h = vanilla.Hub()
serve = h.http.listen()
@h.spawn
def _():
conn = serve.recv()
... | 0.188697 | 0.253578 |
from __future__ import unicode_literals, print_function
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s [%(name)s] {%(threadName)s} %(message)s', level=logging.WARNING)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
from random import randint
from IoticAgent.Core.compat imp... | thing_runner/follow_feed/share_basic_error.py |
from __future__ import unicode_literals, print_function
import logging
logging.basicConfig(format='%(asctime)s %(levelname)s [%(name)s] {%(threadName)s} %(message)s', level=logging.WARNING)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
from random import randint
from IoticAgent.Core.compat imp... | 0.72331 | 0.102305 |
import time
import base
import swagger_client
from docker_api import DockerAPI
from swagger_client.rest import ApiException
def pull_harbor_image(registry, username, password, image, tag, expected_login_error_message = None, expected_error_message = None):
_docker_api = DockerAPI()
_docker_api.docker_login(re... | tests/apitests/python/library/repository.py |
import time
import base
import swagger_client
from docker_api import DockerAPI
from swagger_client.rest import ApiException
def pull_harbor_image(registry, username, password, image, tag, expected_login_error_message = None, expected_error_message = None):
_docker_api = DockerAPI()
_docker_api.docker_login(re... | 0.484868 | 0.164449 |
import cohesity_management_sdk.models.subnet
class AppsConfig(object):
"""Implementation of the 'AppsConfig' model.
TODO: type model description here.
Attributes:
allow_external_traffic (bool): Whether to allow pod external traffic.
apps_mode (AppsModeEnum): Specifies the various modes ... | cohesity_management_sdk/models/apps_config.py |
import cohesity_management_sdk.models.subnet
class AppsConfig(object):
"""Implementation of the 'AppsConfig' model.
TODO: type model description here.
Attributes:
allow_external_traffic (bool): Whether to allow pod external traffic.
apps_mode (AppsModeEnum): Specifies the various modes ... | 0.616936 | 0.239294 |
"""ANTS Apply Transforms interface
"""
from __future__ import (print_function, division, unicode_literals,
absolute_import)
import os
from ..base import TraitedSpec, File, traits, InputMultiPath
from .base import ANTSCommand, ANTSCommandInputSpec
class AverageAffineTransformInputSpec(ANTSCom... | nipype/interfaces/ants/utils.py | """ANTS Apply Transforms interface
"""
from __future__ import (print_function, division, unicode_literals,
absolute_import)
import os
from ..base import TraitedSpec, File, traits, InputMultiPath
from .base import ANTSCommand, ANTSCommandInputSpec
class AverageAffineTransformInputSpec(ANTSCom... | 0.874881 | 0.260895 |
from pysnmp_apps.cli import base
from pysnmp.entity import config
from pysnmp import error
authProtocols = {
'MD5': config.usmHMACMD5AuthProtocol,
'SHA': config.usmHMACSHAAuthProtocol,
'SHA224': config.usmHMAC128SHA224AuthProtocol,
'SHA256': config.usmHMAC192SHA256AuthProtocol,
'SHA384': config.us... | pysnmp_apps/cli/secmod.py | from pysnmp_apps.cli import base
from pysnmp.entity import config
from pysnmp import error
authProtocols = {
'MD5': config.usmHMACMD5AuthProtocol,
'SHA': config.usmHMACSHAAuthProtocol,
'SHA224': config.usmHMAC128SHA224AuthProtocol,
'SHA256': config.usmHMAC192SHA256AuthProtocol,
'SHA384': config.us... | 0.334589 | 0.071624 |
import unittest
import zoom
import zoom.request
class TestTools(unittest.TestCase):
"""test the tools module"""
def setUp(self):
zoom.system.site = zoom.sites.Site()
zoom.system.request = zoom.utils.Bunch(
site=zoom.system.site,
app=zoom.utils.Bunch(templates_paths=[... | tests/unittests/test_tools.py |
import unittest
import zoom
import zoom.request
class TestTools(unittest.TestCase):
"""test the tools module"""
def setUp(self):
zoom.system.site = zoom.sites.Site()
zoom.system.request = zoom.utils.Bunch(
site=zoom.system.site,
app=zoom.utils.Bunch(templates_paths=[... | 0.669313 | 0.52756 |
import functools
import tensorflow.compat.v1 as tf
from poem.core import common
from poem.core import loss_utils
tf.disable_v2_behavior()
class LossUtilsTest(tf.test.TestCase):
def _assert_dict_equal_or_almost_equal(self,
result,
e... | poem/core/loss_utils_test.py | import functools
import tensorflow.compat.v1 as tf
from poem.core import common
from poem.core import loss_utils
tf.disable_v2_behavior()
class LossUtilsTest(tf.test.TestCase):
def _assert_dict_equal_or_almost_equal(self,
result,
e... | 0.753285 | 0.528959 |
from PySide6.QtCore import Qt, QSize
from PySide6.QtWidgets import (QApplication, QDialog, QLayout, QGridLayout,
QMessageBox, QGroupBox, QSpinBox, QSlider,
QProgressBar, QDial, QDialogButtonBox,
QComboBox, QLabel)
class Dialog... | venv/Lib/site-packages/PySide6/examples/widgets/layouts/dynamiclayouts/dynamiclayouts.py | from PySide6.QtCore import Qt, QSize
from PySide6.QtWidgets import (QApplication, QDialog, QLayout, QGridLayout,
QMessageBox, QGroupBox, QSpinBox, QSlider,
QProgressBar, QDial, QDialogButtonBox,
QComboBox, QLabel)
class Dialog... | 0.489992 | 0.094427 |
import firebase_admin
import json
import logging
from firebase_admin import credentials
from firebase_admin import firestore
from firebase_admin import storage
from pathlib import Path
class FirebaseManager(object):
def __init__(self, songsFolder, keysFolder):
'''
Constructor
'''
w... | python-client/firebase.py | import firebase_admin
import json
import logging
from firebase_admin import credentials
from firebase_admin import firestore
from firebase_admin import storage
from pathlib import Path
class FirebaseManager(object):
def __init__(self, songsFolder, keysFolder):
'''
Constructor
'''
w... | 0.304455 | 0.062531 |
import os
import json
import sys
import unittest
from tineyeservices import MulticolorEngineRequest
from tineyeservices import Image
from tineyeservices.exception import TinEyeServiceError, TinEyeServiceWarning
imagepath = os.path.abspath("test/images")
sys.path.append('../')
metadata_json = {"keywords": ["whale", ... | test/test_multicolorengine.py |
import os
import json
import sys
import unittest
from tineyeservices import MulticolorEngineRequest
from tineyeservices import Image
from tineyeservices.exception import TinEyeServiceError, TinEyeServiceWarning
imagepath = os.path.abspath("test/images")
sys.path.append('../')
metadata_json = {"keywords": ["whale", ... | 0.406626 | 0.297471 |
from math import sqrt
from behave import given, when, then # pylint: disable=no-name-in-module
from asserts import assert_float, assert_tuple
from core import point, vector
from shapes import Material, Sphere, Shape
from core import identity_matrix, multiply
from core import translation, scaling, rotation_z
from patte... | features/steps/spheres_steps.py | from math import sqrt
from behave import given, when, then # pylint: disable=no-name-in-module
from asserts import assert_float, assert_tuple
from core import point, vector
from shapes import Material, Sphere, Shape
from core import identity_matrix, multiply
from core import translation, scaling, rotation_z
from patte... | 0.74008 | 0.458652 |
import asyncio
import sys
import typing
from concurrent.futures import ThreadPoolExecutor
from .types import Environ, Message, Receive, Scope, Send, StartResponse, WSGIApp
__all__ = ("WSGIMiddleware",)
class Body:
def __init__(self, loop: asyncio.AbstractEventLoop, receive: Receive) -> None:
self.buffer... | a2wsgi/wsgi.py | import asyncio
import sys
import typing
from concurrent.futures import ThreadPoolExecutor
from .types import Environ, Message, Receive, Scope, Send, StartResponse, WSGIApp
__all__ = ("WSGIMiddleware",)
class Body:
def __init__(self, loop: asyncio.AbstractEventLoop, receive: Receive) -> None:
self.buffer... | 0.356335 | 0.157299 |
"""Create node pool command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.compute import metadata_utils
from googlecloudsdk.api_lib.compute import utils
from... | mac/google-cloud-sdk/lib/surface/container/node_pools/create.py | """Create node pool command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.compute import metadata_utils
from googlecloudsdk.api_lib.compute import utils
from... | 0.76207 | 0.134918 |
import argparse
import dataclasses
import json
import pathlib
import sys
import datetime
from typing import List
import jinja2
from sorald._helpers import jsonkeys
ENCODING = "utf8"
TEMPLATE = r"""# Achievements
This document presents an overview of the pull requests performed with Sorald.
{% for pr in pull_request... | experimentation/tools/sorald/achievements.py | import argparse
import dataclasses
import json
import pathlib
import sys
import datetime
from typing import List
import jinja2
from sorald._helpers import jsonkeys
ENCODING = "utf8"
TEMPLATE = r"""# Achievements
This document presents an overview of the pull requests performed with Sorald.
{% for pr in pull_request... | 0.474388 | 0.263902 |
class ComplexitySpec(object):
"""
Base class of complexity specification
:cvar environment: configs for environmental noise
:cvar propostion: configs for propositional noise
:cvar interaction: configs for interactional noise
:cvar social: configs for social noise
"""
environment =... | simdial/complexity.py |
class ComplexitySpec(object):
"""
Base class of complexity specification
:cvar environment: configs for environmental noise
:cvar propostion: configs for propositional noise
:cvar interaction: configs for interactional noise
:cvar social: configs for social noise
"""
environment =... | 0.840357 | 0.537163 |
# Lint as: python3
"""Flags used in the experiment."""
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('num_steps', 1500, 'Number of epochs we want to train our '
'RL agent')
flags.DEFINE_string(
'train_dir', None, 'Directory in which the training '
'checkpoints and tenso... | meta_reward_learning/textworld/common_flags.py |
# Lint as: python3
"""Flags used in the experiment."""
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('num_steps', 1500, 'Number of epochs we want to train our '
'RL agent')
flags.DEFINE_string(
'train_dir', None, 'Directory in which the training '
'checkpoints and tenso... | 0.772702 | 0.388212 |