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
try: from math import * except ImportError: print("SKIP") import sys sys.exit() test_values = [-100., -1.23456, -1, -0.5, 0.0, 0.5, 1.23456, 100.] test_values_small = [-10., -1.23456, -1, -0.5, 0.0, 0.5, 1.23456, 10.] # so we don't overflow 32-bit precision unit_range_test_values = [-1., -0.75, -0.5, ...
tests/float/math_fun.py
try: from math import * except ImportError: print("SKIP") import sys sys.exit() test_values = [-100., -1.23456, -1, -0.5, 0.0, 0.5, 1.23456, 100.] test_values_small = [-10., -1.23456, -1, -0.5, 0.0, 0.5, 1.23456, 10.] # so we don't overflow 32-bit precision unit_range_test_values = [-1., -0.75, -0.5, ...
0.276788
0.596081
import sqlite3 import sys def index_variation(cursor): cursor.execute('''create index var_chr_start_idx on\ variants(chrom, start)''') cursor.execute('''create index var_type_idx on variants(type)''') cursor.execute('''create index var_gt_counts_idx on \ varian...
gemini/database.py
import sqlite3 import sys def index_variation(cursor): cursor.execute('''create index var_chr_start_idx on\ variants(chrom, start)''') cursor.execute('''create index var_type_idx on variants(type)''') cursor.execute('''create index var_gt_counts_idx on \ varian...
0.351311
0.113776
from .namespaces import TAG, OWL, BRICK """ Set up subclasses of the equipment superclass """ equipment_subclasses = { "HVAC": {"tags": [TAG.HVAC]}, "Weather_Station": {"tags": [TAG.Weather, TAG.Station]}, "Electrical_Equipment": { "tags": [TAG.Electrical, TAG.Equipment], "subclasses": { ...
bricksrc/equipment.py
from .namespaces import TAG, OWL, BRICK """ Set up subclasses of the equipment superclass """ equipment_subclasses = { "HVAC": {"tags": [TAG.HVAC]}, "Weather_Station": {"tags": [TAG.Weather, TAG.Station]}, "Electrical_Equipment": { "tags": [TAG.Electrical, TAG.Equipment], "subclasses": { ...
0.596786
0.50891
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import yaml import ray from ray.test.cluster_utils import Cluster from ray.tune.config_parser import make_parser, resources_to_json from ray.tune.tune import _make_scheduler, run_experiments ...
python/ray/rllib/train.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import yaml import ray from ray.test.cluster_utils import Cluster from ray.tune.config_parser import make_parser, resources_to_json from ray.tune.tune import _make_scheduler, run_experiments ...
0.798265
0.189709
import pandas as pd import numpy as np from matplotlib import pyplot as plt # Series Problem s1 = pd.Series(-3, index=range(2, 11, 2)) s2 = pd.Series({'Bill':31, 'Sarah':28, 'Jane':34, 'Joe':26}) # Random Walk Problem # five random walks of length 100 plotted together N = 100 for i in xrange(5): s1 = np.zeros(N) ...
Python/pandas/PandasSolutions.py
import pandas as pd import numpy as np from matplotlib import pyplot as plt # Series Problem s1 = pd.Series(-3, index=range(2, 11, 2)) s2 = pd.Series({'Bill':31, 'Sarah':28, 'Jane':34, 'Joe':26}) # Random Walk Problem # five random walks of length 100 plotted together N = 100 for i in xrange(5): s1 = np.zeros(N) ...
0.384565
0.587943
from abc import ABC from enum import Enum from typing import List, Set, Optional, Dict class MessageType(Enum): INFO = 0 WARNING = 1 ERROR = 2 class ViewObserver: def on_change(self, change): pass class ViewComponent(ABC): """ Represents a GUI component """ def __init__(se...
bauh/api/abstract/view.py
from abc import ABC from enum import Enum from typing import List, Set, Optional, Dict class MessageType(Enum): INFO = 0 WARNING = 1 ERROR = 2 class ViewObserver: def on_change(self, change): pass class ViewComponent(ABC): """ Represents a GUI component """ def __init__(se...
0.913044
0.258314
import sys import os import numpy as np import argparse from argparse import RawTextHelpFormatter import matplotlib.pyplot as plt import matplotlib from scipy import signal from colour import Color from ec_978 import PACKET_LENGTH_FISB, PACKET_LENGTH_ADSB # number of points to show in x-axis (3 = 0,1,2,3) # The numbe...
eye.py
import sys import os import numpy as np import argparse from argparse import RawTextHelpFormatter import matplotlib.pyplot as plt import matplotlib from scipy import signal from colour import Color from ec_978 import PACKET_LENGTH_FISB, PACKET_LENGTH_ADSB # number of points to show in x-axis (3 = 0,1,2,3) # The numbe...
0.803945
0.63982
from qulacs import Observable from qulacs import QuantumState, QuantumCircuit from qulacs.gate import Probabilistic, X, Y, Z import matplotlib.pyplot as plt from numpy import polyfit def error_mitigation_extrapolate_poly(quantum_circuit_list, error_list, initial_state, ...
error_mitigation/error_mitigation_poly_example.py
from qulacs import Observable from qulacs import QuantumState, QuantumCircuit from qulacs.gate import Probabilistic, X, Y, Z import matplotlib.pyplot as plt from numpy import polyfit def error_mitigation_extrapolate_poly(quantum_circuit_list, error_list, initial_state, ...
0.844024
0.556882
import dcompy.log as log from dcompy.block_tx import * from dcompy.system_error import * from typing import Callable import threading class _Item: def __init__(self): self.protocol = 0 self.pipe = 0 self.timeout = 0 self.req = bytearray() self.resp = bytearray() #...
dcompy/waitlist.py
import dcompy.log as log from dcompy.block_tx import * from dcompy.system_error import * from typing import Callable import threading class _Item: def __init__(self): self.protocol = 0 self.pipe = 0 self.timeout = 0 self.req = bytearray() self.resp = bytearray() #...
0.523908
0.134321
import logging import numpy as np import os from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from object_detection.utils import metrics from object_detection.utils import per_image_evaluation from object_detection.utils import np_box_list class ObjectDetectionEvaluation(object): """Evalu...
object_detection/utils/object_detection_evaluation.py
import logging import numpy as np import os from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from object_detection.utils import metrics from object_detection.utils import per_image_evaluation from object_detection.utils import np_box_list class ObjectDetectionEvaluation(object): """Evalu...
0.723602
0.360151
from peewee import * # @UnusedWildImport from settings import Settings class UnknownField(object): pass class BaseModel(Model): class Meta: settings = Settings.database() db = settings['database'] settings.pop("database", None) database = MySQLDatabase(db, **settings) ...
lolalerter/model.py
from peewee import * # @UnusedWildImport from settings import Settings class UnknownField(object): pass class BaseModel(Model): class Meta: settings = Settings.database() db = settings['database'] settings.pop("database", None) database = MySQLDatabase(db, **settings) ...
0.504639
0.074131
import os import numpy as np import PIL.Image as Image import tensorflow as tf from object_detection.utils import visualization_utils _TESTDATA_PATH = 'object_detection/test_images' class VisualizationUtilsTest(tf.test.TestCase): def create_colorful_test_image(self): """This function creates an image that c...
research/object_detection/utils/visualization_utils_test.py
import os import numpy as np import PIL.Image as Image import tensorflow as tf from object_detection.utils import visualization_utils _TESTDATA_PATH = 'object_detection/test_images' class VisualizationUtilsTest(tf.test.TestCase): def create_colorful_test_image(self): """This function creates an image that c...
0.742048
0.523725
import unittest import numpy as np from parameterized import parameterized from monai.transforms.spatial.array import GridPatch from tests.utils import TEST_NDARRAYS, assert_allclose A = np.arange(16).repeat(3).reshape(4, 4, 3).transpose(2, 0, 1) A11 = A[:, :2, :2] A12 = A[:, :2, 2:] A21 = A[:, 2:, :2] A22 = A[:, 2...
tests/test_grid_patch.py
import unittest import numpy as np from parameterized import parameterized from monai.transforms.spatial.array import GridPatch from tests.utils import TEST_NDARRAYS, assert_allclose A = np.arange(16).repeat(3).reshape(4, 4, 3).transpose(2, 0, 1) A11 = A[:, :2, :2] A12 = A[:, :2, 2:] A21 = A[:, 2:, :2] A22 = A[:, 2...
0.466846
0.761139
import cairo import logging import math logger = logging.getLogger(__name__) class Chart: def __init__(self, context: cairo.Context, x, y, width, height): self.ctx = context self.orig_x = x self.orig_y = y self.width = width self.height = height self.set_x_range(...
src/chart.py
import cairo import logging import math logger = logging.getLogger(__name__) class Chart: def __init__(self, context: cairo.Context, x, y, width, height): self.ctx = context self.orig_x = x self.orig_y = y self.width = width self.height = height self.set_x_range(...
0.525612
0.292993
import codecs """This file contains code to read the train/eval/test data from file and process it, and read the vocab data from file and process it""" import glob import random import struct import csv from tensorflow.core.example import example_pb2 # <s> and </s> are used in the data files to segment the abstracts...
data.py
import codecs """This file contains code to read the train/eval/test data from file and process it, and read the vocab data from file and process it""" import glob import random import struct import csv from tensorflow.core.example import example_pb2 # <s> and </s> are used in the data files to segment the abstracts...
0.724286
0.551332
import sys import asyncio import argparse import aiohttp from asyncsector import AsyncSector from asyncsector.util import get_time async def async_main(loop): ''' Async main function Logs in to Sector Alarm and prints alarm history + temperatures repeatedly with delay. ''' parser = argparse.Ar...
asyncsector/__main__.py
import sys import asyncio import argparse import aiohttp from asyncsector import AsyncSector from asyncsector.util import get_time async def async_main(loop): ''' Async main function Logs in to Sector Alarm and prints alarm history + temperatures repeatedly with delay. ''' parser = argparse.Ar...
0.316581
0.085518
import sys, os from ...ucsmo import ManagedObject from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class VnicLanConnPolicyConsts(): INT_ID_NONE = "none" POLICY_OWNER_LOCAL = "local" POLICY_OWNER_PENDING_POLICY = "pending-policy" POLICY_OWNER_POLICY = "p...
ucsmsdk/mometa/vnic/VnicLanConnPolicy.py
import sys, os from ...ucsmo import ManagedObject from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class VnicLanConnPolicyConsts(): INT_ID_NONE = "none" POLICY_OWNER_LOCAL = "local" POLICY_OWNER_PENDING_POLICY = "pending-policy" POLICY_OWNER_POLICY = "p...
0.25128
0.148263
import ray from ray.job_config import JobConfig from ray import serve from ray.serve.config import ReplicaConfig, DeploymentConfig from ray.serve.utils import msgpack_serialize from ray.serve.generated.serve_pb2 import JAVA, RequestMetadata, RequestWrapper from ray.tests.conftest import shutdown_only # noqa: F401 de...
python/ray/serve/tests/test_cross_language.py
import ray from ray.job_config import JobConfig from ray import serve from ray.serve.config import ReplicaConfig, DeploymentConfig from ray.serve.utils import msgpack_serialize from ray.serve.generated.serve_pb2 import JAVA, RequestMetadata, RequestWrapper from ray.tests.conftest import shutdown_only # noqa: F401 de...
0.548432
0.091504
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from feet import models as feet_models from orders import models as order_models from reviews import models as review_models from . import models class ReviewInline(admin.TabularInl...
users/admin.py
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext_lazy as _ from feet import models as feet_models from orders import models as order_models from reviews import models as review_models from . import models class ReviewInline(admin.TabularInl...
0.332635
0.19673
from json import loads as json_loads import click from tabulate import tabulate from databricks_cli.click_types import OutputClickType, JsonClickType, JobIdClickType from databricks_cli.jobs.api import JobsApi from databricks_cli.utils import eat_exceptions, CONTEXT_SETTINGS, pretty_format, json_cli_base, \ trun...
databricks_cli/jobs/cli.py
from json import loads as json_loads import click from tabulate import tabulate from databricks_cli.click_types import OutputClickType, JsonClickType, JobIdClickType from databricks_cli.jobs.api import JobsApi from databricks_cli.utils import eat_exceptions, CONTEXT_SETTINGS, pretty_format, json_cli_base, \ trun...
0.555676
0.058132
from copy import copy, deepcopy import numpy as np from addict import Dict from .fake_quantize_configuration import read_all_fake_quantize_configurations, get_configurations_by_preset, \ get_configurations_by_qscheme, find_fqs_to_unify, add_range_estimator_configs from .utils import load_hardware_config, merge_n...
tools/pot/openvino/tools/pot/algorithms/quantization/fake_quantize.py
from copy import copy, deepcopy import numpy as np from addict import Dict from .fake_quantize_configuration import read_all_fake_quantize_configurations, get_configurations_by_preset, \ get_configurations_by_qscheme, find_fqs_to_unify, add_range_estimator_configs from .utils import load_hardware_config, merge_n...
0.752013
0.393094
import unittest import echidna.core.spectra as spectra import random import numpy class TestSpectra(unittest.TestCase): def test_fill(self): """ Test the fill method. Basically tests bin positioning makes sense. """ test_decays = 10 test_spectra = spectra.Spectra("Test", ...
echidna/test/test_spectra.py
import unittest import echidna.core.spectra as spectra import random import numpy class TestSpectra(unittest.TestCase): def test_fill(self): """ Test the fill method. Basically tests bin positioning makes sense. """ test_decays = 10 test_spectra = spectra.Spectra("Test", ...
0.781789
0.770896
# This module deals with test data representation for the first task ######################################################################################### import os import csv from dialent.common.util import safeOpen from dialent.common.util import normalize from dialent.config import Config from ...
scripts/dialent/task1/test.py
# This module deals with test data representation for the first task ######################################################################################### import os import csv from dialent.common.util import safeOpen from dialent.common.util import normalize from dialent.config import Config from ...
0.471223
0.278373
from pxr import Gf, Tf, Sdf, Usd, UsdGeom, Vt import unittest, math class TestUsdGeomXformable(unittest.TestCase): def _AssertCloseXf(self, a, b): for av, bv in zip(a, b): self.assertTrue(Gf.IsClose(av, bv, 1e-4)) def test_TranslateOp(self): s = Usd.Stage.CreateInMemory() ...
pxr/usd/usdGeom/testenv/testUsdGeomXformable.py
from pxr import Gf, Tf, Sdf, Usd, UsdGeom, Vt import unittest, math class TestUsdGeomXformable(unittest.TestCase): def _AssertCloseXf(self, a, b): for av, bv in zip(a, b): self.assertTrue(Gf.IsClose(av, bv, 1e-4)) def test_TranslateOp(self): s = Usd.Stage.CreateInMemory() ...
0.471467
0.508666
import pytest from brownie import accounts, compile_source module_source = """ pragma solidity 0.4.25; contract TestModule { address owner; constructor(address _owner) public { owner = _owner; } function getOwner() external view returns (address) { return owner; } function getPermissions() ...
tests/IssuingEntity/Modular/test_attach_detach.py
import pytest from brownie import accounts, compile_source module_source = """ pragma solidity 0.4.25; contract TestModule { address owner; constructor(address _owner) public { owner = _owner; } function getOwner() external view returns (address) { return owner; } function getPermissions() ...
0.574634
0.378804
import sys import os import torch import torch.distributed as dist import torch.nn as nn from torch.utils.data import DataLoader import torch.multiprocessing as mp from torch.nn.parallel import DataParallel from datetime import datetime from pepper_variant.modules.python.models.dataloader_predict import SequenceDatase...
pepper_variant/modules/python/models/predict_distributed_gpu.py
import sys import os import torch import torch.distributed as dist import torch.nn as nn from torch.utils.data import DataLoader import torch.multiprocessing as mp from torch.nn.parallel import DataParallel from datetime import datetime from pepper_variant.modules.python.models.dataloader_predict import SequenceDatase...
0.599602
0.253214
import numpy as np import os import plac import time from tensorflow.keras.optimizers import Nadam from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard from tensorflow.keras.layers import Input from tensorflow.keras import backend as K from model import MobileDetectNetModel from gene...
train.py
import numpy as np import os import plac import time from tensorflow.keras.optimizers import Nadam from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard from tensorflow.keras.layers import Input from tensorflow.keras import backend as K from model import MobileDetectNetModel from gene...
0.802439
0.454351
import _plotly_utils.basevalidators class PointcloudValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name='pointcloud', parent_name='', **kwargs): super(PointcloudValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
plotly/validators/_pointcloud.py
import _plotly_utils.basevalidators class PointcloudValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name='pointcloud', parent_name='', **kwargs): super(PointcloudValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
0.921988
0.436982
__version__ = '1.12.0' import re import logging import time from subprocess import PIPE import subprocess import os from glob import glob as globbing from itertools import repeat from collections import namedtuple import configparser import argparse import sys import errno if sys.version_info < (3,): raise ImportE...
scanner/judge/judge.py
__version__ = '1.12.0' import re import logging import time from subprocess import PIPE import subprocess import os from glob import glob as globbing from itertools import repeat from collections import namedtuple import configparser import argparse import sys import errno if sys.version_info < (3,): raise ImportE...
0.434221
0.113457
import numpy as np import mat4py from easydict import EasyDict as edict import os def integrate_bayes(cues, score, params): likelihood = [] for i, cue in enumerate(cues): if cue == 'MS': struct = mat4py.loadmat(os.path.join(params.data, 'MSlikelihood.mat')) likelihoo...
integrateBayes.py
import numpy as np import mat4py from easydict import EasyDict as edict import os def integrate_bayes(cues, score, params): likelihood = [] for i, cue in enumerate(cues): if cue == 'MS': struct = mat4py.loadmat(os.path.join(params.data, 'MSlikelihood.mat')) likelihoo...
0.280025
0.30606
from collections import OrderedDict import sys import numpy as np import pytest import tvm from tvm import relay, TVMError from tvm.ir.module import IRModule from tvm.relay import testing, transform from tvm.relay.testing import byoc from tvm.relay.op.annotation import compiler_begin, compiler_end from tvm.relay.bac...
tests/python/relay/aot/test_crt_aot.py
from collections import OrderedDict import sys import numpy as np import pytest import tvm from tvm import relay, TVMError from tvm.ir.module import IRModule from tvm.relay import testing, transform from tvm.relay.testing import byoc from tvm.relay.op.annotation import compiler_begin, compiler_end from tvm.relay.bac...
0.618435
0.368548
from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: icx_l3_interface author: "<NAME> (@Commscope)" short_description: Manage Layer-3 interfaces on Ruckus ICX 7000 series switches description: - This module provides declarative management of Layer-3 ...
venv/lib/python3.6/site-packages/ansible_collections/community/network/plugins/modules/network/icx/icx_l3_interface.py
from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: icx_l3_interface author: "<NAME> (@Commscope)" short_description: Manage Layer-3 interfaces on Ruckus ICX 7000 series switches description: - This module provides declarative management of Layer-3 ...
0.794026
0.278101
from hellosign_sdk.tests.functional_tests import BaseTestCase from hellosign_sdk.resource import ResourceList, SignatureRequest, Signature from hellosign_sdk.utils import Forbidden, HSException from time import sleep import tempfile import os class TestSignatureRequest(BaseTestCase): def _send_test_signature_req...
hellosign_sdk/tests/functional_tests/test_signature_request.py
from hellosign_sdk.tests.functional_tests import BaseTestCase from hellosign_sdk.resource import ResourceList, SignatureRequest, Signature from hellosign_sdk.utils import Forbidden, HSException from time import sleep import tempfile import os class TestSignatureRequest(BaseTestCase): def _send_test_signature_req...
0.423577
0.143608
import html.entities as htmlentities from . import Node __all__ = ["HTMLEntity"] class HTMLEntity(Node): """Represents an HTML entity, like ``&nbsp;``, either named or unnamed.""" def __init__(self, value, named=None, hexadecimal=False, hex_char="x"): super().__init__() self._value = value ...
mwparserfromhell/nodes/html_entity.py
import html.entities as htmlentities from . import Node __all__ = ["HTMLEntity"] class HTMLEntity(Node): """Represents an HTML entity, like ``&nbsp;``, either named or unnamed.""" def __init__(self, value, named=None, hexadecimal=False, hex_char="x"): super().__init__() self._value = value ...
0.814496
0.112844
import shutil from pathlib import Path from spikeinterface.core.testing_tools import generate_recording, generate_sorting from spikeinterface import WaveformExtractor, extract_waveforms from spikeinterface.extractors import toy_example, read_mearec from spikeinterface.toolkit import compute_principal_components, compu...
spikeinterface_gui/tests/testingtools.py
import shutil from pathlib import Path from spikeinterface.core.testing_tools import generate_recording, generate_sorting from spikeinterface import WaveformExtractor, extract_waveforms from spikeinterface.extractors import toy_example, read_mearec from spikeinterface.toolkit import compute_principal_components, compu...
0.390708
0.396944
import multiprocessing from time import sleep from datetime import datetime, time from vnpy.event import EventEngine2 from vnpy.trader.vtEvent import EVENT_LOG from vnpy.trader.vtEngine import MainEngine, LogEngine from vnpy.trader.gateway import ctpGateway from vnpy.trader.app import ctaStrategy from vnpy.trader.app...
examples/VnTrader/runCtaTrading.py
import multiprocessing from time import sleep from datetime import datetime, time from vnpy.event import EventEngine2 from vnpy.trader.vtEvent import EVENT_LOG from vnpy.trader.vtEngine import MainEngine, LogEngine from vnpy.trader.gateway import ctpGateway from vnpy.trader.app import ctaStrategy from vnpy.trader.app...
0.145176
0.066995
import traceback import weakref from .base import _AsyncConnDialect from .base import _ConnectionFairy from .base import _ConnectionRecord from .base import Pool from .. import exc from .. import util from ..util import chop_traceback from ..util import queue as sqla_queue from ..util import threading class QueuePoo...
venv/Lib/site-packages/sqlalchemy/pool/impl.py
import traceback import weakref from .base import _AsyncConnDialect from .base import _ConnectionFairy from .base import _ConnectionRecord from .base import Pool from .. import exc from .. import util from ..util import chop_traceback from ..util import queue as sqla_queue from ..util import threading class QueuePoo...
0.778902
0.252689
import json import responses import re import os from rest_framework.test import APITestCase, APIClient from rest_framework.reverse import reverse from rest_framework import status from rest_framework.authtoken.models import Token from django.contrib.auth import get_user_model from django.utils import timezone from ...
api/answers/tests/test_voting_answers.py
import json import responses import re import os from rest_framework.test import APITestCase, APIClient from rest_framework.reverse import reverse from rest_framework import status from rest_framework.authtoken.models import Token from django.contrib.auth import get_user_model from django.utils import timezone from ...
0.467575
0.173603
from unittest.mock import Mock, patch from openpeerpower import setup from openpeerpower.components import frontend async def test_webcomponent_custom_path_not_found(opp): """Test if a web component is found in config panels dir.""" filename = "mock.file" config = { "panel_custom": { ...
tests/components/panel_custom/test_init.py
from unittest.mock import Mock, patch from openpeerpower import setup from openpeerpower.components import frontend async def test_webcomponent_custom_path_not_found(opp): """Test if a web component is found in config panels dir.""" filename = "mock.file" config = { "panel_custom": { ...
0.81772
0.468365
import logging import os from temboardagent.errors import UserError from temboardagent.command import exec_command from temboardagent.tools import validate_parameters from temboardagent.errors import HTTPError from temboardagent.toolkit.configuration import OptionSpec from temboardagent.toolkit import taskmanager from...
tests/temboard-agent-sample-plugins/temboard_agent_sample_plugins.py
import logging import os from temboardagent.errors import UserError from temboardagent.command import exec_command from temboardagent.tools import validate_parameters from temboardagent.errors import HTTPError from temboardagent.toolkit.configuration import OptionSpec from temboardagent.toolkit import taskmanager from...
0.450118
0.093595
import os import azurelinuxagent.common.conf as conf import azurelinuxagent.common.logger as logger from azurelinuxagent.common.event import add_event, WALAEventOperation from azurelinuxagent.common.utils.restutil import KNOWN_WIRESERVER_IP from azurelinuxagent.common.version import AGENT_NAME, CURRENT_VERSION # Na...
azurelinuxagent/common/protocol/metadata_server_migration_util.py
import os import azurelinuxagent.common.conf as conf import azurelinuxagent.common.logger as logger from azurelinuxagent.common.event import add_event, WALAEventOperation from azurelinuxagent.common.utils.restutil import KNOWN_WIRESERVER_IP from azurelinuxagent.common.version import AGENT_NAME, CURRENT_VERSION # Na...
0.345878
0.057812
import re # Properties that must be included by default for any ADObject MANDATORY_PROPS_DEFAULT = ('distinguishedName', 'objectClass', 'objectCategory', 'name', 'description', 'createTimeStamp', 'modifyTimeStamp') # Default properties for User objects MANDATORY_P...
ad_ldap/constants.py
import re # Properties that must be included by default for any ADObject MANDATORY_PROPS_DEFAULT = ('distinguishedName', 'objectClass', 'objectCategory', 'name', 'description', 'createTimeStamp', 'modifyTimeStamp') # Default properties for User objects MANDATORY_P...
0.304352
0.106924
import numpy as np from pandas._testing import assert_frame_equal import pandas as pd import unittest from vader_working_file import VaderReddit as vd df = pd.DataFrame({'Date': [11/30/2021], 'Tags': ['$AMC'], 'Comment': ['The one time I buy $AMC it just pissed my money away']}) class Test_vader_reddit_score(unittes...
tests/test_vaderreddit.py
import numpy as np from pandas._testing import assert_frame_equal import pandas as pd import unittest from vader_working_file import VaderReddit as vd df = pd.DataFrame({'Date': [11/30/2021], 'Tags': ['$AMC'], 'Comment': ['The one time I buy $AMC it just pissed my money away']}) class Test_vader_reddit_score(unittes...
0.595022
0.589007
import pandas as pd import numpy as np from sklearn.impute import SimpleImputer from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.compose import ColumnTransformer import tensorflow as tf from sklearn.decomposition import PCA train = pd.re...
Kaggle/Titanic/Prediction.py
import pandas as pd import numpy as np from sklearn.impute import SimpleImputer from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.compose import ColumnTransformer import tensorflow as tf from sklearn.decomposition import PCA train = pd.re...
0.723798
0.38856
from decimal import Decimal from uuid import UUID import pytest from indexpy.routing.tree import RadixTree @pytest.fixture def tree(): tree = RadixTree() tree.append("/hello/{time:int}", ...) tree.append("/hello", ...) tree.append("/hello/world", ...) tree.append("/sayhi/{name}", ...) tree....
tests/routing/test_tree.py
from decimal import Decimal from uuid import UUID import pytest from indexpy.routing.tree import RadixTree @pytest.fixture def tree(): tree = RadixTree() tree.append("/hello/{time:int}", ...) tree.append("/hello", ...) tree.append("/hello/world", ...) tree.append("/sayhi/{name}", ...) tree....
0.423339
0.251935
import os from math import floor, log import numpy as np import matplotlib as mpl try: if os.environ["PLT_USE_AGG"] == "1": mpl.use("Agg") except KeyError: pass import matplotlib.pyplot as plt from perform.visualization.visualization import Visualization class FieldPlot(Visualization): """Class...
perform/visualization/field_plot.py
import os from math import floor, log import numpy as np import matplotlib as mpl try: if os.environ["PLT_USE_AGG"] == "1": mpl.use("Agg") except KeyError: pass import matplotlib.pyplot as plt from perform.visualization.visualization import Visualization class FieldPlot(Visualization): """Class...
0.679817
0.54952
from __future__ import annotations import logging import typing from typing import Any, Dict, List import fileseq from silex_client.action.command_base import CommandBase from silex_client.utils.parameter_types import ListParameterMeta, PathParameterMeta if typing.TYPE_CHECKING: from silex_client.action.action_...
silex_client/commands/rename.py
from __future__ import annotations import logging import typing from typing import Any, Dict, List import fileseq from silex_client.action.command_base import CommandBase from silex_client.utils.parameter_types import ListParameterMeta, PathParameterMeta if typing.TYPE_CHECKING: from silex_client.action.action_...
0.799364
0.155719
from xscontainer import api_helper from xscontainer import util from xscontainer.util import log import constants import fcntl import errno import os import paramiko import paramiko.rsakey import select import socket import StringIO import sys DOCKER_SOCKET_PATH = '/var/run/docker.sock' SSH_PORT = 22 ERROR_CAUSE_NET...
src/xscontainer/remote_helper/ssh.py
from xscontainer import api_helper from xscontainer import util from xscontainer.util import log import constants import fcntl import errno import os import paramiko import paramiko.rsakey import select import socket import StringIO import sys DOCKER_SOCKET_PATH = '/var/run/docker.sock' SSH_PORT = 22 ERROR_CAUSE_NET...
0.244093
0.049222
from __future__ import unicode_literals from indico.core.db import db from indico.core.db.sqlalchemy.principals import clone_principals from indico.core.db.sqlalchemy.util.models import get_simple_column_attrs from indico.modules.events.cloning import EventCloner from indico.modules.events.models.events import EventT...
indico/modules/events/clone.py
from __future__ import unicode_literals from indico.core.db import db from indico.core.db.sqlalchemy.principals import clone_principals from indico.core.db.sqlalchemy.util.models import get_simple_column_attrs from indico.modules.events.cloning import EventCloner from indico.modules.events.models.events import EventT...
0.682468
0.115561
from typing import Optional, List, Tuple import math import numpy as np import mxnet as mx from mxnet import gluon from mxnet import init from mxnet.gluon import nn, rnn, HybridBlock from gluonts.core.component import validated from gluonts.model.common import Tensor from gluonts.mx.block.feature import FeatureEmbedd...
src/gluonts/model/tft/_layers.py
from typing import Optional, List, Tuple import math import numpy as np import mxnet as mx from mxnet import gluon from mxnet import init from mxnet.gluon import nn, rnn, HybridBlock from gluonts.core.component import validated from gluonts.model.common import Tensor from gluonts.mx.block.feature import FeatureEmbedd...
0.961631
0.362772
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from absl import flags from bandits.core.bayesian_nn import BayesianNN FLAGS = flags.FLAGS def log_gaussian(x, mu, sigma, reduce_sum=True): """Retu...
research/deep_contextual_bandits/bandits/algorithms/variational_neural_bandit_model.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from absl import flags from bandits.core.bayesian_nn import BayesianNN FLAGS = flags.FLAGS def log_gaussian(x, mu, sigma, reduce_sum=True): """Retu...
0.930233
0.345782
import pecan from pecan import rest from wsme import types as wtypes import wsmeext.pecan as wsme_pecan from solum.api.controllers.v1.datamodel import sensor from solum.api.handlers import sensor_handler from solum.common import exception from solum import objects class SensorController(rest.RestController): ""...
solum/api/controllers/v1/sensor.py
import pecan from pecan import rest from wsme import types as wtypes import wsmeext.pecan as wsme_pecan from solum.api.controllers.v1.datamodel import sensor from solum.api.handlers import sensor_handler from solum.common import exception from solum import objects class SensorController(rest.RestController): ""...
0.831622
0.157137
import ast import ujson from ast import literal_eval from datetime import datetime from .core.exceptions import * from distutils.util import strtobool from .core import Schema, DataObject from .utils.converter import datetimeToStr, singleQuoteToDoubleQuote class PainlessDB: """ Painless Database Main Class. ...
painlessdb/db.py
import ast import ujson from ast import literal_eval from datetime import datetime from .core.exceptions import * from distutils.util import strtobool from .core import Schema, DataObject from .utils.converter import datetimeToStr, singleQuoteToDoubleQuote class PainlessDB: """ Painless Database Main Class. ...
0.453262
0.198336
import numpy as np import tensorflow as tf from poem.core import data_utils class DataUtilsTest(tf.test.TestCase): def test_flatten_last_dims(self): # Shape = [2, 3, 4]. x = tf.constant([[[1, 2, 3, 4], [11, 12, 13, 14], [21, 22, 23, 24]], [[31, 32, 33, 34], [41, 42, 43, 44], [51, 52, ...
poem/core/data_utils_test.py
import numpy as np import tensorflow as tf from poem.core import data_utils class DataUtilsTest(tf.test.TestCase): def test_flatten_last_dims(self): # Shape = [2, 3, 4]. x = tf.constant([[[1, 2, 3, 4], [11, 12, 13, 14], [21, 22, 23, 24]], [[31, 32, 33, 34], [41, 42, 43, 44], [51, 52, ...
0.66061
0.830491
from datetime import timedelta import logging import requests from homeassistant.components.light import LightEntity from homeassistant.core import callback import homeassistant.util.dt as dt_util from . import DOMAIN from .entity import RingEntityMixin _LOGGER = logging.getLogger(__name__) # It takes a few secon...
homeassistant/components/ring/light.py
from datetime import timedelta import logging import requests from homeassistant.components.light import LightEntity from homeassistant.core import callback import homeassistant.util.dt as dt_util from . import DOMAIN from .entity import RingEntityMixin _LOGGER = logging.getLogger(__name__) # It takes a few secon...
0.815269
0.148571
from collections import OrderedDict from gluon import current, URL, DIV, IS_EMPTY_OR, IS_IN_SET, IS_NOT_EMPTY from core import FS, ICON, S3CRUD, S3Represent, \ get_filter_options, get_form_record_id, s3_fieldmethod from ..helpers import workflow_tag_represent SITE_WORKFLOW = ("MPAV", "HYGIENE", "LA...
modules/templates/RLPPTM/customise/org.py
from collections import OrderedDict from gluon import current, URL, DIV, IS_EMPTY_OR, IS_IN_SET, IS_NOT_EMPTY from core import FS, ICON, S3CRUD, S3Represent, \ get_filter_options, get_form_record_id, s3_fieldmethod from ..helpers import workflow_tag_represent SITE_WORKFLOW = ("MPAV", "HYGIENE", "LA...
0.700075
0.230779
__version__='3.3.0' __all__= ( 'BarcodeI2of5', 'BarcodeCode128', 'BarcodeStandard93', 'BarcodeExtended93', 'BarcodeStandard39', 'BarcodeExtended39', 'BarcodeMSI', 'BarcodeCodabar', 'BarcodeCode11', 'BarcodeFIM', 'BarcodePOSTNET', ...
env/lib/python3.10/site-packages/reportlab/graphics/barcode/widgets.py
__version__='3.3.0' __all__= ( 'BarcodeI2of5', 'BarcodeCode128', 'BarcodeStandard93', 'BarcodeExtended93', 'BarcodeStandard39', 'BarcodeExtended39', 'BarcodeMSI', 'BarcodeCodabar', 'BarcodeCode11', 'BarcodeFIM', 'BarcodePOSTNET', ...
0.689619
0.198821
from django.utils.http import urlencode from django.shortcuts import render_to_response from django.template import RequestContext from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from openid.consumer.discover import Discover...
allauth/socialaccount/providers/openid/views.py
from django.utils.http import urlencode from django.shortcuts import render_to_response from django.template import RequestContext from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from openid.consumer.discover import Discover...
0.215598
0.047184
class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ if num1 == "0" or num2 == "0": # 处理特殊情况 return "0" l1, l2 = len(num1), len(num2) if l1 < l2: num1, num2 = num2, num1 ...
tencent/array_and_str/multiply.py
class Solution(object): def multiply(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ if num1 == "0" or num2 == "0": # 处理特殊情况 return "0" l1, l2 = len(num1), len(num2) if l1 < l2: num1, num2 = num2, num1 ...
0.52683
0.557183
# UPDATE # @Time : 2020/12/29, 2021/1/4 # @Author : <NAME>, <NAME> # @email : <EMAIL>, <EMAIL> import os import torch from torch import nn from transformers import BertModel from crslab.config import MODEL_PATH from crslab.data import dataset_language_map from crslab.model.base_model import BaseModel from .resou...
crslab/model/policy/profile_bert/profile_bert.py
# UPDATE # @Time : 2020/12/29, 2021/1/4 # @Author : <NAME>, <NAME> # @email : <EMAIL>, <EMAIL> import os import torch from torch import nn from transformers import BertModel from crslab.config import MODEL_PATH from crslab.data import dataset_language_map from crslab.model.base_model import BaseModel from .resou...
0.813498
0.306864
import torch from sklearn.metrics import accuracy_score from torch.nn import Linear from torch.nn.functional import relu, dropout, log_softmax, nll_loss, leaky_relu from torch_geometric.nn import GCNConv from Result import Result class ModelGCNOld(torch.nn.Module): def __init__(self, num_layers, hidden_list, ac...
ModelGCNOld.py
import torch from sklearn.metrics import accuracy_score from torch.nn import Linear from torch.nn.functional import relu, dropout, log_softmax, nll_loss, leaky_relu from torch_geometric.nn import GCNConv from Result import Result class ModelGCNOld(torch.nn.Module): def __init__(self, num_layers, hidden_list, ac...
0.932315
0.539832
from __future__ import print_function, unicode_literals import codecs # Use the c version of ElementTree, which is faster, if possible: try: from xml.etree import cElementTree as ElementTree except ImportError: from xml.etree import ElementTree from six import string_types from nltk.data import SeekableUnic...
env/lib/python3.5/site-packages/nltk/corpus/reader/xmldocs.py
from __future__ import print_function, unicode_literals import codecs # Use the c version of ElementTree, which is faster, if possible: try: from xml.etree import cElementTree as ElementTree except ImportError: from xml.etree import ElementTree from six import string_types from nltk.data import SeekableUnic...
0.848471
0.18704
from unittest import TestCase from keras_bert import Tokenizer class TestTokenizer(TestCase): def test_uncased(self): tokens = [ '[PAD]', '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', '\u535A', '\u63A8', ] token_...
tests/test_tokenizer.py
from unittest import TestCase from keras_bert import Tokenizer class TestTokenizer(TestCase): def test_uncased(self): tokens = [ '[PAD]', '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', '\u535A', '\u63A8', ] token_...
0.731922
0.607925
from __future__ import print_function from bcc import BPF import argparse import ctypes as ct import time # arguments examples = """examples: ./stacksnoop ext4_sync_fs # print kernel stack traces for ext4_sync_fs ./stacksnoop -s ext4_sync_fs # ... also show symbol offsets ./stacksnoop -v ext4_sync_f...
examples/tracing/stacksnoop.py
from __future__ import print_function from bcc import BPF import argparse import ctypes as ct import time # arguments examples = """examples: ./stacksnoop ext4_sync_fs # print kernel stack traces for ext4_sync_fs ./stacksnoop -s ext4_sync_fs # ... also show symbol offsets ./stacksnoop -v ext4_sync_f...
0.263599
0.116613
import numpy as np import librosa import math import random from feature_extraction_scripts.errors import NoSpeechDetected def match_length(noise,sr,desired_length): noise2 = np.array([]) final_noiselength = sr*desired_length original_noiselength = len(noise) frac, int_len = math.modf(final_noise...
speech_commands/feature_extraction_scripts/prep_noise.py
import numpy as np import librosa import math import random from feature_extraction_scripts.errors import NoSpeechDetected def match_length(noise,sr,desired_length): noise2 = np.array([]) final_noiselength = sr*desired_length original_noiselength = len(noise) frac, int_len = math.modf(final_noise...
0.198375
0.456591
from __future__ import absolute_import, division, print_function __all__ = """ Builder """.split() from wwt_data_formats.enums import DataSetType, ProjectionType from wwt_data_formats.imageset import ImageSet from wwt_data_formats.layers import ImageSetLayer, LayerContainerReader from wwt_data_formats.place import Pl...
toasty/builder.py
from __future__ import absolute_import, division, print_function __all__ = """ Builder """.split() from wwt_data_formats.enums import DataSetType, ProjectionType from wwt_data_formats.imageset import ImageSet from wwt_data_formats.layers import ImageSetLayer, LayerContainerReader from wwt_data_formats.place import Pl...
0.873633
0.370852
import eventlet eventlet.monkey_patch() import argparse import boto import json import logging import os import socket import sys from eventlet.greenpool import GreenPool from eventlet import pools from datetime import datetime from dateutil import parser as dtparser now = None def days_ago(tstamp): global now ...
tablesnap/tablechop.py
import eventlet eventlet.monkey_patch() import argparse import boto import json import logging import os import socket import sys from eventlet.greenpool import GreenPool from eventlet import pools from datetime import datetime from dateutil import parser as dtparser now = None def days_ago(tstamp): global now ...
0.223208
0.153105
from pathlib import Path def batch(action, card_dir: Path, max_backup: int = 1): """Performs an `action` repeatedly across a given `region` and `card_slot`. Before using this function, ensure all parameters are valid. Args: action (function): the function to run in batch card_dir (Pa...
batch.py
from pathlib import Path def batch(action, card_dir: Path, max_backup: int = 1): """Performs an `action` repeatedly across a given `region` and `card_slot`. Before using this function, ensure all parameters are valid. Args: action (function): the function to run in batch card_dir (Pa...
0.959278
0.607954
from unittest.mock import patch, Mock from unittest import TestCase from pytest import mark from dateutil import tz from datetime import datetime, timedelta from praw.exceptions import RedditAPIException from requests.models import Response from praw.models import Comment, Submission from prawcore.exceptions import Se...
tests/test_core.py
from unittest.mock import patch, Mock from unittest import TestCase from pytest import mark from dateutil import tz from datetime import datetime, timedelta from praw.exceptions import RedditAPIException from requests.models import Response from praw.models import Comment, Submission from prawcore.exceptions import Se...
0.62395
0.297534
from pathlib import Path import click import tabulate from encapsia_cli import lib @click.group("users") def main(): """Manage users, including superuser and system users.""" @main.command() @click.argument("description") @click.argument("capabilities") @click.pass_obj def add_systemuser(obj, description, cap...
encapsia_cli/users.py
from pathlib import Path import click import tabulate from encapsia_cli import lib @click.group("users") def main(): """Manage users, including superuser and system users.""" @main.command() @click.argument("description") @click.argument("capabilities") @click.pass_obj def add_systemuser(obj, description, cap...
0.601242
0.098036
__author__ = '<NAME>' __version__ = '$Revision: 11839 $'.split()[1] __revision__ = __version__ __date__ = '$Date: 2009-05-05 17:34:17 -0400 (Tue, 05 May 2009) $'.split()[1] __copyright__ = '2007, 2008' __license__ = 'Apache 2.0' __doc__ = ''' Daemon tool to detach from the terminal @requires: U{epydoc<htt...
aisutils/daemon.py
__author__ = '<NAME>' __version__ = '$Revision: 11839 $'.split()[1] __revision__ = __version__ __date__ = '$Date: 2009-05-05 17:34:17 -0400 (Tue, 05 May 2009) $'.split()[1] __copyright__ = '2007, 2008' __license__ = 'Apache 2.0' __doc__ = ''' Daemon tool to detach from the terminal @requires: U{epydoc<htt...
0.269422
0.091058
import logging import netaddr from nuage_neutron.vsdclient.common import cms_id_helper from nuage_neutron.vsdclient.common import constants from nuage_neutron.vsdclient.common import helper from nuage_neutron.vsdclient.common import nuagelib from nuage_neutron.vsdclient import restproxy DHCP_OPTIONS = constants.DHC...
nuage_neutron/vsdclient/resources/dhcpoptions.py
import logging import netaddr from nuage_neutron.vsdclient.common import cms_id_helper from nuage_neutron.vsdclient.common import constants from nuage_neutron.vsdclient.common import helper from nuage_neutron.vsdclient.common import nuagelib from nuage_neutron.vsdclient import restproxy DHCP_OPTIONS = constants.DHC...
0.576423
0.10217
RASP = 0 #RASP = 20 #Local and Remote Neural Network Commands COMMAND = ['../yolo_tiny/darknet', 'detector', 'test', '../yolo_tiny/cfg/obj.data', '../yolo_tiny/cfg/tiny-yolo.cfg', '../yolo_tiny/backup/tiny-yolo_2000.weights'] #COMMAND = ['ssh', '<EMAIL>rew@10.42.0.1', 'cd', '/home/andrew/testing_tiny/darknet2/darknet'...
Game/constants.py
RASP = 0 #RASP = 20 #Local and Remote Neural Network Commands COMMAND = ['../yolo_tiny/darknet', 'detector', 'test', '../yolo_tiny/cfg/obj.data', '../yolo_tiny/cfg/tiny-yolo.cfg', '../yolo_tiny/backup/tiny-yolo_2000.weights'] #COMMAND = ['ssh', '<EMAIL>rew@10.42.0.1', 'cd', '/home/andrew/testing_tiny/darknet2/darknet'...
0.316686
0.285503
import math, pygame, time #Z(n+1) = Z(n) + C def createColorPallet(limit_num): #Creates a color pallet using color_list = [] for i in range(limit_num): color_list.append((0, ((255 * (i + 1))/limit_num), 0)) return color_list def squareImaginaryNum(real, imaginary): realpart = (real ** 2...
CS2/1500_mandelbrot_fractal/1200_mandelbrot_fractal/cal_boye_lynns_julia_set/juliasetsio04(201f).py
import math, pygame, time #Z(n+1) = Z(n) + C def createColorPallet(limit_num): #Creates a color pallet using color_list = [] for i in range(limit_num): color_list.append((0, ((255 * (i + 1))/limit_num), 0)) return color_list def squareImaginaryNum(real, imaginary): realpart = (real ** 2...
0.314998
0.300104
import pprint import sys from abc import ABC, abstractmethod from collections import defaultdict import click from .error import CwsCommandError from ..coworks import TechMicroService class CwsClientCommandOptions: def __init__(self, client_options, execution_context): self.client_options = client_opti...
coworks/cws/command.py
import pprint import sys from abc import ABC, abstractmethod from collections import defaultdict import click from .error import CwsCommandError from ..coworks import TechMicroService class CwsClientCommandOptions: def __init__(self, client_options, execution_context): self.client_options = client_opti...
0.507324
0.112405
import pygtk pygtk.require('2.0') import gtk import gobject from debugger import * from tab_interface import * ICON_COLUMN=0 ID_COLUMN=1 LOCATION_COLUMN=2 class BreakpointTab(gtk.VBox): def __init__(self,mc): TabInterface.validate_implementation(self) gtk.VBox.__init__(self) self._id = None self._m...
ui/breakpoint_tab.py
import pygtk pygtk.require('2.0') import gtk import gobject from debugger import * from tab_interface import * ICON_COLUMN=0 ID_COLUMN=1 LOCATION_COLUMN=2 class BreakpointTab(gtk.VBox): def __init__(self,mc): TabInterface.validate_implementation(self) gtk.VBox.__init__(self) self._id = None self._m...
0.168002
0.09343
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy of the # License at http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed # under the Licens...
floris/tools/floris_utilities.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy of the # License at http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software distributed # under the Licens...
0.940824
0.5816
"""Tests for tensorflow.ops.tf.gather.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tens...
tensorflow/python/kernel_tests/batch_gather_op_test.py
"""Tests for tensorflow.ops.tf.gather.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tens...
0.901904
0.633637
from __future__ import print_function from __future__ import division from __future__ import absolute_import from congress.datalog import factset from congress.tests import base class TestFactSet(base.TestCase): def setUp(self): super(TestFactSet, self).setUp() self.factset = factset.FactSet() ...
congress/tests/datalog/test_factset.py
from __future__ import print_function from __future__ import division from __future__ import absolute_import from congress.datalog import factset from congress.tests import base class TestFactSet(base.TestCase): def setUp(self): super(TestFactSet, self).setUp() self.factset = factset.FactSet() ...
0.633524
0.41561
import argparse import collections import glob import os import time import MxpiDataType_pb2 as MxpiDataType import numpy as np from StreamManagerApi import StreamManagerApi, MxDataInput, InProtobufVector, \ MxProtobufIn, StringVector from src.reader.squad_twomemory import DataProcessor as SquadDataProcessor from s...
research/nlp/ktnet/infer/sdk/main.py
import argparse import collections import glob import os import time import MxpiDataType_pb2 as MxpiDataType import numpy as np from StreamManagerApi import StreamManagerApi, MxDataInput, InProtobufVector, \ MxProtobufIn, StringVector from src.reader.squad_twomemory import DataProcessor as SquadDataProcessor from s...
0.55929
0.25787
"""SQLite parser plugin for Google Chrome history database files.""" from __future__ import unicode_literals from dfdatetime import posix_time as dfdatetime_posix_time from dfdatetime import webkit_time as dfdatetime_webkit_time from plaso.containers import events from plaso.containers import time_events from plaso....
plaso/parsers/sqlite_plugins/chrome_history.py
"""SQLite parser plugin for Google Chrome history database files.""" from __future__ import unicode_literals from dfdatetime import posix_time as dfdatetime_posix_time from dfdatetime import webkit_time as dfdatetime_webkit_time from plaso.containers import events from plaso.containers import time_events from plaso....
0.865878
0.207014
import socket import time import threading import hashlib import json from base64 import b64encode, b64decode from flask import Flask, jsonify, request from Crypto.Cipher import AES class Run: def __init__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.setsockopt(socket....
Lixur Protocol/client/run.py
import socket import time import threading import hashlib import json from base64 import b64encode, b64decode from flask import Flask, jsonify, request from Crypto.Cipher import AES class Run: def __init__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.setsockopt(socket....
0.327023
0.126111
from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: content_view version_added: 1.0.0 short_description: Manage Content Views description: - Create and manage content views author: "<NAME> (@ehelms)" options: name: description: - Name ...
venv/lib/python3.6/site-packages/ansible_collections/theforeman/foreman/plugins/modules/content_view.py
from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: content_view version_added: 1.0.0 short_description: Manage Content Views description: - Create and manage content views author: "<NAME> (@ehelms)" options: name: description: - Name ...
0.799129
0.244713
# Compatibility with Pyhton 2.7 from __future__ import absolute_import, division, print_function, unicode_literals from datetime import datetime class Unit: def __init__(self, symbol, name, factor_to_cmd): self._symbol = symbol self._name = name self._factor_to_cmd = factor_to_cmd ...
hdgfrom/flow.py
# Compatibility with Pyhton 2.7 from __future__ import absolute_import, division, print_function, unicode_literals from datetime import datetime class Unit: def __init__(self, symbol, name, factor_to_cmd): self._symbol = symbol self._name = name self._factor_to_cmd = factor_to_cmd ...
0.88
0.358493
from __future__ import absolute_import import socket import os from contextlib import closing import oneflow.core.control.ctrl_bootstrap_pb2 as ctrl_bootstrap_pb import oneflow.core.job.env_pb2 as env_pb import oneflow.python.framework.c_api_util as c_api_util import oneflow.python.framework.placement_context as plac...
oneflow/python/framework/env_util.py
from __future__ import absolute_import import socket import os from contextlib import closing import oneflow.core.control.ctrl_bootstrap_pb2 as ctrl_bootstrap_pb import oneflow.core.job.env_pb2 as env_pb import oneflow.python.framework.c_api_util as c_api_util import oneflow.python.framework.placement_context as plac...
0.661158
0.218086
import os import requests import json import shutil import hashlib from multiprocessing.pool import ThreadPool class Object: def __init__(self, path, url, kind, name=""): self.path = path self.url = url self.kind = kind self.name = name def mkd(path): if not os.path.isdir(pat...
Core/Launcher/Download.py
import os import requests import json import shutil import hashlib from multiprocessing.pool import ThreadPool class Object: def __init__(self, path, url, kind, name=""): self.path = path self.url = url self.kind = kind self.name = name def mkd(path): if not os.path.isdir(pat...
0.296858
0.085901
"""Test Federated EMNIST dataset utilities.""" import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff from gans.experiments.emnist import emnist_data_utils BATCH_SIZE = 7 def _summarize_model(model): model.summary() print('\n\n\n') def _get_example_client_dataset():...
gans/experiments/emnist/emnist_data_utils_test.py
"""Test Federated EMNIST dataset utilities.""" import collections import numpy as np import tensorflow as tf import tensorflow_federated as tff from gans.experiments.emnist import emnist_data_utils BATCH_SIZE = 7 def _summarize_model(model): model.summary() print('\n\n\n') def _get_example_client_dataset():...
0.796807
0.415017
class SpaceCards: def __init__(self, deck_size: int): self.deck_size = deck_size # "Just like any deck of space cards, there are 10007 cards in the deck numbered 0 through 10006. The deck must # be new - they're still in factory order, with 0 on the top, then 1, then 2, and so on, all t...
22-slam-shuffle/space_cards.py
class SpaceCards: def __init__(self, deck_size: int): self.deck_size = deck_size # "Just like any deck of space cards, there are 10007 cards in the deck numbered 0 through 10006. The deck must # be new - they're still in factory order, with 0 on the top, then 1, then 2, and so on, all t...
0.516839
0.447641
import wx import sys import os import math import uidef import uivar import uilang sys.path.append(os.path.abspath("..")) from win import bootDeviceWin_FlexspiNor from utils import sound class secBootUiCfgFlexspiNor(bootDeviceWin_FlexspiNor.bootDeviceWin_FlexspiNor): def __init__(self, parent): bootDevice...
src/ui/ui_cfg_flexspinor.py
import wx import sys import os import math import uidef import uivar import uilang sys.path.append(os.path.abspath("..")) from win import bootDeviceWin_FlexspiNor from utils import sound class secBootUiCfgFlexspiNor(bootDeviceWin_FlexspiNor.bootDeviceWin_FlexspiNor): def __init__(self, parent): bootDevice...
0.250821
0.059129
import typing from collections import Counter, OrderedDict from typing import Any, Callable, List, Optional from numpy import prod Handle = Callable[[List[Any], List[Any]], typing.Counter[str]] def generic_activation_jit( op_name: str, ) -> Callable[[List[Any], List[Any]], typing.Counter[str]]: """ Th...
fvcore/nn/jit_handles.py
import typing from collections import Counter, OrderedDict from typing import Any, Callable, List, Optional from numpy import prod Handle = Callable[[List[Any], List[Any]], typing.Counter[str]] def generic_activation_jit( op_name: str, ) -> Callable[[List[Any], List[Any]], typing.Counter[str]]: """ Th...
0.924522
0.675263
import getopt import json import os import subprocess import sys from shutil import copyfile from typing import Dict, Tuple def get_input(*argv) -> str: usage = "Usage:\nfinder.py -p <project_directory> -l <locale_directory>" project_directory = '' locale_directory = '' try: opts, args = get...
finder.py
import getopt import json import os import subprocess import sys from shutil import copyfile from typing import Dict, Tuple def get_input(*argv) -> str: usage = "Usage:\nfinder.py -p <project_directory> -l <locale_directory>" project_directory = '' locale_directory = '' try: opts, args = get...
0.150278
0.096877
from django.contrib import messages from django.shortcuts import render, redirect, get_object_or_404 from manager import models, tasks def types(request): return render(request, 'types/index.html', { "type": None, "types": models.DataType.objects.all() }) def types_add(request): obj = mo...
manager/views/types.py
from django.contrib import messages from django.shortcuts import render, redirect, get_object_or_404 from manager import models, tasks def types(request): return render(request, 'types/index.html', { "type": None, "types": models.DataType.objects.all() }) def types_add(request): obj = mo...
0.529507
0.095139
from __future__ import annotations from dataclasses import dataclass from typing import Callable from iotawattpy.sensor import Sensor from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription, ) from homeassistant.const ...
homeassistant/components/iotawatt/sensor.py
from __future__ import annotations from dataclasses import dataclass from typing import Callable from iotawattpy.sensor import Sensor from homeassistant.components.sensor import ( STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, SensorEntityDescription, ) from homeassistant.const ...
0.89684
0.139836
import threading import datetime import copy import collections import ftrack_api from openpype.lib import get_datetime_data from openpype.api import get_project_settings from openpype_modules.ftrack.lib import ServerAction class CreateDailyReviewSessionServerAction(ServerAction): """Create daily review session...
openpype/modules/ftrack/event_handlers_server/action_create_review_session.py
import threading import datetime import copy import collections import ftrack_api from openpype.lib import get_datetime_data from openpype.api import get_project_settings from openpype_modules.ftrack.lib import ServerAction class CreateDailyReviewSessionServerAction(ServerAction): """Create daily review session...
0.537284
0.134463
import argparse import json import re from collections import Counter, defaultdict from pathlib import Path from typing import Union import arabic_reshaper import demoji import matplotlib.pyplot as plt import numpy as np import seaborn as sns from bidi.algorithm import get_display from hazm import Normalizer, sent_tok...
src/stats.py
import argparse import json import re from collections import Counter, defaultdict from pathlib import Path from typing import Union import arabic_reshaper import demoji import matplotlib.pyplot as plt import numpy as np import seaborn as sns from bidi.algorithm import get_display from hazm import Normalizer, sent_tok...
0.725454
0.095814
from abc import ABCMeta, abstractmethod import numpy as np import xarray as xr KEY_LOSS = 'loss' KEY_IN = 'inputs' KEY_OUT = 'outputs' KEY_OUT_PRE = 'pre_activation' KEY_W = 'weights' KEY_B = 'biases' def sigmoid(np_array): return np.divide(1, np.add(1, np.exp(np.multiply(np_array, -1)))) def sigmoid_d(np_array)...
littlenet/layer.py
from abc import ABCMeta, abstractmethod import numpy as np import xarray as xr KEY_LOSS = 'loss' KEY_IN = 'inputs' KEY_OUT = 'outputs' KEY_OUT_PRE = 'pre_activation' KEY_W = 'weights' KEY_B = 'biases' def sigmoid(np_array): return np.divide(1, np.add(1, np.exp(np.multiply(np_array, -1)))) def sigmoid_d(np_array)...
0.587825
0.508788
import re # Metaparser from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Schema, Any, Optional # parser utils from genie.libs.parser.utils.common import Common # ======================================= # Schema for 'show access-lists afi-all' # ====================================...
src/genie/libs/parser/iosxr/show_acl.py
import re # Metaparser from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Schema, Any, Optional # parser utils from genie.libs.parser.utils.common import Common # ======================================= # Schema for 'show access-lists afi-all' # ====================================...
0.368292
0.073397
__all__ = [ "linear", "smooth", "rush_into", "rush_from", "slow_into", "double_smooth", "there_and_back", "there_and_back_with_pause", "running_start", "not_quite_there", "wiggle", "squish_rate_func", "lingering", "exponential_decay", ] import typing from math i...
manim/utils/rate_functions.py
__all__ = [ "linear", "smooth", "rush_into", "rush_from", "slow_into", "double_smooth", "there_and_back", "there_and_back_with_pause", "running_start", "not_quite_there", "wiggle", "squish_rate_func", "lingering", "exponential_decay", ] import typing from math i...
0.855761
0.600481
import requests import bs4 from six.moves import input import json from plugin import Plugin class Quote(Plugin): """ quote prints quote for the day for you or quotes based on a given keyword """ def require(self): yield ("network", True) def complete(self): pass def alias(s...
jarviscli/plugins/quote.py
import requests import bs4 from six.moves import input import json from plugin import Plugin class Quote(Plugin): """ quote prints quote for the day for you or quotes based on a given keyword """ def require(self): yield ("network", True) def complete(self): pass def alias(s...
0.315209
0.150809
import os import io from . import _common from ._common import as_file, files from .abc import ResourceReader from contextlib import suppress from importlib.abc import ResourceLoader from importlib.machinery import ModuleSpec from io import BytesIO, TextIOWrapper from pathlib import Path from types import ModuleType f...
Lib/importlib/resources.py
import os import io from . import _common from ._common import as_file, files from .abc import ResourceReader from contextlib import suppress from importlib.abc import ResourceLoader from importlib.machinery import ModuleSpec from io import BytesIO, TextIOWrapper from pathlib import Path from types import ModuleType f...
0.827584
0.150247