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 |
|---|---|---|---|---|
from crispy_forms.layout import (
BaseInput, ButtonHolder, Div, Field,
Fieldset, HTML, Hidden, Layout, MultiField,
MultiWidgetField
)
from crispy_forms.utils import TEMPLATE_PACK, render_field
__all__ = [
# Defined in this file
"Button", "Column", "IconField", "Reset", "Row", "Submit", "UploadField... | django_crispy_bulma/layout.py | from crispy_forms.layout import (
BaseInput, ButtonHolder, Div, Field,
Fieldset, HTML, Hidden, Layout, MultiField,
MultiWidgetField
)
from crispy_forms.utils import TEMPLATE_PACK, render_field
__all__ = [
# Defined in this file
"Button", "Column", "IconField", "Reset", "Row", "Submit", "UploadField... | 0.653569 | 0.151749 |
def get_H_matrix(a,b,c,alpha,beta,gamma):
return np.matrix([[a*np.sin(beta), b*np.sin(alpha)*np.cos(gamma),0.],
[0., b*np.sin(alpha)*np.sin(gamma), 0.],
[a*np.cos(beta), b*np.cos(alpha), c]])
def replicate(coordinates, abc, lmn, alpha=90.,gamma=90.,beta=90.):
'''
:p... | mcflow/file_formatting/replicate.py | def get_H_matrix(a,b,c,alpha,beta,gamma):
return np.matrix([[a*np.sin(beta), b*np.sin(alpha)*np.cos(gamma),0.],
[0., b*np.sin(alpha)*np.sin(gamma), 0.],
[a*np.cos(beta), b*np.cos(alpha), c]])
def replicate(coordinates, abc, lmn, alpha=90.,gamma=90.,beta=90.):
'''
:p... | 0.330363 | 0.582669 |
from django.db import migrations, models
import django.db.models.deletion
import upcoming_events.models
from django.core.files import File
def create_icons(apps, schema_editor):
from upcoming_events.models import EventIcon
ListOfIcons = [["ESS", "ess-logo.png"], ["DMSC", "dmsc.png"], ["ECDC", "ecdc.png"], ["S... | ecdc_status/upcoming_events/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
import upcoming_events.models
from django.core.files import File
def create_icons(apps, schema_editor):
from upcoming_events.models import EventIcon
ListOfIcons = [["ESS", "ess-logo.png"], ["DMSC", "dmsc.png"], ["ECDC", "ecdc.png"], ["S... | 0.450843 | 0.137938 |
from pathlib import Path
from typing import Tuple, Union
import h5py
from tensorflow import keras
from tensorflow.keras.layers import BatchNormalization, Dense, Dropout, Input
from tensorflow.python.keras.saving import hdf5_format
from ms2deepscore import SpectrumBinner
class SiameseModel:
"""
Class for trai... | ms2deepscore/models/SiameseModel.py | from pathlib import Path
from typing import Tuple, Union
import h5py
from tensorflow import keras
from tensorflow.keras.layers import BatchNormalization, Dense, Dropout, Input
from tensorflow.python.keras.saving import hdf5_format
from ms2deepscore import SpectrumBinner
class SiameseModel:
"""
Class for trai... | 0.95452 | 0.542984 |
import mock
import pytest
from backend.container_service.clusters.constants import ClusterManagerNodeStatus
from backend.container_service.clusters.tools import node as node_tools
from backend.resources.constants import NodeConditionStatus
from backend.tests.container_service.clusters.test_cc_host import fake_fetch_al... | bcs-ui/backend/tests/container_service/clusters/tools/test_node.py | import mock
import pytest
from backend.container_service.clusters.constants import ClusterManagerNodeStatus
from backend.container_service.clusters.tools import node as node_tools
from backend.resources.constants import NodeConditionStatus
from backend.tests.container_service.clusters.test_cc_host import fake_fetch_al... | 0.402392 | 0.41561 |
import sys, os, argparse
import MaterialX as mx
from MaterialX import PyMaterialXGenShader as mx_gen_shader
from MaterialX import PyMaterialXGenGlsl as ms_gen_glsl
from MaterialX import PyMaterialXRender as mx_render
from MaterialX import PyMaterialXRenderGlsl as mx_render_glsl
def main():
parser = argparse.Argum... | python/Scripts/translateshader.py | import sys, os, argparse
import MaterialX as mx
from MaterialX import PyMaterialXGenShader as mx_gen_shader
from MaterialX import PyMaterialXGenGlsl as ms_gen_glsl
from MaterialX import PyMaterialXRender as mx_render
from MaterialX import PyMaterialXRenderGlsl as mx_render_glsl
def main():
parser = argparse.Argum... | 0.443118 | 0.177169 |
from datetime import timedelta
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_SSL
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr... | homeassistant/components/netgear/__init__.py | from datetime import timedelta
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_SSL
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr... | 0.655557 | 0.090937 |
from ayumi import Ayumi
from cerberus import Validator
from typing import Dict
cv = Validator({
"show": {'type': 'string', 'required': True},
"episode": {'type': 'string', 'required': True},
"filesize": {'type': 'integer', 'required': True},
"sub": {'type': 'string', 'required': True}
})
fiv = Validat... | metsuke/metsuke.py | from ayumi import Ayumi
from cerberus import Validator
from typing import Dict
cv = Validator({
"show": {'type': 'string', 'required': True},
"episode": {'type': 'string', 'required': True},
"filesize": {'type': 'integer', 'required': True},
"sub": {'type': 'string', 'required': True}
})
fiv = Validat... | 0.84869 | 0.284899 |
import json
from django.test import TestCase
from tastypie.test import ResourceTestCaseMixin
import logging
logging.disable(logging.CRITICAL)
class ClassAttributes:
def __init__(self, dictionary):
for k, v in dictionary.items():
setattr(self, k, v)
class TestNegativeNetLoad(ResourceTestCaseM... | reo/tests/test_negative_loads.py | import json
from django.test import TestCase
from tastypie.test import ResourceTestCaseMixin
import logging
logging.disable(logging.CRITICAL)
class ClassAttributes:
def __init__(self, dictionary):
for k, v in dictionary.items():
setattr(self, k, v)
class TestNegativeNetLoad(ResourceTestCaseM... | 0.445047 | 0.127952 |
try:
import simplejson as json
except ImportError:
import json
from bigml.api_handlers.resourcehandler import ResourceHandlerMixin
from bigml.api_handlers.resourcehandler import check_resource_type, \
resource_is_ready, get_optiml_id
from bigml.constants import OPTIML_PATH
class OptimlHandlerMixin(Resou... | bigml/api_handlers/optimlhandler.py | try:
import simplejson as json
except ImportError:
import json
from bigml.api_handlers.resourcehandler import ResourceHandlerMixin
from bigml.api_handlers.resourcehandler import check_resource_type, \
resource_is_ready, get_optiml_id
from bigml.constants import OPTIML_PATH
class OptimlHandlerMixin(Resou... | 0.668664 | 0.275742 |
import numpy as np
import MPC
import FootstepPlanner
from multiprocessing import Process, Value, Array
class MPC_Wrapper:
"""Wrapper to run FootstepPlanner + MPC on another process
Args:
dt (float): Time step of the MPC
n_steps (int): Number of time steps in one gait cycle
k_mpc (int... | MPC_Wrapper.py |
import numpy as np
import MPC
import FootstepPlanner
from multiprocessing import Process, Value, Array
class MPC_Wrapper:
"""Wrapper to run FootstepPlanner + MPC on another process
Args:
dt (float): Time step of the MPC
n_steps (int): Number of time steps in one gait cycle
k_mpc (int... | 0.652795 | 0.348673 |
from __future__ import unicode_literals, division, absolute_import, print_function
import os
import subprocess
import sys
import shutil
import re
import json
import tarfile
import zipfile
from . import package_root, build_root, other_packages
from ._pep425 import _pep425tags, _pep425_implementation
if sys.version_in... | dev/deps.py | from __future__ import unicode_literals, division, absolute_import, print_function
import os
import subprocess
import sys
import shutil
import re
import json
import tarfile
import zipfile
from . import package_root, build_root, other_packages
from ._pep425 import _pep425tags, _pep425_implementation
if sys.version_in... | 0.441914 | 0.097005 |
import os
import random
import tempfile
import unittest
from asn1crypto import keys
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from loopchain.crypto.signature import Signer, SignVerifier, lo... | tests/unit/test_signature.py | import os
import random
import tempfile
import unittest
from asn1crypto import keys
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from loopchain.crypto.signature import Signer, SignVerifier, lo... | 0.538255 | 0.149842 |
from random import choice
from django.contrib.auth.models import AnonymousUser, Permission
from django.test.utils import override_settings
from cms.api import create_page
from cms.test_utils.testcases import CMSTestCase
from cms.toolbar.items import AjaxItem, Menu, ModalItem
from richie.apps.core.factories import Us... | tests/apps/courses/test_cms_toolbars.py | from random import choice
from django.contrib.auth.models import AnonymousUser, Permission
from django.test.utils import override_settings
from cms.api import create_page
from cms.test_utils.testcases import CMSTestCase
from cms.toolbar.items import AjaxItem, Menu, ModalItem
from richie.apps.core.factories import Us... | 0.520009 | 0.208763 |
import os
import datetime
from django import template
from django.conf import settings
from django.contrib.gis.geos import GEOSGeometry
from django.template.base import TemplateDoesNotExist
from django.db.models.fields.related import FieldDoesNotExist
from django.utils.timezone import utc
from django.utils.translation... | mapentity/templatetags/mapentity_tags.py | import os
import datetime
from django import template
from django.conf import settings
from django.contrib.gis.geos import GEOSGeometry
from django.template.base import TemplateDoesNotExist
from django.db.models.fields.related import FieldDoesNotExist
from django.utils.timezone import utc
from django.utils.translation... | 0.434461 | 0.144934 |
from collections import deque, defaultdict
from operator import itemgetter
from snakeoil.demandload import demandload, demand_compile_regexp
from snakeoil.fileutils import readlines
from snakeoil.lists import iflatten_instance
from snakeoil.osutils import listdir_files, pjoin
from pkgcore.ebuild.atom import atom
de... | pkgcore/ebuild/pkg_updates.py |
from collections import deque, defaultdict
from operator import itemgetter
from snakeoil.demandload import demandload, demand_compile_regexp
from snakeoil.fileutils import readlines
from snakeoil.lists import iflatten_instance
from snakeoil.osutils import listdir_files, pjoin
from pkgcore.ebuild.atom import atom
de... | 0.542863 | 0.277387 |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.md')) as f:
CHANGES = f.read()
requires = [
'bcrypt',
'psycopg2',
'plaster_pastedeploy'... | setup.py |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.md')) as f:
CHANGES = f.read()
requires = [
'bcrypt',
'psycopg2',
'plaster_pastedeploy'... | 0.283087 | 0.158923 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("public_data", "0017_auto_20210924_2219"),
]
operations = [
migrations.RemoveField(
model_name="artificielle2018",
name="usage_label",
),
migrations.... | public_data/migrations/0018_auto_20210926_2332.py |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("public_data", "0017_auto_20210924_2219"),
]
operations = [
migrations.RemoveField(
model_name="artificielle2018",
name="usage_label",
),
migrations.... | 0.618665 | 0.286465 |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.teachers import FbDeprecatedDialogTeacher, MultiTaskTeacher
from .build import build
import copy
import os
tasks = ... | doc/integrations/pytorch/parlai/tasks/personalized_dialog/agents.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from parlai.core.teachers import FbDeprecatedDialogTeacher, MultiTaskTeacher
from .build import build
import copy
import os
tasks = ... | 0.560132 | 0.067701 |
import numpy as np
from matplotlib import pyplot as plt
from Dataset.DatasetPreprocessor import cross_validation_split
# Function produces scatter-plots for each feature against their respective label
def plot_mean(alphas, meanScores, optimalAlpha, highestScore):
figure = plt.figure()
plt.xscale('log')
p... | RidgeRegression/RidgeAlgorithm.py | import numpy as np
from matplotlib import pyplot as plt
from Dataset.DatasetPreprocessor import cross_validation_split
# Function produces scatter-plots for each feature against their respective label
def plot_mean(alphas, meanScores, optimalAlpha, highestScore):
figure = plt.figure()
plt.xscale('log')
p... | 0.861407 | 0.742632 |
import os, sys
import random
import numpy as np
import yaml
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..'))
from common.geometry import View, PointLight, Lighting
from common.utils.io_utils import read_from_stat_file
class Randomizer(object):
def __init__(self, view_file... | synthesis/src/randomize/randomizer.py | import os, sys
import random
import numpy as np
import yaml
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..'))
from common.geometry import View, PointLight, Lighting
from common.utils.io_utils import read_from_stat_file
class Randomizer(object):
def __init__(self, view_file... | 0.327776 | 0.253457 |
from urwid_stackedwidget import StackedWidget
import urwid
import pytest
# TODO: Test mouse_event()
def stringify(raw):
"""
:param raw: A list of byte strings (raw output from widget.text)
"""
return '\n'.join(map(str, raw))
@pytest.fixture
def stacked_widget1():
stacked_widget = StackedWidget(... | tests/test_basic.py | from urwid_stackedwidget import StackedWidget
import urwid
import pytest
# TODO: Test mouse_event()
def stringify(raw):
"""
:param raw: A list of byte strings (raw output from widget.text)
"""
return '\n'.join(map(str, raw))
@pytest.fixture
def stacked_widget1():
stacked_widget = StackedWidget(... | 0.431345 | 0.53279 |
from .helper_funcs import *
from pyfiberamp.mode_shape import ModeShape
class OpticalChannel:
def __init__(self, v, dv, input_power, direction, overlaps, mode_func, gain, absorption, loss, label,
reflection_target_label, reflection_coeff, channel_type):
self.v = v
self.dv = dv
... | pyfiberamp/optical_channel.py | from .helper_funcs import *
from pyfiberamp.mode_shape import ModeShape
class OpticalChannel:
def __init__(self, v, dv, input_power, direction, overlaps, mode_func, gain, absorption, loss, label,
reflection_target_label, reflection_coeff, channel_type):
self.v = v
self.dv = dv
... | 0.907125 | 0.292059 |
from contextlib import suppress
from git import Git, GitCommandError
from github.Repository import Repository
from msm import SkillRepo, SkillEntry
from os.path import join
from subprocess import call
from msk.exceptions import AlreadyUpdated, NotUploaded
from msk.global_context import GlobalContext
from msk.lazy impo... | msk/repo_action.py | from contextlib import suppress
from git import Git, GitCommandError
from github.Repository import Repository
from msm import SkillRepo, SkillEntry
from os.path import join
from subprocess import call
from msk.exceptions import AlreadyUpdated, NotUploaded
from msk.global_context import GlobalContext
from msk.lazy impo... | 0.539954 | 0.119049 |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.models.base_model_ import Model
from openapi_server import util
class SwapSpaceMonitorMemoryUsage2(Model):
"""NOTE: This class is auto generated by OpenAPI Ge... | clients/python-flask/generated/openapi_server/models/swap_space_monitor_memory_usage2.py |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.models.base_model_ import Model
from openapi_server import util
class SwapSpaceMonitorMemoryUsage2(Model):
"""NOTE: This class is auto generated by OpenAPI Ge... | 0.807043 | 0.183082 |
import numpy as np
from joblib import Parallel, delayed
import torch
from src.clustering_models.clusternet_modules.clusternet_trainer import (
ClusterNetTrainer,
)
def _parallel_compute_distance(X, cluster):
n_samples = X.shape[0]
dis_mat = np.zeros((n_samples, 1))
for i in range(n_samples):
... | src/clustering_models/clusternet.py |
import numpy as np
from joblib import Parallel, delayed
import torch
from src.clustering_models.clusternet_modules.clusternet_trainer import (
ClusterNetTrainer,
)
def _parallel_compute_distance(X, cluster):
n_samples = X.shape[0]
dis_mat = np.zeros((n_samples, 1))
for i in range(n_samples):
... | 0.846514 | 0.321939 |
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class PyObjectSynthProviderTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
NO_DEBUG_INFO_TESTCASE = True
def test_print_array... | lldb/packages/Python/lldbsuite/test/functionalities/data-formatter/pyobjsynthprovider/TestPyObjSynthProvider.py | from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class PyObjectSynthProviderTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
NO_DEBUG_INFO_TESTCASE = True
def test_print_array... | 0.572723 | 0.22946 |
"""Tests for the OLE Compound File summary and document summary plugins."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import olecf # pylint: disable=unused-import
from plaso.parsers.olecf_plugins import summary
from tests import test_lib as shared_test_lib
from tests.parsers.ole... | tests/parsers/olecf_plugins/summary.py | """Tests for the OLE Compound File summary and document summary plugins."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import olecf # pylint: disable=unused-import
from plaso.parsers.olecf_plugins import summary
from tests import test_lib as shared_test_lib
from tests.parsers.ole... | 0.680985 | 0.54952 |
import os
import re
import sys
import types
import unittest
from unittest.mock import MagicMock
from moderngl_window.utils import module_loading
# Mock modules
class Mock(MagicMock):
@classmethod
def __getattr__(cls, name):
return MagicMock()
MOCK_MODULES = [
'glfw',
'sdl2'... | tests/test_docs.py | import os
import re
import sys
import types
import unittest
from unittest.mock import MagicMock
from moderngl_window.utils import module_loading
# Mock modules
class Mock(MagicMock):
@classmethod
def __getattr__(cls, name):
return MagicMock()
MOCK_MODULES = [
'glfw',
'sdl2'... | 0.407098 | 0.165492 |
from self_py_fun.PreFun import *
plt.style.use('ggplot')
import csv
import seaborn as sns
sns.set_context('notebook')
# If running this file on the cluster, comment out the tensorflow-related functions and imports.
class ExistMLPred(EEGPreFun):
def __init__(self, *args, **kwargs):
super(ExistMLPred, self... | Python/self_py_fun/ExistMLFun.py | from self_py_fun.PreFun import *
plt.style.use('ggplot')
import csv
import seaborn as sns
sns.set_context('notebook')
# If running this file on the cluster, comment out the tensorflow-related functions and imports.
class ExistMLPred(EEGPreFun):
def __init__(self, *args, **kwargs):
super(ExistMLPred, self... | 0.553988 | 0.372448 |
import httplib, urllib, re
from datetime import *
from push import *
import time
import MySQLdb
class iHDate:
def __init__(self):
self.date = date.today()
def isTodayMonday(self):
if self.date.weekday() == 0:
return True
else:
return False
def isTodayFrida... | fund.py |
import httplib, urllib, re
from datetime import *
from push import *
import time
import MySQLdb
class iHDate:
def __init__(self):
self.date = date.today()
def isTodayMonday(self):
if self.date.weekday() == 0:
return True
else:
return False
def isTodayFrida... | 0.299515 | 0.131842 |
import re
from datetime import timedelta
from enum import Enum
from typing import Union, Tuple, List
from django.apps import apps
from django.core import exceptions
from django.conf import settings
from django.db.models import F, Count, Min, Max, Sum, Value, Avg, ExpressionWrapper, DurationField, FloatField, Model, JS... | data_interrogator/interrogators.py | import re
from datetime import timedelta
from enum import Enum
from typing import Union, Tuple, List
from django.apps import apps
from django.core import exceptions
from django.conf import settings
from django.db.models import F, Count, Min, Max, Sum, Value, Avg, ExpressionWrapper, DurationField, FloatField, Model, JS... | 0.715523 | 0.236142 |
"""Adapter related object holder."""
import logging
from compass.db.api import adapter as adapter_api
from compass.db.api import database
from compass.db.api import permission
from compass.db.api import user as user_api
from compass.db.api import utils
from compass.db import exception
SUPPORTED_FIELDS = [
'name... | compass/db/api/adapter_holder.py |
"""Adapter related object holder."""
import logging
from compass.db.api import adapter as adapter_api
from compass.db.api import database
from compass.db.api import permission
from compass.db.api import user as user_api
from compass.db.api import utils
from compass.db import exception
SUPPORTED_FIELDS = [
'name... | 0.640973 | 0.105395 |
import os
import sys
import nltk
#nltk.download('punkt')
from nltk.tokenize import word_tokenize
from nltk.tokenize import RegexpTokenizer
from nltk import *
stemmer = PorterStemmer()
def __termID(a):
global termID
termID = a
def __docID(a):
global docID
docID=a
def __offset(a):
global offset
offset=a
def __t... | read_index.py | import os
import sys
import nltk
#nltk.download('punkt')
from nltk.tokenize import word_tokenize
from nltk.tokenize import RegexpTokenizer
from nltk import *
stemmer = PorterStemmer()
def __termID(a):
global termID
termID = a
def __docID(a):
global docID
docID=a
def __offset(a):
global offset
offset=a
def __t... | 0.032977 | 0.127056 |
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
class Heteroscedasticity_tests():
""" Generic class for Heteroscedasticity tests as
Park and Glejser methods.
Both methods use linear regression for functions of tested income feature and residuals as out... | heteroscedasticity/Heteroscedasticity_test_general.py | import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
class Heteroscedasticity_tests():
""" Generic class for Heteroscedasticity tests as
Park and Glejser methods.
Both methods use linear regression for functions of tested income feature and residuals as out... | 0.719285 | 0.561996 |
import os
import os.path
import pygame
import pygame.transform
import pygame.image
import pygame.font
from syntaxerrorgame.ui.button import Button
pygame.font.init()
ENEMY_FONT = pygame.font.SysFont('Times New Roman', 48)
FONT18 = pygame.font.Font(os.path.join('assets', 'fonts/VT323-Regular.ttf'), 18)
FONT32 = p... | syntaxerrorgame/ui/__init__.py |
import os
import os.path
import pygame
import pygame.transform
import pygame.image
import pygame.font
from syntaxerrorgame.ui.button import Button
pygame.font.init()
ENEMY_FONT = pygame.font.SysFont('Times New Roman', 48)
FONT18 = pygame.font.Font(os.path.join('assets', 'fonts/VT323-Regular.ttf'), 18)
FONT32 = p... | 0.325521 | 0.1532 |
from enum import Enum
from typing import List, Tuple, Union
from numpy import *
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from k_means import k_means, get_group_center
from ransac import *
from blend import *
from L2_Net import L2Net
import time
def... | stitch.py | from enum import Enum
from typing import List, Tuple, Union
from numpy import *
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from k_means import k_means, get_group_center
from ransac import *
from blend import *
from L2_Net import L2Net
import time
def... | 0.602997 | 0.217213 |
import logging
from jinja2 import Environment, FileSystemLoader
from ops.charm import CharmBase
from ops.framework import StoredState
from ops.main import main
from ops.model import ActiveStatus
from ops.pebble import ChangeError
from cluster import KnotCluster
logger = logging.getLogger(__name__)
class KnotOper... | src/charm.py |
import logging
from jinja2 import Environment, FileSystemLoader
from ops.charm import CharmBase
from ops.framework import StoredState
from ops.main import main
from ops.model import ActiveStatus
from ops.pebble import ChangeError
from cluster import KnotCluster
logger = logging.getLogger(__name__)
class KnotOper... | 0.465387 | 0.078784 |
import unittest
from pprint import pprint
import pandas as pd
from cadCAD.engine import ExecutionMode, ExecutionContext, Executor
from testing.models import param_sweep
from cadCAD import configs
from testing.generic_test import make_generic_test
from testing.models.param_sweep import some_function, g as sweep_param... | testing/tests/param_sweep.py | import unittest
from pprint import pprint
import pandas as pd
from cadCAD.engine import ExecutionMode, ExecutionContext, Executor
from testing.models import param_sweep
from cadCAD import configs
from testing.generic_test import make_generic_test
from testing.models.param_sweep import some_function, g as sweep_param... | 0.580352 | 0.641001 |
from hvad.utils import get_translation
class NULL:pass
class BaseDescriptor(object):
"""
Base descriptor class with a helper to get the translations instance.
"""
def __init__(self, opts):
self.opts = opts
def translation(self, instance):
cached = getattr(instance, self.opts.t... | hvad/descriptors.py | from hvad.utils import get_translation
class NULL:pass
class BaseDescriptor(object):
"""
Base descriptor class with a helper to get the translations instance.
"""
def __init__(self, opts):
self.opts = opts
def translation(self, instance):
cached = getattr(instance, self.opts.t... | 0.81457 | 0.080213 |
from django.urls import reverse
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase, APIClient
from .fixture import RegiaoFactory
User = get_user_model()
class RegiaoViewSetTests(APITestCase):... | localizacao/tests/test_viewsets_regiao.py | from django.urls import reverse
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase, APIClient
from .fixture import RegiaoFactory
User = get_user_model()
class RegiaoViewSetTests(APITestCase):... | 0.46563 | 0.250907 |
from typing import Any
ADC1 = 1073815552 # type: int
ADC123_COMMON = 1073816320 # type: int
ADC2 = 1073815808 # type: int
ADC3 = 1073816064 # type: int
ADC_CR1 = 4 # type: int
ADC_CR2 = 8 # type: int
ADC_DR = 76 # type: int
ADC_HTR = 36 # type: int
ADC_JDR1 = 60 # type: int
ADC_JDR2 = 64 # type: int
ADC_JDR3... | stubs/micropython-v1_12-pyboard/stm.py | from typing import Any
ADC1 = 1073815552 # type: int
ADC123_COMMON = 1073816320 # type: int
ADC2 = 1073815808 # type: int
ADC3 = 1073816064 # type: int
ADC_CR1 = 4 # type: int
ADC_CR2 = 8 # type: int
ADC_DR = 76 # type: int
ADC_HTR = 36 # type: int
ADC_JDR1 = 60 # type: int
ADC_JDR2 = 64 # type: int
ADC_JDR3... | 0.285173 | 0.078113 |
import os
import queue
import base64
import asyncio
import threading
import exchangelib
from mailtk.data import Mailbox, ThreadInfo, Flag
from mailtk.accounts.base import AccountBase
class MailboxExchange(Mailbox):
_fields = 'folder'
class ThreadInfoExchange(ThreadInfo):
_fields = 'folder message_id'
class... | mailtk/accounts/ews.py | import os
import queue
import base64
import asyncio
import threading
import exchangelib
from mailtk.data import Mailbox, ThreadInfo, Flag
from mailtk.accounts.base import AccountBase
class MailboxExchange(Mailbox):
_fields = 'folder'
class ThreadInfoExchange(ThreadInfo):
_fields = 'folder message_id'
class... | 0.284377 | 0.055209 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | yangram/conversations/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | 0.511229 | 0.128744 |
import pybox.helpers.data as data_helpers
import pybox.datastore.data_to_html as pbdsdth
import pybox.datastore.data_table_row as pbdsdtr
from copy import deepcopy
from datetime import date, datetime
from math import ceil, floor
from tabulate import tabulate
from tqdm import tqdm
DATA_TYPES = [int, float, complex, bo... | pybox/datastore/data_table.py | import pybox.helpers.data as data_helpers
import pybox.datastore.data_to_html as pbdsdth
import pybox.datastore.data_table_row as pbdsdtr
from copy import deepcopy
from datetime import date, datetime
from math import ceil, floor
from tabulate import tabulate
from tqdm import tqdm
DATA_TYPES = [int, float, complex, bo... | 0.77949 | 0.343534 |
from bcar.car import Car
import ipywidgets.widgets as widgets
from ipywidgets import HBox, VBox, Button
import time
class BCar():
def __init__(self):
self.car = Car()
self.panel = ButtonGroup()
self.m_steer = 0
self.m_gear = 0
self.press_count = 0
def play(self)... | bcar/bcar.py | from bcar.car import Car
import ipywidgets.widgets as widgets
from ipywidgets import HBox, VBox, Button
import time
class BCar():
def __init__(self):
self.car = Car()
self.panel = ButtonGroup()
self.m_steer = 0
self.m_gear = 0
self.press_count = 0
def play(self)... | 0.407923 | 0.266745 |
import pandas as pd
import numpy as np
from numpy import array
from numpy import argmax
import os, re
import cv2
import imageio
def preprocess_input(image, fixed_size=128):
'''
'''
image_size = image.shape[:2]
ratio = float(fixed_size)/max(image_size)
new_size = tuple([int(x*ratio) for ... | data_utils.py |
import pandas as pd
import numpy as np
from numpy import array
from numpy import argmax
import os, re
import cv2
import imageio
def preprocess_input(image, fixed_size=128):
'''
'''
image_size = image.shape[:2]
ratio = float(fixed_size)/max(image_size)
new_size = tuple([int(x*ratio) for ... | 0.313735 | 0.354573 |
"""Timeline resources for version 1 of the Timesketch API."""
import codecs
import json
import logging
import uuid
import six
import elasticsearch
from flask import request
from flask import abort
from flask import current_app
from flask_restful import Resource
from flask_login import login_required
from flask_login ... | timesketch/api/v1/resources/timeline.py | """Timeline resources for version 1 of the Timesketch API."""
import codecs
import json
import logging
import uuid
import six
import elasticsearch
from flask import request
from flask import abort
from flask import current_app
from flask_restful import Resource
from flask_login import login_required
from flask_login ... | 0.743727 | 0.114616 |
import logging
from torch import nn
from torch.optim import Adam
from bilstm_network import BiLstmNetwork
from data_pipeline import DataPipeline
from label_pipeline import LabelPipeline
from train import Train
from train_pipeline import TrainPipeline
from transform_label_encoder import TransformLabelEncoder
from tran... | src/train_builder.py | import logging
from torch import nn
from torch.optim import Adam
from bilstm_network import BiLstmNetwork
from data_pipeline import DataPipeline
from label_pipeline import LabelPipeline
from train import Train
from train_pipeline import TrainPipeline
from transform_label_encoder import TransformLabelEncoder
from tran... | 0.906291 | 0.433202 |
import time
import datetime
from telethon import TelegramClient
from telethon.client import users
from telethon.tl.types import ChannelParticipantsRecent
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChatBanne... | joinfilter.py | import time
import datetime
from telethon import TelegramClient
from telethon.client import users
from telethon.tl.types import ChannelParticipantsRecent
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChatBanne... | 0.258794 | 0.105119 |
import numpy as np
import tensorflow as tf
from railrl.misc.tf_test_case import TFTestCase
from railrl.predictors.mlp_state_action_network import MlpStateActionNetwork
class TestStateActionNetwork(TFTestCase):
def test_set_and_get_params(self):
action_dim = 5
obs_dim = 7
output_dim = 3
... | tests/predictors/test_state_action_network.py | import numpy as np
import tensorflow as tf
from railrl.misc.tf_test_case import TFTestCase
from railrl.predictors.mlp_state_action_network import MlpStateActionNetwork
class TestStateActionNetwork(TFTestCase):
def test_set_and_get_params(self):
action_dim = 5
obs_dim = 7
output_dim = 3
... | 0.671471 | 0.544135 |
import sys
import traceback
from abc import ABCMeta, abstractmethod
from importlib import import_module
import six
from werkzeug.utils import find_modules
from pgadmin.utils import server_utils
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
class TestsGeneratorRegistry(ABC... | openresty-win32-build/thirdparty/x86/pgsql/pgAdmin 4/web/pgadmin/utils/route.py |
import sys
import traceback
from abc import ABCMeta, abstractmethod
from importlib import import_module
import six
from werkzeug.utils import find_modules
from pgadmin.utils import server_utils
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
class TestsGeneratorRegistry(ABC... | 0.36557 | 0.110856 |
import re
import string
from mathics.core.parser.errors import ScanError
from mathics.core.parser.prescanner import Prescanner
from mathics.core.characters import letters, letterlikes
# special patterns
number_pattern = r'''
( (?# Two possible forms depending on whether base is specified)
(\d+\^\^([a-zA-Z0-9]+... | mathics/core/parser/tokeniser.py |
import re
import string
from mathics.core.parser.errors import ScanError
from mathics.core.parser.prescanner import Prescanner
from mathics.core.characters import letters, letterlikes
# special patterns
number_pattern = r'''
( (?# Two possible forms depending on whether base is specified)
(\d+\^\^([a-zA-Z0-9]+... | 0.578567 | 0.239961 |
import sys
import unittest
import doctest
from pymaybe import maybe, Something, Nothing
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
def load_tests(loader, tests, ignore):
import pymaybe
tests.addTests(
doctest.DocTestSuite(
pymaybe,
globs=pymaybe.get_doctest... | tests/test_pymaybe.py | import sys
import unittest
import doctest
from pymaybe import maybe, Something, Nothing
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
def load_tests(loader, tests, ignore):
import pymaybe
tests.addTests(
doctest.DocTestSuite(
pymaybe,
globs=pymaybe.get_doctest... | 0.402392 | 0.681667 |
# Copyright 2016 <NAME>
# 2016 <NAME>
# Apache 2.0.
# we're using python 3.x style print but want it to work in python 2.x,
from __future__ import print_function
from collections import defaultdict
import argparse
import sys
class StrToBoolAction(argparse.Action):
""" A custom action to convert bools... | egs/wsj/s5/steps/dict/prons_to_lexicon.py |
# Copyright 2016 <NAME>
# 2016 <NAME>
# Apache 2.0.
# we're using python 3.x style print but want it to work in python 2.x,
from __future__ import print_function
from collections import defaultdict
import argparse
import sys
class StrToBoolAction(argparse.Action):
""" A custom action to convert bools... | 0.599837 | 0.176494 |
from __future__ import print_function
import os
import sys
import warnings
import entrypoints
from six.moves import urllib
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
from mlflow.store import DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH
from mlflow.store.art... | mlflow/tracking/utils.py | from __future__ import print_function
import os
import sys
import warnings
import entrypoints
from six.moves import urllib
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
from mlflow.store import DEFAULT_LOCAL_FILE_AND_ARTIFACT_PATH
from mlflow.store.art... | 0.640861 | 0.077204 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from datasets.all_datasets_meta.datasets_meta import DatasetsMeta
from models.conv_util import ResConvOps, gather_second_d
from utils.tf_util import TfUtil
DEBUG = False
DEFAULT_DTYPE... | models/meshnet_model.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from datasets.all_datasets_meta.datasets_meta import DatasetsMeta
from models.conv_util import ResConvOps, gather_second_d
from utils.tf_util import TfUtil
DEBUG = False
DEFAULT_DTYPE... | 0.631822 | 0.157202 |
from typing import Tuple
from rio_tiler.errors import RioTilerError
class InvalidModlandGridID(RioTilerError):
"""Invalid MODLAND grid id."""
# Only non-fill tiles (460)
# format:
# horizontal_grid, vertical_grid, bbox(xmin, ymin, xmax, ymax)
MODLAND_GRID = [
("14", "00", (-180.0, 80.0, -172.7151, 80.408... | rio_tiler_pds/modis/modland_grid.py | from typing import Tuple
from rio_tiler.errors import RioTilerError
class InvalidModlandGridID(RioTilerError):
"""Invalid MODLAND grid id."""
# Only non-fill tiles (460)
# format:
# horizontal_grid, vertical_grid, bbox(xmin, ymin, xmax, ymax)
MODLAND_GRID = [
("14", "00", (-180.0, 80.0, -172.7151, 80.408... | 0.74158 | 0.300354 |
import torch
import torch.nn as nn
from typing import Tuple
from openspeech.encoders.openspeech_encoder import OpenspeechEncoder
from openspeech.modules import Conv2dSubsampling, Linear, ConformerBlock, Transpose
class ConformerEncoder(OpenspeechEncoder):
r"""
Transformer models are good at capturing conten... | openspeech/encoders/conformer_encoder.py |
import torch
import torch.nn as nn
from typing import Tuple
from openspeech.encoders.openspeech_encoder import OpenspeechEncoder
from openspeech.modules import Conv2dSubsampling, Linear, ConformerBlock, Transpose
class ConformerEncoder(OpenspeechEncoder):
r"""
Transformer models are good at capturing conten... | 0.975946 | 0.560313 |
import numpy as np
import pytest
import qpimage
def hologram(size=64):
x = np.arange(size).reshape(-1, 1) - size / 2
y = np.arange(size).reshape(1, -1) - size / 2
amp = np.linspace(.9, 1.1, size * size).reshape(size, size)
pha = np.linspace(0, 2, size * size).reshape(size, size)
rad = x**2 + y**... | tests/test_holo.py | import numpy as np
import pytest
import qpimage
def hologram(size=64):
x = np.arange(size).reshape(-1, 1) - size / 2
y = np.arange(size).reshape(1, -1) - size / 2
amp = np.linspace(.9, 1.1, size * size).reshape(size, size)
pha = np.linspace(0, 2, size * size).reshape(size, size)
rad = x**2 + y**... | 0.596903 | 0.758488 |
from __future__ import absolute_import
import torch
import argparse
import sys, os
from analysis.PytorchA import analyse
from analysis.utils import save_csv
from torch.autograd import Variable
import torch.nn as nn
"""
Supporting analyse the inheritors of torch.nn.Moudule class.
Command:`pytorch_analyser.py [-h] [--o... | pytorch_analyser.py | from __future__ import absolute_import
import torch
import argparse
import sys, os
from analysis.PytorchA import analyse
from analysis.utils import save_csv
from torch.autograd import Variable
import torch.nn as nn
"""
Supporting analyse the inheritors of torch.nn.Moudule class.
Command:`pytorch_analyser.py [-h] [--o... | 0.638272 | 0.258133 |
import numpy as np
import math
import random
from batchgenerators.transforms import AbstractTransform
import sys
sys.path.append(".")
from kits19cnn.io.custom_augmentations import foreground_crop, center_crop, \
random_resized_crop
class RandomResizedCropTransform(Abstra... | kits19cnn/io/custom_transforms.py | import numpy as np
import math
import random
from batchgenerators.transforms import AbstractTransform
import sys
sys.path.append(".")
from kits19cnn.io.custom_augmentations import foreground_crop, center_crop, \
random_resized_crop
class RandomResizedCropTransform(Abstra... | 0.624408 | 0.50293 |
import json
import re
from urllib.parse import urlparse
import scrapy
from scrapy.selector import Selector
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
class GoldsGymSpider(scrapy.Spider):
name = "goldsgym"
item_attributes = { 'brand': "Gold's Gym" }
allowed_domai... | locations/spiders/goldsgym.py | import json
import re
from urllib.parse import urlparse
import scrapy
from scrapy.selector import Selector
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
class GoldsGymSpider(scrapy.Spider):
name = "goldsgym"
item_attributes = { 'brand': "Gold's Gym" }
allowed_domai... | 0.414188 | 0.24935 |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import re
import logging
from flexget import plugin
from flexget.event import event
from flexget.plugins.plugin_urlrewriting import UrlRewritingError
from flexget.utils import ... | flexget/plugins/urlrewrite/serienjunkies.py | from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import re
import logging
from flexget import plugin
from flexget.event import event
from flexget.plugins.plugin_urlrewriting import UrlRewritingError
from flexget.utils import ... | 0.296043 | 0.087447 |
from neutron.common import constants as neutron_const
from neutron.common import utils
from neutron.extensions import portbindings
from neutron.extensions import providernet as prov_net
from neutron.plugins.common import constants as plugin_const
from neutron.plugins.ml2 import db
from neutron.plugins.ml2 import drive... | networking_nec/nwa/l2/drivers/mech_necnwa.py |
from neutron.common import constants as neutron_const
from neutron.common import utils
from neutron.extensions import portbindings
from neutron.extensions import providernet as prov_net
from neutron.plugins.common import constants as plugin_const
from neutron.plugins.ml2 import db
from neutron.plugins.ml2 import drive... | 0.413359 | 0.068351 |
from unittest.mock import patch
from homeassistant import config_entries
from homeassistant.components.aladdin_connect.config_flow import InvalidAuth
from homeassistant.components.aladdin_connect.const import DOMAIN
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssista... | tests/components/aladdin_connect/test_config_flow.py | from unittest.mock import patch
from homeassistant import config_entries
from homeassistant.components.aladdin_connect.config_flow import InvalidAuth
from homeassistant.components.aladdin_connect.const import DOMAIN
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssista... | 0.727975 | 0.333978 |
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from utils.enum_type import EPT
class MultiHeadAttention(nn.Module):
r"""Multi-head Attention is proposed in the following paper:
Attention Is All You Need.
"""
def __init__(self, embedding_size, num_head... | mwp_solver/module/Attention/multi_head_attention.py |
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from utils.enum_type import EPT
class MultiHeadAttention(nn.Module):
r"""Multi-head Attention is proposed in the following paper:
Attention Is All You Need.
"""
def __init__(self, embedding_size, num_head... | 0.954573 | 0.601915 |
from parlai.core.build_data import download_models
from parlai.core.dict import DictionaryAgent
from parlai.core.params import ParlaiParser, modelzoo_path
from parlai.agents.seq2seq.seq2seq import Seq2seqAgent
from projects.convai2.build_dict import build_dict
from projects.convai2.eval_ppl import eval_ppl
import torc... | projects/convai2/baselines/seq2seq/eval_ppl.py |
from parlai.core.build_data import download_models
from parlai.core.dict import DictionaryAgent
from parlai.core.params import ParlaiParser, modelzoo_path
from parlai.agents.seq2seq.seq2seq import Seq2seqAgent
from projects.convai2.build_dict import build_dict
from projects.convai2.eval_ppl import eval_ppl
import torc... | 0.66061 | 0.331566 |
import unittest
import requests
import json
base_url = 'http://localhost:5000'
''' BEFORE RUNNING TESTS RUN python dbhelper.py '''
class TestEndPoints(unittest.TestCase):
def test_registration_methods_allowed(self):
''' only POST allowed '''
endpoint = f'{base_url}/registration'
# GET request
... | tests/test_api.py | import unittest
import requests
import json
base_url = 'http://localhost:5000'
''' BEFORE RUNNING TESTS RUN python dbhelper.py '''
class TestEndPoints(unittest.TestCase):
def test_registration_methods_allowed(self):
''' only POST allowed '''
endpoint = f'{base_url}/registration'
# GET request
... | 0.334916 | 0.164567 |
import FWCore.ParameterSet.Config as cms
process = cms.Process("electrons")
process.load("Configuration.StandardSequences.GeometryDB_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.load("Configuration.StandardSequences.MagneticField_cff")
process.load("RecoEcal.Configurat... | RecoEgamma/EgammaElectronProducers/test/egammaRecHitsToElectronSeeds_cfg.py | import FWCore.ParameterSet.Config as cms
process = cms.Process("electrons")
process.load("Configuration.StandardSequences.GeometryDB_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.load("Configuration.StandardSequences.MagneticField_cff")
process.load("RecoEcal.Configurat... | 0.435541 | 0.049566 |
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
import numpy as np
import lsst.geom as lsstGeom
from lsst.afw import cameraGeom
from lsst.obs.lsst.imsim import ImsimMapper
__all__ = ['plot_amp_boundaries', 'plot_det', 'plot_focal_plane',
... | python/focal_plane_plotting.py | import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
import numpy as np
import lsst.geom as lsstGeom
from lsst.afw import cameraGeom
from lsst.obs.lsst.imsim import ImsimMapper
__all__ = ['plot_amp_boundaries', 'plot_det', 'plot_focal_plane',
... | 0.88642 | 0.698715 |
from __future__ import print_function, division, absolute_import
import math
import types
import ctypes
from functools import partial
import numba.typesystem
from numba.typesystem import itypesystem, numpy_support
from numba import numbawrapper
from numba.support.ctypes_support import is_ctypes, from_ctypes_value
fr... | oldnumba/typesystem/constants.py | from __future__ import print_function, division, absolute_import
import math
import types
import ctypes
from functools import partial
import numba.typesystem
from numba.typesystem import itypesystem, numpy_support
from numba import numbawrapper
from numba.support.ctypes_support import is_ctypes, from_ctypes_value
fr... | 0.495361 | 0.29381 |
# Use, modification and distribution is subject to the Boost Software
# License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Test skeleton/content
import boost.parallel.mpi as mpi
import skeleton_content
def test_skeleton_and_content(comm, root,... | REDSI_1160929_1161573/boost_1_67_0/libs/mpi/test/python/skeleton_content_test.py |
# Use, modification and distribution is subject to the Boost Software
# License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Test skeleton/content
import boost.parallel.mpi as mpi
import skeleton_content
def test_skeleton_and_content(comm, root,... | 0.506103 | 0.182608 |
import gtk
import vtk
from render_window import PyLocatorRenderWindow
from events import EventHandler, UndoRegistry
from shared import shared
from dialogs import edit_label_of_marker
INTERACT_CURSOR, MOVE_CURSOR, COLOR_CURSOR, SELECT_CURSOR, DELETE_CURSOR, LABEL_CURSOR, SCREENSHOT_CURSOR = gtk.gdk.ARROW, gtk.gdk.HAND2... | pylocator/marker_window_interactor.py | import gtk
import vtk
from render_window import PyLocatorRenderWindow
from events import EventHandler, UndoRegistry
from shared import shared
from dialogs import edit_label_of_marker
INTERACT_CURSOR, MOVE_CURSOR, COLOR_CURSOR, SELECT_CURSOR, DELETE_CURSOR, LABEL_CURSOR, SCREENSHOT_CURSOR = gtk.gdk.ARROW, gtk.gdk.HAND2... | 0.229104 | 0.062962 |
from Switch import Switch
from pyof.foundation.basic_types import DPID
from FileWriter import FileWriter
from FlowModGenerator import FlowModGenerator
from PacketInEchoGenerator import PacketInEchoGenerator
import time
import argparse
def run_latency(warmup_time_s, upstream_ip, upstream_port, duration_s, ssl):
sw... | PyBench/Main.py | from Switch import Switch
from pyof.foundation.basic_types import DPID
from FileWriter import FileWriter
from FlowModGenerator import FlowModGenerator
from PacketInEchoGenerator import PacketInEchoGenerator
import time
import argparse
def run_latency(warmup_time_s, upstream_ip, upstream_port, duration_s, ssl):
sw... | 0.580947 | 0.239572 |
from __future__ import absolute_import, division, print_function, unicode_literals
from glob import glob
from logging import getLogger
from os import listdir
from os.path import basename, isdir, isfile, join, lexists, dirname
from ..base.constants import CONDA_TARBALL_EXTENSION, PREFIX_MAGIC_FILE
from ..base.context ... | conda/core/prefix_data.py | from __future__ import absolute_import, division, print_function, unicode_literals
from glob import glob
from logging import getLogger
from os import listdir
from os.path import basename, isdir, isfile, join, lexists, dirname
from ..base.constants import CONDA_TARBALL_EXTENSION, PREFIX_MAGIC_FILE
from ..base.context ... | 0.460774 | 0.138345 |
import warnings
from collections import OrderedDict, Iterable
from torch import nn
import torch
import torchvision
from .base import Core2d
from ... import regularizers
from ..affine import Bias2DLayer, Scale2DLayer
from ..activations import AdaptiveELU
from ..hermite import (
HermiteConv2D,
RotationEquivaria... | neuralpredictors/layers/cores/conv2d.py | import warnings
from collections import OrderedDict, Iterable
from torch import nn
import torch
import torchvision
from .base import Core2d
from ... import regularizers
from ..affine import Bias2DLayer, Scale2DLayer
from ..activations import AdaptiveELU
from ..hermite import (
HermiteConv2D,
RotationEquivaria... | 0.910782 | 0.538559 |
import cv2
import paddle
import numpy as np
import albumentations as al
def get_augmentation():
return al.Compose([
al.RandomResizedCrop(512, 512, scale=(0.2, 1.)),
al.Compose(
[
# NOTE: RandomBrightnessContrast replaces ColorJitter
al.RandomBrightnessCo... | contrib/DomainAdaptation/utils/augmentation.py | import cv2
import paddle
import numpy as np
import albumentations as al
def get_augmentation():
return al.Compose([
al.RandomResizedCrop(512, 512, scale=(0.2, 1.)),
al.Compose(
[
# NOTE: RandomBrightnessContrast replaces ColorJitter
al.RandomBrightnessCo... | 0.637708 | 0.469216 |
from __future__ import division
from __future__ import print_function
import argparse
import gzip
import os
import sys
import urllib
try:
from urllib.error import URLError
from urllib.request import urlretrieve
except ImportError:
from urllib2 import URLError
from urllib import urlretrie... | cpp/tools/download_mnist.py | from __future__ import division
from __future__ import print_function
import argparse
import gzip
import os
import sys
import urllib
try:
from urllib.error import URLError
from urllib.request import urlretrieve
except ImportError:
from urllib2 import URLError
from urllib import urlretrie... | 0.250088 | 0.049612 |
import cPickle as pickle
import os
import sys
import time
from datetime import datetime
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.preprocessing import MinMaxScaler
from modlamp.descriptors import PeptideDescriptor
seed = np.random.RandomState(seed=3)
... | AL_final.py | import cPickle as pickle
import os
import sys
import time
from datetime import datetime
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import pairwise_distances
from sklearn.preprocessing import MinMaxScaler
from modlamp.descriptors import PeptideDescriptor
seed = np.random.RandomState(seed=3)
... | 0.464173 | 0.281518 |
import numpy as np
from .base import ScalarField
from ..geometry.coord_systems import (
cartesian_to_spherical,
cartesian_to_cylindrical)
from ..ransac import (
single_fit,
RANSAC_MODELS,
RANSAC_SAMPLERS)
class XYZScalarField(ScalarField):
def extract_info(self):
self.points = self.py... | pyntcloud/scalar_fields/xyz.py | import numpy as np
from .base import ScalarField
from ..geometry.coord_systems import (
cartesian_to_spherical,
cartesian_to_cylindrical)
from ..ransac import (
single_fit,
RANSAC_MODELS,
RANSAC_SAMPLERS)
class XYZScalarField(ScalarField):
def extract_info(self):
self.points = self.py... | 0.74512 | 0.414691 |
import numpy as np
from compmech.conecyl import ConeCyl
def test_static():
wmin_ref = [
['clpt_donnell_bc1', -0.0512249327106],
['clpt_donnell_bc2', -0.0500855846496],
['clpt_donnell_bc3', -0.0509280039584],
['clpt_donnell_bc4', -0.0498127720591],
['fsd... | compmech/conecyl/tests/test_static.py | import numpy as np
from compmech.conecyl import ConeCyl
def test_static():
wmin_ref = [
['clpt_donnell_bc1', -0.0512249327106],
['clpt_donnell_bc2', -0.0500855846496],
['clpt_donnell_bc3', -0.0509280039584],
['clpt_donnell_bc4', -0.0498127720591],
['fsd... | 0.358016 | 0.548553 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import logging
from PIL import Image
from PIL import ImageOps
DEFAULT_OPACITY = 0 # Between (0, 255)
# Conversion settings
_REQUIRED_MIN_DIMENSION = 10 # required minimum size of converted image
... | facets_atlasmaker/convert.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import logging
from PIL import Image
from PIL import ImageOps
DEFAULT_OPACITY = 0 # Between (0, 255)
# Conversion settings
_REQUIRED_MIN_DIMENSION = 10 # required minimum size of converted image
... | 0.853211 | 0.2553 |
import logging
import io
from ..common import SourceLocation
from .token import CToken
from ..tools.handlexer import HandLexerBase, Char
class SourceFile:
""" Presents the current file. """
def __init__(self, name):
self.filename = name
self.row = 1
def __repr__(self):
return '<... | ppci/lang/c/lexer.py |
import logging
import io
from ..common import SourceLocation
from .token import CToken
from ..tools.handlexer import HandLexerBase, Char
class SourceFile:
""" Presents the current file. """
def __init__(self, name):
self.filename = name
self.row = 1
def __repr__(self):
return '<... | 0.345989 | 0.158142 |
import json
import numpy as np
_json_keys = dict(
data="arraydata",
dtype="arraydtype",
shape="arraysize"
)
_complex_keys = dict(
real="real",
imag="imag"
)
def dumps(data, json_keys=None, complex_keys=None):
global _json_keys, _complex_keys
if json_keys is None:
json_key... | numpy_json.py | import json
import numpy as np
_json_keys = dict(
data="arraydata",
dtype="arraydtype",
shape="arraysize"
)
_complex_keys = dict(
real="real",
imag="imag"
)
def dumps(data, json_keys=None, complex_keys=None):
global _json_keys, _complex_keys
if json_keys is None:
json_key... | 0.298389 | 0.192862 |
import django
if django.VERSION < (1, 8):
from django.core.context_processors import csrf
else:
from django.template.context_processors import csrf
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from .. impo... | floreal/views/edit_user_purchases.py |
import django
if django.VERSION < (1, 8):
from django.core.context_processors import csrf
else:
from django.template.context_processors import csrf
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from .. impo... | 0.267313 | 0.088939 |
from pathlib import Path
import sqlite3
import pandas as pd
from tqdm import tqdm
from sys import stderr
from imageio import imread, imwrite
import numpy as np
from skimage import transform as tf
from matplotlib import pyplot as plt
from transform_utils import scale_pixel_box_coordinates, crop_image
from compare_one_sr... | recover_leaf_sr_transparency.py | from pathlib import Path
import sqlite3
import pandas as pd
from tqdm import tqdm
from sys import stderr
from imageio import imread, imwrite
import numpy as np
from skimage import transform as tf
from matplotlib import pyplot as plt
from transform_utils import scale_pixel_box_coordinates, crop_image
from compare_one_sr... | 0.488039 | 0.187486 |
import numpy as np
import torch
from typing import Callable, Dict, Optional, Tuple
from alibi_detect.cd.base import BaseLSDDDrift
from alibi_detect.utils.pytorch.kernels import GaussianRBF
from alibi_detect.utils.pytorch.distance import permed_lsdds
class LSDDDriftTorch(BaseLSDDDrift):
def __init__(
s... | alibi_detect/cd/pytorch/lsdd.py | import numpy as np
import torch
from typing import Callable, Dict, Optional, Tuple
from alibi_detect.cd.base import BaseLSDDDrift
from alibi_detect.utils.pytorch.kernels import GaussianRBF
from alibi_detect.utils.pytorch.distance import permed_lsdds
class LSDDDriftTorch(BaseLSDDDrift):
def __init__(
s... | 0.946634 | 0.625753 |
from contextlib import redirect_stdout, redirect_stderr
from datetime import datetime
from pathlib import Path
import os
import sys
import tempfile
import time
from typing import Mapping, List, Optional
from .fileutils import PathLike, tee_stdout, tee_stderr
from .parameters import Parameters
from .plugin import Temp... | src/watts/plugin_pyarc.py |
from contextlib import redirect_stdout, redirect_stderr
from datetime import datetime
from pathlib import Path
import os
import sys
import tempfile
import time
from typing import Mapping, List, Optional
from .fileutils import PathLike, tee_stdout, tee_stderr
from .parameters import Parameters
from .plugin import Temp... | 0.722037 | 0.153549 |
from pandapipes import pandapipesNet
from pandapipes.multinet.control.run_control_multinet import prepare_run_ctrl, run_control
from pandapipes.timeseries.run_time_series import init_default_outputwriter as init_default_ow_pps
from pandapower import pandapowerNet
from pandapower.control.util.diagnostic import control_... | pandapipes/multinet/timeseries/run_time_series_multinet.py |
from pandapipes import pandapipesNet
from pandapipes.multinet.control.run_control_multinet import prepare_run_ctrl, run_control
from pandapipes.timeseries.run_time_series import init_default_outputwriter as init_default_ow_pps
from pandapower import pandapowerNet
from pandapower.control.util.diagnostic import control_... | 0.666171 | 0.441252 |
import json, os
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect, get_object_or_404
from jobs.query import DataFinder
from models import Season, Episode, Request
import sys
from wsgiref.util import FileWrapper
VIDEOS_URL_PREFIX = 'http://localhost/'
VIDEOS_PATH_PREFIX = 'j... | thruline-master/ThruLineDjango/ThruLine/views.py | import json, os
from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect, get_object_or_404
from jobs.query import DataFinder
from models import Season, Episode, Request
import sys
from wsgiref.util import FileWrapper
VIDEOS_URL_PREFIX = 'http://localhost/'
VIDEOS_PATH_PREFIX = 'j... | 0.287668 | 0.133783 |
import time
import urllib
from pyspark.sql import Row
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
# Get the file path, if not local download from web.
def get_data_file(isLocal):
if(isLocal):
filepath = "C:\\Users... | Resources/apache-spark-pyspark-sql/nypd_mv_collision_analysis/3.py | import time
import urllib
from pyspark.sql import Row
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
# Get the file path, if not local download from web.
def get_data_file(isLocal):
if(isLocal):
filepath = "C:\\Users... | 0.431824 | 0.124346 |
"""Tests for `mbed_tools.targets.get_board`."""
import pytest
from unittest import mock
from mbed_tools.targets._internal.exceptions import BoardAPIError
# Import from top level as this is the expected interface for users
from mbed_tools.targets import get_board_by_online_id, get_board_by_product_code, get_board_by_... | tests/targets/test_get_board.py | """Tests for `mbed_tools.targets.get_board`."""
import pytest
from unittest import mock
from mbed_tools.targets._internal.exceptions import BoardAPIError
# Import from top level as this is the expected interface for users
from mbed_tools.targets import get_board_by_online_id, get_board_by_product_code, get_board_by_... | 0.889778 | 0.539954 |
import logging
import pytest
from ocs_ci.framework.testlib import ManageTest, libtest
from ocs_ci.ocs.cluster import CephCluster
from ocs_ci.helpers import helpers
log = logging.getLogger(__name__)
@pytest.fixture(scope="class")
def test_fixture(request):
"""
Create disks
"""
self = request.node.cl... | tests/libtest/test_cluster_utils.py | import logging
import pytest
from ocs_ci.framework.testlib import ManageTest, libtest
from ocs_ci.ocs.cluster import CephCluster
from ocs_ci.helpers import helpers
log = logging.getLogger(__name__)
@pytest.fixture(scope="class")
def test_fixture(request):
"""
Create disks
"""
self = request.node.cl... | 0.47025 | 0.30319 |
import pytest
import json
import logging
import traceback
from urllib.parse import urlparse, parse_qsl
from pytest_httpserver import HTTPServer
from werkzeug.datastructures import Headers as HTTPHeaders
from werkzeug import Response as WerkzeugResponse, Request as WerkzeugRequest
LOG = logging.getLogger(__name__)
_... | tests/rss_proxy_server.py | import pytest
import json
import logging
import traceback
from urllib.parse import urlparse, parse_qsl
from pytest_httpserver import HTTPServer
from werkzeug.datastructures import Headers as HTTPHeaders
from werkzeug import Response as WerkzeugResponse, Request as WerkzeugRequest
LOG = logging.getLogger(__name__)
_... | 0.355439 | 0.238406 |
from http.server import SimpleHTTPRequestHandler
import logging
import os
import socket
import socketserver
import threading
import urllib.parse
logger = logging.getLogger(__name__)
def _translate_path(path, root):
"""Direct copy of /http/server.py except that ``root`` replaces the call
to ``os.getcwd()``. ... | src/dativetop/serve/servejsapp.py | from http.server import SimpleHTTPRequestHandler
import logging
import os
import socket
import socketserver
import threading
import urllib.parse
logger = logging.getLogger(__name__)
def _translate_path(path, root):
"""Direct copy of /http/server.py except that ``root`` replaces the call
to ``os.getcwd()``. ... | 0.554712 | 0.06885 |
from stacks.utils.RMFTestCase import *
from mock.mock import MagicMock, call, patch
from only_for_platform import not_for_platform, PLATFORM_WINDOWS
@not_for_platform(PLATFORM_WINDOWS)
class TestGangliaServer(RMFTestCase):
COMMON_SERVICES_PACKAGE_DIR = "GANGLIA/3.5.0/package"
STACK_VERSION = "2.0.6"
def test... | ambari-server/src/test/python/stacks/2.0.6/GANGLIA/test_ganglia_server.py | from stacks.utils.RMFTestCase import *
from mock.mock import MagicMock, call, patch
from only_for_platform import not_for_platform, PLATFORM_WINDOWS
@not_for_platform(PLATFORM_WINDOWS)
class TestGangliaServer(RMFTestCase):
COMMON_SERVICES_PACKAGE_DIR = "GANGLIA/3.5.0/package"
STACK_VERSION = "2.0.6"
def test... | 0.290578 | 0.112551 |
import pytest
from plenum.test.view_change.helper import ensure_all_nodes_have_same_data, \
start_stopped_node
from plenum.common.constants import DOMAIN_LEDGER_ID, LedgerState, POOL_LEDGER_ID
from plenum.test.helper import sendReqsToNodesAndVerifySuffReplies
from plenum.test.pool_transactions.conftest import loo... | plenum/test/node_catchup/test_node_catchup_when_3_not_primary_node_restarted.py | import pytest
from plenum.test.view_change.helper import ensure_all_nodes_have_same_data, \
start_stopped_node
from plenum.common.constants import DOMAIN_LEDGER_ID, LedgerState, POOL_LEDGER_ID
from plenum.test.helper import sendReqsToNodesAndVerifySuffReplies
from plenum.test.pool_transactions.conftest import loo... | 0.449634 | 0.508422 |
import asyncio
import json
import logging
from pathlib import Path
import urllib
import xml.etree.ElementTree as ET
import aiofiles
import aiohttp
from aiohttp import FormData
# === Global vars ===
FORMAT = (
"[%(asctime)s][%(name)s][%(process)d %(processName)s]" "[%(levelname)-8s](L:%(lineno)s) %(funcName)s: %(m... | tests/integration/run_tests.py | import asyncio
import json
import logging
from pathlib import Path
import urllib
import xml.etree.ElementTree as ET
import aiofiles
import aiohttp
from aiohttp import FormData
# === Global vars ===
FORMAT = (
"[%(asctime)s][%(name)s][%(process)d %(processName)s]" "[%(levelname)-8s](L:%(lineno)s) %(funcName)s: %(m... | 0.560974 | 0.20044 |
import io
import os
from urllib.parse import urlparse
import requests
import yaml
from doozerlib.exceptions import DoozerFatalError
from doozerlib.exectools import cmd_assert
from doozerlib.logutil import getLogger
from doozerlib.model import Missing
from doozerlib.pushd import Dir
from doozerlib.util import is_in_di... | doozerlib/source_modifications.py | import io
import os
from urllib.parse import urlparse
import requests
import yaml
from doozerlib.exceptions import DoozerFatalError
from doozerlib.exectools import cmd_assert
from doozerlib.logutil import getLogger
from doozerlib.model import Missing
from doozerlib.pushd import Dir
from doozerlib.util import is_in_di... | 0.656658 | 0.241534 |