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 math
import logging
import warnings
import scipy.constants
import scipy.interpolate
from tkp.telescope.lofar import antennaarrays
logger = logging.getLogger(__name__)
ANTENNAE_PER_TILE = 16
TILES_PER_CORE_STATION = 24
TILES_PER_REMOTE_STATION = 48
TILES_PER_INTL_STATION = 96
def noise_level(freq_eff, bandw... | tkp/telescope/lofar/noise.py | import math
import logging
import warnings
import scipy.constants
import scipy.interpolate
from tkp.telescope.lofar import antennaarrays
logger = logging.getLogger(__name__)
ANTENNAE_PER_TILE = 16
TILES_PER_CORE_STATION = 24
TILES_PER_REMOTE_STATION = 48
TILES_PER_INTL_STATION = 96
def noise_level(freq_eff, bandw... | 0.635788 | 0.428293 |
from Pipeline.main.PositionSize.Position import Position
from Pipeline.main.Utils.ExchangeUtil import ExchangeUtil
from Pipeline.main.Utils.AccountUtil import AccountUtil
from Pipeline.main.Utils.EmailUtil import EmailUtil
from Pipeline.main.PullData.Price.Pull import Pull
from pymongo import MongoClient
import numpy a... | Pipeline/main/Strategy/Open/OpenTrade.py | from Pipeline.main.PositionSize.Position import Position
from Pipeline.main.Utils.ExchangeUtil import ExchangeUtil
from Pipeline.main.Utils.AccountUtil import AccountUtil
from Pipeline.main.Utils.EmailUtil import EmailUtil
from Pipeline.main.PullData.Price.Pull import Pull
from pymongo import MongoClient
import numpy a... | 0.361954 | 0.161287 |
from contextlib import contextmanager
from unittest.mock import AsyncMock, MagicMock, patch
from aiosenseme import SensemeDevice, SensemeDiscovery
from homeassistant.components.senseme import config_flow
MOCK_NAME = "<NAME>"
MOCK_UUID = "77a6b7b3-925d-4695-a415-76d76dca4444"
MOCK_ADDRESS = "127.0.0.1"
device = Mag... | tests/components/senseme/__init__.py |
from contextlib import contextmanager
from unittest.mock import AsyncMock, MagicMock, patch
from aiosenseme import SensemeDevice, SensemeDiscovery
from homeassistant.components.senseme import config_flow
MOCK_NAME = "<NAME>"
MOCK_UUID = "77a6b7b3-925d-4695-a415-76d76dca4444"
MOCK_ADDRESS = "127.0.0.1"
device = Mag... | 0.73782 | 0.154663 |
import matplotlib.pyplot as plt
from numpy import gradient, inf, linspace, pi, power, sqrt, std
from pandas import read_csv
from scipy.integrate import romb, simps
from scipy.optimize import least_squares as ls
from scipy.stats import gaussian_kde as kde
from fast_deriv import FastUnivariateDensityDerivative as FUDD
... | kernel_functions.py | import matplotlib.pyplot as plt
from numpy import gradient, inf, linspace, pi, power, sqrt, std
from pandas import read_csv
from scipy.integrate import romb, simps
from scipy.optimize import least_squares as ls
from scipy.stats import gaussian_kde as kde
from fast_deriv import FastUnivariateDensityDerivative as FUDD
... | 0.681939 | 0.564459 |
from abc import ABC
from abc import abstractmethod
class Strategy(ABC):
'''Abstract strategy class (used as an implementation base).'''
def __init__(self, network):
'''Create a strategy.
*** This method could be updated, but not mandatory. ***
Initialize the strategy by collecting all neurons in the ... | CV_adv/DNNtest/strategy/strategy.py | from abc import ABC
from abc import abstractmethod
class Strategy(ABC):
'''Abstract strategy class (used as an implementation base).'''
def __init__(self, network):
'''Create a strategy.
*** This method could be updated, but not mandatory. ***
Initialize the strategy by collecting all neurons in the ... | 0.888166 | 0.345933 |
import argparse
import logging
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import os
from datetime import datetime, timedelta
import matplotlib
import numpy as np
import torch
import torch.optim as optim
import wandb
from torch.opt... | train.py | import argparse
import logging
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import os
from datetime import datetime, timedelta
import matplotlib
import numpy as np
import torch
import torch.optim as optim
import wandb
from torch.opt... | 0.440951 | 0.088269 |
import utils
import logging
import os
import csv
from abc import ABCMeta
from dataservice import AbstractDataService
class AbstractPersistenceService(metaclass=ABCMeta):
"""
Persistence service pulls data from data service, processes it, and then stores it.
"""
def __init__(self, data_service: Ab... | persistenceservice.py | import utils
import logging
import os
import csv
from abc import ABCMeta
from dataservice import AbstractDataService
class AbstractPersistenceService(metaclass=ABCMeta):
"""
Persistence service pulls data from data service, processes it, and then stores it.
"""
def __init__(self, data_service: Ab... | 0.391406 | 0.10961 |
from py_build.build import BuildCompleteState, BuildConfigureState, BuildError, BuildErrorState, BuildRunningState, Builder, BuilderError
import pytest
@pytest.fixture
def builder_configure():
return Builder(BuildConfigureState)
@pytest.fixture
def builder_complete():
return Builder(BuildCompleteState)
@pyte... | tests/test_builder_states.py | from py_build.build import BuildCompleteState, BuildConfigureState, BuildError, BuildErrorState, BuildRunningState, Builder, BuilderError
import pytest
@pytest.fixture
def builder_configure():
return Builder(BuildConfigureState)
@pytest.fixture
def builder_complete():
return Builder(BuildCompleteState)
@pyte... | 0.520984 | 0.376279 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import os
import urllib
import numpy as np
import tensorflow as tf
def main():
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_without_header(
filename="data/train... | learn.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import os
import urllib
import numpy as np
import tensorflow as tf
def main():
# Load datasets.
training_set = tf.contrib.learn.datasets.base.load_csv_without_header(
filename="data/train... | 0.826046 | 0.232005 |
from .._compat import basestring
from ..adapters.ingres import Ingres, IngresUnicode
from .base import SQLDialect
from . import dialects, sqltype_for
@dialects.register_for(Ingres)
class IngresDialect(SQLDialect):
SEQNAME = 'ii***lineitemsequence'
@sqltype_for('text')
def type_text(self):
return ... | gluon/packages/dal/pydal/dialects/ingres.py | from .._compat import basestring
from ..adapters.ingres import Ingres, IngresUnicode
from .base import SQLDialect
from . import dialects, sqltype_for
@dialects.register_for(Ingres)
class IngresDialect(SQLDialect):
SEQNAME = 'ii***lineitemsequence'
@sqltype_for('text')
def type_text(self):
return ... | 0.458106 | 0.087876 |
from logging import getLogger
from sys import platform as _platform
from subprocess import Popen, PIPE,DEVNULL, STDOUT
from pathlib import Path
import requests
from kivymd.uix.list import OneLineListItem
from kivymd.uix.dialog import MDDialog
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.textfield impor... | tesseractXplore/tesseract.py | from logging import getLogger
from sys import platform as _platform
from subprocess import Popen, PIPE,DEVNULL, STDOUT
from pathlib import Path
import requests
from kivymd.uix.list import OneLineListItem
from kivymd.uix.dialog import MDDialog
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.textfield impor... | 0.189521 | 0.07373 |
""" Test queries with ModelSEEDDatabase compounds/reactions data """
import unittest
from nosqlbiosets.dbutils import DBconnection
from nosqlbiosets.graphutils import neighbors_graph, shortest_paths,\
set_degree_as_weight
from nosqlbiosets.modelseed.query import QueryModelSEED
qry = QueryModelSEED(db="MongoDB", i... | tests/test_modelseeddb_queries.py | """ Test queries with ModelSEEDDatabase compounds/reactions data """
import unittest
from nosqlbiosets.dbutils import DBconnection
from nosqlbiosets.graphutils import neighbors_graph, shortest_paths,\
set_degree_as_weight
from nosqlbiosets.modelseed.query import QueryModelSEED
qry = QueryModelSEED(db="MongoDB", i... | 0.571408 | 0.610453 |
import pprint
import re # noqa: F401
import six
class Constants(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the valu... | midgard_client/midgard_client/models/constants.py | import pprint
import re # noqa: F401
import six
class Constants(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the valu... | 0.622918 | 0.446917 |
import argparse
import sys
from collections import defaultdict
# Check correct usage
parser = argparse.ArgumentParser(description="Parse some data.")
parser.add_argument('input', metavar='input', type=str,
help='Input data file.')
args = parser.parse_args()
data = []
grid = defaultdict(int)
# P... | 2021/src/day-05.py |
import argparse
import sys
from collections import defaultdict
# Check correct usage
parser = argparse.ArgumentParser(description="Parse some data.")
parser.add_argument('input', metavar='input', type=str,
help='Input data file.')
args = parser.parse_args()
data = []
grid = defaultdict(int)
# P... | 0.279828 | 0.230389 |
class Color:
""" Color formats."""
alpha_num = "100"
def __init__(self, hex_code):
if not self.is_valid_hex_code(hex_code):
raise ValueError("{} is not a valid hex code".format(hex_code))
self._hex = hex_code
@staticmethod
def is_valid_hex_code(value):
if value.... | src/xthematic/colors.py | class Color:
""" Color formats."""
alpha_num = "100"
def __init__(self, hex_code):
if not self.is_valid_hex_code(hex_code):
raise ValueError("{} is not a valid hex code".format(hex_code))
self._hex = hex_code
@staticmethod
def is_valid_hex_code(value):
if value.... | 0.902796 | 0.24068 |
from enum import Enum, auto
class Direction(Enum):
EAST = auto()
NORTH = auto()
WEST = auto()
SOUTH = auto()
def translate(pos, direction, distance):
if direction == "N":
pos = (pos[0]+distance, pos[1])
elif direction == "S":
pos = (pos[0]-distance, pos[1])
elif direction... | adventofcode/day12.py | from enum import Enum, auto
class Direction(Enum):
EAST = auto()
NORTH = auto()
WEST = auto()
SOUTH = auto()
def translate(pos, direction, distance):
if direction == "N":
pos = (pos[0]+distance, pos[1])
elif direction == "S":
pos = (pos[0]-distance, pos[1])
elif direction... | 0.698741 | 0.658541 |
import typing
from cloudevents.sdk import exceptions
from cloudevents.sdk.converters import base
from cloudevents.sdk.converters import binary
from cloudevents.sdk.converters import structured
from cloudevents.sdk.event import base as event_base
class HTTPMarshaller(object):
"""
HTTP Marshaller class.
... | cloudevents/sdk/marshaller.py |
import typing
from cloudevents.sdk import exceptions
from cloudevents.sdk.converters import base
from cloudevents.sdk.converters import binary
from cloudevents.sdk.converters import structured
from cloudevents.sdk.event import base as event_base
class HTTPMarshaller(object):
"""
HTTP Marshaller class.
... | 0.828349 | 0.166337 |
import arcpy
import math
## Variables
# 3D Lateral Line feature class
laterals = r"N:\foo\bar.gdb\laterals_fc"
perf_fc = r"N:\foo\bar.gdb\perf_point_fc"
# Unique ID for lateral
unique_well_id_name = "BHLID"
unique_well_id = 433
# Measured distance in feet
perf = 12090
# Create empty lists for stor... | create_perfs.py | import arcpy
import math
## Variables
# 3D Lateral Line feature class
laterals = r"N:\foo\bar.gdb\laterals_fc"
perf_fc = r"N:\foo\bar.gdb\perf_point_fc"
# Unique ID for lateral
unique_well_id_name = "BHLID"
unique_well_id = 433
# Measured distance in feet
perf = 12090
# Create empty lists for stor... | 0.202996 | 0.296591 |
from __future__ import annotations
import logging
from typing import IO
import boto3
import click
import click_log
import colorlog
import json
from access_undenied_aws import analysis
from access_undenied_aws import common
from access_undenied_aws import logger
from access_undenied_aws import organizations
def _in... | access_undenied_aws/cli.py | from __future__ import annotations
import logging
from typing import IO
import boto3
import click
import click_log
import colorlog
import json
from access_undenied_aws import analysis
from access_undenied_aws import common
from access_undenied_aws import logger
from access_undenied_aws import organizations
def _in... | 0.602412 | 0.074534 |
import argparse
import ray
from ray import tune
from ray.rllib.models import ModelCatalog
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.utils import try_import_tf
from ray.rllib.utils.annotations ... | rllib/examples/batch_norm_model.py |
import argparse
import ray
from ray import tune
from ray.rllib.models import ModelCatalog
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.misc import normc_initializer
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.utils import try_import_tf
from ray.rllib.utils.annotations ... | 0.90942 | 0.356167 |
import os
import sys
from fastapi_websocket_rpc import logger
from fastapi_websocket_rpc.rpc_channel import RpcChannel
# Add parent path to use local src as package for tests
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import asyncio
from multiprocessing import Process
i... | tests/server_with_remote_id_test.py | import os
import sys
from fastapi_websocket_rpc import logger
from fastapi_websocket_rpc.rpc_channel import RpcChannel
# Add parent path to use local src as package for tests
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import asyncio
from multiprocessing import Process
i... | 0.353428 | 0.094929 |
import colors
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from ssh_transport import SSHTransportConnection
from utils import parse_byte, generate_byte, \
parse_uint32, generate_uint32, \
parse_string, generate_string, \
... | ssh_connection.py | import colors
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from ssh_transport import SSHTransportConnection
from utils import parse_byte, generate_byte, \
parse_uint32, generate_uint32, \
parse_string, generate_string, \
... | 0.526586 | 0.164081 |
try:
import Tkinter as tk
import ttk
except ImportError:
import tkinter as tk
import tkinter.ttk as ttk
class Base_Form(object):
"""Base class of all forms"""
def __init__(self, widget_class, master, action, hidden_input, kw):
self.action = action
if hidden_input is None:
... | recipes/Python/580714_Form_actilike_html_forms/recipe-580714.py |
try:
import Tkinter as tk
import ttk
except ImportError:
import tkinter as tk
import tkinter.ttk as ttk
class Base_Form(object):
"""Base class of all forms"""
def __init__(self, widget_class, master, action, hidden_input, kw):
self.action = action
if hidden_input is None:
... | 0.430746 | 0.115511 |
import asyncio
import os
import pytest
from async_negotiate_sspi import NegotiateAuth, NegotiateAuthWS
from dotenv import load_dotenv
from piwebasync import Controller, HTTPClient, WebsocketClient, WebsocketMessage
from piwebasync.exceptions import ChannelClosedError, ChannelClosedOK, ChannelUpdateError, ChannelRollb... | tests/websockets/test_client.py | import asyncio
import os
import pytest
from async_negotiate_sspi import NegotiateAuth, NegotiateAuthWS
from dotenv import load_dotenv
from piwebasync import Controller, HTTPClient, WebsocketClient, WebsocketMessage
from piwebasync.exceptions import ChannelClosedError, ChannelClosedOK, ChannelUpdateError, ChannelRollb... | 0.55254 | 0.225672 |
from __future__ import print_function, division
import onnx
import numpy as np
import pytest
from onnx.helper import make_tensor_value_info, make_graph, make_model
from tests.utils import run_model
def import_and_compute(op_type, input_data_left, input_data_right, opset=7, **node_attributes):
inputs = [np.arr... | tests/test_ops_binary.py |
from __future__ import print_function, division
import onnx
import numpy as np
import pytest
from onnx.helper import make_tensor_value_info, make_graph, make_model
from tests.utils import run_model
def import_and_compute(op_type, input_data_left, input_data_right, opset=7, **node_attributes):
inputs = [np.arr... | 0.835852 | 0.607343 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DataElement',
fields=[
('id', models.CharField(max_length=... | app/core/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DataElement',
fields=[
('id', models.CharField(max_length=... | 0.567577 | 0.193452 |
import os
from absl import logging
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import strategy_combinations
# pylint: enable=g-direct-ten... | official/nlp/nhnet/models_test.py | import os
from absl import logging
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import strategy_combinations
# pylint: enable=g-direct-ten... | 0.700485 | 0.231397 |
import pytest
from datadog_checks.nginx import Nginx
from . import common
@pytest.mark.e2e
@pytest.mark.skipif(common.USING_VTS, reason="Non-VTS test")
def test_e2e(dd_agent_check, instance):
aggregator = dd_agent_check(instance, rate=True)
aggregator.assert_metric('nginx.net.writing', count=2, tags=common... | nginx/tests/test_e2e.py | import pytest
from datadog_checks.nginx import Nginx
from . import common
@pytest.mark.e2e
@pytest.mark.skipif(common.USING_VTS, reason="Non-VTS test")
def test_e2e(dd_agent_check, instance):
aggregator = dd_agent_check(instance, rate=True)
aggregator.assert_metric('nginx.net.writing', count=2, tags=common... | 0.583203 | 0.451689 |
import copy
import torch.nn as nn
from torch.nn import Module as Module
from bert_modules.utils import BertLayerNorm, BertSelfAttention, gelu
class BertSelfOutput(Module):
def __init__(self, config):
super(BertSelfOutput, self).__init__()
self.dense = nn.Linear(config['hidden_dim'], config['hidde... | bert_modules/bert_modules.py | import copy
import torch.nn as nn
from torch.nn import Module as Module
from bert_modules.utils import BertLayerNorm, BertSelfAttention, gelu
class BertSelfOutput(Module):
def __init__(self, config):
super(BertSelfOutput, self).__init__()
self.dense = nn.Linear(config['hidden_dim'], config['hidde... | 0.89546 | 0.336304 |
from __future__ import absolute_import
from .printmsg import PrintMsg
from .lamb import Lambda
from .config import Config
from os.path import basename
import os
import json
import yaml
"""
Default config yaml
"""
DEFAULT_CONFIG = {
"Description": None,
"FunctionName": None,
"Handler": "lambda_handler",
... | albt/project.py | from __future__ import absolute_import
from .printmsg import PrintMsg
from .lamb import Lambda
from .config import Config
from os.path import basename
import os
import json
import yaml
"""
Default config yaml
"""
DEFAULT_CONFIG = {
"Description": None,
"FunctionName": None,
"Handler": "lambda_handler",
... | 0.409103 | 0.069132 |
from django.db import models
from django.db.models.fields import BooleanField
from accounts.models import Account
from store.models import Product, Variation
from righteous.db.models import OrderStatusChoices
# Create your models here.\
class Payment(models.Model):
user = models.ForeignKey(Account, on_delete=mod... | Django/e-commerce-website/orders/models.py | from django.db import models
from django.db.models.fields import BooleanField
from accounts.models import Account
from store.models import Product, Variation
from righteous.db.models import OrderStatusChoices
# Create your models here.\
class Payment(models.Model):
user = models.ForeignKey(Account, on_delete=mod... | 0.643105 | 0.128034 |
import unittest
from lighty.templates import Template
class VariableFieldTestCase(unittest.TestCase):
"""Test case for block template tag
"""
def setUp(self):
self.value = 'value'
self.variable_template = Template(name='base.html')
self.variable_template.parse("{{ simple_var }}")... | tests/variable_fields.py | import unittest
from lighty.templates import Template
class VariableFieldTestCase(unittest.TestCase):
"""Test case for block template tag
"""
def setUp(self):
self.value = 'value'
self.variable_template = Template(name='base.html')
self.variable_template.parse("{{ simple_var }}")... | 0.568895 | 0.386792 |
## Copyright 2009-2021 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
import sys
import shutil
from glob import glob
from shutil import which
import argparse
from common import *
MODEL_VERSION='v1.4.0'
# Parse the command-line arguments
parser = argparse.ArgumentParser(description='Runs all tests, includ... | scripts/test.py |
## Copyright 2009-2021 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
import sys
import shutil
from glob import glob
from shutil import which
import argparse
from common import *
MODEL_VERSION='v1.4.0'
# Parse the command-line arguments
parser = argparse.ArgumentParser(description='Runs all tests, includ... | 0.430028 | 0.110856 |
import base64
import datetime
import hmac
import logging
import random
import sys
import time
from hashlib import sha1
import requests
from six.moves import urllib
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAME... | lexicon/providers/aliyun.py | import base64
import datetime
import hmac
import logging
import random
import sys
import time
from hashlib import sha1
import requests
from six.moves import urllib
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAME... | 0.446495 | 0.100746 |
import pymysql
import sqlite3
import os, sys
from pymilvusdm.setting import MILVUS_TB, MILVUS_TBF, METRIC_DIC
class ReadMilvusMeta():
def __init__(self, logger, milvus_dir, mysql_p=None):
self.logger = logger
self.conn = None
self.cursor = None
if mysql_p:
self.connect_m... | pymilvusdm/core/read_milvus_meta.py | import pymysql
import sqlite3
import os, sys
from pymilvusdm.setting import MILVUS_TB, MILVUS_TBF, METRIC_DIC
class ReadMilvusMeta():
def __init__(self, logger, milvus_dir, mysql_p=None):
self.logger = logger
self.conn = None
self.cursor = None
if mysql_p:
self.connect_m... | 0.181553 | 0.127245 |
""" Character Error Ratio (CER) metric. """
from typing import List
import jiwer
import jiwer.transforms as tr
import datasets
class SentencesToListOfCharacters(tr.AbstractTransform):
def process_string(self, s: str):
return list(s)
def process_list(self, inp: List[str]):
chars = []
... | metrics/cer/cer.py | """ Character Error Ratio (CER) metric. """
from typing import List
import jiwer
import jiwer.transforms as tr
import datasets
class SentencesToListOfCharacters(tr.AbstractTransform):
def process_string(self, s: str):
return list(s)
def process_list(self, inp: List[str]):
chars = []
... | 0.949763 | 0.693648 |
import asyncio
from haphilipsjs.typing import SystemType
from openpeerpower.components.remote import (
ATTR_DELAY_SECS,
ATTR_NUM_REPEATS,
DEFAULT_DELAY_SECS,
RemoteEntity,
)
from . import LOGGER, PhilipsTVDataUpdateCoordinator
from .const import CONF_SYSTEM, DOMAIN
async def async_setup_entry(opp,... | openpeerpower/components/philips_js/remote.py |
import asyncio
from haphilipsjs.typing import SystemType
from openpeerpower.components.remote import (
ATTR_DELAY_SECS,
ATTR_NUM_REPEATS,
DEFAULT_DELAY_SECS,
RemoteEntity,
)
from . import LOGGER, PhilipsTVDataUpdateCoordinator
from .const import CONF_SYSTEM, DOMAIN
async def async_setup_entry(opp,... | 0.784814 | 0.116714 |
from collections import OrderedDict
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from aw_nas import utils, assert_rollout_type
from aw_nas.common import DifferentiableRollout as DiffRollout
from aw_nas.controller.base import BaseController
class DiffController(BaseController, ... | aw_nas/controller/differentiable.py | from collections import OrderedDict
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from aw_nas import utils, assert_rollout_type
from aw_nas.common import DifferentiableRollout as DiffRollout
from aw_nas.controller.base import BaseController
class DiffController(BaseController, ... | 0.95637 | 0.302109 |
import random
from typing import Optional
import othello
from log_referee import LogReferee
import evaluation
class MinimaxAgent(othello.Agent):
def __init__(self, play_as: othello.Player, search_depth: int =2, eval_func=evaluation.heuristic_eval_comprehensive) -> None:
super().__init__()
self.pl... | minimax_agent.py | import random
from typing import Optional
import othello
from log_referee import LogReferee
import evaluation
class MinimaxAgent(othello.Agent):
def __init__(self, play_as: othello.Player, search_depth: int =2, eval_func=evaluation.heuristic_eval_comprehensive) -> None:
super().__init__()
self.pl... | 0.724968 | 0.229158 |
import random
from datetime import datetime
from stdnum import verhoeff
from rapidpro_webhooks.apps.core.db import db
from rapidpro_webhooks.apps.core.exceptions import VoucherException
class Voucher(db.Model):
__tablename__ = 'voucher_vouchers'
id = db.Column(db.Integer, primary_key=True)
flow_id = db... | rapidpro_webhooks/apps/vouchers/models.py | import random
from datetime import datetime
from stdnum import verhoeff
from rapidpro_webhooks.apps.core.db import db
from rapidpro_webhooks.apps.core.exceptions import VoucherException
class Voucher(db.Model):
__tablename__ = 'voucher_vouchers'
id = db.Column(db.Integer, primary_key=True)
flow_id = db... | 0.52756 | 0.055643 |
from __future__ import unicode_literals, division, absolute_import
import logging
import urllib
import feedparser
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.search import torrent_availability, normalize_unicode
log = logging.getLogger('kat')
class ... | flexget/plugins/search_kat.py | from __future__ import unicode_literals, division, absolute_import
import logging
import urllib
import feedparser
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.search import torrent_availability, normalize_unicode
log = logging.getLogger('kat')
class ... | 0.465387 | 0.071461 |
import os
import math
import sys
import time
from os.path import abspath, basename, join
from seisflows.tools import msg
from seisflows.tools import unix
from seisflows.tools.tools import call, findpath, saveobj
from seisflows.config import ParameterError, custom_import
PAR = sys.modules['seisflows_parameters']
PATH ... | seisflows/system/pbs_sm.py | import os
import math
import sys
import time
from os.path import abspath, basename, join
from seisflows.tools import msg
from seisflows.tools import unix
from seisflows.tools.tools import call, findpath, saveobj
from seisflows.config import ParameterError, custom_import
PAR = sys.modules['seisflows_parameters']
PATH ... | 0.29931 | 0.106784 |
import unittest
import sys
import os
sys.path.append(os.path.abspath(os.path.join(__file__, "../../python")))
from petitBloc import block
from petitBloc import box
from petitBloc import port
from petitBloc import chain
from petitBloc import workerManager
from petitBloc import const
import time
class MakeNumbers(block... | test/logging_test.py | import unittest
import sys
import os
sys.path.append(os.path.abspath(os.path.join(__file__, "../../python")))
from petitBloc import block
from petitBloc import box
from petitBloc import port
from petitBloc import chain
from petitBloc import workerManager
from petitBloc import const
import time
class MakeNumbers(block... | 0.339061 | 0.36523 |
import collections
import glob
import os
import pickle
import re
import numpy as np
import scipy.stats as stats
from nasbench_analysis.eval_darts_one_shot_model_in_nasbench import natural_keys
def parse_log(path):
f = open(os.path.join(path, 'log.txt'), 'r')
# Read in the relevant information
train_accu... | experiments/analysis/utils.py | import collections
import glob
import os
import pickle
import re
import numpy as np
import scipy.stats as stats
from nasbench_analysis.eval_darts_one_shot_model_in_nasbench import natural_keys
def parse_log(path):
f = open(os.path.join(path, 'log.txt'), 'r')
# Read in the relevant information
train_accu... | 0.533154 | 0.33444 |
# STDLIB
import io
import re
from textwrap import dedent
from warnings import warn
from astropy import config as _config
from astropy.utils.exceptions import AstropyWarning
__all__ = [
'Conf', 'conf', 'warn_or_raise', 'vo_raise', 'vo_reraise', 'vo_warn',
'warn_unknown_attrs', 'parse_vowarning', 'VOWarning',
... | astropy/io/votable/exceptions.py | # STDLIB
import io
import re
from textwrap import dedent
from warnings import warn
from astropy import config as _config
from astropy.utils.exceptions import AstropyWarning
__all__ = [
'Conf', 'conf', 'warn_or_raise', 'vo_raise', 'vo_reraise', 'vo_warn',
'warn_unknown_attrs', 'parse_vowarning', 'VOWarning',
... | 0.541409 | 0.160102 |
import cv2
import numpy as np
class Button_finder:
"""
This node is responsible for the button detection
using template matching in multiple scales
"""
def __init__(self, img_rgb, acc_certainty):
self.img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
self.w = -1
self.h =... | src/elevator/scripts/button_finder.py | import cv2
import numpy as np
class Button_finder:
"""
This node is responsible for the button detection
using template matching in multiple scales
"""
def __init__(self, img_rgb, acc_certainty):
self.img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
self.w = -1
self.h =... | 0.670069 | 0.350199 |
from django.contrib import admin
from django.utils import timezone
from django.utils.functional import curry
from django.utils.translation import ugettext_lazy as _
from pinax.images.admin import ImageInline
from pinax.images.models import ImageSet
from .conf import settings
from .forms import AdminPostForm
from .mod... | pinax/blog/admin.py | from django.contrib import admin
from django.utils import timezone
from django.utils.functional import curry
from django.utils.translation import ugettext_lazy as _
from pinax.images.admin import ImageInline
from pinax.images.models import ImageSet
from .conf import settings
from .forms import AdminPostForm
from .mod... | 0.432063 | 0.154249 |
import json
import unittest
from messagebird import Client, ErrorException
from messagebird.base import Base
from messagebird.client import VOICE_TYPE
try:
from unittest.mock import Mock
except ImportError:
# mock was added to unittest in Python 3.3, but was an external library
# before.
from mock impo... | tests/test_call.py | import json
import unittest
from messagebird import Client, ErrorException
from messagebird.base import Base
from messagebird.client import VOICE_TYPE
try:
from unittest.mock import Mock
except ImportError:
# mock was added to unittest in Python 3.3, but was an external library
# before.
from mock impo... | 0.529507 | 0.285129 |
import cv2.cv as cv
color_tracker_window = "Color Tracker"
class ColorTracker:
def __init__(self):
cv.NamedWindow( color_tracker_window, 1 )
self.capture = cv.CaptureFromCAM(2)
def run(self):
while True:
img = cv.QueryFrame( self.capture )
... | showers/pi/cameraovtest2.py |
import cv2.cv as cv
color_tracker_window = "Color Tracker"
class ColorTracker:
def __init__(self):
cv.NamedWindow( color_tracker_window, 1 )
self.capture = cv.CaptureFromCAM(2)
def run(self):
while True:
img = cv.QueryFrame( self.capture )
... | 0.322206 | 0.355355 |
import os
import os.path
import re
from .Triangle import Triangle
from .Solid import Solid
from .Point import Point
class File(object):
""" File-object
Example for a file definition
>>> file1 = File(1, "foo.txt")
"""
def __init__(self,ID=None, Filepath=None):
self.__filepath = Filepath
... | ToOptix/FEMPy/Geometry/STLPhraser.py | import os
import os.path
import re
from .Triangle import Triangle
from .Solid import Solid
from .Point import Point
class File(object):
""" File-object
Example for a file definition
>>> file1 = File(1, "foo.txt")
"""
def __init__(self,ID=None, Filepath=None):
self.__filepath = Filepath
... | 0.554109 | 0.177811 |
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from configs.config_train import *
import tensorflow.contrib.slim.nets
class Training(object):
def __init__(self):
a=1
def training(self, sess, model, images, is_training, y_true):
with tf.v... | training/training.py |
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from configs.config_train import *
import tensorflow.contrib.slim.nets
class Training(object):
def __init__(self):
a=1
def training(self, sess, model, images, is_training, y_true):
with tf.v... | 0.786828 | 0.235405 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class _PositionAttentionModule(nn.Module):
""" Position attention module"""
def __init__(self, in_channels, **kwargs):
super(_PositionAttentionModule, self).__init__()
self.conv_b = nn.Conv2d(in_channels, in_channels /... | models/ClassicNetwork/blocks/DaNet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class _PositionAttentionModule(nn.Module):
""" Position attention module"""
def __init__(self, in_channels, **kwargs):
super(_PositionAttentionModule, self).__init__()
self.conv_b = nn.Conv2d(in_channels, in_channels /... | 0.949751 | 0.456531 |
import framebuf
import i2c
import utime as time
from micropython import const
# a few register definitions
_SET_CONTRAST = const(0x81)
_SET_NORM_INV = const(0xa6)
_SET_DISP = const(0xae)
_SET_SCAN_DIR = const(0xc0)
_SET_SEG_REMAP = const(0xa0)
_LOW_COLUMN_ADDRESS = const(0x00)
_H... | ssd1306.py | import framebuf
import i2c
import utime as time
from micropython import const
# a few register definitions
_SET_CONTRAST = const(0x81)
_SET_NORM_INV = const(0xa6)
_SET_DISP = const(0xae)
_SET_SCAN_DIR = const(0xc0)
_SET_SEG_REMAP = const(0xa0)
_LOW_COLUMN_ADDRESS = const(0x00)
_H... | 0.384103 | 0.090173 |
import click
import sys
from odc.io.text import click_range2d
from ._cli_common import main
@main.command('save-tasks')
@click.option('--grid',
type=str,
help=("Grid name or spec: albers_au_25,albers_africa_{10|20|30|60},"
"'crs;pixel_resolution;shape_in_pixels'"),
... | libs/stats/odc/stats/_cli_save_tasks.py | import click
import sys
from odc.io.text import click_range2d
from ._cli_common import main
@main.command('save-tasks')
@click.option('--grid',
type=str,
help=("Grid name or spec: albers_au_25,albers_africa_{10|20|30|60},"
"'crs;pixel_resolution;shape_in_pixels'"),
... | 0.359477 | 0.191706 |
# Data generated from http://www.json-generator.com/
# Using the following template
# [
# '{{repeat(100, 200)}}',
# {
# id: '{{objectId()}}',
# is_active: '{{bool()}}',
# number_of_children: '{{integer(0, 4)}}',
# age: '{{integer(15, 68)}}',
# eye_color: '{{random("blue", "brown", "green", "pur... | tests/fake_data.py |
# Data generated from http://www.json-generator.com/
# Using the following template
# [
# '{{repeat(100, 200)}}',
# {
# id: '{{objectId()}}',
# is_active: '{{bool()}}',
# number_of_children: '{{integer(0, 4)}}',
# age: '{{integer(15, 68)}}',
# eye_color: '{{random("blue", "brown", "green", "pur... | 0.341473 | 0.360011 |
import os
import tempfile
import shutil
import subprocess
import argparse
OPT_KONTAIN = "/opt/kontain"
OPT_KONTAIN_BIN = f"{OPT_KONTAIN}/bin"
KONTAIN_GCC = f"{OPT_KONTAIN_BIN}/kontain-gcc"
KM = f"{OPT_KONTAIN_BIN}/km"
INSTALL_URL = "https://raw.githubusercontent.com/kontainapp/km/master/km-releases/kontain-install.sh... | tools/release/tests/test_release_local/test_release_local.py | import os
import tempfile
import shutil
import subprocess
import argparse
OPT_KONTAIN = "/opt/kontain"
OPT_KONTAIN_BIN = f"{OPT_KONTAIN}/bin"
KONTAIN_GCC = f"{OPT_KONTAIN_BIN}/kontain-gcc"
KM = f"{OPT_KONTAIN_BIN}/km"
INSTALL_URL = "https://raw.githubusercontent.com/kontainapp/km/master/km-releases/kontain-install.sh... | 0.243013 | 0.068289 |
import sys
import numpy as np
import pytest
pytest.importorskip("pyxir")
import pyxir.contrib.target.DPUCADX8G
import pyxir.contrib.target.DPUCZDX8G
import tvm
from tvm import relay
from tvm.relay import transform
from tvm.relay.op.contrib.vitis_ai import annotation
from tvm.relay.build_module import bind_params_by_... | tests/python/contrib/test_vitis_ai/test_vitis_ai_codegen.py | import sys
import numpy as np
import pytest
pytest.importorskip("pyxir")
import pyxir.contrib.target.DPUCADX8G
import pyxir.contrib.target.DPUCZDX8G
import tvm
from tvm import relay
from tvm.relay import transform
from tvm.relay.op.contrib.vitis_ai import annotation
from tvm.relay.build_module import bind_params_by_... | 0.547706 | 0.33162 |
import logging
import sqlite3
from sqlite3 import Error
import time
from datetime import datetime
from statistics import variance, stdev
logging.basicConfig(filename='analyze_projects.log', filemode='a',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
#logging.getLogger().a... | analyze_data/analyzeProjects.py | import logging
import sqlite3
from sqlite3 import Error
import time
from datetime import datetime
from statistics import variance, stdev
logging.basicConfig(filename='analyze_projects.log', filemode='a',
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
#logging.getLogger().a... | 0.288268 | 0.21036 |
import requests
import boto3
from progressbar import progressbar
from datetime import datetime
import csv, os, argparse
from py_dataset import dataset
from subprocess import run, Popen, PIPE
def purr_eprints(connect_string, sql_script_name):
"""purr_eprints - contact the MySQL on a remote EPrints server and
r... | resolver.py | import requests
import boto3
from progressbar import progressbar
from datetime import datetime
import csv, os, argparse
from py_dataset import dataset
from subprocess import run, Popen, PIPE
def purr_eprints(connect_string, sql_script_name):
"""purr_eprints - contact the MySQL on a remote EPrints server and
r... | 0.323915 | 0.132711 |
import sys
import click
from team_formation import config
from team_formation.data_helpers import process_canvas_courses, \
process_canvas_group_categories
def course_prompt(canvas):
courses = canvas.get_courses(
enrollment_type='teacher',
enrollment_state='active',
per_page=config.PER... | team_formation/prompts.py | import sys
import click
from team_formation import config
from team_formation.data_helpers import process_canvas_courses, \
process_canvas_group_categories
def course_prompt(canvas):
courses = canvas.get_courses(
enrollment_type='teacher',
enrollment_state='active',
per_page=config.PER... | 0.176885 | 0.143908 |
import json
from pyspark.ml.feature import StringIndexer
from pyspark.ml.feature import MinMaxScaler
from pyspark.sql.types import IntegerType, DoubleType
from pyspark.sql.functions import col, lit
# keep the file sizes smaller for large distribution experiments
spark.conf.set("spark.sql.files.maxRecordsPerFile", 10... | deepctr/dist_utils/process_criteo.py | import json
from pyspark.ml.feature import StringIndexer
from pyspark.ml.feature import MinMaxScaler
from pyspark.sql.types import IntegerType, DoubleType
from pyspark.sql.functions import col, lit
# keep the file sizes smaller for large distribution experiments
spark.conf.set("spark.sql.files.maxRecordsPerFile", 10... | 0.344664 | 0.366987 |
import boto3
from pprint import pprint
PERMITTED_PORTS = [80, 443]
REPLACE_IP = '127.0.0.1/32'
ALL_IP = '0.0.0.0'
ALL_NET = '/0'
def correct_rule(security_group, bad_rule, ingress=False):
print('=== Bad rule detected ...')
print(bad_rule)
good_rule = bad_rule.copy()
good_rule['IpRanges'] = [{'CidrIp... | remediate_default_sg.py |
import boto3
from pprint import pprint
PERMITTED_PORTS = [80, 443]
REPLACE_IP = '127.0.0.1/32'
ALL_IP = '0.0.0.0'
ALL_NET = '/0'
def correct_rule(security_group, bad_rule, ingress=False):
print('=== Bad rule detected ...')
print(bad_rule)
good_rule = bad_rule.copy()
good_rule['IpRanges'] = [{'CidrIp... | 0.271252 | 0.129678 |
from .log import log
class C_new:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
class C_init:
def __init__(self, *args):
log("__init__", args)
class C_reduce:
def __reduce__(self):
log("__reduce__")
return self.__cla... | tests/objects/new_getnewargs.py | from .log import log
class C_new:
def __new__(cls, *args, **kwargs):
log("__new__", args, kwargs)
return object.__new__(cls)
class C_init:
def __init__(self, *args):
log("__init__", args)
class C_reduce:
def __reduce__(self):
log("__reduce__")
return self.__cla... | 0.649801 | 0.052741 |
from pymtl3 import *
#-------------------------------------------------------------------------
# Buffer
#-------------------------------------------------------------------------
class Buffer( Component ):
def construct( s ):
s.data = b8(0)
# By scheduling writes before reads the buffer will model a wire.... | examples/ex01_basics/IncrMethodModular_test.py | from pymtl3 import *
#-------------------------------------------------------------------------
# Buffer
#-------------------------------------------------------------------------
class Buffer( Component ):
def construct( s ):
s.data = b8(0)
# By scheduling writes before reads the buffer will model a wire.... | 0.566858 | 0.119974 |
from datetime import datetime
import json
import logging
import uuid
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseServerError
from django.shortcuts import render
from django.template.context im... | corehq/ex-submodules/soil/views.py | from datetime import datetime
import json
import logging
import uuid
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.http import HttpResponseRedirect, Http404, HttpResponse, HttpResponseServerError
from django.shortcuts import render
from django.template.context im... | 0.399694 | 0.052352 |
class DimGen(object):
def __init__(self):
self.dim = (0.,0.,1.,1.)
class DimUnit(DimGen):
def __init__(self):
super(DimUnit, self).__init__()
def generate(self, canvas, yy):
yy.dim = (0.,0.,1.,1.)
""" Edge anchors """
class RightOf(DimGen):
def __init__(self, nm, pad=0.... | Emmer/dimension.py | class DimGen(object):
def __init__(self):
self.dim = (0.,0.,1.,1.)
class DimUnit(DimGen):
def __init__(self):
super(DimUnit, self).__init__()
def generate(self, canvas, yy):
yy.dim = (0.,0.,1.,1.)
""" Edge anchors """
class RightOf(DimGen):
def __init__(self, nm, pad=0.... | 0.828973 | 0.449091 |
from bokeh.models.annotations import Legend
import pandas as pd
import numpy as np
df = pd.read_csv('covid-data-2021-05-24.csv')
df['date'] = pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
df['year'] = df['date'].dt.year
df['new_cases_density'] = df['new_cases'] / df['population']*100
df['total_vaccin... | covid19_bokeh.py | from bokeh.models.annotations import Legend
import pandas as pd
import numpy as np
df = pd.read_csv('covid-data-2021-05-24.csv')
df['date'] = pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
df['year'] = df['date'].dt.year
df['new_cases_density'] = df['new_cases'] / df['population']*100
df['total_vaccin... | 0.364891 | 0.322446 |
from azure.devops.connection import \
Connection
from azure.devops.exceptions import \
AzureDevOpsServiceError
from msrest.authentication import \
BasicTokenAuthentication, \
BasicAuthentication
from opsdroid.events import \
UserInvite, \
JoinRoom
from opsdroid.logging im... | __init__.py | from azure.devops.connection import \
Connection
from azure.devops.exceptions import \
AzureDevOpsServiceError
from msrest.authentication import \
BasicTokenAuthentication, \
BasicAuthentication
from opsdroid.events import \
UserInvite, \
JoinRoom
from opsdroid.logging im... | 0.318273 | 0.11358 |
from .configuration_mbart import MBartConfig
from .file_utils import add_start_docstrings
from .modeling_bart import BartForConditionalGeneration
_CONFIG_FOR_DOC = "MBartConfig"
_TOKENIZER_FOR_DOC = "MBartTokenizer"
MBART_PRETRAINED_MODEL_ARCHIVE_LIST = [
"facebook/mbart-large-cc25",
"facebook/mbart-large-en... | src/transformers/modeling_mbart.py | from .configuration_mbart import MBartConfig
from .file_utils import add_start_docstrings
from .modeling_bart import BartForConditionalGeneration
_CONFIG_FOR_DOC = "MBartConfig"
_TOKENIZER_FOR_DOC = "MBartTokenizer"
MBART_PRETRAINED_MODEL_ARCHIVE_LIST = [
"facebook/mbart-large-cc25",
"facebook/mbart-large-en... | 0.863636 | 0.239811 |
import pytest
import yaml
import json
from validate import json_ordered
class TestInconsistentObjects():
get_inconsistent_metadata = {
"type": "get_inconsistent_metadata",
"args": {}
}
reload_metadata = {
"type": "reload_metadata",
"args": {}
}
drop_inconsistent_me... | server/tests-py/test_inconsistent_meta.py | import pytest
import yaml
import json
from validate import json_ordered
class TestInconsistentObjects():
get_inconsistent_metadata = {
"type": "get_inconsistent_metadata",
"args": {}
}
reload_metadata = {
"type": "reload_metadata",
"args": {}
}
drop_inconsistent_me... | 0.519278 | 0.331931 |
import os
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
while strOperation != '=': # Приложение выводит результат вычислений когда получает от пользователя =.
os.system("clear")
v... | lesson2/hw3_new.py | import os
flag, isOperand, isOperator = 0, 0, 0
Variable, Result = 0.0, 0.0
strOperation, strForResult = '', 'Expression = '
while strOperation != '=': # Приложение выводит результат вычислений когда получает от пользователя =.
os.system("clear")
v... | 0.057223 | 0.316119 |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__description__ = '''
Vrátí entropii pro jednotlivé sloupce
Inputs:
- vstupní adresář s *.csv
'''
import sys
import os.path
import pandas as pd
from pprint import pprint
import numpy as np
from math import log2 as log2
# root of lib repository
PROJECT_... | py/tools/getEntropy.py | __author__ = "<NAME>"
__email__ = "<EMAIL>"
__description__ = '''
Vrátí entropii pro jednotlivé sloupce
Inputs:
- vstupní adresář s *.csv
'''
import sys
import os.path
import pandas as pd
from pprint import pprint
import numpy as np
from math import log2 as log2
# root of lib repository
PROJECT_... | 0.254694 | 0.179387 |
import io
import logging
import os
import re
from typing import List
from pygls.lsp.types import (NumType, Position, Range, TextDocumentContentChangeEvent,
TextDocumentItem, TextDocumentSyncKind, WorkspaceFolder)
from pygls.uris import to_fs_path, uri_scheme
# TODO: this is not the best e... | pygls/workspace.py | import io
import logging
import os
import re
from typing import List
from pygls.lsp.types import (NumType, Position, Range, TextDocumentContentChangeEvent,
TextDocumentItem, TextDocumentSyncKind, WorkspaceFolder)
from pygls.uris import to_fs_path, uri_scheme
# TODO: this is not the best e... | 0.644784 | 0.426023 |
"""Tests for Bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import bijectors as tfb
from tensorflow_probability.python.bijectors impo... | tensorflow_probability/python/bijectors/shifted_gompertz_cdf_test.py | """Tests for Bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python import bijectors as tfb
from tensorflow_probability.python.bijectors impo... | 0.903055 | 0.63168 |
import abc
import numpy as np
from casex import AircraftSpecs
from numba import njit
from sklearn.mixture import GaussianMixture
from seedpod_ground_risk.path_analysis.utils import bearing_to_angle, rotate_2d
@njit(cache=True)
def paef_to_ned_with_wind(x):
"""
Transform PAE frame distances to NED frame and ... | seedpod_ground_risk/path_analysis/descent_models/descent_model.py | import abc
import numpy as np
from casex import AircraftSpecs
from numba import njit
from sklearn.mixture import GaussianMixture
from seedpod_ground_risk.path_analysis.utils import bearing_to_angle, rotate_2d
@njit(cache=True)
def paef_to_ned_with_wind(x):
"""
Transform PAE frame distances to NED frame and ... | 0.877451 | 0.673386 |
r"""
.. _ref_ex_advanced2:
Mesh Refinement
---------------
Perform a mesh refinement study.
In this example the convergence of the torsion constant is investigated through an analysis of an
I Section. The mesh is refined both by modifying the mesh size and by specifying the number of
points making up the root radius.... | examples/01-advanced/02_mesh_refinement.py | r"""
.. _ref_ex_advanced2:
Mesh Refinement
---------------
Perform a mesh refinement study.
In this example the convergence of the torsion constant is investigated through an analysis of an
I Section. The mesh is refined both by modifying the mesh size and by specifying the number of
points making up the root radius.... | 0.92348 | 0.756358 |
import pytest
import xarray as xr
from runtime.steppers.machine_learning import (
non_negative_sphum,
update_temperature_tendency_to_conserve_mse,
update_moisture_tendency_to_ensure_non_negative_humidity,
non_negative_sphum_mse_conserving,
)
import vcm
sphum = 1.0e-3 * xr.DataArray(data=[1.0, 1.0, 1.0... | workflows/prognostic_c48_run/tests/test_steppers.py | import pytest
import xarray as xr
from runtime.steppers.machine_learning import (
non_negative_sphum,
update_temperature_tendency_to_conserve_mse,
update_moisture_tendency_to_ensure_non_negative_humidity,
non_negative_sphum_mse_conserving,
)
import vcm
sphum = 1.0e-3 * xr.DataArray(data=[1.0, 1.0, 1.0... | 0.500977 | 0.632673 |
from pathlib import Path
import abc
import inspect
import time
import tensorflow as tf
from synethesia.framework.model_skeleton import Model
class SessionHandler(object):
def __init__(self, model, model_name, checkpoint_dir="./checkpoints", logdir="./logs", max_saves_to_keep=5):
if not isinstance(model... | synethesia/framework/session_management.py | from pathlib import Path
import abc
import inspect
import time
import tensorflow as tf
from synethesia.framework.model_skeleton import Model
class SessionHandler(object):
def __init__(self, model, model_name, checkpoint_dir="./checkpoints", logdir="./logs", max_saves_to_keep=5):
if not isinstance(model... | 0.719581 | 0.212212 |
import re
import sys
import time
from urllib.request import urlopen
import cv2
import numpy as np
def process_stream(url, processor):
connected = False
while True:
if connected:
print("Disconnected from", url)
connected = False
stream = None... | robot-vision/mjpg_client.py |
import re
import sys
import time
from urllib.request import urlopen
import cv2
import numpy as np
def process_stream(url, processor):
connected = False
while True:
if connected:
print("Disconnected from", url)
connected = False
stream = None... | 0.175962 | 0.073897 |
from PIL import Image
import numpy as np
import glob
import os
from util import image_augmenter as ia
class Loader(object):
def __init__(self, dir_original, dir_segmented, init_size=(256, 256), one_hot=True):
self._data = Loader.import_data(dir_original, dir_segmented, init_size, one_hot)
... | util/loader.py | from PIL import Image
import numpy as np
import glob
import os
from util import image_augmenter as ia
class Loader(object):
def __init__(self, dir_original, dir_segmented, init_size=(256, 256), one_hot=True):
self._data = Loader.import_data(dir_original, dir_segmented, init_size, one_hot)
... | 0.632162 | 0.332934 |
from typing import Iterable, cast
import numpy as np
import pytest
import sympy
import cirq
def assert_optimizes(before: cirq.Circuit,
expected: cirq.Circuit,
compare_unitaries: bool = True,
eject_parameterized: bool = False):
opt = cirq.EjectPhased... | cirq/optimizers/eject_phased_paulis_test.py | from typing import Iterable, cast
import numpy as np
import pytest
import sympy
import cirq
def assert_optimizes(before: cirq.Circuit,
expected: cirq.Circuit,
compare_unitaries: bool = True,
eject_parameterized: bool = False):
opt = cirq.EjectPhased... | 0.870115 | 0.715896 |
load("@bazel_gazelle//:deps.bzl", "go_repository")
def go_repositories():
go_repository(
name = "co_honnef_go_tools",
importpath = "honnef.co/go/tools",
sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=",
version = "v0.0.0-20190523083050-ea95bdfd59fc",
)
go_repository(
... | repositories.bzl | load("@bazel_gazelle//:deps.bzl", "go_repository")
def go_repositories():
go_repository(
name = "co_honnef_go_tools",
importpath = "honnef.co/go/tools",
sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=",
version = "v0.0.0-20190523083050-ea95bdfd59fc",
)
go_repository(
... | 0.163179 | 0.142351 |
import sys
import warnings
from typing import Union
from tqdm.auto import trange
sys.path.append('../..')
from crisp import Distribution, PopulationInfectionStatus
import argparse
from matplotlib.pyplot import *
from matplotlib import cycler
import numpy as np
import random
def init_contacts(S, T, qIbar=20.0, R0... | code/experiments/exp_5.1/exp51.py | import sys
import warnings
from typing import Union
from tqdm.auto import trange
sys.path.append('../..')
from crisp import Distribution, PopulationInfectionStatus
import argparse
from matplotlib.pyplot import *
from matplotlib import cycler
import numpy as np
import random
def init_contacts(S, T, qIbar=20.0, R0... | 0.506347 | 0.365853 |
import unittest
import os
from musixmatch import Musixmatch
class TestMusixmatch(unittest.TestCase):
def setUp(self):
self.musixmatch = Musixmatch(os.environ.get('APIKEY'))
self.url = 'http://api.musixmatch.com/ws/1.1/'
def test_get_url(self):
self.assertEqual(self.musixmatch
... | tests/tests.py | import unittest
import os
from musixmatch import Musixmatch
class TestMusixmatch(unittest.TestCase):
def setUp(self):
self.musixmatch = Musixmatch(os.environ.get('APIKEY'))
self.url = 'http://api.musixmatch.com/ws/1.1/'
def test_get_url(self):
self.assertEqual(self.musixmatch
... | 0.425486 | 0.171963 |
from feature_engine.encoding import OrdinalEncoder, RareLabelEncoder
from feature_engine.imputation import (
AddMissingIndicator,
CategoricalImputer,
MeanMedianImputer,
)
from feature_engine.selection import DropFeatures
from feature_engine.transformation import LogTransformer
from feature_engine.wrappers i... | section-05-production-model-package/regression_model/pipeline.py | from feature_engine.encoding import OrdinalEncoder, RareLabelEncoder
from feature_engine.imputation import (
AddMissingIndicator,
CategoricalImputer,
MeanMedianImputer,
)
from feature_engine.selection import DropFeatures
from feature_engine.transformation import LogTransformer
from feature_engine.wrappers i... | 0.714728 | 0.207938 |
import warnings
import numpy as np
from nems import epoch as nep
from nems.signal import SignalBase
def _epoch_name_handler(rec_or_sig, epoch_names):
'''
helper function to transform heterogeneous inputs of epochs names (epoch names, list of epochs names, keywords) into
the corresponding list of epoch n... | src/utils/cpp_parameter_handlers.py | import warnings
import numpy as np
from nems import epoch as nep
from nems.signal import SignalBase
def _epoch_name_handler(rec_or_sig, epoch_names):
'''
helper function to transform heterogeneous inputs of epochs names (epoch names, list of epochs names, keywords) into
the corresponding list of epoch n... | 0.782995 | 0.526099 |
import glob
import cv2
import os
import numpy as np
from keras.models import load_model
labels = ["100won", "10won", "500won", "50won"]
model = load_model('model/my_model.h5')
img_path = glob.glob("data/origin_images/*.jpg")
for path in img_path:
# Read image
org = cv2.imread(path)
img = cv2.resize(org,... | coin_predict.py | import glob
import cv2
import os
import numpy as np
from keras.models import load_model
labels = ["100won", "10won", "500won", "50won"]
model = load_model('model/my_model.h5')
img_path = glob.glob("data/origin_images/*.jpg")
for path in img_path:
# Read image
org = cv2.imread(path)
img = cv2.resize(org,... | 0.47317 | 0.258301 |
import numpy as np
from reciprocalspaceship.dtypes import MTZIntDtype
def add_rfree(dataset, fraction=0.05, bins=20, inplace=False):
"""
Add an r-free flag to the dataset object for refinement.
R-free flags are used to identify reflections which are not used in automated refinement routines.
This is ... | reciprocalspaceship/utils/rfree.py | import numpy as np
from reciprocalspaceship.dtypes import MTZIntDtype
def add_rfree(dataset, fraction=0.05, bins=20, inplace=False):
"""
Add an r-free flag to the dataset object for refinement.
R-free flags are used to identify reflections which are not used in automated refinement routines.
This is ... | 0.870088 | 0.554018 |
import os
import sys
from glob import glob
import setuptools
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
from distutils.sysconfig import get_config_var, get_python_inc
from distutils.version import LooseVersion
import versioneer
assert LooseVersion(setupt... | setup.py | import os
import sys
from glob import glob
import setuptools
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
from distutils.sysconfig import get_config_var, get_python_inc
from distutils.version import LooseVersion
import versioneer
assert LooseVersion(setupt... | 0.309337 | 0.095139 |
import nnpy
import ptf
import ptf.platforms.nn as nn
import ptf.ptfutils as ptfutils
import ptf.packet as scapy
import ptf.mask as mask
from ptf.base_tests import BaseTest
from ptf.dataplane import DataPlane, DataPlanePortNN
from tests.common.utilities import wait_until
class PtfAdapterNNConnectionError(Exception):
... | tests/common/plugins/ptfadapter/ptfadapter.py | import nnpy
import ptf
import ptf.platforms.nn as nn
import ptf.ptfutils as ptfutils
import ptf.packet as scapy
import ptf.mask as mask
from ptf.base_tests import BaseTest
from ptf.dataplane import DataPlane, DataPlanePortNN
from tests.common.utilities import wait_until
class PtfAdapterNNConnectionError(Exception):
... | 0.628179 | 0.323327 |
# Part of the PsychoPy library
# Copyright (C) 2002-2018 <NAME> (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from __future__ import absolute_import, print_function
from psychopy.visual.shape import BaseShapeStim
from psychopy.tools.attributetools import a... | venv/Lib/site-packages/psychopy/visual/pie.py | # Part of the PsychoPy library
# Copyright (C) 2002-2018 <NAME> (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).
from __future__ import absolute_import, print_function
from psychopy.visual.shape import BaseShapeStim
from psychopy.tools.attributetools import a... | 0.946609 | 0.663298 |
import os
from thermo import heatform
from thermo import util
import automol.inchi
import automol.smiles
# Inchi string for methyl nitrate (CH3ONO2)
ICH = 'InChI=1S/CH3NO3/c1-5-2(3)4/h1H3'
SMI = 'C=CC(=O)O'
ICH2 = automol.smiles.inchi(SMI)
# Thermp output file name
THERMP_OUTFILE_NAME = os.path.join(os.getcwd(), 'run... | tests/thermo/test__heatform.py | import os
from thermo import heatform
from thermo import util
import automol.inchi
import automol.smiles
# Inchi string for methyl nitrate (CH3ONO2)
ICH = 'InChI=1S/CH3NO3/c1-5-2(3)4/h1H3'
SMI = 'C=CC(=O)O'
ICH2 = automol.smiles.inchi(SMI)
# Thermp output file name
THERMP_OUTFILE_NAME = os.path.join(os.getcwd(), 'run... | 0.294114 | 0.286032 |
import json
from typing import Dict
from bamboo_engine import metrics, exceptions
from bamboo_engine.eri import Data, DataInput, ExecutionData, CallbackData
from pipeline.eri import codec
from pipeline.eri.models import Data as DBData
from pipeline.eri.models import ExecutionData as DBExecutionData
from pipeline.eri.... | runtime/bamboo-pipeline/pipeline/eri/imp/data.py | import json
from typing import Dict
from bamboo_engine import metrics, exceptions
from bamboo_engine.eri import Data, DataInput, ExecutionData, CallbackData
from pipeline.eri import codec
from pipeline.eri.models import Data as DBData
from pipeline.eri.models import ExecutionData as DBExecutionData
from pipeline.eri.... | 0.566378 | 0.353763 |
from flask import request,session, render_template, current_app, url_for
import random
from datetime import datetime
from app.common.ajax import *
from app.common.upload_file import *
from app.common.common import strdecode
from .models import *
from .import_html import *
def upload_tmpimg(*args, **kwargs):
imag... | app/home/ajax.py |
from flask import request,session, render_template, current_app, url_for
import random
from datetime import datetime
from app.common.ajax import *
from app.common.upload_file import *
from app.common.common import strdecode
from .models import *
from .import_html import *
def upload_tmpimg(*args, **kwargs):
imag... | 0.407451 | 0.101634 |
def sendEmail(fromGmail, fromPwd, toEmails, subject, body):
# Import smtp library
import smtplib
# Initialize vars
usr = fromGmail
pwd = <PASSWORD>Pwd
FROM = usr
TO = toEmails if type(toEmails) is list else [toEmails]
SUBJECT = subject
TEXT = body
# Prepare and attempt to send ... | passcrack.py | def sendEmail(fromGmail, fromPwd, toEmails, subject, body):
# Import smtp library
import smtplib
# Initialize vars
usr = fromGmail
pwd = <PASSWORD>Pwd
FROM = usr
TO = toEmails if type(toEmails) is list else [toEmails]
SUBJECT = subject
TEXT = body
# Prepare and attempt to send ... | 0.233881 | 0.164785 |
from octis.models.model import AbstractModel
import numpy as np
from gensim.models import hdpmodel
import gensim.corpora as corpora
import octis.configuration.citations as citations
import octis.configuration.defaults as defaults
class HDP(AbstractModel):
id2word = None
id_corpus = None
use_partitions = ... | octis/models/HDP.py | from octis.models.model import AbstractModel
import numpy as np
from gensim.models import hdpmodel
import gensim.corpora as corpora
import octis.configuration.citations as citations
import octis.configuration.defaults as defaults
class HDP(AbstractModel):
id2word = None
id_corpus = None
use_partitions = ... | 0.861742 | 0.387111 |
import unittest
from transformers import XLMRobertaXLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ..generation.test_generation_utils import GenerationTesterMixin
from ..test_configuration_common import ConfigTester
from ..test_modeling_common import ModelT... | tests/xlm_roberta_xl/test_modeling_xlm_roberta_xl.py |
import unittest
from transformers import XLMRobertaXLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ..generation.test_generation_utils import GenerationTesterMixin
from ..test_configuration_common import ConfigTester
from ..test_modeling_common import ModelT... | 0.784484 | 0.332202 |
# Parameterized type: <T>
class PropertyStore:
def setProperty(self, key, value):
"""
Returns void
Parameters:
key: Stringvalue: T
Throws:
PropertyStoreException
"""
pass
def getProperty(self, key):
"""
Returns T
... | org/apache/helix/store/PropertyStore.py |
# Parameterized type: <T>
class PropertyStore:
def setProperty(self, key, value):
"""
Returns void
Parameters:
key: Stringvalue: T
Throws:
PropertyStoreException
"""
pass
def getProperty(self, key):
"""
Returns T
... | 0.560012 | 0.141637 |
from typing import (
Any,
Collection,
Dict,
Iterator,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import numpy as np
from pystiche import ComplexObject
from pystiche.loss import MultiOperatorLoss
from pystiche.misc import zip_equal
from pystiche.ops import ComparisonOperator, Operator... | pystiche/pyramid/pyramid.py | from typing import (
Any,
Collection,
Dict,
Iterator,
Optional,
Sequence,
Set,
Tuple,
Union,
)
import numpy as np
from pystiche import ComplexObject
from pystiche.loss import MultiOperatorLoss
from pystiche.misc import zip_equal
from pystiche.ops import ComparisonOperator, Operator... | 0.890488 | 0.521654 |
from __future__ import division
from enum import Enum
import pytest
from mock import call, MagicMock, Mock
from pytest import raises, approx
import numpy as np
import torch
from torch.nn import Linear
from torch.nn.functional import mse_loss
from torch.optim import SGD
from ignite.engine import Engine, Events, State,... | tests/ignite/engine/test_engine.py | from __future__ import division
from enum import Enum
import pytest
from mock import call, MagicMock, Mock
from pytest import raises, approx
import numpy as np
import torch
from torch.nn import Linear
from torch.nn.functional import mse_loss
from torch.optim import SGD
from ignite.engine import Engine, Events, State,... | 0.862844 | 0.372448 |