code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from __future__ import absolute_import
import re
import flask
import opentracing
import opentracing.ext.tags as ext
import wrapt
from ...log import logger
from ...singletons import agent, tracer
from ...util.secrets import strip_secrets_from_query
path_tpl_re = re.compile('<.*>')
def before_request_with_instana(... | instana/instrumentation/flask/vanilla.py |
from __future__ import absolute_import
import re
import flask
import opentracing
import opentracing.ext.tags as ext
import wrapt
from ...log import logger
from ...singletons import agent, tracer
from ...util.secrets import strip_secrets_from_query
path_tpl_re = re.compile('<.*>')
def before_request_with_instana(... | 0.500488 | 0.079818 |
import os
import sys
import errno
import shutil
import glob
import pwd
import codecs
import hashlib
import tarfile
from socket import gethostname
f_ext = os.path.splitext
f_expand = os.path.expanduser
f_size = os.path.getsize
is_file = os.path.isfile
is_dir = os.path.isdir
get_dir = os.path.dirname
def owner_na... | surreal/utils/filesys.py | import os
import sys
import errno
import shutil
import glob
import pwd
import codecs
import hashlib
import tarfile
from socket import gethostname
f_ext = os.path.splitext
f_expand = os.path.expanduser
f_size = os.path.getsize
is_file = os.path.isfile
is_dir = os.path.isdir
get_dir = os.path.dirname
def owner_na... | 0.511229 | 0.153074 |
from dearpygui.core import *
from dearpygui.simple import *
from dearpygui.demo import show_demo
import docker
import threading
import time
import webbrowser
import requests
import json
import os
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
# noinspection PyUnresolvedReferences
from psycop... | mgmt.py | from dearpygui.core import *
from dearpygui.simple import *
from dearpygui.demo import show_demo
import docker
import threading
import time
import webbrowser
import requests
import json
import os
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
# noinspection PyUnresolvedReferences
from psycop... | 0.291283 | 0.078254 |
from ..output import OutputDevice
try:
import sounddevice
except ModuleNotFoundError:
pass
def get_cv_output_devices():
return list(sounddevice.query_devices())
class CVOutputDevice(OutputDevice):
"""
CVOutputDevice: Sends output to CV over an audio I/O device.
"""
def audio_callback(sel... | isobar/io/cv/output.py | from ..output import OutputDevice
try:
import sounddevice
except ModuleNotFoundError:
pass
def get_cv_output_devices():
return list(sounddevice.query_devices())
class CVOutputDevice(OutputDevice):
"""
CVOutputDevice: Sends output to CV over an audio I/O device.
"""
def audio_callback(sel... | 0.726911 | 0.222088 |
import inspect
from fnmatch import fnmatchcase
from typing import Union
from sciunit.base import SciUnit
from sciunit.capabilities import Capability
class Model(SciUnit):
"""Abstract base class for sciunit models."""
def __init__(self, name=None, **params):
"""Instantiate model."""
if name ... | sciunit/models/base.py |
import inspect
from fnmatch import fnmatchcase
from typing import Union
from sciunit.base import SciUnit
from sciunit.capabilities import Capability
class Model(SciUnit):
"""Abstract base class for sciunit models."""
def __init__(self, name=None, **params):
"""Instantiate model."""
if name ... | 0.878262 | 0.355663 |
from concurrent import futures
import time
import grpc
import gen_test_file
import metrics_plain
from paddle_fl.feature_engineering.core.federated_feature_engineering_server import FederatedFeatureEngineeringServer
SERVER_ADRESS = 'localhost:50051'
def gen_server():
"""
gen serever listen on port
"""
... | python/paddle_fl/feature_engineering/example/metrics_test_server.py | from concurrent import futures
import time
import grpc
import gen_test_file
import metrics_plain
from paddle_fl.feature_engineering.core.federated_feature_engineering_server import FederatedFeatureEngineeringServer
SERVER_ADRESS = 'localhost:50051'
def gen_server():
"""
gen serever listen on port
"""
... | 0.496338 | 0.133981 |
import tensorflow as tf
import numpy as np
import logging
import logging.config
import time
from config import get_logging_config, args, evaluation_logfile, train_dir
from config import config as net_config
from paths import CKPT_ROOT
from utils import decode_bboxes, batch_iou
from skimage.transform import resize as ... | benchmark.py | import tensorflow as tf
import numpy as np
import logging
import logging.config
import time
from config import get_logging_config, args, evaluation_logfile, train_dir
from config import config as net_config
from paths import CKPT_ROOT
from utils import decode_bboxes, batch_iou
from skimage.transform import resize as ... | 0.439507 | 0.105349 |
from __future__ import division, print_function, absolute_import
from scipy.stats import betabinom, hypergeom, bernoulli, boltzmann
import numpy as np
from numpy.testing import assert_almost_equal, assert_equal, assert_allclose
def test_hypergeom_logpmf():
# symmetries test
# f(k,N,K,n) = f(n-k,N,N-K,n) = f(... | chatbot_env/Lib/site-packages/scipy/stats/tests/test_discrete_distns.py | from __future__ import division, print_function, absolute_import
from scipy.stats import betabinom, hypergeom, bernoulli, boltzmann
import numpy as np
from numpy.testing import assert_almost_equal, assert_equal, assert_allclose
def test_hypergeom_logpmf():
# symmetries test
# f(k,N,K,n) = f(n-k,N,N-K,n) = f(... | 0.76986 | 0.434101 |
from functools import partial
from six.moves import xrange, cStringIO
import pysmt.operators as op
from pysmt.environment import get_env
from pysmt.walkers import TreeWalker, DagWalker, handles
from pysmt.utils import quote
class SmtPrinter(TreeWalker):
def __init__(self, stream):
TreeWalker.__init__(s... | pysmt/smtlib/printers.py | from functools import partial
from six.moves import xrange, cStringIO
import pysmt.operators as op
from pysmt.environment import get_env
from pysmt.walkers import TreeWalker, DagWalker, handles
from pysmt.utils import quote
class SmtPrinter(TreeWalker):
def __init__(self, stream):
TreeWalker.__init__(s... | 0.671578 | 0.251108 |
def the_cards():
assigned = input("The cards are: ")
cardsArray = assigned.split(" ")
return cardsArray
def dealing_cards(cardsArray):
# 确定翻面牌的花色和大小
lead_card = cardsArray[0]
if lead_card[0] == "T":
lead_value = 10
elif lead_card[0] == "J":
lead_value = 11
elif lea... | Work10/Agram.py | def the_cards():
assigned = input("The cards are: ")
cardsArray = assigned.split(" ")
return cardsArray
def dealing_cards(cardsArray):
# 确定翻面牌的花色和大小
lead_card = cardsArray[0]
if lead_card[0] == "T":
lead_value = 10
elif lead_card[0] == "J":
lead_value = 11
elif lea... | 0.129375 | 0.421671 |
class AsyncSwitchStacks:
def __init__(self, session):
super().__init__()
self._session = session
async def getNetworkSwitchStacks(self, networkId: str):
"""
**List the switch stacks in a network**
https://developer.cisco.com/meraki/api/#!get-network-switch-stacks
... | meraki_v0/aio/api/switch_stacks.py | class AsyncSwitchStacks:
def __init__(self, session):
super().__init__()
self._session = session
async def getNetworkSwitchStacks(self, networkId: str):
"""
**List the switch stacks in a network**
https://developer.cisco.com/meraki/api/#!get-network-switch-stacks
... | 0.79999 | 0.212538 |
#/*******************************************************************************
#* Portions Copyright (C) 2008 Novell, Inc. All rights reserved.
#*
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that the following conditions are met:
#*
#* - Redistribut... | gmetad-python/gmetad.py |
#/*******************************************************************************
#* Portions Copyright (C) 2008 Novell, Inc. All rights reserved.
#*
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that the following conditions are met:
#*
#* - Redistribut... | 0.447823 | 0.04679 |
import bpy
import numpy
from mathutils import Matrix
from mathutils.geometry import intersect_line_plane
import sprytile_utils
import sprytile_uv
from sprytile_uv import UvDataLayers
class ToolFill:
modal = None
left_down = False
def __init__(self, modal, rx_source):
self.modal = modal
rx... | sprytile_tools/tool_fill.py | import bpy
import numpy
from mathutils import Matrix
from mathutils.geometry import intersect_line_plane
import sprytile_utils
import sprytile_uv
from sprytile_uv import UvDataLayers
class ToolFill:
modal = None
left_down = False
def __init__(self, modal, rx_source):
self.modal = modal
rx... | 0.796253 | 0.271961 |
import os
import warnings
from unittest import TestCase, main
import numpy
from numpy.testing import assert_allclose, assert_equal
from cogent3 import (
DNA,
PROTEIN,
RNA,
load_aligned_seqs,
make_aligned_seqs,
make_unaligned_seqs,
)
from cogent3.evolve.distance import EstimateDistances
from ... | tests/test_evolve/test_distance.py | import os
import warnings
from unittest import TestCase, main
import numpy
from numpy.testing import assert_allclose, assert_equal
from cogent3 import (
DNA,
PROTEIN,
RNA,
load_aligned_seqs,
make_aligned_seqs,
make_unaligned_seqs,
)
from cogent3.evolve.distance import EstimateDistances
from ... | 0.639398 | 0.595963 |
import requests
import json
import time
import sys
import struct
import binascii
url = "http://127.0.0.1:26605/jsonrpc"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}
def rpc_call(method, params):
payload = {
"method": method,
"params": params,
"id"... | scripts/reward/withdraw.py | import requests
import json
import time
import sys
import struct
import binascii
url = "http://127.0.0.1:26605/jsonrpc"
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}
def rpc_call(method, params):
payload = {
"method": method,
"params": params,
"id"... | 0.327561 | 0.111241 |
from uuid import uuid1
from django.core.cache import cache
from django.test import TestCase
from Net640.apps.user_profile.models import User
from Net640.apps.user_profile.models import RELATIONSHIP_FRIENDS, RELATIONSHIP_REQUEST_HAS_SENT
from Net640.apps.user_profile.models import RELATIONSHIP_WAITING_FOR_ACCEPT, NO_RE... | Net640/apps/user_profile/tests/test_models.py | from uuid import uuid1
from django.core.cache import cache
from django.test import TestCase
from Net640.apps.user_profile.models import User
from Net640.apps.user_profile.models import RELATIONSHIP_FRIENDS, RELATIONSHIP_REQUEST_HAS_SENT
from Net640.apps.user_profile.models import RELATIONSHIP_WAITING_FOR_ACCEPT, NO_RE... | 0.500244 | 0.186058 |
import argparse
import inflect
import os
import pip
try:
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
import sys
ie = inflect.engine()
try:
__import__('yaml')
except ImportError:
for item in parse_requirements("./tools/lint/requirements.t... | tools/lint/lint.py |
import argparse
import inflect
import os
import pip
try:
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
import sys
ie = inflect.engine()
try:
__import__('yaml')
except ImportError:
for item in parse_requirements("./tools/lint/requirements.t... | 0.192274 | 0.109849 |
import random
class LetterData:
def __init__(self, letter):
self.count = 1
self.letter = letter
self.next = {}
def increment(self):
self.count += 1
def addNext(self, nextLetter):
if nextLetter in self.next:
self.next[nextLetter].increment()
else... | sillyWord/sillywords.py | import random
class LetterData:
def __init__(self, letter):
self.count = 1
self.letter = letter
self.next = {}
def increment(self):
self.count += 1
def addNext(self, nextLetter):
if nextLetter in self.next:
self.next[nextLetter].increment()
else... | 0.296043 | 0.379177 |
import unittest
from enum import Enum
import re
from pampy import match_value, match, HEAD, TAIL, _, MatchError
class PampyBasicTests(unittest.TestCase):
def test_match_value(self):
def match_value_bool(pat, var):
return match_value(pat, var)[0]
self.assertTrue(match_value_bool(3, 3... | tests/test_basic.py | import unittest
from enum import Enum
import re
from pampy import match_value, match, HEAD, TAIL, _, MatchError
class PampyBasicTests(unittest.TestCase):
def test_match_value(self):
def match_value_bool(pat, var):
return match_value(pat, var)[0]
self.assertTrue(match_value_bool(3, 3... | 0.628179 | 0.745329 |
import numpy as np
import warnings
import yaml
# same convention as elsewhere
SHEAR_SHEAR = 0
SHEAR_POS = 1
POS_POS = 2
def ccl_read_yaml(filename, **kwargs):
import pyccl as ccl
"""Read the parameters from a YAML file.
Args:
filename (:obj:`str`) Filename to read parameters from.
"""
wit... | txpipe/utils/theory.py | import numpy as np
import warnings
import yaml
# same convention as elsewhere
SHEAR_SHEAR = 0
SHEAR_POS = 1
POS_POS = 2
def ccl_read_yaml(filename, **kwargs):
import pyccl as ccl
"""Read the parameters from a YAML file.
Args:
filename (:obj:`str`) Filename to read parameters from.
"""
wit... | 0.676406 | 0.336495 |
from abc import ABC,abstractmethod
class WorkOrderInterface(ABC):
"""
WorkOrderRegistryInterface is an abstract base class that contains
abstract APIs to manage work orders
"""
def __init__(self):
super().__init__()
@abstractmethod
def work_order_submit(self, wo_request_json_str,... | examples/common/python/connectors/interfaces/work_order_interface.py |
from abc import ABC,abstractmethod
class WorkOrderInterface(ABC):
"""
WorkOrderRegistryInterface is an abstract base class that contains
abstract APIs to manage work orders
"""
def __init__(self):
super().__init__()
@abstractmethod
def work_order_submit(self, wo_request_json_str,... | 0.788583 | 0.468122 |
import json
import unittest
import warnings
# Disable not-grouped imports that conflicts with isort
from unittest.mock import (MagicMock, Mock, patch, # pylint: disable=C0412
sentinel)
from urllib.error import HTTPError
from kytos.core.api_server import APIServer
from kytos.core.napps impor... | tests/unit/test_core/test_api_server.py | import json
import unittest
import warnings
# Disable not-grouped imports that conflicts with isort
from unittest.mock import (MagicMock, Mock, patch, # pylint: disable=C0412
sentinel)
from urllib.error import HTTPError
from kytos.core.api_server import APIServer
from kytos.core.napps impor... | 0.546496 | 0.214229 |
import sys
assert sys.platform == "win32"
from ctypes import byref, windll
from ctypes.wintypes import DWORD, HANDLE
from typing import Any, Optional, TextIO
from prompt_toolkit.data_structures import Size
from prompt_toolkit.win32_types import STD_OUTPUT_HANDLE
from .base import Output
from .color_depth import Col... | Lib/site-packages/prompt_toolkit/output/windows10.py | import sys
assert sys.platform == "win32"
from ctypes import byref, windll
from ctypes.wintypes import DWORD, HANDLE
from typing import Any, Optional, TextIO
from prompt_toolkit.data_structures import Size
from prompt_toolkit.win32_types import STD_OUTPUT_HANDLE
from .base import Output
from .color_depth import Col... | 0.490724 | 0.184565 |
import serial
import struct
import time
import threading
import warnings
from .message import Message
from enums.PTPMode import PTPMode
from enums.CommunicationProtocolIDs import CommunicationProtocolIDs
from enums.ControlValues import ControlValues
class Dobot:
def __init__(self, port, verbose=False):
... | src/extensions/scratch3_dobot/Dobot Extension/pydobot/backup/dobot.py | import serial
import struct
import time
import threading
import warnings
from .message import Message
from enums.PTPMode import PTPMode
from enums.CommunicationProtocolIDs import CommunicationProtocolIDs
from enums.ControlValues import ControlValues
class Dobot:
def __init__(self, port, verbose=False):
... | 0.523664 | 0.098252 |
import json
import os
import os.path as osp
import torch
import yaml
import mmcv
from ....parallel.utils import is_module_wrapper
from ...dist_utils import master_only
from ..hook import HOOKS
from .base import LoggerHook
@HOOKS.register_module()
class PaviLoggerHook(LoggerHook):
"""Class to visual model, log m... | mmcv/runner/hooks/logger/pavi.py | import json
import os
import os.path as osp
import torch
import yaml
import mmcv
from ....parallel.utils import is_module_wrapper
from ...dist_utils import master_only
from ..hook import HOOKS
from .base import LoggerHook
@HOOKS.register_module()
class PaviLoggerHook(LoggerHook):
"""Class to visual model, log m... | 0.652463 | 0.158012 |
from pages.detailpage import DetailPage
class InstanceDetailPage(DetailPage):
def __init__(self, tester, instance_id, instance_name=None):
self.instance_name = instance_name
self.instance_id = instance_id
self.tester = tester
self.print_test_context()
self.verify_instance_d... | tests/selenium/guiops/pages/instance/instancedetail.py | from pages.detailpage import DetailPage
class InstanceDetailPage(DetailPage):
def __init__(self, tester, instance_id, instance_name=None):
self.instance_name = instance_name
self.instance_id = instance_id
self.tester = tester
self.print_test_context()
self.verify_instance_d... | 0.453988 | 0.070144 |
import requests
RESPONSE_CODES = {
200: "Operation successful",
204: "The resource was deleted successfully",
404: "Resource not found",
422: "Invalid input",
}
class AirbyteResponse:
def __init__(self, response):
if response.status_code in RESPONSE_CODES:
self.message = RESPO... | airbyte_client.py | import requests
RESPONSE_CODES = {
200: "Operation successful",
204: "The resource was deleted successfully",
404: "Resource not found",
422: "Invalid input",
}
class AirbyteResponse:
def __init__(self, response):
if response.status_code in RESPONSE_CODES:
self.message = RESPO... | 0.296247 | 0.07579 |
from dataclasses import dataclass
from typing import Tuple, List, Optional
from src.types.name_puzzle_condition import NPC
from src.types.program import Program
from src.types.coin import Coin
from src.types.header import Header
from src.types.sized_bytes import bytes32
from src.util.mempool_check_conditions import ge... | src/types/full_block.py | from dataclasses import dataclass
from typing import Tuple, List, Optional
from src.types.name_puzzle_condition import NPC
from src.types.program import Program
from src.types.coin import Coin
from src.types.header import Header
from src.types.sized_bytes import bytes32
from src.util.mempool_check_conditions import ge... | 0.832747 | 0.38122 |
import registration_struct_wf as regstruct
import registration_func_wf as regfunc
import nipype.pipeline.engine as pe
from nipype.interfaces.utility import IdentityInterface, Function
import nipype.interfaces.io as nio
import explore.helper_functions as hf
import numpy as np
"""
INPUT PARAMETERS
"""
grab_bdir = '/dat... | preprocess/registration_setup.py | import registration_struct_wf as regstruct
import registration_func_wf as regfunc
import nipype.pipeline.engine as pe
from nipype.interfaces.utility import IdentityInterface, Function
import nipype.interfaces.io as nio
import explore.helper_functions as hf
import numpy as np
"""
INPUT PARAMETERS
"""
grab_bdir = '/dat... | 0.490968 | 0.244961 |
OSS_USER_METADATA_PREFIX = "x-oss-meta-"
OSS_CANNED_ACL = "x-oss-acl"
IF_UNMODIFIED_SINCE = "If-Unmodified-Since"
IF_MATCH = "If-Match"
OSS_COPY_OBJECT_SOURCE = "x-oss-copy-source"
OSS_COPY_OBJECT_SOURCE_RANGE = "x-oss-copy-source-range"
OSS_REQUEST_ID = "x-oss-request-id"
OSS_SECURITY_TOKEN = "x-oss-security-toke... | oss2/headers.py | OSS_USER_METADATA_PREFIX = "x-oss-meta-"
OSS_CANNED_ACL = "x-oss-acl"
IF_UNMODIFIED_SINCE = "If-Unmodified-Since"
IF_MATCH = "If-Match"
OSS_COPY_OBJECT_SOURCE = "x-oss-copy-source"
OSS_COPY_OBJECT_SOURCE_RANGE = "x-oss-copy-source-range"
OSS_REQUEST_ID = "x-oss-request-id"
OSS_SECURITY_TOKEN = "x-oss-security-toke... | 0.281406 | 0.06486 |
import pygame
import sys
import rospy
from geometry_msgs.msg import Twist
# Vamos acompanhar o estado dessas teclas
KEYS = [pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d]
# Indice dos eixos x e y do joystick
X_AXIS = 0
Y_AXIS = 4
INVERT_X_AXIS = True
INVERT_Y_AXIS = True
ROBOTS = 3
# Namespace dos tópicos que ire... | scripts/keyboard_node.py | import pygame
import sys
import rospy
from geometry_msgs.msg import Twist
# Vamos acompanhar o estado dessas teclas
KEYS = [pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d]
# Indice dos eixos x e y do joystick
X_AXIS = 0
Y_AXIS = 4
INVERT_X_AXIS = True
INVERT_Y_AXIS = True
ROBOTS = 3
# Namespace dos tópicos que ire... | 0.145844 | 0.251401 |
import numpy as np
import scipy.sparse as sps
from mars.tests.core import TestBase
from mars.tensor.execution.core import Executor
from mars.tensor.expressions.datasource import tensor, ones_like, zeros, zeros_like, full, \
arange, empty, empty_like, diag, diagflat, eye, linspace, meshgrid, indices, \
triu, t... | mars/tensor/execution/tests/test_datasource_execute.py |
import numpy as np
import scipy.sparse as sps
from mars.tests.core import TestBase
from mars.tensor.execution.core import Executor
from mars.tensor.expressions.datasource import tensor, ones_like, zeros, zeros_like, full, \
arange, empty, empty_like, diag, diagflat, eye, linspace, meshgrid, indices, \
triu, t... | 0.703244 | 0.744633 |
import numpy as np
from Supervised.Classification.LogisticRegression import classify_logistic
def load_data():
"""
加载数据集
"""
with open('../../../Data/LogisticRegression/HorseColic/HorseColicTraining.txt', 'r') as f_train:
trian_data=f_train.readlines()
training_set = []
training_labels ... | Supervised/Classification/LogisticRegression/logistic_horsecolic.py | import numpy as np
from Supervised.Classification.LogisticRegression import classify_logistic
def load_data():
"""
加载数据集
"""
with open('../../../Data/LogisticRegression/HorseColic/HorseColicTraining.txt', 'r') as f_train:
trian_data=f_train.readlines()
training_set = []
training_labels ... | 0.31279 | 0.419529 |
from __future__ import annotations
import re
from enum import Enum
from epcpy.epc_schemes.base_scheme import EPCScheme, GS1Element, TagEncodable
from epcpy.utils.common import (
ConvertException,
binary_to_int,
decode_partition_table,
encode_partition_table,
parse_header_and_truncate_binary,
s... | epcpy/epc_schemes/cpi.py | from __future__ import annotations
import re
from enum import Enum
from epcpy.epc_schemes.base_scheme import EPCScheme, GS1Element, TagEncodable
from epcpy.utils.common import (
ConvertException,
binary_to_int,
decode_partition_table,
encode_partition_table,
parse_header_and_truncate_binary,
s... | 0.84572 | 0.291951 |
from bs4 import BeautifulSoup as Soup
from datasette.utils import allowed_pragmas
from .fixtures import ( # noqa
app_client,
app_client_base_url_prefix,
app_client_shorter_time_limit,
app_client_two_attached_databases,
app_client_with_hash,
make_app_client,
METADATA,
)
from .utils import as... | tests/test_html.py | from bs4 import BeautifulSoup as Soup
from datasette.utils import allowed_pragmas
from .fixtures import ( # noqa
app_client,
app_client_base_url_prefix,
app_client_shorter_time_limit,
app_client_two_attached_databases,
app_client_with_hash,
make_app_client,
METADATA,
)
from .utils import as... | 0.482185 | 0.287443 |
import json
import logging
import queue
import time
import schedule
from faucetconfgetsetter import FaucetLocalConfGetSetter
from faucetconfgetsetter import get_sdn_connect
from faucetconfgetsetter import get_test_config
from poseidon_core.constants import NO_DATA
from poseidon_core.controllers.sdnconnect import SDNCo... | tests/test_main.py | import json
import logging
import queue
import time
import schedule
from faucetconfgetsetter import FaucetLocalConfGetSetter
from faucetconfgetsetter import get_sdn_connect
from faucetconfgetsetter import get_test_config
from poseidon_core.constants import NO_DATA
from poseidon_core.controllers.sdnconnect import SDNCo... | 0.489015 | 0.152726 |
import sys
import os
import argparse
from qtpy.QtCore import QTimer
from qtpy import QtGui, QtWidgets
import glue
from glue.utils.qt import get_qapp
from glue.app.qt import GlueApplication
from glue.main import get_splash, load_data_files, load_plugins
try:
from glue.utils.qt.decorators import die_on_error
excep... | cubeviz/cubeviz.py | import sys
import os
import argparse
from qtpy.QtCore import QTimer
from qtpy import QtGui, QtWidgets
import glue
from glue.utils.qt import get_qapp
from glue.app.qt import GlueApplication
from glue.main import get_splash, load_data_files, load_plugins
try:
from glue.utils.qt.decorators import die_on_error
excep... | 0.433742 | 0.148571 |
from pyshorteners import Shortener
from commands.command import Command
from fbchat import Message
from fbchat import Mention
import datetime
import dateutil.parser
import pickle
import os
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.reque... | commands/events.py | from pyshorteners import Shortener
from commands.command import Command
from fbchat import Message
from fbchat import Mention
import datetime
import dateutil.parser
import pickle
import os
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.reque... | 0.373876 | 0.093554 |
import argparse
import json
import numpy as np
import os
import shutil
import time
import torch
from tqdm import tqdm
from flowmatch.eval.networks.vis import draw_images
from flowmatch import test as flow_test
from baselines.sift import test as sift_test
from flowmatch.datasets import load_dataset
from flowmatch.netw... | pipeline/eval/run_siftverify.py | import argparse
import json
import numpy as np
import os
import shutil
import time
import torch
from tqdm import tqdm
from flowmatch.eval.networks.vis import draw_images
from flowmatch import test as flow_test
from baselines.sift import test as sift_test
from flowmatch.datasets import load_dataset
from flowmatch.netw... | 0.471223 | 0.212518 |
from __future__ import absolute_import, division, print_function
import sys
import os
import pandas as pd
import gzip
import datashape
from datashape import Option, string
from collections import Iterator
from into.backends.csv import (CSV, append, convert, resource,
csv_to_DataFrame, CSV_to_chunks_of_datafra... | into/backends/tests/test_csv.py | from __future__ import absolute_import, division, print_function
import sys
import os
import pandas as pd
import gzip
import datashape
from datashape import Option, string
from collections import Iterator
from into.backends.csv import (CSV, append, convert, resource,
csv_to_DataFrame, CSV_to_chunks_of_datafra... | 0.395718 | 0.319055 |
import os
import unittest
from telemetry.core import cros_interface
from telemetry.core import util
from telemetry.internal.browser import browser_finder
from telemetry.internal.browser import extension_to_load
from telemetry.testing import options_for_unittests
import py_utils
class CrOSTestCase(unittest.TestCase... | telemetry/telemetry/internal/backends/chrome/cros_test_case.py |
import os
import unittest
from telemetry.core import cros_interface
from telemetry.core import util
from telemetry.internal.browser import browser_finder
from telemetry.internal.browser import extension_to_load
from telemetry.testing import options_for_unittests
import py_utils
class CrOSTestCase(unittest.TestCase... | 0.454714 | 0.141608 |
__all__ = ()
from .base import ChannelMetadataBase
from .guild_announcements import ChannelMetadataGuildAnnouncements
from .guild_category import ChannelMetadataGuildCategory
from .guild_directory import ChannelMetadataGuildDirectory
from .guild_forum import ChannelMetadataGuildForum
from .guild_stage import ChannelM... | hata/discord/channel/metadata/utils.py | __all__ = ()
from .base import ChannelMetadataBase
from .guild_announcements import ChannelMetadataGuildAnnouncements
from .guild_category import ChannelMetadataGuildCategory
from .guild_directory import ChannelMetadataGuildDirectory
from .guild_forum import ChannelMetadataGuildForum
from .guild_stage import ChannelM... | 0.616243 | 0.053527 |
import argparse
import csv
import itertools
import logging
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(logging.StreamHandler())
def generate_html(input_file_path, output_file_path=None, row=1):
with open(inp... | csv_to_html.py |
import argparse
import csv
import itertools
import logging
import os
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
LOGGER = logging.getLogger(__name__)
LOGGER.addHandler(logging.StreamHandler())
def generate_html(input_file_path, output_file_path=None, row=1):
with open(inp... | 0.274935 | 0.071754 |
from dagster import List, String, execute_pipeline, pipeline, solid
from repos.{{cookiecutter.dagster_repo}}.pipelines.{{cookiecutter.project_slug}}.modes import (
local,
dev,
prod,
)
from repos.{{cookiecutter.dagster_repo}}.pipelines.{{cookiecutter.project_slug}}.presets import PRESETS
from repos.{{cookiec... | {{ cookiecutter.project_slug }}/main.py | from dagster import List, String, execute_pipeline, pipeline, solid
from repos.{{cookiecutter.dagster_repo}}.pipelines.{{cookiecutter.project_slug}}.modes import (
local,
dev,
prod,
)
from repos.{{cookiecutter.dagster_repo}}.pipelines.{{cookiecutter.project_slug}}.presets import PRESETS
from repos.{{cookiec... | 0.296552 | 0.23601 |
import string
def get_position():
# inputs voor de stap posities
pos_1 = input("Startpositie : ")
pos_2 = input("Positie na de Zet : ")
# terug geven van de positie
return pos_1, pos_2
def calc_step(pos_1, pos_2):
# beide posities worden omgezet naar een array
pos_1 = list(pos_1)
po... | Week 1/opdracht_4.py | import string
def get_position():
# inputs voor de stap posities
pos_1 = input("Startpositie : ")
pos_2 = input("Positie na de Zet : ")
# terug geven van de positie
return pos_1, pos_2
def calc_step(pos_1, pos_2):
# beide posities worden omgezet naar een array
pos_1 = list(pos_1)
po... | 0.177526 | 0.670824 |
from . import BaseActor
class DiMPActor(BaseActor):
"""Actor for training the DiMP network."""
def __init__(self, net, objective, loss_weight=None):
super().__init__(net, objective)
if loss_weight is None:
loss_weight = {'iou': 1.0, 'test_clf': 1.0}
self.loss_weight = loss_... | lib/pytracking/ltr/actors/tracking.py | from . import BaseActor
class DiMPActor(BaseActor):
"""Actor for training the DiMP network."""
def __init__(self, net, objective, loss_weight=None):
super().__init__(net, objective)
if loss_weight is None:
loss_weight = {'iou': 1.0, 'test_clf': 1.0}
self.loss_weight = loss_... | 0.88856 | 0.395251 |
import warnings
import pytest
from astropy import units as u
from astropy.tests.helper import assert_quantity_allclose
from astropy.modeling.models import Mapping, Pix2Sky_TAN, Gaussian1D
from astropy.modeling import models
from astropy.modeling.core import _ModelMeta
def test_gaussian1d_bounding_box():
g = Ga... | astropy/modeling/tests/test_quantities_model.py | import warnings
import pytest
from astropy import units as u
from astropy.tests.helper import assert_quantity_allclose
from astropy.modeling.models import Mapping, Pix2Sky_TAN, Gaussian1D
from astropy.modeling import models
from astropy.modeling.core import _ModelMeta
def test_gaussian1d_bounding_box():
g = Ga... | 0.725843 | 0.524212 |
import requests
from flask_restful import Resource
from flask import (
request,
g,
render_template,
redirect,
request,
url_for,
flash,
current_app,
Response,
)
from datetime import datetime
from ..models import User, Permission, login_manager
from flask_jwt_extended import create_acc... | app/api/Auth.py | import requests
from flask_restful import Resource
from flask import (
request,
g,
render_template,
redirect,
request,
url_for,
flash,
current_app,
Response,
)
from datetime import datetime
from ..models import User, Permission, login_manager
from flask_jwt_extended import create_acc... | 0.487063 | 0.125333 |
import re
from setuptools import setup, find_packages
with open('base58check/__init__.py', 'rt') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
try:
from... | setup.py | import re
from setuptools import setup, find_packages
with open('base58check/__init__.py', 'rt') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
try:
from... | 0.409929 | 0.156201 |
import rogue.interfaces.memory
import pyrogue
import serial
import queue
import threading
class UartMemory(rogue.interfaces.memory.Slave):
def __init__(self, device, baud, timeout=1, **kwargs):
super().__init__(4,4096) # Set min and max size to 4 bytes
self._log = pyrogue.logInit(cls=self, name=f... | python/pyrogue/protocols/_uart.py |
import rogue.interfaces.memory
import pyrogue
import serial
import queue
import threading
class UartMemory(rogue.interfaces.memory.Slave):
def __init__(self, device, baud, timeout=1, **kwargs):
super().__init__(4,4096) # Set min and max size to 4 bytes
self._log = pyrogue.logInit(cls=self, name=f... | 0.461745 | 0.145692 |
import argparse
import json
import logging
from typing import Dict, Any
from allennlp.common import Params
from allennlp.common.util import prepare_environment
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.iterators import DataIterator
from allennlp.models.archival ... | LAUG/nlu/milu_new/evaluate.py | import argparse
import json
import logging
from typing import Dict, Any
from allennlp.common import Params
from allennlp.common.util import prepare_environment
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.iterators import DataIterator
from allennlp.models.archival ... | 0.783782 | 0.183082 |
import sys
import requests
import argparse
import logging
MODULE_NAME = "EOS-Voter RPC Test"
FORMAT = '%(asctime)-15s -- %(levelname)s -- %(message)s'
logging.basicConfig(format = FORMAT, level=logging.INFO)
#Here are RPC methods which shall be user at tests:
#status code: 200 OK
#http://192.168.4.208:8888/v1/chain... | tests/eos_voter_rpc_tests.py |
import sys
import requests
import argparse
import logging
MODULE_NAME = "EOS-Voter RPC Test"
FORMAT = '%(asctime)-15s -- %(levelname)s -- %(message)s'
logging.basicConfig(format = FORMAT, level=logging.INFO)
#Here are RPC methods which shall be user at tests:
#status code: 200 OK
#http://192.168.4.208:8888/v1/chain... | 0.292595 | 0.141578 |
import os
import six
import numpy
from chainerchem.dataset.indexers.numpy_tuple_dataset_feature_indexer import NumpyTupleDatasetFeatureIndexer # NOQA
class NumpyTupleDataset(object):
"""Dataset of a tuple of datasets.
It combines multiple datasets into one dataset. Each example is represented
by a tu... | chainerchem/datasets/numpy_tuple_dataset.py | import os
import six
import numpy
from chainerchem.dataset.indexers.numpy_tuple_dataset_feature_indexer import NumpyTupleDatasetFeatureIndexer # NOQA
class NumpyTupleDataset(object):
"""Dataset of a tuple of datasets.
It combines multiple datasets into one dataset. Each example is represented
by a tu... | 0.843477 | 0.61855 |
from enum import Enum
class Currency(str, Enum):
usd = "USD"
cad = "CAD"
gbp = "GBP"
eur = "EUR"
cop = "COP"
jpy = "JPY"
cny = "CNY"
aud = "AUD"
inr = "INR"
aed = "AED"
afn = "AFN"
all = "ALL"
amd = "AMD"
ang = "ANG"
aoa = "AOA"
ars = "ARS"
awg = "... | sdk/cognitiveservices/azure-cognitiveservices-search-visualsearch/azure/cognitiveservices/search/visualsearch/models/visual_search_client_enums.py |
from enum import Enum
class Currency(str, Enum):
usd = "USD"
cad = "CAD"
gbp = "GBP"
eur = "EUR"
cop = "COP"
jpy = "JPY"
cny = "CNY"
aud = "AUD"
inr = "INR"
aed = "AED"
afn = "AFN"
all = "ALL"
amd = "AMD"
ang = "ANG"
aoa = "AOA"
ars = "ARS"
awg = "... | 0.396419 | 0.109897 |
import re
import unittest
from unittest.mock import patch
from click.testing import CliRunner
from tests.util import read_data, DETERMINISTIC_HEADER, skip_if_exception
try:
import blackd
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web
except ImportError:
has_... | tests/test_blackd.py | import re
import unittest
from unittest.mock import patch
from click.testing import CliRunner
from tests.util import read_data, DETERMINISTIC_HEADER, skip_if_exception
try:
import blackd
from aiohttp.test_utils import AioHTTPTestCase, unittest_run_loop
from aiohttp import web
except ImportError:
has_... | 0.359701 | 0.40251 |
class SynErr(Exception):
def __init__(self, *args, **info):
self.errinfo = info
Exception.__init__(self, self._getExcMsg())
def _getExcMsg(self):
props = sorted(self.errinfo.items())
displ = ' '.join(['%s=%r' % (p, v) for (p, v) in props])
return '%s: %s' % (self.__clas... | synapse/exc.py | class SynErr(Exception):
def __init__(self, *args, **info):
self.errinfo = info
Exception.__init__(self, self._getExcMsg())
def _getExcMsg(self):
props = sorted(self.errinfo.items())
displ = ' '.join(['%s=%r' % (p, v) for (p, v) in props])
return '%s: %s' % (self.__clas... | 0.652352 | 0.105441 |
from peachpy import *
from peachpy.x86_64 import *
def add_offset(int_size, array, offset):
if int_size == 64:
SHL(offset, 3)
elif int_size == 32:
SHL(offset, 2)
ADD(array, offset)
return array
class MM:
gen_reg = [rax, rbx, rcx, rdx,
rsi, rdi, r8, r9,
... | peachpy/unpack.py | from peachpy import *
from peachpy.x86_64 import *
def add_offset(int_size, array, offset):
if int_size == 64:
SHL(offset, 3)
elif int_size == 32:
SHL(offset, 2)
ADD(array, offset)
return array
class MM:
gen_reg = [rax, rbx, rcx, rdx,
rsi, rdi, r8, r9,
... | 0.502197 | 0.266823 |
from annogesiclib.helper import Helper
from annogesiclib.gff3 import Gff3Parser
def get_feature(gene, file_type):
if "Name" in gene.attributes.keys():
feature = gene.attributes["Name"]
elif "locus_tag" in gene.attributes.keys():
feature = gene.attributes["locus_tag"]
else:
if file_... | annogesiclib/get_inter_seq.py | from annogesiclib.helper import Helper
from annogesiclib.gff3 import Gff3Parser
def get_feature(gene, file_type):
if "Name" in gene.attributes.keys():
feature = gene.attributes["Name"]
elif "locus_tag" in gene.attributes.keys():
feature = gene.attributes["locus_tag"]
else:
if file_... | 0.293 | 0.32744 |
import re
import time
import base64
import json
from environment import ctx
from command import Command
class Cluster(object):
def __init__(self):
self.cmd = Command()
self.deployment_template = '''
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: '{name}'
namespace: {namespace}
labe... | features/steps/cluster.py | import re
import time
import base64
import json
from environment import ctx
from command import Command
class Cluster(object):
def __init__(self):
self.cmd = Command()
self.deployment_template = '''
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: '{name}'
namespace: {namespace}
labe... | 0.352759 | 0.20203 |
import gym
import time
import numpy as np
import torch
import torch.nn as nn
from torch.optim import Adam
from torch.distributions import MultivariateNormal
from .base_alg import BasePolicyGradient
# torch.autograd.set_detect_anomaly(True)
class PPO(BasePolicyGradient):
"""
This is the PPO class we wil... | homework3/ppo/ppo.py | import gym
import time
import numpy as np
import torch
import torch.nn as nn
from torch.optim import Adam
from torch.distributions import MultivariateNormal
from .base_alg import BasePolicyGradient
# torch.autograd.set_detect_anomaly(True)
class PPO(BasePolicyGradient):
"""
This is the PPO class we wil... | 0.757525 | 0.60092 |
import os
import sys
import time
import logging
import numpy as np
import torch
from torch import nn
from torch.nn.utils import clip_grad_norm_
import torch.nn.init as init
import utils
import schedule
import metric
class Trainer(object):
def __init__ (self, model, config, tr_loader, cv_loader):
self.conf... | src/trainer.py | import os
import sys
import time
import logging
import numpy as np
import torch
from torch import nn
from torch.nn.utils import clip_grad_norm_
import torch.nn.init as init
import utils
import schedule
import metric
class Trainer(object):
def __init__ (self, model, config, tr_loader, cv_loader):
self.conf... | 0.488527 | 0.159087 |
import os
import json
import torch
import numpy as np
from torch.utils.data import Dataset
import random
def uniform_sample(input_feature, sample_len):
input_len = input_feature.shape[0]
assert sample_len > 0, "WRONG SAMPLE_LEN {}, THIS PARAM MUST BE GREATER THAN 0.".format(sample_len)
if sam... | dataset/dataset_class.py | import os
import json
import torch
import numpy as np
from torch.utils.data import Dataset
import random
def uniform_sample(input_feature, sample_len):
input_len = input_feature.shape[0]
assert sample_len > 0, "WRONG SAMPLE_LEN {}, THIS PARAM MUST BE GREATER THAN 0.".format(sample_len)
if sam... | 0.467575 | 0.168446 |
from __future__ import absolute_import, unicode_literals
import pytest
from case import Mock
from celery.utils import debug
def test_on_blocking(patching):
getframeinfo = patching('inspect.getframeinfo')
frame = Mock(name='frame')
with pytest.raises(RuntimeError):
debug._on_blocking(1, frame)
... | desktop/core/ext-py/celery-4.2.1/t/unit/utils/test_debug.py | from __future__ import absolute_import, unicode_literals
import pytest
from case import Mock
from celery.utils import debug
def test_on_blocking(patching):
getframeinfo = patching('inspect.getframeinfo')
frame = Mock(name='frame')
with pytest.raises(RuntimeError):
debug._on_blocking(1, frame)
... | 0.511473 | 0.387372 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
l2 = tf.keras.regularizers.l2
class ConvBlock(tf.keras.Model):
"""Convolutional Block consisting of (batchnorm->relu->conv).
Arguments:
num_filters: number of filters passed t... | sourceCode/image2sky/densenet.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
l2 = tf.keras.regularizers.l2
class ConvBlock(tf.keras.Model):
"""Convolutional Block consisting of (batchnorm->relu->conv).
Arguments:
num_filters: number of filters passed t... | 0.946547 | 0.461866 |
import typing
from ucloud.core.client import Client
from ucloud.services.ugn.schemas import apis
class UGNClient(Client):
def __init__(
self, config: dict, transport=None, middleware=None, logger=None
):
super(UGNClient, self).__init__(config, transport, middleware, logger)
def attach_... | ucloud/services/ugn/client.py |
import typing
from ucloud.core.client import Client
from ucloud.services.ugn.schemas import apis
class UGNClient(Client):
def __init__(
self, config: dict, transport=None, middleware=None, logger=None
):
super(UGNClient, self).__init__(config, transport, middleware, logger)
def attach_... | 0.528777 | 0.11221 |
from .latchresponse import LatchResponse
import logging
import time
class LatchAuth(object):
API_VERSION = "1.0"
API_HOST = "latch.elevenpaths.com"
API_PORT = 443
API_HTTPS = True
API_PROXY = None
API_PROXY_PORT = None
API_CHECK_STATUS_URL = "/api/" + API_VERSION + "/status"
API_PAIR_U... | latch/latch_sdk_python/latchauth.py | from .latchresponse import LatchResponse
import logging
import time
class LatchAuth(object):
API_VERSION = "1.0"
API_HOST = "latch.elevenpaths.com"
API_PORT = 443
API_HTTPS = True
API_PROXY = None
API_PROXY_PORT = None
API_CHECK_STATUS_URL = "/api/" + API_VERSION + "/status"
API_PAIR_U... | 0.572484 | 0.052741 |
"""Tests for tensorflow.ops.one_hot_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
class OneHotTest(tf.test.TestCase):
def _testOneHot(self, truth, use_gpu=False, expected_err_re=None,
... | tensorflow/python/kernel_tests/one_hot_op_test.py |
"""Tests for tensorflow.ops.one_hot_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
class OneHotTest(tf.test.TestCase):
def _testOneHot(self, truth, use_gpu=False, expected_err_re=None,
... | 0.866655 | 0.576244 |
import numpy as np
import torch
from absl.testing import absltest
from dlrm.cuda_ext import dotBasedInteract
DECIMAL_MATRIX = 0
DECIMAL_LINEAR = 0
MAX_INT_VALUE = 1024 # clip integers larger than `MAX_INT_VALUE` (used in debugging only).
SEED = 12345
SCALE = 1 # Scale the random numbers to check different ranges.
P... | NVIDIA/benchmarks/dlrm/implementations/pytorch/tests/dot_based_interact.py | import numpy as np
import torch
from absl.testing import absltest
from dlrm.cuda_ext import dotBasedInteract
DECIMAL_MATRIX = 0
DECIMAL_LINEAR = 0
MAX_INT_VALUE = 1024 # clip integers larger than `MAX_INT_VALUE` (used in debugging only).
SEED = 12345
SCALE = 1 # Scale the random numbers to check different ranges.
P... | 0.754915 | 0.562237 |
import unittest
from pathlib import Path
# project
from src.flax_log.parsers import harvester_activity_parser
class TestHarvesterActivityParser(unittest.TestCase):
def setUp(self) -> None:
self.parser = harvester_activity_parser.HarvesterActivityParser()
self.example_logs_path = Path(__file__).re... | tests/chia_log/parsers/test_harvester_activity_parser.py | import unittest
from pathlib import Path
# project
from src.flax_log.parsers import harvester_activity_parser
class TestHarvesterActivityParser(unittest.TestCase):
def setUp(self) -> None:
self.parser = harvester_activity_parser.HarvesterActivityParser()
self.example_logs_path = Path(__file__).re... | 0.63273 | 0.451871 |
import os
import warnings
from typing import Dict
import torch
import torch.nn as nn
import torch.optim as optim
from kdtools.datasets import (
BILUOVSentencesDS,
DependencyTreeDS,
FocusOnEntityDS,
SelectedDS,
from_biluov,
match_tokens_to_entities,
to_biluov,
)
from kdtools.encoders import ... | src/ehealth20.py | import os
import warnings
from typing import Dict
import torch
import torch.nn as nn
import torch.optim as optim
from kdtools.datasets import (
BILUOVSentencesDS,
DependencyTreeDS,
FocusOnEntityDS,
SelectedDS,
from_biluov,
match_tokens_to_entities,
to_biluov,
)
from kdtools.encoders import ... | 0.732209 | 0.274946 |
from Tkinter import *
from Canvas import Line, Rectangle
import random
XGRID = 10
YGRID = 10
WIDTH = 6
class Array:
def __init__(self, master, data=None):
self.master = master
self.frame = Frame(self.master)
self.frame.pack(fill=X)
self.label = Label(self.frame)
self.lab... | Demo/tkinter/guido/sortvisu.py | from Tkinter import *
from Canvas import Line, Rectangle
import random
XGRID = 10
YGRID = 10
WIDTH = 6
class Array:
def __init__(self, master, data=None):
self.master = master
self.frame = Frame(self.master)
self.frame.pack(fill=X)
self.label = Label(self.frame)
self.lab... | 0.474875 | 0.302146 |
from tests import unittest
from aliyunsdkcore.endpoint.local_config_regional_endpoint_resolver \
import LocalConfigRegionalEndpointResolver
from aliyunsdkcore.endpoint.resolver_endpoint_request import ResolveEndpointRequest
class TestLocalConfigRegionalEndpointResolver(unittest.TestCase):
def test_resolver(... | aliyun-python-sdk-core/tests/endpoint/test_local_config_regional_endpoint_resolver.py |
from tests import unittest
from aliyunsdkcore.endpoint.local_config_regional_endpoint_resolver \
import LocalConfigRegionalEndpointResolver
from aliyunsdkcore.endpoint.resolver_endpoint_request import ResolveEndpointRequest
class TestLocalConfigRegionalEndpointResolver(unittest.TestCase):
def test_resolver(... | 0.486088 | 0.22762 |
import typer
from ChristisMongo.table.get import *
import os , json
from tabulate import tabulate
from typing import Optional
app = typer.Typer()
@app.command()
def stage(verbose: int = typer.Option(0,"--verbose","-v",count=True),
all: bool = typer.Option(False, "--all"),
jsson: Optional[bool] = t... | christis/cmd_database/view.py | import typer
from ChristisMongo.table.get import *
import os , json
from tabulate import tabulate
from typing import Optional
app = typer.Typer()
@app.command()
def stage(verbose: int = typer.Option(0,"--verbose","-v",count=True),
all: bool = typer.Option(False, "--all"),
jsson: Optional[bool] = t... | 0.384219 | 0.111096 |
from django.contrib.auth import get_user_model
from django.http import HttpResponseBadRequest
from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from surfcar.questions.models import Question, Answer
class TestViews(TestCase):
"""
Includes tests for all the functionality
... | surfcar/questions/tests/test_views.py | from django.contrib.auth import get_user_model
from django.http import HttpResponseBadRequest
from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from surfcar.questions.models import Question, Answer
class TestViews(TestCase):
"""
Includes tests for all the functionality
... | 0.566498 | 0.280955 |
import logging
import subprocess
import tempfile
from aladdin.config import load_git_configs
from aladdin.lib.docker import DockerCommands, Tag
from aladdin.lib.git import Git
from aladdin.lib.k8s.helm import Helm
from aladdin.lib.utils import working_directory
from aladdin.lib.project_conf import ProjectConf
from ala... | aladdin/commands/publish.py | import logging
import subprocess
import tempfile
from aladdin.config import load_git_configs
from aladdin.lib.docker import DockerCommands, Tag
from aladdin.lib.git import Git
from aladdin.lib.k8s.helm import Helm
from aladdin.lib.utils import working_directory
from aladdin.lib.project_conf import ProjectConf
from ala... | 0.31342 | 0.109182 |
import os
import sys
import re
import shutil
import subprocess
import datetime
import pprint
def camel_to_snake(name, delim='_'):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1{0}\2'.format(delim), name)
return re.sub('([a-z0-9])([A-Z])', r'\1{0}\2'.format(delim), s1).lower()
def snake_to_camel(name, delim='_'):
r... | bsm/util/__init__.py | import os
import sys
import re
import shutil
import subprocess
import datetime
import pprint
def camel_to_snake(name, delim='_'):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1{0}\2'.format(delim), name)
return re.sub('([a-z0-9])([A-Z])', r'\1{0}\2'.format(delim), s1).lower()
def snake_to_camel(name, delim='_'):
r... | 0.168788 | 0.082697 |
import pickle
import unittest
import numpy as np
import numpy.testing as npt
import pandas as pd
import pytest
import theano
import theano.tensor as tt
import pymc3 as pm
from pymc3 import Deterministic, Potential
from pymc3.distributions import HalfCauchy, Normal, transforms
from pymc3.model import ValueGradFuncti... | pymc3/tests/test_model.py |
import pickle
import unittest
import numpy as np
import numpy.testing as npt
import pandas as pd
import pytest
import theano
import theano.tensor as tt
import pymc3 as pm
from pymc3 import Deterministic, Potential
from pymc3.distributions import HalfCauchy, Normal, transforms
from pymc3.model import ValueGradFuncti... | 0.674372 | 0.599485 |
def combustivel():
tipo = int(input('''MENU
[0] CONFIGURAR
[1] ETANOL
[2] GASOLINA
Digite aqui: '''))
return tipo
def valor_combustivel(tipo, valor_atualizado=0):
lista = [1, 5.4, 2, 6.98]
if valor_atualizado != 0:
if tipo == 1:
lista[1] = valor_atualizado
... | ExerciciosPython/Ex- Classes/Bomba de combustivel.py | def combustivel():
tipo = int(input('''MENU
[0] CONFIGURAR
[1] ETANOL
[2] GASOLINA
Digite aqui: '''))
return tipo
def valor_combustivel(tipo, valor_atualizado=0):
lista = [1, 5.4, 2, 6.98]
if valor_atualizado != 0:
if tipo == 1:
lista[1] = valor_atualizado
... | 0.351979 | 0.499146 |
import pytest
from cuml import LinearRegression as cuLinearRegression
from cuml import Ridge as cuRidge
from sklearn.linear_model import LinearRegression as skLinearRegression
from sklearn.linear_model import Ridge as skRidge
from utils import array_equal
import cudf
import numpy as np
@pytest.mark.parametrize('datat... | python/cuML/test/test_linear_model.py |
import pytest
from cuml import LinearRegression as cuLinearRegression
from cuml import Ridge as cuRidge
from sklearn.linear_model import LinearRegression as skLinearRegression
from sklearn.linear_model import Ridge as skRidge
from utils import array_equal
import cudf
import numpy as np
@pytest.mark.parametrize('datat... | 0.501953 | 0.832543 |
import pytest
import numpy as np
import sparse
from sparse import DOK
from sparse._utils import assert_eq
@pytest.mark.parametrize("shape", [(2,), (2, 3), (2, 3, 4)])
@pytest.mark.parametrize("density", [0.1, 0.3, 0.5, 0.7])
def test_random_shape_nnz(shape, density):
s = sparse.random(shape, density, format="do... | sparse/tests/test_dok.py | import pytest
import numpy as np
import sparse
from sparse import DOK
from sparse._utils import assert_eq
@pytest.mark.parametrize("shape", [(2,), (2, 3), (2, 3, 4)])
@pytest.mark.parametrize("density", [0.1, 0.3, 0.5, 0.7])
def test_random_shape_nnz(shape, density):
s = sparse.random(shape, density, format="do... | 0.785267 | 0.823009 |
from typing import Any
import collections
# Задача 1. Найти количество различных элементов массива. Пример: для [1 4 5 1 1 3] ответ 4.
def count_unique_elems(arr) -> int:
arr_new = [arr[0]]
for i in range(len(arr)):
if arr[i] in arr_new:
pass
else:
arr_new.append(arr[i]... | main.py | from typing import Any
import collections
# Задача 1. Найти количество различных элементов массива. Пример: для [1 4 5 1 1 3] ответ 4.
def count_unique_elems(arr) -> int:
arr_new = [arr[0]]
for i in range(len(arr)):
if arr[i] in arr_new:
pass
else:
arr_new.append(arr[i]... | 0.273186 | 0.485051 |
import collections
import concurrent.futures
import datetime
import json
import os
import subprocess
import sys
from functools import wraps
from pathlib import Path
from threading import Thread
from time import time
import click
from click import BadParameter
from tqdm import tqdm
from syndicate.commons.log_helper im... | syndicate/core/helper.py | import collections
import concurrent.futures
import datetime
import json
import os
import subprocess
import sys
from functools import wraps
from pathlib import Path
from threading import Thread
from time import time
import click
from click import BadParameter
from tqdm import tqdm
from syndicate.commons.log_helper im... | 0.371593 | 0.09236 |
import sys
import irc.bot
import requests
class TwitchBot(irc.bot.SingleServerIRCBot):
def __init__(self, username, client_id, token, channel):
self.client_id = client_id
self.token = token
self.channel = '#' + channel
# Get the channel id, we will need this for v5 API calls
... | chatbot.py | import sys
import irc.bot
import requests
class TwitchBot(irc.bot.SingleServerIRCBot):
def __init__(self, username, client_id, token, channel):
self.client_id = client_id
self.token = token
self.channel = '#' + channel
# Get the channel id, we will need this for v5 API calls
... | 0.294519 | 0.086401 |
# Classes which wrap one Widget.
# Wrapper: a base class for Widgets which contain one other Widget.
# Frame: positions its contained Widget within a graphic, which it stretches
# to cover the Widget's area, or the space within which it is contained.
# TitleFrame: like Frame, but has a title region on to... | libs/kytten/frame.py |
# Classes which wrap one Widget.
# Wrapper: a base class for Widgets which contain one other Widget.
# Frame: positions its contained Widget within a graphic, which it stretches
# to cover the Widget's area, or the space within which it is contained.
# TitleFrame: like Frame, but has a title region on to... | 0.777553 | 0.245328 |
import json
import re
import scrapy
from locations.items import GeojsonPointItem
SCRIPT_JSON = 'normalize-space(//script[@type="application/ld+json"]/text())'
PHONE = 'normalize-space(//span[@class="telephone-text bold"]//text())'
class SpiritHalloween(scrapy.Spider):
name = 'spirit-halloween'
download_de... | locations/spiders/spirithalloween.py | import json
import re
import scrapy
from locations.items import GeojsonPointItem
SCRIPT_JSON = 'normalize-space(//script[@type="application/ld+json"]/text())'
PHONE = 'normalize-space(//span[@class="telephone-text bold"]//text())'
class SpiritHalloween(scrapy.Spider):
name = 'spirit-halloween'
download_de... | 0.402392 | 0.133783 |
import requests, random, string
from enum import Enum
HANGMAN_ART = [
"""
------
| |
|
|
|
|
|
|
|
----------
""", """
------
| |
| O
|
|
|
|
|
|
----------
""", """
------
| |
| O
| -+-
|
|
|
|
|
----------
""", """
------
| |
| O
| \-+-
|
|... | hang_man.py | import requests, random, string
from enum import Enum
HANGMAN_ART = [
"""
------
| |
|
|
|
|
|
|
|
----------
""", """
------
| |
| O
|
|
|
|
|
|
----------
""", """
------
| |
| O
| -+-
|
|
|
|
|
----------
""", """
------
| |
| O
| \-+-
|
|... | 0.482185 | 0.257797 |
from .charts_options import (
BarItem,
BarBackgroundStyleOpts,
BMapCopyrightTypeOpts,
BMapGeoLocationControlOpts,
BMapNavigationControlOpts,
BMapOverviewMapControlOpts,
BMapScaleControlOpts,
BMapTypeControlOpts,
BoxplotItem,
CandleStickItem,
ComponentTitleOpts,
... | pyecharts/options/__init__.py |
from .charts_options import (
BarItem,
BarBackgroundStyleOpts,
BMapCopyrightTypeOpts,
BMapGeoLocationControlOpts,
BMapNavigationControlOpts,
BMapOverviewMapControlOpts,
BMapScaleControlOpts,
BMapTypeControlOpts,
BoxplotItem,
CandleStickItem,
ComponentTitleOpts,
... | 0.433502 | 0.078148 |
from unittest import TestCase
# Third party
from peewee import SqliteDatabase
from peewee import Model
from peewee import CharField
# Local imports
from rewardify.rarity import Rarity
from rewardify.probability import RarityProbability
from rewardify.probability import ProbabilityField
class TestRarityProbability(... | tests/test_probability.py | from unittest import TestCase
# Third party
from peewee import SqliteDatabase
from peewee import Model
from peewee import CharField
# Local imports
from rewardify.rarity import Rarity
from rewardify.probability import RarityProbability
from rewardify.probability import ProbabilityField
class TestRarityProbability(... | 0.790247 | 0.624007 |
import os
import pytest
from bless.aws_lambda.bless_lambda import lambda_handler
from tests.ssh.vectors import EXAMPLE_RSA_PUBLIC_KEY, RSA_CA_PRIVATE_KEY_PASSWORD, \
EXAMPLE_ED25519_PUBLIC_KEY
class Context(object):
aws_request_id = 'bogus aws_request_id'
invoked_function_arn = 'bogus invoked_function_a... | tests/aws_lambda/test_bless_lambda.py | import os
import pytest
from bless.aws_lambda.bless_lambda import lambda_handler
from tests.ssh.vectors import EXAMPLE_RSA_PUBLIC_KEY, RSA_CA_PRIVATE_KEY_PASSWORD, \
EXAMPLE_ED25519_PUBLIC_KEY
class Context(object):
aws_request_id = 'bogus aws_request_id'
invoked_function_arn = 'bogus invoked_function_a... | 0.348756 | 0.224629 |
import time
import subprocess
import commands
import re
import sys
import pexpect
import random
from common.OpTestConstants import OpTestConstants as BMC_CONST
from common.OpTestError import OpTestError
import unittest
import OpTestConfiguration
from common.OpTestSystem import OpSystemState
import logging
import OpT... | testcases/EPOW.py | import time
import subprocess
import commands
import re
import sys
import pexpect
import random
from common.OpTestConstants import OpTestConstants as BMC_CONST
from common.OpTestError import OpTestError
import unittest
import OpTestConfiguration
from common.OpTestSystem import OpSystemState
import logging
import OpT... | 0.194062 | 0.135919 |
import json
import logging
from typing import List
from absl import logging
import tensorflow as tf
from uncertainty_baselines.models import criteo_mlp
from uncertainty_baselines.models import efficientnet
from uncertainty_baselines.models import efficientnet_batch_ensemble
from uncertainty_baselines.models import ge... | uncertainty_baselines/models/models.py | import json
import logging
from typing import List
from absl import logging
import tensorflow as tf
from uncertainty_baselines.models import criteo_mlp
from uncertainty_baselines.models import efficientnet
from uncertainty_baselines.models import efficientnet_batch_ensemble
from uncertainty_baselines.models import ge... | 0.763484 | 0.197773 |
import logging
import time
class NoopService(object):
"""
Noop Model handler implementation.
Extend from BaseModelHandler is optional
"""
def __init__(self):
self._context = None
self.initialized = False
def initialize(self, context):
"""
Initialize model. Th... | frontend/modelarchive/src/test/resources/models/noop-no-manifest/service.py | import logging
import time
class NoopService(object):
"""
Noop Model handler implementation.
Extend from BaseModelHandler is optional
"""
def __init__(self):
self._context = None
self.initialized = False
def initialize(self, context):
"""
Initialize model. Th... | 0.723407 | 0.339855 |
from pixelsort import pixelsort
from PIL import Image
from pathlib import Path
from time import sleep
from multiprocessing import Process, freeze_support
def main_prog():
f_images = "images"
i = "squirrel.jpg"
#i = "DSC04688_EDIT_1000.jpg"
p = Path()
image_p_in = p / f_images / i
mask_user_s... | Prototyping Code/test.py | from pixelsort import pixelsort
from PIL import Image
from pathlib import Path
from time import sleep
from multiprocessing import Process, freeze_support
def main_prog():
f_images = "images"
i = "squirrel.jpg"
#i = "DSC04688_EDIT_1000.jpg"
p = Path()
image_p_in = p / f_images / i
mask_user_s... | 0.291384 | 0.187263 |
from easydict import EasyDict
from typing import List, Dict, Tuple, Optional
import numpy as np
import torch
import torch.nn as nn
from visualDet3D.networks.utils.utils import calc_iou
from visualDet3D.utils.timer import profile
class SigmoidFocalLoss(nn.Module):
def __init__(self, gamma=0.0, balance_weights=torc... | visualDet3D/networks/heads/losses.py | from easydict import EasyDict
from typing import List, Dict, Tuple, Optional
import numpy as np
import torch
import torch.nn as nn
from visualDet3D.networks.utils.utils import calc_iou
from visualDet3D.utils.timer import profile
class SigmoidFocalLoss(nn.Module):
def __init__(self, gamma=0.0, balance_weights=torc... | 0.967549 | 0.710333 |
from sage.categories.fields import Fields
_Fields = Fields()
def row_iterator(A):
for i in range(A.nrows()):
yield A.row(i)
def prm_mul(p1, p2, mask_free, prec):
"""
Return the product of ``p1`` and ``p2``, putting free variables in
``mask_free`` to `1`.
This function is mainly use as ... | src/sage/matrix/matrix_misc.py |
from sage.categories.fields import Fields
_Fields = Fields()
def row_iterator(A):
for i in range(A.nrows()):
yield A.row(i)
def prm_mul(p1, p2, mask_free, prec):
"""
Return the product of ``p1`` and ``p2``, putting free variables in
``mask_free`` to `1`.
This function is mainly use as ... | 0.87804 | 0.746624 |
from unittest import TestCase
import json
from tornado_stub_client import stub, reset
from tornado_stub_client.collection import RequestCollection
class CommandsTest(TestCase):
""" the stub() command is actually a class who's initializer returns
itself, so we can do stub().and_return() in a ruby rspec mock fa... | tests/test_commands.py | from unittest import TestCase
import json
from tornado_stub_client import stub, reset
from tornado_stub_client.collection import RequestCollection
class CommandsTest(TestCase):
""" the stub() command is actually a class who's initializer returns
itself, so we can do stub().and_return() in a ruby rspec mock fa... | 0.685529 | 0.343782 |
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.utils import plugin_docs
from ansible.plugins.loader import fragment_loader
except ImportError:
# Ignored for the unit tests
pass
from fnmatch import fnmatch
from builtins import map
from six import iteritems
import os
import yaml
i... | build-doc/ansible_module_documentation.py | from ansible.module_utils.basic import AnsibleModule
try:
from ansible.utils import plugin_docs
from ansible.plugins.loader import fragment_loader
except ImportError:
# Ignored for the unit tests
pass
from fnmatch import fnmatch
from builtins import map
from six import iteritems
import os
import yaml
i... | 0.664758 | 0.394726 |
import os
import pytest
from clade import Clade
from clade.cmds import iter_cmds, iter_cmds_by_which
from clade.envs import iter_envs
from tests.test_intercept import test_project_make, calculate_loc
from tests.test_functions import funcs_are_ok, funcs_by_file_are_ok, funcs_are_consistent, filtered_funcs_by_file_are... | tests/test_interface.py |
import os
import pytest
from clade import Clade
from clade.cmds import iter_cmds, iter_cmds_by_which
from clade.envs import iter_envs
from tests.test_intercept import test_project_make, calculate_loc
from tests.test_functions import funcs_are_ok, funcs_by_file_are_ok, funcs_are_consistent, filtered_funcs_by_file_are... | 0.458591 | 0.439807 |
import inspect
# code from https://github.com/hartikainen/serializable/blob/master/serializable/serializable.py
class Serializable(object):
def __initialize(self, locals_):
if getattr(self, "_Serializable__initialized", False):
return
signature = inspect.signature(self.__init__)
... | malib/core/serializable.py | import inspect
# code from https://github.com/hartikainen/serializable/blob/master/serializable/serializable.py
class Serializable(object):
def __initialize(self, locals_):
if getattr(self, "_Serializable__initialized", False):
return
signature = inspect.signature(self.__init__)
... | 0.766905 | 0.238406 |
def recipeland_com(page, recipe):
try:
recipe['datePublished'] = page.xpath(
'//span[@itemprop="datePublished"]')[0].text_content().strip()
except:
pass
try:
recipe['isBasedOnUrl'] = page.xpath(
'//link[@rel="canonical"]')[0].attrib['href'].strip()
... | src/extractors/recipeland.py | def recipeland_com(page, recipe):
try:
recipe['datePublished'] = page.xpath(
'//span[@itemprop="datePublished"]')[0].text_content().strip()
except:
pass
try:
recipe['isBasedOnUrl'] = page.xpath(
'//link[@rel="canonical"]')[0].attrib['href'].strip()
... | 0.19475 | 0.101679 |