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 discord, requests, json from discord.ext import commands from fake_useragent import UserAgent bot = commands.Bot( command_prefix="-", help_command=None, case_insensitive=True, intents=discord.Intents.all(), ) TOKEN = "" @bot.event async def on_ready(): print("Bot is ready") await bot....
main.py
import discord, requests, json from discord.ext import commands from fake_useragent import UserAgent bot = commands.Bot( command_prefix="-", help_command=None, case_insensitive=True, intents=discord.Intents.all(), ) TOKEN = "" @bot.event async def on_ready(): print("Bot is ready") await bot....
0.121334
0.116286
from __future__ import absolute_import, unicode_literals from mock import MagicMock, patch, PropertyMock from unittest import TestCase from gs.group.groups.list.membergroups import ( MemberGroups, PublicGroups, RestrictedGroups, PrivateGroups, SecretGroups, ) class TestMemberGroups(TestCase): def test_lower_n...
gs/group/groups/list/tests/membergroups.py
from __future__ import absolute_import, unicode_literals from mock import MagicMock, patch, PropertyMock from unittest import TestCase from gs.group.groups.list.membergroups import ( MemberGroups, PublicGroups, RestrictedGroups, PrivateGroups, SecretGroups, ) class TestMemberGroups(TestCase): def test_lower_n...
0.75401
0.14814
from homeassistant.components.cover import ( ATTR_POSITION, SUPPORT_CLOSE, SUPPORT_CLOSE_TILT, SUPPORT_OPEN, SUPPORT_OPEN_TILT, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION, SUPPORT_STOP, SUPPORT_STOP_TILT, CoverEntity, ) from homeassistant.core import callback from homeassist...
homeassistant/components/acmeda/cover.py
from homeassistant.components.cover import ( ATTR_POSITION, SUPPORT_CLOSE, SUPPORT_CLOSE_TILT, SUPPORT_OPEN, SUPPORT_OPEN_TILT, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION, SUPPORT_STOP, SUPPORT_STOP_TILT, CoverEntity, ) from homeassistant.core import callback from homeassist...
0.798776
0.165863
from __future__ import annotations from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import logging from fontTools.designspaceLib import ( AxisDescriptor, AxisLabelDescriptor, DesignSpaceDocument, DesignSpaceDocumentError, DiscreteAxisDescriptor, SimpleLocationD...
Lib/site-packages/fontTools/designspaceLib/statNames.py
from __future__ import annotations from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import logging from fontTools.designspaceLib import ( AxisDescriptor, AxisLabelDescriptor, DesignSpaceDocument, DesignSpaceDocumentError, DiscreteAxisDescriptor, SimpleLocationD...
0.738198
0.181916
import numpy as np from data import indicator_basis, ou_process from utils import allclose_sign, allclose_trajs, allclose_trajs_sign import pytest import ref_corr import ivac def make_data(ns, dt, nbins): """Generate featurized data for testing.""" return [indicator_basis(ou_process(n, dt), nbins) for n in n...
tests/test_linear.py
import numpy as np from data import indicator_basis, ou_process from utils import allclose_sign, allclose_trajs, allclose_trajs_sign import pytest import ref_corr import ivac def make_data(ns, dt, nbins): """Generate featurized data for testing.""" return [indicator_basis(ou_process(n, dt), nbins) for n in n...
0.797754
0.823683
import numpy as np import scipy.optimize from optwrapper import base, utils, lp class Soln( base.Soln ): def __init__( self ): super().__init__() self.retval = -1 self.message = "Uninitialized Solution" def getStatus( self ): return self.message class Solver( base.Solver )...
optwrapper/scipy_linprog.py
import numpy as np import scipy.optimize from optwrapper import base, utils, lp class Soln( base.Soln ): def __init__( self ): super().__init__() self.retval = -1 self.message = "Uninitialized Solution" def getStatus( self ): return self.message class Solver( base.Solver )...
0.306216
0.144783
# pylint: disable=too-many-lines,too-many-locals,too-many-public-methods,too-few-public-methods from typing import Any, Dict, List, Optional from ...models import Compliance from ..base import ApiBaseClass class ComplianceApi(ApiBaseClass): """Endpoints for creating, getting and downloading compliance reports."...
matterapi/endpoints/async_api/compliance.py
# pylint: disable=too-many-lines,too-many-locals,too-many-public-methods,too-few-public-methods from typing import Any, Dict, List, Optional from ...models import Compliance from ..base import ApiBaseClass class ComplianceApi(ApiBaseClass): """Endpoints for creating, getting and downloading compliance reports."...
0.840783
0.17037
# part 4 import logging import os import warnings # Suppress warnings warnings.simplefilter('ignore') import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from guiltytargets.pipeline import rank_targets, write_gat2vec_input_files from guiltytargets.ppi_network_annotation import generate_ppi_net...
src/scripts/compare_gat2vec_hyperparams_adjust.py
# part 4 import logging import os import warnings # Suppress warnings warnings.simplefilter('ignore') import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from guiltytargets.pipeline import rank_targets, write_gat2vec_input_files from guiltytargets.ppi_network_annotation import generate_ppi_net...
0.386763
0.237267
import rospy from ar_track_alvar.msg import AlvarMarkers from geometry_msgs.msg import Twist from math import copysign class ARFollower(): def __init__(self): rospy.init_node("ar_follower") # Set the shutdown function (stop the robot) rospy.on_shutdown(self.shutdown...
src/rbx2/rbx2_ar_tags/nodes/ar_follower.py
import rospy from ar_track_alvar.msg import AlvarMarkers from geometry_msgs.msg import Twist from math import copysign class ARFollower(): def __init__(self): rospy.init_node("ar_follower") # Set the shutdown function (stop the robot) rospy.on_shutdown(self.shutdown...
0.674158
0.373447
begin_unit comment|'# Copyright 2013 Rackspace Hosting' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comme...
nova/api/openstack/compute/instance_actions.py
begin_unit comment|'# Copyright 2013 Rackspace Hosting' nl|'\n' comment|'# All Rights Reserved.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comme...
0.55254
0.05498
from __future__ import division, absolute_import, print_function import re import sys import os import subprocess __doc__ = """This module generates a DEF file from the symbols in an MSVC-compiled DLL import library. It correctly discriminates between data and functions. The data is collected from the output of the...
env/lib/python3.6/site-packages/numpy/distutils/lib2def.py
from __future__ import division, absolute_import, print_function import re import sys import os import subprocess __doc__ = """This module generates a DEF file from the symbols in an MSVC-compiled DLL import library. It correctly discriminates between data and functions. The data is collected from the output of the...
0.287268
0.246159
#: Definitions for parts of module schema definitions = { 'array_of_strings': { 'type': 'array', 'default': [], 'items': { 'type': 'string' } }, 'dictionary_of_strings': { 'type': 'object', 'patternProperties': { r'\w[\w-]*': { # key ...
lib/spack/spack/schema/modules.py
#: Definitions for parts of module schema definitions = { 'array_of_strings': { 'type': 'array', 'default': [], 'items': { 'type': 'string' } }, 'dictionary_of_strings': { 'type': 'object', 'patternProperties': { r'\w[\w-]*': { # key ...
0.531209
0.257613
import errno import functools import logging import os import pkg_resources import sys import threading import time import werkzeug.local from future.moves.urllib.parse import urlparse import future.utils # look up table for errno's # FIXME: maybe add more codes? ERROR_CODES = errno.errorcode.copy() ERROR_CODES[-1]...
talisker/util.py
import errno import functools import logging import os import pkg_resources import sys import threading import time import werkzeug.local from future.moves.urllib.parse import urlparse import future.utils # look up table for errno's # FIXME: maybe add more codes? ERROR_CODES = errno.errorcode.copy() ERROR_CODES[-1]...
0.366476
0.085901
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__ = ['RouterArgs', 'Router'] @pulumi.input_type class RouterArgs: def __init__(__self__, *, networ...
sdk/python/pulumi_gcp/compute/router.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__ = ['RouterArgs', 'Router'] @pulumi.input_type class RouterArgs: def __init__(__self__, *, networ...
0.909394
0.126785
import sys import math import torch.nn as nn from .baseRNN import BaseRNN class EncoderRNN(BaseRNN): r""" Applies a multi-layer RNN to an input sequence. Args: vocab_size (int): size of the vocabulary max_len (int): a maximum allowed length for the sequence to be processed hidden_...
models/EncoderRNN.py
import sys import math import torch.nn as nn from .baseRNN import BaseRNN class EncoderRNN(BaseRNN): r""" Applies a multi-layer RNN to an input sequence. Args: vocab_size (int): size of the vocabulary max_len (int): a maximum allowed length for the sequence to be processed hidden_...
0.873781
0.660255
import argparse import json import os from distutils.util import strtobool from os.path import join, dirname import sys from watercooler_utils import arm_ops from watercooler_utils import az from watercooler_utils import blob_ops from watercooler_utils import adf_ops from watercooler_utils import common from config i...
solutions/watercooler/deployment/azure/scripts/post-deployment.py
import argparse import json import os from distutils.util import strtobool from os.path import join, dirname import sys from watercooler_utils import arm_ops from watercooler_utils import az from watercooler_utils import blob_ops from watercooler_utils import adf_ops from watercooler_utils import common from config i...
0.295027
0.056314
from odoo import api, fields, models, tools, SUPERUSER_ID from odoo.addons.base.models.res_partner import _tz_get class LeaveReportCalendar(models.Model): _name = "hr.leave.report.calendar" _description = 'Time Off Calendar' _auto = False _order = "start_datetime DESC, employee_id" name = field...
addons/hr_holidays/report/hr_leave_report_calendar.py
from odoo import api, fields, models, tools, SUPERUSER_ID from odoo.addons.base.models.res_partner import _tz_get class LeaveReportCalendar(models.Model): _name = "hr.leave.report.calendar" _description = 'Time Off Calendar' _auto = False _order = "start_datetime DESC, employee_id" name = field...
0.524882
0.152064
import shapefile class Kedua: def __init__(self): self.kedua = shapefile.Writer('kedua', shapeType = shapefile.POLYGON) self.kedua.shapeType self.kedua.field('nama_ruangan', 'C') #<NAME> - 1174035 def tanggaBawahKiri(self, label): self.kedua.record(label) self.kedu...
kedua.py
import shapefile class Kedua: def __init__(self): self.kedua = shapefile.Writer('kedua', shapeType = shapefile.POLYGON) self.kedua.shapeType self.kedua.field('nama_ruangan', 'C') #<NAME> - 1174035 def tanggaBawahKiri(self, label): self.kedua.record(label) self.kedu...
0.300643
0.443179
# Imports import discord from discord.ext import commands import datetime import re import json import asyncio import logging class PollCommand(commands.Cog): def __init__(self, bot): self.bot = bot self.count_dict = {} self.total_count = {} self.poll_check_dict = {} self...
bot/exts/utils/poll.py
# Imports import discord from discord.ext import commands import datetime import re import json import asyncio import logging class PollCommand(commands.Cog): def __init__(self, bot): self.bot = bot self.count_dict = {} self.total_count = {} self.poll_check_dict = {} self...
0.312895
0.099908
__all__ = [ "token_names", "Token", "LexerError", "Lexer", ] from enum import Enum as _Enum from typing import Iterator as _Iterator from typing import Sequence as _Sequence try: from lex import token_names as _token_names except ImportError: from src.lex import token_names as _token_names c...
src/lex/__init__.py
__all__ = [ "token_names", "Token", "LexerError", "Lexer", ] from enum import Enum as _Enum from typing import Iterator as _Iterator from typing import Sequence as _Sequence try: from lex import token_names as _token_names except ImportError: from src.lex import token_names as _token_names c...
0.940072
0.300117
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------...
azure-devops/azext_devops/devops_sdk/v5_1/feed/models.py
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------...
0.907145
0.265693
import numpy as np from scipy import stats from .distparams import distcont # this is not a proper statistical test for convergence, but only # verifies that the estimate and true values do not differ by too much n_repl1 = 1000 # sample size for first run n_repl2 = 5000 # sample size for second run, if first run f...
venv/Lib/site-packages/statsmodels/sandbox/distributions/tests/_est_fit.py
import numpy as np from scipy import stats from .distparams import distcont # this is not a proper statistical test for convergence, but only # verifies that the estimate and true values do not differ by too much n_repl1 = 1000 # sample size for first run n_repl2 = 5000 # sample size for second run, if first run f...
0.514156
0.41567
"""Python command line interface for running TOCO.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys from tensorflow.contrib.lite.python import lite from tensorflow.contrib.lite.python import lite_constants from tensor...
tensorflow/contrib/lite/python/tflite_convert.py
"""Python command line interface for running TOCO.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os import sys from tensorflow.contrib.lite.python import lite from tensorflow.contrib.lite.python import lite_constants from tensor...
0.796846
0.264323
"""Common modeling utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Optional, Text import numpy as np import tensorflow as tf import tensorflow.compat.v1 as tf1 from tensorflow.python.tpu import tpu_function @tf.keras.utils....
official/legacy/image_classification/efficientnet/common_modules.py
"""Common modeling utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Optional, Text import numpy as np import tensorflow as tf import tensorflow.compat.v1 as tf1 from tensorflow.python.tpu import tpu_function @tf.keras.utils....
0.965479
0.310812
from abc import ABC, abstractmethod from textwrap import dedent from pants.build_graph.address_lookup_error import AddressLookupError from pants.testutil.test_base import TestBase from pants.contrib.go.register import build_file_aliases class GoLocalSourceTestBase(ABC): # NB: We assume we're mixed into a TestB...
contrib/go/tests/python/pants_test/contrib/go/targets/go_local_source_test_base.py
from abc import ABC, abstractmethod from textwrap import dedent from pants.build_graph.address_lookup_error import AddressLookupError from pants.testutil.test_base import TestBase from pants.contrib.go.register import build_file_aliases class GoLocalSourceTestBase(ABC): # NB: We assume we're mixed into a TestB...
0.862598
0.251699
import gc import pytest from types import TracebackType # NOQA from typing import Any # NOQA from typing import Dict # NOQA from typing import Optional # NOQA from typing import Type # NOQA from optuna import create_study from optuna.integration import ChainerMNStudy from optuna.storages import BaseStorage # NOQ...
tests/integration_tests/test_chainermn.py
import gc import pytest from types import TracebackType # NOQA from typing import Any # NOQA from typing import Dict # NOQA from typing import Optional # NOQA from typing import Type # NOQA from optuna import create_study from optuna.integration import ChainerMNStudy from optuna.storages import BaseStorage # NOQ...
0.690976
0.348507
import asyncio import logging import typing import aiohttp from discord.ext.ipc.errors import * log = logging.getLogger(__name__) class Client: """ Handles webserver side requests to the bot process. Parameters ---------- host: str The IP or host of the IPC server, defaults to localhost...
discord/ext/ipc/client.py
import asyncio import logging import typing import aiohttp from discord.ext.ipc.errors import * log = logging.getLogger(__name__) class Client: """ Handles webserver side requests to the bot process. Parameters ---------- host: str The IP or host of the IPC server, defaults to localhost...
0.704567
0.138345
"""Private utilities for locally-connected layers.""" import numpy as np import tensorflow.compat.v2 as tf from keras import backend from keras.utils import conv_utils def get_locallyconnected_mask( input_shape, kernel_shape, strides, padding, data_format ): """Return a mask representing connectivity of a l...
keras/layers/locally_connected/locally_connected_utils.py
"""Private utilities for locally-connected layers.""" import numpy as np import tensorflow.compat.v2 as tf from keras import backend from keras.utils import conv_utils def get_locallyconnected_mask( input_shape, kernel_shape, strides, padding, data_format ): """Return a mask representing connectivity of a l...
0.977756
0.748972
import os import sys # 3rd party from gi.repository import Gio, Gtk from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as\ FigureCanvas from matplotlib.figure import Figure import pandas as pd import pylab as pl import quantpy as qp DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') ...
quantpy/gui/app.py
import os import sys # 3rd party from gi.repository import Gio, Gtk from matplotlib.backends.backend_gtk3cairo import FigureCanvasGTK3Cairo as\ FigureCanvas from matplotlib.figure import Figure import pandas as pd import pylab as pl import quantpy as qp DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') ...
0.197677
0.100216
OUT_IN = ''' , "parametersChanges" : [ { "ifAnyIsTrue": [ "rand >= .5" ], "doThesechanges": { "Perturbation::parameters": { "rotationScalingFactor": 0.1 } }, "otherwise": { "Perturbation::parameters": { "rotationScalingFactor": 0.25 }...
pele_platform/constants/pele_params.py
OUT_IN = ''' , "parametersChanges" : [ { "ifAnyIsTrue": [ "rand >= .5" ], "doThesechanges": { "Perturbation::parameters": { "rotationScalingFactor": 0.1 } }, "otherwise": { "Perturbation::parameters": { "rotationScalingFactor": 0.25 }...
0.389082
0.517205
import json from .data_utils.data_loader import image_segmentation_generator, \ verify_segmentation_dataset import glob import six from keras.callbacks import Callback def find_latest_checkpoint(checkpoints_path, fail_safe=True): def get_epoch_number_from_path(path): return path.replace(checkpoints_p...
segmentation/keras_segmentation/train.py
import json from .data_utils.data_loader import image_segmentation_generator, \ verify_segmentation_dataset import glob import six from keras.callbacks import Callback def find_latest_checkpoint(checkpoints_path, fail_safe=True): def get_epoch_number_from_path(path): return path.replace(checkpoints_p...
0.709824
0.260166
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import numpy as np from pandas import DataFrame, Series from pandas.util.testing import (assert_series_equal, assert_frame_equal, assert_almost_equal) import trackpy...
trackpy/tests/test_motion.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import numpy as np from pandas import DataFrame, Series from pandas.util.testing import (assert_series_equal, assert_frame_equal, assert_almost_equal) import trackpy...
0.814901
0.671686
"""Test ``migrate`` command.""" import os from pathlib import Path import pytest from renku import LocalClient from renku.cli import cli from renku.core.management.config import RENKU_HOME from renku.core.management.migrate import SUPPORTED_PROJECT_VERSION, get_migrations @pytest.mark.migration def test_migrate_dat...
tests/cli/test_migrate.py
"""Test ``migrate`` command.""" import os from pathlib import Path import pytest from renku import LocalClient from renku.cli import cli from renku.core.management.config import RENKU_HOME from renku.core.management.migrate import SUPPORTED_PROJECT_VERSION, get_migrations @pytest.mark.migration def test_migrate_dat...
0.653348
0.572902
"""Tests for multi_worker_util.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.protobuf import cluster_pb2 from tensorflow.python.distribute import multi_worker_util from tensorflow.python.eager import test from tensorflow.python.tr...
tensorflow/python/distribute/multi_worker_util_test.py
"""Tests for multi_worker_util.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.protobuf import cluster_pb2 from tensorflow.python.distribute import multi_worker_util from tensorflow.python.eager import test from tensorflow.python.tr...
0.875088
0.549459
import gym from gym import spaces from gym.utils import seeding def cmp(a, b): return int((a > b)) - int((a < b)) # 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10 deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def draw_card(np_random): return np_random.choice(deck) def draw_hand(np_random): re...
rl/envs/blackjack.py
import gym from gym import spaces from gym.utils import seeding def cmp(a, b): return int((a > b)) - int((a < b)) # 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10 deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def draw_card(np_random): return np_random.choice(deck) def draw_hand(np_random): re...
0.337968
0.454291
# Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import salt.utils.path # Import Salt Libs from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) def __virtual__(): """ Check to see if firewall-cmd exists ...
salt/modules/firewalld.py
# Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import logging import re import salt.utils.path # Import Salt Libs from salt.exceptions import CommandExecutionError log = logging.getLogger(__name__) def __virtual__(): """ Check to see if firewall-cmd exists ...
0.638497
0.156717
'文件接收方' import socket import threading import header import os from printworker import PrintWorker def transfer_file(sock, path): '接收文件' # 文件大小 file_size = None # 已接收文件大小 recv_size = 0 # 待保存文件的路径 save_file_path = None # 接收的文件 fp = None # 打印类型 print_type = None ...
receiver.py
'文件接收方' import socket import threading import header import os from printworker import PrintWorker def transfer_file(sock, path): '接收文件' # 文件大小 file_size = None # 已接收文件大小 recv_size = 0 # 待保存文件的路径 save_file_path = None # 接收的文件 fp = None # 打印类型 print_type = None ...
0.094544
0.082771
from typing import Callable, TYPE_CHECKING from enum import Enum if TYPE_CHECKING: from unit import Unit class Strategy(Enum): HOLD = 1 ADVANCE = 2 CHARGE = 3 HCHARGE = 4 DISTANCE = 5 def get_strategy_function(strategy: Strategy) -> Callable[["Unit", float, float], None]: options = { ...
src/stratgey.py
from typing import Callable, TYPE_CHECKING from enum import Enum if TYPE_CHECKING: from unit import Unit class Strategy(Enum): HOLD = 1 ADVANCE = 2 CHARGE = 3 HCHARGE = 4 DISTANCE = 5 def get_strategy_function(strategy: Strategy) -> Callable[["Unit", float, float], None]: options = { ...
0.819424
0.52683
import logging import pytest from subprocess import TimeoutExpired from ocs_ci.ocs.exceptions import CephHealthException, ResourceWrongStatusException from ocs_ci.utility.utils import ceph_health_check_base from ocs_ci.ocs import constants, machine, ocp, defaults from ocs_ci.ocs.node import ( drain_nodes, sc...
tests/manage/z_cluster/nodes/test_nodes_maintenance.py
import logging import pytest from subprocess import TimeoutExpired from ocs_ci.ocs.exceptions import CephHealthException, ResourceWrongStatusException from ocs_ci.utility.utils import ceph_health_check_base from ocs_ci.ocs import constants, machine, ocp, defaults from ocs_ci.ocs.node import ( drain_nodes, sc...
0.474388
0.329972
from absl.testing import parameterized import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import uncertainty_baselines as ub from uncertainty_baselines.datasets import dialog_state_tracking max_dial_len = dialog_state_tracking.MAX_DIALOG_LEN max_utt_len = dialog_state_tracking.MAX_UTT_LEN ...
uncertainty_baselines/datasets/dialog_state_tracking_test.py
from absl.testing import parameterized import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import uncertainty_baselines as ub from uncertainty_baselines.datasets import dialog_state_tracking max_dial_len = dialog_state_tracking.MAX_DIALOG_LEN max_utt_len = dialog_state_tracking.MAX_UTT_LEN ...
0.757346
0.64579
from __future__ import print_function import os import sys import tempfile from chromite.lib import cros_test_lib from chromite.lib import table from chromite.scripts import merge_package_status as mps assert sys.version_info >= (3, 6), 'This module requires Python 3.6+' # pylint: disable=protected-access class...
scripts/merge_package_status_unittest.py
from __future__ import print_function import os import sys import tempfile from chromite.lib import cros_test_lib from chromite.lib import table from chromite.scripts import merge_package_status as mps assert sys.version_info >= (3, 6), 'This module requires Python 3.6+' # pylint: disable=protected-access class...
0.496094
0.169475
import optparse from typing import List, Tuple, Dict import stun import struct import socket FullCone: str = "Full Cone" # 0 RestrictNAT: str = "Restrict NAT" # 1 RestrictPortNAT: str = "Restrict Port NAT" # 2 SymmetricNAT: str = "Symmetric NAT" # 3 UnknownNAT: str = "Unknown NAT" # 4 NATTYPE = (FullCone, Restri...
psy/network.py
import optparse from typing import List, Tuple, Dict import stun import struct import socket FullCone: str = "Full Cone" # 0 RestrictNAT: str = "Restrict NAT" # 1 RestrictPortNAT: str = "Restrict Port NAT" # 2 SymmetricNAT: str = "Symmetric NAT" # 3 UnknownNAT: str = "Unknown NAT" # 4 NATTYPE = (FullCone, Restri...
0.445047
0.109016
from typing import Any, Tuple from lxml import objectify, etree from sdRDM.tools.utils import snake_to_camel class XMLWriter: @classmethod def to_xml( cls, root_name: str, values: dict, props: dict, to_string: bool = True ) -> objectify.ObjectifiedElement: ...
easyDataverse/tools/xmltools.py
from typing import Any, Tuple from lxml import objectify, etree from sdRDM.tools.utils import snake_to_camel class XMLWriter: @classmethod def to_xml( cls, root_name: str, values: dict, props: dict, to_string: bool = True ) -> objectify.ObjectifiedElement: ...
0.832985
0.3341
import unittest from pythainlp.tag import perceptron, pos_tag, pos_tag_sents, unigram from pythainlp.tag.locations import tag_provinces from pythainlp.tag.named_entity import ThaiNameTagger from pythainlp.tokenize import ( word_tokenize, ) class TestTagPackage(unittest.TestCase): def test_pos_tag(self): ...
tests/test_tag.py
import unittest from pythainlp.tag import perceptron, pos_tag, pos_tag_sents, unigram from pythainlp.tag.locations import tag_provinces from pythainlp.tag.named_entity import ThaiNameTagger from pythainlp.tokenize import ( word_tokenize, ) class TestTagPackage(unittest.TestCase): def test_pos_tag(self): ...
0.498291
0.610541
import typing from construct import Construct from retro_data_structures.formats.ancs import ANCS, Ancs from retro_data_structures.formats.anim import ANIM, Anim from retro_data_structures.base_resource import BaseResource, AssetType from retro_data_structures.formats.char import CHAR, Char from retro_data_structures...
retro_data_structures/formats/__init__.py
import typing from construct import Construct from retro_data_structures.formats.ancs import ANCS, Ancs from retro_data_structures.formats.anim import ANIM, Anim from retro_data_structures.base_resource import BaseResource, AssetType from retro_data_structures.formats.char import CHAR, Char from retro_data_structures...
0.444324
0.231289
from datetime import timedelta as td from django.conf import settings from django.core.signing import base64_hmac from django.utils.timezone import now from hc.api.models import Check from hc.test import BaseTestCase class BadgeTestCase(BaseTestCase): def setUp(self): super(BadgeTestCase, self).setUp()...
hc/api/tests/test_badge.py
from datetime import timedelta as td from django.conf import settings from django.core.signing import base64_hmac from django.utils.timezone import now from hc.api.models import Check from hc.test import BaseTestCase class BadgeTestCase(BaseTestCase): def setUp(self): super(BadgeTestCase, self).setUp()...
0.582135
0.259063
import flavio from . import observables from flavio.classes import Observable, Prediction import cmath def bsvll_obs(function, q2, wc_obj, par, B, V, lep): ml = par['m_'+lep] mB = par['m_'+B] mV = par['m_'+V] y = par['DeltaGamma/Gamma_'+B]/2. if q2 < 4*ml**2 or q2 > (mB-mV)**2: return 0 ...
flavio/physics/bdecays/bvll/observables_bs.py
import flavio from . import observables from flavio.classes import Observable, Prediction import cmath def bsvll_obs(function, q2, wc_obj, par, B, V, lep): ml = par['m_'+lep] mB = par['m_'+B] mV = par['m_'+V] y = par['DeltaGamma/Gamma_'+B]/2. if q2 < 4*ml**2 or q2 > (mB-mV)**2: return 0 ...
0.525369
0.342517
import os import socket import sys from subprocess import STDOUT, Popen, DEVNULL from typing import Iterable, List from prefect import config from prefect.agent import Agent from prefect.environments.storage import GCS, S3, Azure, Local from prefect.serialization.storage import StorageSchema from prefect.utilities.gra...
src/prefect/agent/local/agent.py
import os import socket import sys from subprocess import STDOUT, Popen, DEVNULL from typing import Iterable, List from prefect import config from prefect.agent import Agent from prefect.environments.storage import GCS, S3, Azure, Local from prefect.serialization.storage import StorageSchema from prefect.utilities.gra...
0.710025
0.550366
from sympy.assumptions import Q, ask from sympy.core import Add, Basic, Expr, Float, Mul, Pow, S from sympy.core.numbers import (ImaginaryUnit, Infinity, Integer, NaN, NegativeInfinity, NumberSymbol, Rational) from sympy.functions import Abs, im, re from sympy.ntheory import isprime from sympy.multipledispa...
sympy/assumptions/handlers/ntheory.py
from sympy.assumptions import Q, ask from sympy.core import Add, Basic, Expr, Float, Mul, Pow, S from sympy.core.numbers import (ImaginaryUnit, Infinity, Integer, NaN, NegativeInfinity, NumberSymbol, Rational) from sympy.functions import Abs, im, re from sympy.ntheory import isprime from sympy.multipledispa...
0.470493
0.171408
import argparse import logging import os import subprocess from typing import Any, Dict import jinja2 import yaml CONFIGS_DIR = "/etc/magma/configs" TEMPLATES_DIR = "/etc/magma/templates" OUTPUT_DIR = "/etc/nghttpx" OBSIDIAN_PORT = 9081 def _load_services() -> Dict[Any, Any]: """ Return the services from the r...
orc8r/cloud/docker/proxy/run_nghttpx.py
import argparse import logging import os import subprocess from typing import Any, Dict import jinja2 import yaml CONFIGS_DIR = "/etc/magma/configs" TEMPLATES_DIR = "/etc/magma/templates" OUTPUT_DIR = "/etc/nghttpx" OBSIDIAN_PORT = 9081 def _load_services() -> Dict[Any, Any]: """ Return the services from the r...
0.470493
0.067547
import matplotlib.pyplot as plt class LinePlot: """ A simple line plot with one or more variables """ def __init__(self, plot_data, plot_func='plot', **kwargs): self.plot_data = plot_data self.plot_func = plot_func self.plot_args = kwargs self._x_label = "" ...
spiceplot/plots/simple.py
import matplotlib.pyplot as plt class LinePlot: """ A simple line plot with one or more variables """ def __init__(self, plot_data, plot_func='plot', **kwargs): self.plot_data = plot_data self.plot_func = plot_func self.plot_args = kwargs self._x_label = "" ...
0.910977
0.662796
import asyncio import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.helpers import discovery from homeassistant.helpers.entity import Entity from homeassistant.components.discovery import SERVICE_XIAOMI_GW from homeassistant.const import (ATTR_BATTERY_LEVEL, EV...
homeassistant/components/xiaomi_aqara.py
import asyncio import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.helpers import discovery from homeassistant.helpers.entity import Entity from homeassistant.components.discovery import SERVICE_XIAOMI_GW from homeassistant.const import (ATTR_BATTERY_LEVEL, EV...
0.498535
0.069352
from test.zoo.pipeline.utils.test_utils import ZooTestCase import numpy as np import pandas as pd import os from numpy.testing import assert_array_almost_equal from zoo.orca.automl.xgboost.XGBoost import XGBoost from zoo.chronos.feature.identity_transformer import IdentityTransformer import pytest class TestXgbreg...
pyzoo/test/zoo/orca/automl/xgboost/test_xgbregressor.py
from test.zoo.pipeline.utils.test_utils import ZooTestCase import numpy as np import pandas as pd import os from numpy.testing import assert_array_almost_equal from zoo.orca.automl.xgboost.XGBoost import XGBoost from zoo.chronos.feature.identity_transformer import IdentityTransformer import pytest class TestXgbreg...
0.591133
0.457743
import re import requests from bs4 import BeautifulSoup from taemin import plugin class TaeminNiceBot(plugin.TaeminPlugin): def __init__(self, taemin): plugin.TaeminPlugin.__init__(self, taemin) self.mapping = [ (r"""((?:http[s]?://)?(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)([\w\-]+)(...
taemin/plugins/nicebot/plugin.py
import re import requests from bs4 import BeautifulSoup from taemin import plugin class TaeminNiceBot(plugin.TaeminPlugin): def __init__(self, taemin): plugin.TaeminPlugin.__init__(self, taemin) self.mapping = [ (r"""((?:http[s]?://)?(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)([\w\-]+)(...
0.376623
0.119768
import logging import warnings import torch import torch.nn as nn from torch.nn import CrossEntropyLoss, MSELoss from .configuration_roberta import RobertaConfig from .file_utils import add_start_docstrings, add_start_docstrings_to_callable from .modeling_bert import BertEmbeddings, BertLayerNorm, BertModel, BertPreT...
src/transformers/modeling_roberta.py
import logging import warnings import torch import torch.nn as nn from torch.nn import CrossEntropyLoss, MSELoss from .configuration_roberta import RobertaConfig from .file_utils import add_start_docstrings, add_start_docstrings_to_callable from .modeling_bert import BertEmbeddings, BertLayerNorm, BertModel, BertPreT...
0.929079
0.314932
import os import cStringIO from PIL import Image from django.db.models import ImageField from django.db.models.fields.files import ImageFieldFile from django.conf import settings from django.core.cache import cache from django.core.files.base import ContentFile from athumb.exceptions import UploadedImageIsUnreadableEr...
athumb/fields.py
import os import cStringIO from PIL import Image from django.db.models import ImageField from django.db.models.fields.files import ImageFieldFile from django.conf import settings from django.core.cache import cache from django.core.files.base import ContentFile from athumb.exceptions import UploadedImageIsUnreadableEr...
0.471953
0.143758
from app.models import Donor, Donation, Item, ItemDevice from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse from django.views.decorators.http import require_GET import simplejson as json @login_required(login_url='/login') @require_GET def autocomplete_name(re...
app/views/api_views.py
from app.models import Donor, Donation, Item, ItemDevice from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse from django.views.decorators.http import require_GET import simplejson as json @login_required(login_url='/login') @require_GET def autocomplete_name(re...
0.369088
0.113555
import torch from torch.autograd import Variable import numpy as np from train import params from util import utils import torch.optim as optim def train(training_mode, feature_extractor, class_classifier, domain_classifier, class_criterion, domain_criterion, source_dataloader, target_dataloader, optimize...
train/train.py
import torch from torch.autograd import Variable import numpy as np from train import params from util import utils import torch.optim as optim def train(training_mode, feature_extractor, class_classifier, domain_classifier, class_criterion, domain_criterion, source_dataloader, target_dataloader, optimize...
0.68742
0.482917
import glob import os import sys import warnings import IECore import Gaffer import GafferTest class test( Gaffer.Application ) : def __init__( self ) : Gaffer.Application.__init__( self, """ Runs the unit tests for all of Gaffer's python modules and libraries. These are run automatically as part...
apps/test/test-1.py
import glob import os import sys import warnings import IECore import Gaffer import GafferTest class test( Gaffer.Application ) : def __init__( self ) : Gaffer.Application.__init__( self, """ Runs the unit tests for all of Gaffer's python modules and libraries. These are run automatically as part...
0.349089
0.740655
# This script takes the Debug log output from the golang build server, and # will play it back to servers via sourcegraph.com's LSP HTTP layer import json import requests api = 'http://127.0.0.1/.api/xlang/' # Uncomment for production #api = 'https://sourcegraph.com/.api/xlang/' def main(lines): for num, line i...
enterprise/cmd/xlang-go/internal/server/replay-traffic.py
# This script takes the Debug log output from the golang build server, and # will play it back to servers via sourcegraph.com's LSP HTTP layer import json import requests api = 'http://127.0.0.1/.api/xlang/' # Uncomment for production #api = 'https://sourcegraph.com/.api/xlang/' def main(lines): for num, line i...
0.280025
0.18159
from typing import List, Optional import pytest from gbq.dto import Structure class DatasetListItem: def __init__(self, dataset_id: str, project: str): self.dataset_id = dataset_id self.project = project class SchemaField: def __init__( self, name: str, mode: str, field_type: str, ...
tests/fixtures.py
from typing import List, Optional import pytest from gbq.dto import Structure class DatasetListItem: def __init__(self, dataset_id: str, project: str): self.dataset_id = dataset_id self.project = project class SchemaField: def __init__( self, name: str, mode: str, field_type: str, ...
0.860691
0.368803
from torch.utils.data import Dataset import os from os.path import join import torchvision.transforms as transforms import random from PIL import Image from torchOnVideo.super_resolution.utils import * class TrainISeeBetter(Dataset): def __init__(self, image_dir, nFrames, upscale_factor, data_augmentation, file_l...
torchOnVideo/datasets/Vimeo90KSeptuplet/super_resolution/train_iseebetter.py
from torch.utils.data import Dataset import os from os.path import join import torchvision.transforms as transforms import random from PIL import Image from torchOnVideo.super_resolution.utils import * class TrainISeeBetter(Dataset): def __init__(self, image_dir, nFrames, upscale_factor, data_augmentation, file_l...
0.779154
0.289755
import json from data_source import DataSource import features_utility from manifest_features import CreateManifestFeatures, ConvertDottedKeysToNested from third_party.json_schema_compiler.json_parse import Parse def _ListifyAndSortDocs(features, app_name): '''Convert a |feautres| dictionary, and all 'children' di...
chrome/common/extensions/docs/server2/manifest_data_source.py
import json from data_source import DataSource import features_utility from manifest_features import CreateManifestFeatures, ConvertDottedKeysToNested from third_party.json_schema_compiler.json_parse import Parse def _ListifyAndSortDocs(features, app_name): '''Convert a |feautres| dictionary, and all 'children' di...
0.64232
0.28173
import datetime from google.cloud._helpers import _datetime_to_rfc3339 from google.cloud.client import JSONClient from google.cloud.monitoring.connection import Connection from google.cloud.monitoring.group import Group from google.cloud.monitoring.metric import Metric from google.cloud.monitoring.metric import Metric...
monitoring/google/cloud/monitoring/client.py
import datetime from google.cloud._helpers import _datetime_to_rfc3339 from google.cloud.client import JSONClient from google.cloud.monitoring.connection import Connection from google.cloud.monitoring.group import Group from google.cloud.monitoring.metric import Metric from google.cloud.monitoring.metric import Metric...
0.850158
0.221666
__author__ = "<NAME>" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" from Bio import SeqIO from Bio.Seq import Seq import sys tsv = open(sys.argv[1], "r") readlines = tsv.readlines() tsv.close() gtf = open(sys.argv[2], "r") readgtf = gtf.readlines() gtf.close() genomefile = open(sys.argv[3], "rU") genomeSeqIOdict...
bin/GTF-to-FASTA_EverythingButGTF.py
__author__ = "<NAME>" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" from Bio import SeqIO from Bio.Seq import Seq import sys tsv = open(sys.argv[1], "r") readlines = tsv.readlines() tsv.close() gtf = open(sys.argv[2], "r") readgtf = gtf.readlines() gtf.close() genomefile = open(sys.argv[3], "rU") genomeSeqIOdict...
0.186762
0.186225
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo class Inception3(nn.Module): def __init__(self, num_classes=512, aux_logits=True, transform_input=False): super(Inception3, self).__init__() self.aux_logits = aux_logits self.trans...
student_net_learning/models/inception3.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo class Inception3(nn.Module): def __init__(self, num_classes=512, aux_logits=True, transform_input=False): super(Inception3, self).__init__() self.aux_logits = aux_logits self.trans...
0.930655
0.563078
from setuptools import setup, Extension import os import sys import subprocess hidapi_topdir = os.path.join("hidapi") hidapi_include = os.path.join(hidapi_topdir, "hidapi") system_hidapi = 0 libs = [] src = ["hid.pyx", "chid.pxd"] def hidapi_src(platform): return os.path.join(hidapi_topdir, platform, "hid.c") ...
cython-hidapi/setup.py
from setuptools import setup, Extension import os import sys import subprocess hidapi_topdir = os.path.join("hidapi") hidapi_include = os.path.join(hidapi_topdir, "hidapi") system_hidapi = 0 libs = [] src = ["hid.pyx", "chid.pxd"] def hidapi_src(platform): return os.path.join(hidapi_topdir, platform, "hid.c") ...
0.181155
0.041715
import json import os import torch import torch.nn.functional as F from collections import OrderedDict from .base_cam import BaseCAM import numpy as np # Load the dictionary of model configs # that for each model has the name of # the last layer before the GAP filepath = os.path.join(os.path.dirname(__file__), 'model...
cams/grad_cam.py
import json import os import torch import torch.nn.functional as F from collections import OrderedDict from .base_cam import BaseCAM import numpy as np # Load the dictionary of model configs # that for each model has the name of # the last layer before the GAP filepath = os.path.join(os.path.dirname(__file__), 'model...
0.824674
0.344085
import argparse import logging import os import sys from typing import Any, Dict, List, Mapping, MutableSequence, Optional, Union, cast from urllib.parse import urlparse import pkg_resources # part of setuptools from rdflib import __version__ as rdflib_version from rdflib.parser import Parser from rdflib.plugin impo...
schema_salad/main.py
import argparse import logging import os import sys from typing import Any, Dict, List, Mapping, MutableSequence, Optional, Union, cast from urllib.parse import urlparse import pkg_resources # part of setuptools from rdflib import __version__ as rdflib_version from rdflib.parser import Parser from rdflib.plugin impo...
0.568536
0.100746
import ctypes from enum import Enum import os import re from catkit.interfaces.LaserSource import LaserSource import catkit.util """Interface for a laser source.""" # Load Thorlabs uart lib, e.g., uart_library_win64.dll. try: UART_lib = ctypes.cdll.LoadLibrary(os.environ.get('CATKIT_THORLABS_UART_LIB_PATH')) exc...
catkit/hardware/thorlabs/ThorlabsMCLS1.py
import ctypes from enum import Enum import os import re from catkit.interfaces.LaserSource import LaserSource import catkit.util """Interface for a laser source.""" # Load Thorlabs uart lib, e.g., uart_library_win64.dll. try: UART_lib = ctypes.cdll.LoadLibrary(os.environ.get('CATKIT_THORLABS_UART_LIB_PATH')) exc...
0.735357
0.076064
import mxnet as mx import symbol_utils def Act(data, act_type, name): # ignore param act_type, set it in this function body = mx.sym.LeakyReLU(data=data, act_type='prelu', name=name) # act = mx.sym.Activation(data=bn, act_type='relu', name='%s%s_relu' %(name, suffix)) return body def Conv(data, num...
train/symbols/fmobilenet.py
import mxnet as mx import symbol_utils def Act(data, act_type, name): # ignore param act_type, set it in this function body = mx.sym.LeakyReLU(data=data, act_type='prelu', name=name) # act = mx.sym.Activation(data=bn, act_type='relu', name='%s%s_relu' %(name, suffix)) return body def Conv(data, num...
0.675978
0.557725
import logging from enum import Enum from typing import Any, Dict, List, Optional, Union from ... import Logger from .base import BaseValidator from .exceptions import SchemaValidationError RULES_KEY = "rules" FEATURE_DEFAULT_VAL_KEY = "default" CONDITIONS_KEY = "conditions" RULE_MATCH_VALUE = "when_match" CONDITION_...
aws_lambda_powertools/utilities/feature_flags/schema.py
import logging from enum import Enum from typing import Any, Dict, List, Optional, Union from ... import Logger from .base import BaseValidator from .exceptions import SchemaValidationError RULES_KEY = "rules" FEATURE_DEFAULT_VAL_KEY = "default" CONDITIONS_KEY = "conditions" RULE_MATCH_VALUE = "when_match" CONDITION_...
0.891478
0.420778
from __future__ import unicode_literals import unittest from django.utils import html class TestUtilsHtml(unittest.TestCase): def check_output(self, function, value, output=None): """ Check that function(value) equals output. If output is None, check that function(value) equals value. ...
tests/regressiontests/utils/html.py
from __future__ import unicode_literals import unittest from django.utils import html class TestUtilsHtml(unittest.TestCase): def check_output(self, function, value, output=None): """ Check that function(value) equals output. If output is None, check that function(value) equals value. ...
0.51562
0.2627
import time import json import csv OVERLAP_DIRECTORY = "../data/processed_data/overlap/" OVERLAP_OUTFILE_DESTINATION = "../data/processed_data/overlap/cross_party_donor_overlap.csv" TOTALS_OUTFILE_DESTINATION = "../data/processed_data/overlap/cross_party_donor_totals.csv" def process_comparison(main_id, compare_id...
scripts/find_crossparty_overlap.py
import time import json import csv OVERLAP_DIRECTORY = "../data/processed_data/overlap/" OVERLAP_OUTFILE_DESTINATION = "../data/processed_data/overlap/cross_party_donor_overlap.csv" TOTALS_OUTFILE_DESTINATION = "../data/processed_data/overlap/cross_party_donor_totals.csv" def process_comparison(main_id, compare_id...
0.300848
0.230649
import json import sys import logging import requests import os from urllib3.util.retry import Retry from urllib import parse from requests.adapters import HTTPAdapter from gitlabform.configuration.core import ConfigurationCore, KeyNotFoundException class GitLabCore: url = None token = None ssl_verify = ...
gitlabform/gitlab/core.py
import json import sys import logging import requests import os from urllib3.util.retry import Retry from urllib import parse from requests.adapters import HTTPAdapter from gitlabform.configuration.core import ConfigurationCore, KeyNotFoundException class GitLabCore: url = None token = None ssl_verify = ...
0.436862
0.15393
from msrest.serialization import Model class FabricErrorError(Model): """Error object containing error code and error message. All required parameters must be populated in order to send to Azure. :param code: Required. Defines the fabric error codes that be returned as part of the error object in ...
azure-servicefabric/azure/servicefabric/models/fabric_error_error.py
from msrest.serialization import Model class FabricErrorError(Model): """Error object containing error code and error message. All required parameters must be populated in order to send to Azure. :param code: Required. Defines the fabric error codes that be returned as part of the error object in ...
0.759047
0.097133
"""Permission to Roles Manager (Adapter) """ from zope.interface import implementer from zope.security.permission import allPermissions from zope.securitypolicy.role import checkRole from zope.securitypolicy.interfaces import Allow, Deny, Unset from zope.securitypolicy.interfaces import IRolePermissionManager from zop...
src/zope/securitypolicy/rolepermission.py
"""Permission to Roles Manager (Adapter) """ from zope.interface import implementer from zope.security.permission import allPermissions from zope.securitypolicy.role import checkRole from zope.securitypolicy.interfaces import Allow, Deny, Unset from zope.securitypolicy.interfaces import IRolePermissionManager from zop...
0.655887
0.232223
import torch from torch.utils import data class RandomSampler(data.sampler.Sampler): """Based off of pytorch RandomSampler and DistributedSampler. Essentially a RandomSampler, but this class lets the user set an epoch like DistributedSampler Samples elements randomly. If without replacement, then samp...
megatron/data/samplers.py
import torch from torch.utils import data class RandomSampler(data.sampler.Sampler): """Based off of pytorch RandomSampler and DistributedSampler. Essentially a RandomSampler, but this class lets the user set an epoch like DistributedSampler Samples elements randomly. If without replacement, then samp...
0.904915
0.684758
import json import boto3 import mock from mock import patch from moto import mock_iam, mock_sts from pytest import raises from security_monkey import db, app, ARN_PREFIX from security_monkey.datastore import Account, AccountType, Technology, Item, ItemAudit, ItemRevision, WatcherConfig from security_monkey.monitors i...
security_monkey/tests/scheduling/test_celery_scheduler.py
import json import boto3 import mock from mock import patch from moto import mock_iam, mock_sts from pytest import raises from security_monkey import db, app, ARN_PREFIX from security_monkey.datastore import Account, AccountType, Technology, Item, ItemAudit, ItemRevision, WatcherConfig from security_monkey.monitors i...
0.484624
0.21565
import tensorflow as tf from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt # Load and split dataset. This has a slightly different structure than usual as it uses a dataset instead of a np array (train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()...
5 - Computer Vision/image_detection_with_cnn.py
import tensorflow as tf from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt # Load and split dataset. This has a slightly different structure than usual as it uses a dataset instead of a np array (train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()...
0.876489
0.677626
import esgfpid import logging import sys import datetime input('Make sure you have an exchange "test123" ready, including a queue and the required bindings (see inside this script). Ok? (press any key)') if not len(sys.argv) == 4: print('Please call with <host> <user> <password>!') exit(999) # Please fill i...
manual_tests/test04_datacart.py
import esgfpid import logging import sys import datetime input('Make sure you have an exchange "test123" ready, including a queue and the required bindings (see inside this script). Ok? (press any key)') if not len(sys.argv) == 4: print('Please call with <host> <user> <password>!') exit(999) # Please fill i...
0.110844
0.121191
from agent import Agent class HumanAgent(Agent): # overriding abstract method def reinforce_owned_territory(self, state): territory_name = input('Reinforce owned territory: ').strip() return state.board.territories[territory_name] # overriding abstract method def reinforce_neutral_ter...
human_agent.py
from agent import Agent class HumanAgent(Agent): # overriding abstract method def reinforce_owned_territory(self, state): territory_name = input('Reinforce owned territory: ').strip() return state.board.territories[territory_name] # overriding abstract method def reinforce_neutral_ter...
0.470493
0.421373
import numpy as np from sklearn.metrics import confusion_matrix VOC_CLASSES = [ "background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"...
metrics/stream_metrics.py
import numpy as np from sklearn.metrics import confusion_matrix VOC_CLASSES = [ "background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"...
0.670285
0.35855
from wdom.tag import NewTagClass as NewTag from wdom.themes import Button as _Button from wdom.themes import * name = 'KATHAMO' project_url = 'http://kathamo.github.io/' project_repository = 'https://github.com/kathamo/Kathamo' license = 'MIT License' license_url = 'https://github.com/kathamo/Kathamo/blob/master/LICE...
wdom/themes/kathamo.py
from wdom.tag import NewTagClass as NewTag from wdom.themes import Button as _Button from wdom.themes import * name = 'KATHAMO' project_url = 'http://kathamo.github.io/' project_repository = 'https://github.com/kathamo/Kathamo' license = 'MIT License' license_url = 'https://github.com/kathamo/Kathamo/blob/master/LICE...
0.641984
0.064772
import math import StringIO import types __pychecker__ = 'no-returnvalues' WS = set([' ', '\t', '\r', '\n', '\x08', '\x0c']) DIGITS = set([str(i) for i in range(0, 10)]) NUMSTART = DIGITS.union(['.', '-', '+']) NUMCHARS = NUMSTART.union(['e', 'E']) ESC_MAP = {'n': '\n', 't': '\t', 'r': '\r', 'b': '\x08', 'f': '\x0c'} R...
examples/microjson/mutants/CRP_Num_mutant_1486201313.py
import math import StringIO import types __pychecker__ = 'no-returnvalues' WS = set([' ', '\t', '\r', '\n', '\x08', '\x0c']) DIGITS = set([str(i) for i in range(0, 10)]) NUMSTART = DIGITS.union(['.', '-', '+']) NUMCHARS = NUMSTART.union(['e', 'E']) ESC_MAP = {'n': '\n', 't': '\t', 'r': '\r', 'b': '\x08', 'f': '\x0c'} R...
0.444083
0.231527
class ClassGenerationContext(object): def __init__(self, universe): self._universe = universe self._name = None self._super_name = None self._class_side = False # to be overridden self._number_of_instance_fields_of_super = -1 self._number_of_class_fields_o...
som/compiler/class_generation_context.py
class ClassGenerationContext(object): def __init__(self, universe): self._universe = universe self._name = None self._super_name = None self._class_side = False # to be overridden self._number_of_instance_fields_of_super = -1 self._number_of_class_fields_o...
0.581422
0.126434
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from research.fivo.fivo.models import base from research.fivo.fivo.test_utils import create_vrnn class VrnnTest(tf.test.TestCase): def test_vrnn_normal_emissi...
research/fivo/fivo/models/vrnn_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from research.fivo.fivo.models import base from research.fivo.fivo.test_utils import create_vrnn class VrnnTest(tf.test.TestCase): def test_vrnn_normal_emissi...
0.844297
0.479504
import re from gluon import current from core import s3_str PLACEHOLDER = re.compile(r"\{([^{}]+)\}") # ============================================================================= def formatmap(template, mapping): """ Helper to replace placeholders in template using mapping @param: template, ...
modules/templates/RLPPTM/notifications.py
import re from gluon import current from core import s3_str PLACEHOLDER = re.compile(r"\{([^{}]+)\}") # ============================================================================= def formatmap(template, mapping): """ Helper to replace placeholders in template using mapping @param: template, ...
0.781289
0.326432
import copy from typing import List, Optional, Union from qiskit.circuit.exceptions import CircuitError # pylint: disable=cyclic-import from .quantumcircuit import QuantumCircuit from .gate import Gate from .quantumregister import QuantumRegister from ._utils import _ctrl_state_to_int class ControlledGate(Gate): ...
qiskit/circuit/controlledgate.py
import copy from typing import List, Optional, Union from qiskit.circuit.exceptions import CircuitError # pylint: disable=cyclic-import from .quantumcircuit import QuantumCircuit from .gate import Gate from .quantumregister import QuantumRegister from ._utils import _ctrl_state_to_int class ControlledGate(Gate): ...
0.945235
0.514583
import string import random SYMBOLS = list('!"#$%&\'()*+,-./:;?@[]^_`{|}~') UPPERCASE = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S,' 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] LOWERCASE = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', '...
src/main.py
import string import random SYMBOLS = list('!"#$%&\'()*+,-./:;?@[]^_`{|}~') UPPERCASE = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S,' 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] LOWERCASE = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', '...
0.149252
0.258575
import numpy as np import pytest from pyrender import ( DirectionalLight, SpotLight, PointLight, Texture, PerspectiveCamera, OrthographicCamera, ) from pyrender.constants import SHADOW_TEX_SZ def test_directional_light(): d = DirectionalLight() assert d.name is None assert np.all...
tests/unit/test_lights.py
import numpy as np import pytest from pyrender import ( DirectionalLight, SpotLight, PointLight, Texture, PerspectiveCamera, OrthographicCamera, ) from pyrender.constants import SHADOW_TEX_SZ def test_directional_light(): d = DirectionalLight() assert d.name is None assert np.all...
0.791741
0.742982
"""Memory leak detection utility.""" from tensorflow.python.framework.python_memory_checker import _PythonMemoryChecker from tensorflow.python.profiler import trace from tensorflow.python.util import tf_inspect try: from tensorflow.python.platform.cpp_memory_checker import _CppMemoryChecker as CppMemoryChecker # p...
tensorflow/python/framework/memory_checker.py
"""Memory leak detection utility.""" from tensorflow.python.framework.python_memory_checker import _PythonMemoryChecker from tensorflow.python.profiler import trace from tensorflow.python.util import tf_inspect try: from tensorflow.python.platform.cpp_memory_checker import _CppMemoryChecker as CppMemoryChecker # p...
0.825027
0.267193
import os from unittest import mock from django.contrib.auth.models import Permission, User from django.shortcuts import get_object_or_404 from django.test.utils import override_settings from django.utils import translation from django.utils.translation import gettext as _ from django.conf import settings # Workarou...
geotrek/common/tests/__init__.py
import os from unittest import mock from django.contrib.auth.models import Permission, User from django.shortcuts import get_object_or_404 from django.test.utils import override_settings from django.utils import translation from django.utils.translation import gettext as _ from django.conf import settings # Workarou...
0.490236
0.214157
import os.path, sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) import mcpi.minecraft as minecraft from math import sqrt from PIL import Image # Connect to minecraft server 127.0.0.1 as player 'steve' mc = minecraft.Minecraft.create(address="127.0.0.1", name="steve") # Poss...
examples/mcpi_pixel_art.py
import os.path, sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) import mcpi.minecraft as minecraft from math import sqrt from PIL import Image # Connect to minecraft server 127.0.0.1 as player 'steve' mc = minecraft.Minecraft.create(address="127.0.0.1", name="steve") # Poss...
0.304972
0.284718
from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ --- author: Ansible Networking Team cliconf: vyos short_description: Use vyos cliconf to run command on VyOS platform description: - This vyos plugin provides low level abstraction apis for sending and rec...
virt/ansible-latest/lib/python2.7/site-packages/ansible/plugins/cliconf/vyos.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ --- author: Ansible Networking Team cliconf: vyos short_description: Use vyos cliconf to run command on VyOS platform description: - This vyos plugin provides low level abstraction apis for sending and rec...
0.390476
0.127002
"""Tests for tensorflow_probability.python.math.generic.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from absl.testing import parameterized import numpy as np from scipy import special as sp_special import tensorflow.compat.v1 a...
tensorflow_probability/python/math/generic_test.py
"""Tests for tensorflow_probability.python.math.generic.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from absl.testing import parameterized import numpy as np from scipy import special as sp_special import tensorflow.compat.v1 a...
0.912855
0.519095
import os import sys from typing import Optional import pytest import torch from packaging.version import Version from pkg_resources import get_distribution from pytorch_lightning.utilities import ( _APEX_AVAILABLE, _DEEPSPEED_AVAILABLE, _FAIRSCALE_AVAILABLE, _FAIRSCALE_FULLY_SHARDED_AVAILABLE, _H...
tests/helpers/runif.py
import os import sys from typing import Optional import pytest import torch from packaging.version import Version from pkg_resources import get_distribution from pytorch_lightning.utilities import ( _APEX_AVAILABLE, _DEEPSPEED_AVAILABLE, _FAIRSCALE_AVAILABLE, _FAIRSCALE_FULLY_SHARDED_AVAILABLE, _H...
0.651798
0.268985
from __future__ import absolute_import from __future__ import division from __future__ import print_function import gin import gym import numpy as np import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.environments import batched_py_environment from tf_agents.environments im...
social_rl/adversarial_env/adversarial_env.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import gin import gym import numpy as np import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.environments import batched_py_environment from tf_agents.environments im...
0.90269
0.386156
import os from os.path import join import json CURRENT_FOLDER = os.path.abspath(os.path.dirname(__file__)) def process_file(task_file_contents, folder_path): task_data = json.loads(task_file_contents) result = [] for task in task_data["tasks"]: assert all(x in task for x in ("name", "tester", "so...
tasks/task_lister.py
import os from os.path import join import json CURRENT_FOLDER = os.path.abspath(os.path.dirname(__file__)) def process_file(task_file_contents, folder_path): task_data = json.loads(task_file_contents) result = [] for task in task_data["tasks"]: assert all(x in task for x in ("name", "tester", "so...
0.223377
0.169406
from datetime import timedelta import logging from requests.exceptions import ConnectTimeout, HTTPError import voluptuous as vol from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_ACCESS_TOKEN, CONF_SCAN_INTERVAL) import homeassistant.helpers.config_validation as cv from homeassistant.core import callback f...
homeassistant/components/hydrawise/__init__.py
from datetime import timedelta import logging from requests.exceptions import ConnectTimeout, HTTPError import voluptuous as vol from homeassistant.const import ( ATTR_ATTRIBUTION, CONF_ACCESS_TOKEN, CONF_SCAN_INTERVAL) import homeassistant.helpers.config_validation as cv from homeassistant.core import callback f...
0.673192
0.111919