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 os from unittest import mock import pytest from django.conf import settings from django.test import TestCase from metaci.build.management.commands.run_build import Command from metaci.build.models import Build from metaci.conftest import ( BranchFactory, OrgFactory, PlanFactory, PlanRepositoryF...
metaci/build/management/commands/tests/test_run_build.py
import os from unittest import mock import pytest from django.conf import settings from django.test import TestCase from metaci.build.management.commands.run_build import Command from metaci.build.models import Build from metaci.conftest import ( BranchFactory, OrgFactory, PlanFactory, PlanRepositoryF...
0.49585
0.240842
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, ValidationError from wtforms.validators import EqualTo, DataRequired, Email from flask_wtf.file import FileAllowed, FileField from main_app.models import User class LoginForm(FlaskForm): email = StringField('Email', val...
main_app/users/form.py
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, ValidationError from wtforms.validators import EqualTo, DataRequired, Email from flask_wtf.file import FileAllowed, FileField from main_app.models import User class LoginForm(FlaskForm): email = StringField('Email', val...
0.415847
0.132739
import pytest from pymysql.constants.ER import CONSTRAINT_FAILED, LOCK_WAIT_TIMEOUT, LOCK_DEADLOCK from pymysql.err import InternalError, MySQLError, OperationalError from sqlalchemy.exc import InterfaceError, StatementError from ichnaea.db import retry_on_mysql_lock_fail class TestDatabase: def test_constructo...
ichnaea/tests/test_db.py
import pytest from pymysql.constants.ER import CONSTRAINT_FAILED, LOCK_WAIT_TIMEOUT, LOCK_DEADLOCK from pymysql.err import InternalError, MySQLError, OperationalError from sqlalchemy.exc import InterfaceError, StatementError from ichnaea.db import retry_on_mysql_lock_fail class TestDatabase: def test_constructo...
0.607663
0.338405
import copy import json import pytest from web3 import Web3 from web3.providers.eth_tester import EthereumTesterProvider from ethpm import V2_PACKAGES_DIR from ethpm.utils.chains import ( get_chain_id, create_block_uri, ) PACKAGE_NAMES = [ 'escrow', 'owned', 'piper-coin', 'safe-math-lib', ...
tests/conftest.py
import copy import json import pytest from web3 import Web3 from web3.providers.eth_tester import EthereumTesterProvider from ethpm import V2_PACKAGES_DIR from ethpm.utils.chains import ( get_chain_id, create_block_uri, ) PACKAGE_NAMES = [ 'escrow', 'owned', 'piper-coin', 'safe-math-lib', ...
0.341253
0.234259
# VOC dataset utility functions import numpy as np VOC_CLASSES_LIST = [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', ...
utils/voc.py
# VOC dataset utility functions import numpy as np VOC_CLASSES_LIST = [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', ...
0.873862
0.576304
import logging from dynaconf import settings from tabulate import tabulate from talkative_client.commands import AbstractCommand, main_commands from talkative_client.db import User, UserHistory, Chat, Messages from talkative_client.jim_mes import Message logger = logging.getLogger('client__message') class MessageC...
talkative_client/talkative_client/message/commands.py
import logging from dynaconf import settings from tabulate import tabulate from talkative_client.commands import AbstractCommand, main_commands from talkative_client.db import User, UserHistory, Chat, Messages from talkative_client.jim_mes import Message logger = logging.getLogger('client__message') class MessageC...
0.341692
0.095307
import slug_preview.models from django.conf import settings from django.db import migrations, models import fluent_blogs.appsettings import fluent_blogs.base_models def make_site(apps, schema_editor): Site = apps.get_model("sites", "Site") if Site.objects.count() == 0: site = Site() site.pk =...
fluent_blogs/migrations/0001_initial.py
import slug_preview.models from django.conf import settings from django.db import migrations, models import fluent_blogs.appsettings import fluent_blogs.base_models def make_site(apps, schema_editor): Site = apps.get_model("sites", "Site") if Site.objects.count() == 0: site = Site() site.pk =...
0.427994
0.186984
import time import pkgutil import json import ssl import asyncio import websockets import time from web3.auto import w3 from eth_account.messages import encode_defunct from web3 import Web3 class WsAPI: def __init__(self, endpoint="wss://api.dex.blue/ws/v1", network="mainnet", web3Provider="https://mainnet.infura...
dexblue/dexblue.py
import time import pkgutil import json import ssl import asyncio import websockets import time from web3.auto import w3 from eth_account.messages import encode_defunct from web3 import Web3 class WsAPI: def __init__(self, endpoint="wss://api.dex.blue/ws/v1", network="mainnet", web3Provider="https://mainnet.infura...
0.370112
0.072637
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from PyTorchDisentanglement.models.base import BaseModel import PyTorchDisentanglement.models.model_loader as ml class Ensemble(BaseModel): def setup_model(self): self.models = [] for model_idx, params in enumera...
models/ensemble.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from PyTorchDisentanglement.models.base import BaseModel import PyTorchDisentanglement.models.model_loader as ml class Ensemble(BaseModel): def setup_model(self): self.models = [] for model_idx, params in enumera...
0.642208
0.310681
import ast from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from flask import current_app, g session_manager = None def get_db(): """Connect to the configured database. The connection is unique for each request and will be reused if this is c...
discovery-provider/src/utils/db_session.py
import ast from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from flask import current_app, g session_manager = None def get_db(): """Connect to the configured database. The connection is unique for each request and will be reused if this is c...
0.6137
0.054249
def get_counter_name(mode,tg_type,comp_type,direction): from spytest.tgen import tgen_utils return tgen_utils.get_counter_name(mode,tg_type,comp_type,direction) def validate_tgen_traffic(**kwargs): from spytest.tgen import tgen_utils return tgen_utils.validate_tgen_traffic(**kwargs) def validate_packet_...
spytest/spytest/tgen_api.py
def get_counter_name(mode,tg_type,comp_type,direction): from spytest.tgen import tgen_utils return tgen_utils.get_counter_name(mode,tg_type,comp_type,direction) def validate_tgen_traffic(**kwargs): from spytest.tgen import tgen_utils return tgen_utils.validate_tgen_traffic(**kwargs) def validate_packet_...
0.542863
0.236351
# # GAN으로 새로운 패션아이템 생성하기 # *GAN을 이용하여 새로운 패션 아이템을 만들어봅니다* # 이 프로젝트는 최윤제님의 파이토치 튜토리얼 사용 허락을 받아 참고했습니다. # * [yunjey/pytorch-tutorial](https://github.com/yunjey/pytorch-tutorial) - MIT License import os import torch import torchvision import torch.nn as nn import torch.optim as optim from torchvision import transforms, ...
09-경쟁하며_학습하는_GAN/gan.py
# # GAN으로 새로운 패션아이템 생성하기 # *GAN을 이용하여 새로운 패션 아이템을 만들어봅니다* # 이 프로젝트는 최윤제님의 파이토치 튜토리얼 사용 허락을 받아 참고했습니다. # * [yunjey/pytorch-tutorial](https://github.com/yunjey/pytorch-tutorial) - MIT License import os import torch import torchvision import torch.nn as nn import torch.optim as optim from torchvision import transforms, ...
0.68458
0.756335
import asyncio from datetime import datetime import logging from unittest.mock import Mock, patch import pytest from aiohttp.client_exceptions import ClientError, WSServerHandshakeError from aiohttp.client_reqrep import ClientResponse, RequestInfo from aiohttp.http_websocket import WSMsgType from zwave_js_server.clie...
test/test_client.py
import asyncio from datetime import datetime import logging from unittest.mock import Mock, patch import pytest from aiohttp.client_exceptions import ClientError, WSServerHandshakeError from aiohttp.client_reqrep import ClientResponse, RequestInfo from aiohttp.http_websocket import WSMsgType from zwave_js_server.clie...
0.712432
0.247203
from manim import * from typing import Iterable from colour import Color class Mandelbrot(PGroup): def __init__( self, length: float = 7, max_steps: int = 25, threshold: float = 4, color_scheme: Iterable[Color] = [BLACK, GREEN, BLACK], stroke...
mandelbrot/mandelbrot.py
from manim import * from typing import Iterable from colour import Color class Mandelbrot(PGroup): def __init__( self, length: float = 7, max_steps: int = 25, threshold: float = 4, color_scheme: Iterable[Color] = [BLACK, GREEN, BLACK], stroke...
0.845544
0.310342
import numpy as np import lightkurve as lk from sklearn.model_selection import KFold from .cutout_data import CutoutData from .cpm_model import CPM from .poly_model import PolyModel from .custom_model import CustomModel class PixelModel(object): """A pixel model object that can store the different model componen...
tess_cpm/model.py
import numpy as np import lightkurve as lk from sklearn.model_selection import KFold from .cutout_data import CutoutData from .cpm_model import CPM from .poly_model import PolyModel from .custom_model import CustomModel class PixelModel(object): """A pixel model object that can store the different model componen...
0.805364
0.267444
from .utils import NamespacedClient, query_params, _make_path, SKIP_IN_PATH class SlmClient(NamespacedClient): @query_params() def delete_lifecycle(self, policy_id, params=None, headers=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/slm-api-delete-policy.html>`_ ...
elasticsearch/client/slm.py
from .utils import NamespacedClient, query_params, _make_path, SKIP_IN_PATH class SlmClient(NamespacedClient): @query_params() def delete_lifecycle(self, policy_id, params=None, headers=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/slm-api-delete-policy.html>`_ ...
0.865793
0.19063
from pprint import pformat from typing import Any, Dict, List, Optional from pytezos.context.impl import ExecutionContext from pytezos.context.mixin import ContextMixin # type: ignore from pytezos.contract.call import ContractCallResult, skip_nones from pytezos.jupyter import get_class_docstring from pytezos.logging ...
src/pytezos/contract/view.py
from pprint import pformat from typing import Any, Dict, List, Optional from pytezos.context.impl import ExecutionContext from pytezos.context.mixin import ContextMixin # type: ignore from pytezos.contract.call import ContractCallResult, skip_nones from pytezos.jupyter import get_class_docstring from pytezos.logging ...
0.81772
0.234878
import logging import argparse import random from typing import List import soundfile from nemo.collections.asr.parts.preprocessing.segment import AudioSegment from morsecodetoolkit.util import functional from morsecodetoolkit.alphabet import MorseAlphabet, Symbol def get_args() -> argparse.Namespace: parser = ...
morsecodetoolkit/bin/text_to_morse.py
import logging import argparse import random from typing import List import soundfile from nemo.collections.asr.parts.preprocessing.segment import AudioSegment from morsecodetoolkit.util import functional from morsecodetoolkit.alphabet import MorseAlphabet, Symbol def get_args() -> argparse.Namespace: parser = ...
0.828002
0.187318
from .GetTKK import getTKK import time import ctypes import requests class GoogleTranslate(): def __init__(self, sl='', tl='', domainnames=""): """ A python wrapped free and unlimited API for Google Translate. :param sl:from Language :param tl:to Language :param domainn...
google_translate_api_python/GoogleTranslate.py
from .GetTKK import getTKK import time import ctypes import requests class GoogleTranslate(): def __init__(self, sl='', tl='', domainnames=""): """ A python wrapped free and unlimited API for Google Translate. :param sl:from Language :param tl:to Language :param domainn...
0.073206
0.280215
import torch.nn.functional as F import torch.nn as nn import torch from torch.autograd import Variable from base.base_policy import BasePolicy from base.common import * class Policy(BasePolicy): def __init__(self, opts): super(Policy, self).__init__(opts) # (6) Decode: Decodes aggregated views to...
src/pose-estimation/policy.py
import torch.nn.functional as F import torch.nn as nn import torch from torch.autograd import Variable from base.base_policy import BasePolicy from base.common import * class Policy(BasePolicy): def __init__(self, opts): super(Policy, self).__init__(opts) # (6) Decode: Decodes aggregated views to...
0.859044
0.355635
from pyvcloud.vcd.client import E from pyvcloud.vcd.client import EntityType from pyvcloud.vcd.client import RelationType from pyvcloud.vcd.exceptions import InvalidParameterException from pyvcloud.vcd.utils import get_admin_href class Gateway(object): def __init__(self, client, name=None, href=None, resource=No...
pyvcloud/vcd/gateway.py
from pyvcloud.vcd.client import E from pyvcloud.vcd.client import EntityType from pyvcloud.vcd.client import RelationType from pyvcloud.vcd.exceptions import InvalidParameterException from pyvcloud.vcd.utils import get_admin_href class Gateway(object): def __init__(self, client, name=None, href=None, resource=No...
0.811415
0.129265
from contentLengthSIPHeaderField import ContentLengthSIPHeaderField from viaSIPHeaderField import ViaSIPHeaderField from acceptSIPHeaderField import AcceptSIPHeaderField from acceptEncodingSIPHeaderField import AcceptEncodingSIPHeaderField from acceptLanguageSIPHeaderField import AcceptLanguageSIPHeaderField from allow...
bobstack/sipmessaging/concreteheaderfields/__init__.py
from contentLengthSIPHeaderField import ContentLengthSIPHeaderField from viaSIPHeaderField import ViaSIPHeaderField from acceptSIPHeaderField import AcceptSIPHeaderField from acceptEncodingSIPHeaderField import AcceptEncodingSIPHeaderField from acceptLanguageSIPHeaderField import AcceptLanguageSIPHeaderField from allow...
0.466603
0.031739
from tests.utils import BaseTestCase from django.contrib.auth import get_user_model from django.test.utils import override_settings from rest_framework.authtoken.models import Token from django.test.utils import override_settings from drf_registration.utils import users from drf_registration.api.user import UserSerial...
tests/src/utils/test_users.py
from tests.utils import BaseTestCase from django.contrib.auth import get_user_model from django.test.utils import override_settings from rest_framework.authtoken.models import Token from django.test.utils import override_settings from drf_registration.utils import users from drf_registration.api.user import UserSerial...
0.524882
0.217358
import hashlib import json import logging import backoff import requests from prometheus_client import Counter prom_update_request_status_code = Counter('dnsclient_update_requests_total', 'Status code of request', ['status_code']) class UpdateNotifier: def __init__(self, dns_record, host, shared_secret): ...
notifier.py
import hashlib import json import logging import backoff import requests from prometheus_client import Counter prom_update_request_status_code = Counter('dnsclient_update_requests_total', 'Status code of request', ['status_code']) class UpdateNotifier: def __init__(self, dns_record, host, shared_secret): ...
0.620392
0.066965
# Third party Python libraries. import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning # Custom Python libraries. from . import logger # Disable warning: "InsecureRequestWarning: Unverified HTTPS request is being made. # Adding certificate verification is strongly advised" # https:...
agent/modules/api.py
# Third party Python libraries. import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning # Custom Python libraries. from . import logger # Disable warning: "InsecureRequestWarning: Unverified HTTPS request is being made. # Adding certificate verification is strongly advised" # https:...
0.848251
0.178025
from sqlalchemy import Column from sqlalchemy.types import JSON, Text, Boolean, TIMESTAMP, BigInteger from sqlalchemy.dialects import postgresql as psql from steampipe_alchemy import Base class AwsEc2Ami(Base): __tablename__ = 'aws_ec2_ami' name = Column('name', Text, primary_key=True, nullable=True) imag...
steampipe_alchemy/models/aws_ec2_ami.py
from sqlalchemy import Column from sqlalchemy.types import JSON, Text, Boolean, TIMESTAMP, BigInteger from sqlalchemy.dialects import postgresql as psql from steampipe_alchemy import Base class AwsEc2Ami(Base): __tablename__ = 'aws_ec2_ami' name = Column('name', Text, primary_key=True, nullable=True) imag...
0.520984
0.224034
from field.field import Field from game_field.game_field import GameField from game_field.game_field_checker import check_field, find_exit from models.cell import Empty, Key, Stun, RubberRoom, Teleport, Armory, Sleep, Exit from models.direction import Direction from models.player import Player from models.position impo...
field/generator/field_generator.py
from field.field import Field from game_field.game_field import GameField from game_field.game_field_checker import check_field, find_exit from models.cell import Empty, Key, Stun, RubberRoom, Teleport, Armory, Sleep, Exit from models.direction import Direction from models.player import Player from models.position impo...
0.472197
0.197503
import os import appmap from .appmap_test_base import AppMapTestBase from appmap._implementation.configuration import ConfigFilter, splitname from appmap._implementation.recording import NullFilter class TestConfiguration(AppMapTestBase): def test_can_be_enabled(self, monkeypatch): """Test that recording...
appmap/test/test_configuration.py
import os import appmap from .appmap_test_base import AppMapTestBase from appmap._implementation.configuration import ConfigFilter, splitname from appmap._implementation.recording import NullFilter class TestConfiguration(AppMapTestBase): def test_can_be_enabled(self, monkeypatch): """Test that recording...
0.456894
0.153042
import time import datetime from pyoddgen.generators.basegen import BaseGenerator from pyoddgen.config import ObjectDetectionConfiguration from pyoddgen.tools.distribution import Distribution from pyoddgen.datastructures.objectdetectionrecord import ObjectDetectionDataRecord class ObjectDetectionGenerator(BaseGenera...
pyoddgen/generators/objdetgen.py
import time import datetime from pyoddgen.generators.basegen import BaseGenerator from pyoddgen.config import ObjectDetectionConfiguration from pyoddgen.tools.distribution import Distribution from pyoddgen.datastructures.objectdetectionrecord import ObjectDetectionDataRecord class ObjectDetectionGenerator(BaseGenera...
0.391406
0.178615
import pytest from nlpiper.transformers.cleaners import ( CleanAccents, CleanEmail, CleanEOF, CleanMarkup, CleanNumber, CleanPunctuation, CleanURL, ) from nlpiper.core.document import ( Document, Token ) class TestCleanersValidations: @pytest.mark.parametrize('inputs', ["stri...
tests/transformers/test_cleaners.py
import pytest from nlpiper.transformers.cleaners import ( CleanAccents, CleanEmail, CleanEOF, CleanMarkup, CleanNumber, CleanPunctuation, CleanURL, ) from nlpiper.core.document import ( Document, Token ) class TestCleanersValidations: @pytest.mark.parametrize('inputs', ["stri...
0.449151
0.705211
import paho.mqtt.client as mqtt import time from .. import utils # These imports are auto generated files. import messages_pb2 as messages import proto_io as ProtoIO from google.protobuf.message import Message # These imports are auto generated files. import logging logger = logging.getLogger(__name__) class IOAnt: ...
ioant/ioant/sdk/sdk.py
import paho.mqtt.client as mqtt import time from .. import utils # These imports are auto generated files. import messages_pb2 as messages import proto_io as ProtoIO from google.protobuf.message import Message # These imports are auto generated files. import logging logger = logging.getLogger(__name__) class IOAnt: ...
0.180937
0.043325
import os import cv2 import numpy as np from skimage import io, color import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.spatial import distance def surface_plot (matrix, title, fig, **kwargs): (x, y) = np.meshgrid(np.arange(matrix.shape[0]), np.arange(matrix.shape[1])) ax = fi...
utility_funcitions.py
import os import cv2 import numpy as np from skimage import io, color import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.spatial import distance def surface_plot (matrix, title, fig, **kwargs): (x, y) = np.meshgrid(np.arange(matrix.shape[0]), np.arange(matrix.shape[1])) ax = fi...
0.336876
0.634345
import numpy as np from matplotlib import pyplot as plt import time import h5py import copy import hoshi.ptycho as hpty startTime = time.time() ############################################################################### ######## USER CONTROL ##################################################...
hoshi/ePIE_sergio_mE_v5.py
import numpy as np from matplotlib import pyplot as plt import time import h5py import copy import hoshi.ptycho as hpty startTime = time.time() ############################################################################### ######## USER CONTROL ##################################################...
0.112186
0.179746
import argparse import os.path import sys class RegmapDebugfs(): """RegmapDebugfs is a class for accessing the debugfs inteface of regmaps in the linux kernel""" def __init__(self, regmapdir): self.registers_path = os.path.join(regmapdir, 'registers') self.range_path = os.path.join(re...
python/opae.admin/opae/admin/tools/regmap_debugfs.py
import argparse import os.path import sys class RegmapDebugfs(): """RegmapDebugfs is a class for accessing the debugfs inteface of regmaps in the linux kernel""" def __init__(self, regmapdir): self.registers_path = os.path.join(regmapdir, 'registers') self.range_path = os.path.join(re...
0.351645
0.249596
import re from collections import defaultdict from datetime import datetime from threading import Event, Thread, RLock from queue import Empty, Queue import sublime from .utils import ( show_password_input, ) JUPYTER_PROTOCOL_VERSION = '5.0' REPLY_STATUS_OK = "ok" REPLY_STATUS_ERROR = "error" REPLY_STATUS_ABOR...
kernel.py
import re from collections import defaultdict from datetime import datetime from threading import Event, Thread, RLock from queue import Empty, Queue import sublime from .utils import ( show_password_input, ) JUPYTER_PROTOCOL_VERSION = '5.0' REPLY_STATUS_OK = "ok" REPLY_STATUS_ERROR = "error" REPLY_STATUS_ABOR...
0.434221
0.075075
from datetime import datetime import pandas as pd import requests import os import shopify import time here = os.path.dirname(os.path.abspath(__file__)) f_name = 'Clickbank '+ datetime.today().strftime('%Y-%m-%d') + '.csv' csv_clickbank = os.path.join(here,f_name) df = pd.read_csv(csv_clickbank) df_clickbank = df[df["...
testheader.py
from datetime import datetime import pandas as pd import requests import os import shopify import time here = os.path.dirname(os.path.abspath(__file__)) f_name = 'Clickbank '+ datetime.today().strftime('%Y-%m-%d') + '.csv' csv_clickbank = os.path.join(here,f_name) df = pd.read_csv(csv_clickbank) df_clickbank = df[df["...
0.215846
0.064801
import numpy as np import cv2 import os def rotate_img(img, iteration = 1): #0: remain same, +n: rotate left in 90*n degree, -n: rotate right in 90*n degree (some part of img is sliced off) if len(img.shape) == 3: height, width, _ = img.shape else: height, width = img.shape rotated_img...
pyramid_b_decoding.py
import numpy as np import cv2 import os def rotate_img(img, iteration = 1): #0: remain same, +n: rotate left in 90*n degree, -n: rotate right in 90*n degree (some part of img is sliced off) if len(img.shape) == 3: height, width, _ = img.shape else: height, width = img.shape rotated_img...
0.271928
0.376279
from sparv import Config, SourceStructureParser, wizard __config__ = [ Config("export.default", description="List of exporters to use by default"), Config("export.annotations", description="List of automatic annotations to include in export"), Config("export.source_annotations", description="List of annota...
sparv/core_modules/export/__init__.py
from sparv import Config, SourceStructureParser, wizard __config__ = [ Config("export.default", description="List of exporters to use by default"), Config("export.annotations", description="List of automatic annotations to include in export"), Config("export.source_annotations", description="List of annota...
0.780537
0.38798
# standard library import concurrent.futures import os import sys import time # 3rd party library import requests SLEEP_TIME = 0.1 def problem_url_exist(problem): # problem format is "Two-Sum" prefix = "https://leetcode.com/problems/" url = prefix + problem.lower() + '/' return url_exist(url), url ...
scripts/add_url.py
# standard library import concurrent.futures import os import sys import time # 3rd party library import requests SLEEP_TIME = 0.1 def problem_url_exist(problem): # problem format is "Two-Sum" prefix = "https://leetcode.com/problems/" url = prefix + problem.lower() + '/' return url_exist(url), url ...
0.449151
0.116689
import torch import torch.nn as nn import torch.nn.functional as F import math def conv3x3(in_planes, out_planes, stride=1): " 3x3 convolution with padding " return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion=1 def __...
models/resnet_cifar.py
import torch import torch.nn as nn import torch.nn.functional as F import math def conv3x3(in_planes, out_planes, stride=1): " 3x3 convolution with padding " return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion=1 def __...
0.930766
0.535584
from pyramid_oereb.contrib.print_proxy.mapfish_print.mapfish_print import Renderer from pyramid_oereb.core.config import Config # #TODO check that the config is actually changed def test_config_wms_url_params(config_path, DummyRenderInfo): Config._config = None Config.init('./tests/contrib.print_proxy.mapfis...
tests/contrib.print_proxy.mapfish_print/test_mapfish_print_configuration.py
from pyramid_oereb.contrib.print_proxy.mapfish_print.mapfish_print import Renderer from pyramid_oereb.core.config import Config # #TODO check that the config is actually changed def test_config_wms_url_params(config_path, DummyRenderInfo): Config._config = None Config.init('./tests/contrib.print_proxy.mapfis...
0.337859
0.209915
from copy import deepcopy import numpy as np from interpolation import interp from numba import njit from quantecon.optimize import newton_secant from HARK import makeOnePeriodOOSolver, HARKobject from HARK.ConsumptionSaving.ConsIndShockModel import ( ConsumerSolution, ValueFunc, MargValueFunc, MargMa...
HARK/ConsumptionSaving/ConsIndShockModelFast.py
from copy import deepcopy import numpy as np from interpolation import interp from numba import njit from quantecon.optimize import newton_secant from HARK import makeOnePeriodOOSolver, HARKobject from HARK.ConsumptionSaving.ConsIndShockModel import ( ConsumerSolution, ValueFunc, MargValueFunc, MargMa...
0.841142
0.338788
import solt.transforms as slt import solt.core as slc import numpy as np import pytest import sys import inspect import torch from .fixtures import * def get_transforms_solt(): trfs = [] for name, obj in inspect.getmembers(sys.modules["solt.transforms"]): if inspect.isclass(obj): trfs.app...
tests/test_base_transforms.py
import solt.transforms as slt import solt.core as slc import numpy as np import pytest import sys import inspect import torch from .fixtures import * def get_transforms_solt(): trfs = [] for name, obj in inspect.getmembers(sys.modules["solt.transforms"]): if inspect.isclass(obj): trfs.app...
0.440229
0.580293
import pprint import re # noqa: F401 import six class DocxInsertImageRequest(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 ...
cloudmersive_convert_api_client/models/docx_insert_image_request.py
import pprint import re # noqa: F401 import six class DocxInsertImageRequest(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 ...
0.636918
0.109849
<<<<<<< HEAD import CONFIG as config import torch class BERTDataset: def __init__(self,tweet,sentiment): self.tweet = tweet self.sentiment = sentiment self.tokenizer = config.TOKENIZER self.max_len = config.MAX_LEN def __len__(self): return len(self.tweet) ...
Sentiment Classifier/dataset.py
<<<<<<< HEAD import CONFIG as config import torch class BERTDataset: def __init__(self,tweet,sentiment): self.tweet = tweet self.sentiment = sentiment self.tokenizer = config.TOKENIZER self.max_len = config.MAX_LEN def __len__(self): return len(self.tweet) ...
0.406626
0.213808
# region Description """ scanner.py: Scan local network Author: <NAME> License: MIT Copyright 2019, Raw-packet Project """ # endregion # region Import # region Raw-packet modules from raw_packet.Utils.network import Ethernet_raw, ARP_raw from raw_packet.Utils.tm import ThreadManager from raw_packet.Utils.base import...
raw_packet/Scanners/arp_scanner.py
# region Description """ scanner.py: Scan local network Author: <NAME> License: MIT Copyright 2019, Raw-packet Project """ # endregion # region Import # region Raw-packet modules from raw_packet.Utils.network import Ethernet_raw, ARP_raw from raw_packet.Utils.tm import ThreadManager from raw_packet.Utils.base import...
0.554109
0.115586
# Import Python libs from __future__ import absolute_import # Import Salt Testing libs from tests.support.unit import skipIf, TestCase from tests.support.mock import ( MagicMock, patch, NO_MOCK, NO_MOCK_REASON, ) # Import Salt libs import salt.cloud EXAMPLE_PROVIDERS = { 'nyc_vcenter': {'vmware': {'...
tests/unit/test_map_conf.py
# Import Python libs from __future__ import absolute_import # Import Salt Testing libs from tests.support.unit import skipIf, TestCase from tests.support.mock import ( MagicMock, patch, NO_MOCK, NO_MOCK_REASON, ) # Import Salt libs import salt.cloud EXAMPLE_PROVIDERS = { 'nyc_vcenter': {'vmware': {'...
0.561696
0.138142
import argparse import json import multiprocessing import os from pathlib import Path import _pickle as cPickle import numpy as np import scipy as scipy import scipy.io.wavfile from config_path import get_paths from parallel_proc import process from utils import ProgressBar, is_clipped, wav_format_to_float def chec...
check_noisy_mix.py
import argparse import json import multiprocessing import os from pathlib import Path import _pickle as cPickle import numpy as np import scipy as scipy import scipy.io.wavfile from config_path import get_paths from parallel_proc import process from utils import ProgressBar, is_clipped, wav_format_to_float def chec...
0.428712
0.17266
from unittest import TestCase from unittest.mock import Mock from Orange.data import ContinuousVariable, DiscreteVariable, Domain from Orange.widgets.settings import ( ContextSetting, PerfectDomainContextHandler, Context, Setting, ) from Orange.widgets.utils import vartype Continuous = vartype(Contin...
orange3/Orange/widgets/tests/test_perfect_domain_context_handler.py
from unittest import TestCase from unittest.mock import Mock from Orange.data import ContinuousVariable, DiscreteVariable, Domain from Orange.widgets.settings import ( ContextSetting, PerfectDomainContextHandler, Context, Setting, ) from Orange.widgets.utils import vartype Continuous = vartype(Contin...
0.719581
0.475301
import pprint import six from enum import Enum class InstallmentPlanConfiguration: swagger_types = { 'base_currency': 'str', 'conditions': 'list[int]', 'id': 'int', 'installment_fee': 'float', 'interest_rate': 'float', 'linked_space_id': 'int', 'minim...
wallee/models/installment_plan_configuration.py
import pprint import six from enum import Enum class InstallmentPlanConfiguration: swagger_types = { 'base_currency': 'str', 'conditions': 'list[int]', 'id': 'int', 'installment_fee': 'float', 'interest_rate': 'float', 'linked_space_id': 'int', 'minim...
0.613815
0.221687
from oslo_log import log as logging from tempest import config from tempest.lib import decorators from designate_tempest_plugin.tests import base from designate_tempest_plugin import data_utils as dns_data_utils LOG = logging.getLogger(__name__) CONF = config.CONF class QuotasV2Test(base.BaseDnsV2Test): cre...
designate_tempest_plugin/tests/scenario/v2/test_quotas.py
from oslo_log import log as logging from tempest import config from tempest.lib import decorators from designate_tempest_plugin.tests import base from designate_tempest_plugin import data_utils as dns_data_utils LOG = logging.getLogger(__name__) CONF = config.CONF class QuotasV2Test(base.BaseDnsV2Test): cre...
0.323487
0.100172
import argparse import math import random from education_math_homework_generator.pdflatex_functions import convert_latex_to_pdf from education_math_homework_generator.pdflatex_functions import remove_temporary_files # Credits: # Code to generate lines and shapes from overleaf: # https://www.overleaf.com/learn/latex/...
education_math_homework_generator/gen_measurement.py
import argparse import math import random from education_math_homework_generator.pdflatex_functions import convert_latex_to_pdf from education_math_homework_generator.pdflatex_functions import remove_temporary_files # Credits: # Code to generate lines and shapes from overleaf: # https://www.overleaf.com/learn/latex/...
0.694199
0.338842
import torch from semseg.util import dataset, transform, config def get_mean_std(data_set): """Get mean and standard deviation of RGB values for the given dataset.""" value_scale = 255 mean_cs = [0.485, 0.456, 0.406] mean_cs = [item * value_scale for item in mean_cs] std_cs = [0.229, 0.224, 0.225...
dataset.py
import torch from semseg.util import dataset, transform, config def get_mean_std(data_set): """Get mean and standard deviation of RGB values for the given dataset.""" value_scale = 255 mean_cs = [0.485, 0.456, 0.406] mean_cs = [item * value_scale for item in mean_cs] std_cs = [0.229, 0.224, 0.225...
0.843766
0.551513
import pyabc import tempfile import pytest import os import numpy as np # create and run some model def model(p): return {'ss0': p['p0'] + 0.1 * np.random.uniform(), 'ss1': p['p1'] + 0.1 * np.random.uniform()} p_true = {'p0': 3, 'p1': 4} observation = {'ss0': p_true['p0'], 'ss1': p_true['p1']} lim...
test/visualization/test_visualization.py
import pyabc import tempfile import pytest import os import numpy as np # create and run some model def model(p): return {'ss0': p['p0'] + 0.1 * np.random.uniform(), 'ss1': p['p1'] + 0.1 * np.random.uniform()} p_true = {'p0': 3, 'p1': 4} observation = {'ss0': p_true['p0'], 'ss1': p_true['p1']} lim...
0.397938
0.449151
import csv class Cards: def getStarpowersID(): CardSkillsID = [] with open('Logic/Files/assets/csv_logic/cards.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0 or line_c...
Logic/Files/Classes/Cards.py
import csv class Cards: def getStarpowersID(): CardSkillsID = [] with open('Logic/Files/assets/csv_logic/cards.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0 or line_c...
0.066161
0.291882
# * Copyright (c) 2009-2019. Authors: see NOTICE file. # * # * Licensed under the Apache License, Version 2.0 (the "License"); # * you may not use this file except in compliance with the License. # * You may obtain a copy of the License at # * # * http://www.apache.org/licenses/LICENSE-2.0 # * # * Unless required...
cytomineprojectmigrator/importer.py
# * Copyright (c) 2009-2019. Authors: see NOTICE file. # * # * Licensed under the Apache License, Version 2.0 (the "License"); # * you may not use this file except in compliance with the License. # * You may obtain a copy of the License at # * # * http://www.apache.org/licenses/LICENSE-2.0 # * # * Unless required...
0.644896
0.104752
R1 = { 'device_type': 'cisco_ios', 'host': '10.0.0.21', 'username': 'user1', 'password': '<PASSWORD>', 'secret': 'secret1' } R2 = { 'device_type': 'cisco_ios', 'host': '10.0.0.22', 'username': 'user1', 'password': '<PASSWORD>', 'secret': 'secret1' } R3 = { 'device_type': 'c...
inventory/rtr_inv.py
R1 = { 'device_type': 'cisco_ios', 'host': '10.0.0.21', 'username': 'user1', 'password': '<PASSWORD>', 'secret': 'secret1' } R2 = { 'device_type': 'cisco_ios', 'host': '10.0.0.22', 'username': 'user1', 'password': '<PASSWORD>', 'secret': 'secret1' } R3 = { 'device_type': 'c...
0.280222
0.189203
import matplotlib.pyplot as plt import numpy as np import tikzplotlib import scipy.stats as stats def gaussian(x, mean, amplitude, standard_deviation): return amplitude * np.exp( - (x - mean)**2 / (2*standard_deviation ** 2)) axis_label_size = 18 font = {'family' : 'normal', 'weight' : 'bold', ...
plot_creation_scripts/centrality_historgrams/MLP_lap_cen_dis_200_epochs_fashion_line.py
import matplotlib.pyplot as plt import numpy as np import tikzplotlib import scipy.stats as stats def gaussian(x, mean, amplitude, standard_deviation): return amplitude * np.exp( - (x - mean)**2 / (2*standard_deviation ** 2)) axis_label_size = 18 font = {'family' : 'normal', 'weight' : 'bold', ...
0.464902
0.343094
The 4 Phases of the U.P.E.R. Problem-Solving Framework ****** UNDERSTAND ****** - Objective: - Write an algorithm that takes in a single input string and returns the left-most integer in that string as the single output. - Expected Input(s): - Number Of: 1 - Data Type(s): string - Var Name...
edabit/hard/left_digit/left_digit.py
The 4 Phases of the U.P.E.R. Problem-Solving Framework ****** UNDERSTAND ****** - Objective: - Write an algorithm that takes in a single input string and returns the left-most integer in that string as the single output. - Expected Input(s): - Number Of: 1 - Data Type(s): string - Var Name...
0.765944
0.826292
import datetime from typing import Type, Optional, Any, Tuple, Dict import django from copy import copy from django.core.exceptions import FieldError from django.db.models import Field, Model from django.db.models.sql import UpdateQuery, InsertQuery, Query from django.db.models.sql.compiler import SQLCompiler from .c...
src/django_pg_bulk_update/set_functions.py
import datetime from typing import Type, Optional, Any, Tuple, Dict import django from copy import copy from django.core.exceptions import FieldError from django.db.models import Field, Model from django.db.models.sql import UpdateQuery, InsertQuery, Query from django.db.models.sql.compiler import SQLCompiler from .c...
0.786705
0.143308
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wells', '0006_load_casing_code'), ] operations = [ migrations.RenameField( model_name='casing', ...
app/backend/wells/migrations/0007_auto_20180816_0030.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wells', '0006_load_casing_code'), ] operations = [ migrations.RenameField( model_name='casing', ...
0.642657
0.088151
import re from typing import Union KEYSEPARATOR = "/" ID_REGEX = r"[1-9]\d*" ID_PATTERN = re.compile(ID_REGEX) class Collection: """ The first part of a full qualified field (also known as "key"), e. g. motion_change_recommendation. """ def __init__(self, collection: str) -> None: self....
openslides_backend/shared/patterns.py
import re from typing import Union KEYSEPARATOR = "/" ID_REGEX = r"[1-9]\d*" ID_PATTERN = re.compile(ID_REGEX) class Collection: """ The first part of a full qualified field (also known as "key"), e. g. motion_change_recommendation. """ def __init__(self, collection: str) -> None: self....
0.830181
0.28011
import traceback import sys from unittest import TestResult import datetime from teamcity.messages import TeamcityServiceMessages def _is_string(obj): if sys.version_info >= (3, 0): return isinstance(obj, str) else: return isinstance(obj, basestring) # Added *k to some methods to get compat...
teamcity/unittestpy.py
import traceback import sys from unittest import TestResult import datetime from teamcity.messages import TeamcityServiceMessages def _is_string(obj): if sys.version_info >= (3, 0): return isinstance(obj, str) else: return isinstance(obj, basestring) # Added *k to some methods to get compat...
0.281801
0.201892
from typing import Any, Dict, List, Literal from prefect import Flow from prefect.utilities import logging logger = logging.get_logger() from ..task_utils import ( add_ingestion_metadata_task, df_to_parquet, ) from ..tasks import SAPRFCToDF, DuckDBCreateTableFromParquet class SAPToDuckDB(Flow): def __in...
viadot/flows/sap_to_duckdb.py
from typing import Any, Dict, List, Literal from prefect import Flow from prefect.utilities import logging logger = logging.get_logger() from ..task_utils import ( add_ingestion_metadata_task, df_to_parquet, ) from ..tasks import SAPRFCToDF, DuckDBCreateTableFromParquet class SAPToDuckDB(Flow): def __in...
0.779238
0.144752
import unittest from click.testing import CliRunner from time import sleep from competition import generate # FOR SOME REASONS THOSE TESTS WORK ONLY IF WE START ONE AFTER THE OTHER MANUALLY # I suspect this might be because we exended the Command class from click class CommandLineCombinationTest(unittest.TestCase): ...
tests/commandline_parsing_tests.py
import unittest from click.testing import CliRunner from time import sleep from competition import generate # FOR SOME REASONS THOSE TESTS WORK ONLY IF WE START ONE AFTER THE OTHER MANUALLY # I suspect this might be because we exended the Command class from click class CommandLineCombinationTest(unittest.TestCase): ...
0.576304
0.425307
from datetime import datetime import discord import pytz from discord.ext import commands class Events(commands.Cog): def __init__(self, client): self.client = client self.IST = pytz.timezone('Asia/Kolkata') @commands.Cog.listener() async def on_ready(self): print(f"{self.__class...
cogs/events.py
from datetime import datetime import discord import pytz from discord.ext import commands class Events(commands.Cog): def __init__(self, client): self.client = client self.IST = pytz.timezone('Asia/Kolkata') @commands.Cog.listener() async def on_ready(self): print(f"{self.__class...
0.515864
0.195902
import os import numpy as np from joblib import dump, load from sklearn.model_selection import train_test_split from .data import * from .impl import * from .util import * def extract( model, X, y, trainSize=0.7, outputPath=None, isClassify=True, featureNames=[], catFeaturesInds=[]...
dtextract/base.py
import os import numpy as np from joblib import dump, load from sklearn.model_selection import train_test_split from .data import * from .impl import * from .util import * def extract( model, X, y, trainSize=0.7, outputPath=None, isClassify=True, featureNames=[], catFeaturesInds=[]...
0.596198
0.496643
import unittest from hangman.Hangman import Hangman class TestHangman(unittest.TestCase): def test_init(self): play = Hangman(word="bmw") self.assertEqual(play.word, "bmw") self.assertEqual(play.total_word, "***") self.assertEqual(play.num_try, 0) def test_init2(self): ...
test.py
import unittest from hangman.Hangman import Hangman class TestHangman(unittest.TestCase): def test_init(self): play = Hangman(word="bmw") self.assertEqual(play.word, "bmw") self.assertEqual(play.total_word, "***") self.assertEqual(play.num_try, 0) def test_init2(self): ...
0.425605
0.636381
from cal import add # importing add function only print(add(1, 3)) # variables # multiple assignments x = y = z = 1 sa, sb, sc = 1, 2, "name" print(sa) # to delete reference del sa, x # splice x = "hello" print(x.upper()) print(dir("string")) print(x[0]) print(x.replace('h', 'w')) print(x[1:4]) # string formatti...
main.py
from cal import add # importing add function only print(add(1, 3)) # variables # multiple assignments x = y = z = 1 sa, sb, sc = 1, 2, "name" print(sa) # to delete reference del sa, x # splice x = "hello" print(x.upper()) print(dir("string")) print(x[0]) print(x.replace('h', 'w')) print(x[1:4]) # string formatti...
0.355775
0.381565
import os import pymongo import pprint import re import json import sys import datetime import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib import font_manager, rc, style from tqdm import tqdm connection = pymo...
python/Brand_matching_200615.py.0178c11de2aea3662585c30f92ebf0e6.py
import os import pymongo import pprint import re import json import sys import datetime import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib import font_manager, rc, style from tqdm import tqdm connection = pymo...
0.125119
0.19923
import torch from torch import nn from torch.nn import functional as F import torchvision class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) class UnFlatten(nn.Module): def forward(self, input, size=256): return input.view(input.size(0), size, 3, 8) ...
learning_racer/vae/vae.py
import torch from torch import nn from torch.nn import functional as F import torchvision class Flatten(nn.Module): def forward(self, input): return input.view(input.size(0), -1) class UnFlatten(nn.Module): def forward(self, input, size=256): return input.view(input.size(0), size, 3, 8) ...
0.959039
0.503601
from enum import IntEnum from typing import Dict, Callable import chess import board from .capture import creates_hanging_piece_threat_capture, creates_material_gain_capture from .mate import creates_mate_threat def make_tactic_threat_detector(tactic: board.Tactic): def detector(fen: str, move: chess.Move): ...
board/threats/__init__.py
from enum import IntEnum from typing import Dict, Callable import chess import board from .capture import creates_hanging_piece_threat_capture, creates_material_gain_capture from .mate import creates_mate_threat def make_tactic_threat_detector(tactic: board.Tactic): def detector(fen: str, move: chess.Move): ...
0.472683
0.280062
import requests import json from scripts.data_process import extractor from math import ceil class bangumi: @staticmethod def get_bangumi_info(media_id: int) -> dict: Data = requests.get(f'https://api.bilibili.com/pgc/review/user?media_id={media_id}') JsonData = json.loads(Data.tex...
WebApi/bangumi.py
import requests import json from scripts.data_process import extractor from math import ceil class bangumi: @staticmethod def get_bangumi_info(media_id: int) -> dict: Data = requests.get(f'https://api.bilibili.com/pgc/review/user?media_id={media_id}') JsonData = json.loads(Data.tex...
0.324342
0.176849
import numpy as np import scipy.signal as signal import logging import os from copy import deepcopy import logging log = logging.getLogger(__name__) def import_iir(filename): """ imports csv files generated with Mathematica notebooks of the form a1_0,b0_0,b1_0 a1_1,b0_1,b1_1 a1_2,b0_2,b1_2 . ...
pycqed/measurement/waveform_control/fluxpulse_predistortion.py
import numpy as np import scipy.signal as signal import logging import os from copy import deepcopy import logging log = logging.getLogger(__name__) def import_iir(filename): """ imports csv files generated with Mathematica notebooks of the form a1_0,b0_0,b1_0 a1_1,b0_1,b1_1 a1_2,b0_2,b1_2 . ...
0.74872
0.482185
import json import re import nbformat from . import ParseError from ._common import RE_JSON def deserialize(source): """Convert ``.jupyter`` string representation to Jupyter notebook. Lines have to be terminated with ``'\\n'`` (a.k.a. :term:`universal newlines` mode). If *source* is an iterable, ...
src/jupyter_format/_reader.py
import json import re import nbformat from . import ParseError from ._common import RE_JSON def deserialize(source): """Convert ``.jupyter`` string representation to Jupyter notebook. Lines have to be terminated with ``'\\n'`` (a.k.a. :term:`universal newlines` mode). If *source* is an iterable, ...
0.434461
0.32985
from PySide2 import QtCore, QtGui, QtWidgets class Ui_HelpWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setObjectName("HelpWindow") self.setFixedSize(601, 450) self.setStyleSheet("background-color:black") self.setWindowFlags(QtCore.Qt.FramelessW...
help.py
from PySide2 import QtCore, QtGui, QtWidgets class Ui_HelpWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setObjectName("HelpWindow") self.setFixedSize(601, 450) self.setStyleSheet("background-color:black") self.setWindowFlags(QtCore.Qt.FramelessW...
0.257392
0.056055
import requests import datetime from xml.etree.ElementTree import fromstring from http.client import responses from . import Api, ParameterException, ApiException NAMESPACE = "{http://www.collegenet.com/r25}" class TwentyFiveLive(Api): """ Class that optimizes api calls to the CollegeNet 25Live REST interfac...
profpy/apis/TwentyFiveLive.py
import requests import datetime from xml.etree.ElementTree import fromstring from http.client import responses from . import Api, ParameterException, ApiException NAMESPACE = "{http://www.collegenet.com/r25}" class TwentyFiveLive(Api): """ Class that optimizes api calls to the CollegeNet 25Live REST interfac...
0.669637
0.127191
import datetime import github3 import pytest from . import helper get_milestone_example_data = helper.create_example_data_helper( 'milestone_example' ) example_data = get_milestone_example_data() url_for = helper.create_url_helper("https://api.github.com/repos/octocat/" "Hello-...
tests/unit/test_issues_milestone.py
import datetime import github3 import pytest from . import helper get_milestone_example_data = helper.create_example_data_helper( 'milestone_example' ) example_data = get_milestone_example_data() url_for = helper.create_url_helper("https://api.github.com/repos/octocat/" "Hello-...
0.804751
0.418103
from tkinter import * import tkinter.ttk as ttk from tkinter.tix import * from PIL import ImageTk from palette.functions import * class App(Tk): def __init__(self): Tk.__init__(self) Tk.title(self, "Palette") Tk.geometry(self, "360x480+500+200") Tk.resizable(self, 0, 0) i...
main.py
from tkinter import * import tkinter.ttk as ttk from tkinter.tix import * from PIL import ImageTk from palette.functions import * class App(Tk): def __init__(self): Tk.__init__(self) Tk.title(self, "Palette") Tk.geometry(self, "360x480+500+200") Tk.resizable(self, 0, 0) i...
0.521227
0.136062
from __future__ import absolute_import import os.path import csv import multiprocessing import random from ..datasets import fileutils from ..datasets import segment as sg def extract(feature_folder, extractor_function, output_dir=None, old_segment_format=True, normali...
src/sics_seizure_prediction/features/feature_extractor.py
from __future__ import absolute_import import os.path import csv import multiprocessing import random from ..datasets import fileutils from ..datasets import segment as sg def extract(feature_folder, extractor_function, output_dir=None, old_segment_format=True, normali...
0.680454
0.372191
# nwscan 0.3 # author: <NAME> # email: <EMAIL> # date: 20190109 import subprocess import sys import optparse from multiprocessing.pool import ThreadPool import ipaddr from socket import inet_aton version = '0.3' # Parse and validate arguments def get_parsed_args(): usage = 'usage: %prog network [options]' ...
nwscan/nwscan.py
# nwscan 0.3 # author: <NAME> # email: <EMAIL> # date: 20190109 import subprocess import sys import optparse from multiprocessing.pool import ThreadPool import ipaddr from socket import inet_aton version = '0.3' # Parse and validate arguments def get_parsed_args(): usage = 'usage: %prog network [options]' ...
0.31258
0.090695
import numpy as np import sys from theano import function from theano import tensor as T _, model_path, sigma = sys.argv from pylearn2.utils import serial model = serial.load(model_path) from pylearn2.config import yaml_parse dataset = yaml_parse.load(model.dataset_yaml_src) dataset = dataset.get_test_set() from pyle...
ll.py
import numpy as np import sys from theano import function from theano import tensor as T _, model_path, sigma = sys.argv from pylearn2.utils import serial model = serial.load(model_path) from pylearn2.config import yaml_parse dataset = yaml_parse.load(model.dataset_yaml_src) dataset = dataset.get_test_set() from pyle...
0.275812
0.38145
import argparse from uqcsbot import bot, Command from bs4 import BeautifulSoup from datetime import datetime from requests.exceptions import RequestException from typing import List from uqcsbot.utils.command_utils import loading_status, UsageSyntaxException import requests MAX_COUPONS = 10 # Prevents abuse COUPONESE...
uqcsbot/scripts/dominos.py
import argparse from uqcsbot import bot, Command from bs4 import BeautifulSoup from datetime import datetime from requests.exceptions import RequestException from typing import List from uqcsbot.utils.command_utils import loading_status, UsageSyntaxException import requests MAX_COUPONS = 10 # Prevents abuse COUPONESE...
0.682256
0.125762
import simplejson as json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayUserAgreementSignResponse(AlipayResponse): def __init__(self): super(AlipayUserAgreementSignResponse, self).__init__() self._agreement_no = None self._alipay_logon_id = None se...
alipay/aop/api/response/AlipayUserAgreementSignResponse.py
import simplejson as json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayUserAgreementSignResponse(AlipayResponse): def __init__(self): super(AlipayUserAgreementSignResponse, self).__init__() self._agreement_no = None self._alipay_logon_id = None se...
0.534127
0.064742
import os import sys import rhcephcompose from rhcephcompose import main import pytest @pytest.fixture def conf(fixtures_dir): return os.path.join(fixtures_dir, 'basic.conf') class FakeCompose(object): def run(self): pass class ComposeRecorder(object): """ Record the arg to the Compose object'...
rhcephcompose/tests/test_main.py
import os import sys import rhcephcompose from rhcephcompose import main import pytest @pytest.fixture def conf(fixtures_dir): return os.path.join(fixtures_dir, 'basic.conf') class FakeCompose(object): def run(self): pass class ComposeRecorder(object): """ Record the arg to the Compose object'...
0.316053
0.28829
from __future__ import absolute_import from logging import getLogger import traceback from collections import defaultdict, namedtuple, MutableSet import bisect import numpy from mceditlib.blocktypes import itemtypes from mceditlib.blocktypes.json_resources import openResource, getJsonFile log = getLogger(__name__) ...
src/mceditlib/blocktypes/__init__.py
from __future__ import absolute_import from logging import getLogger import traceback from collections import defaultdict, namedtuple, MutableSet import bisect import numpy from mceditlib.blocktypes import itemtypes from mceditlib.blocktypes.json_resources import openResource, getJsonFile log = getLogger(__name__) ...
0.517815
0.216405
from datetime import datetime, timedelta from flask import url_for, request, flash, redirect from flask_login import current_user from flask_rauth import RauthOAuth2, RauthOAuth1 from flaskext.babel import lazy_gettext as _ from ..models import db, Key, User from ..views import auth class AbstractRAuth(object): ...
base/auth/oauth/base.py
from datetime import datetime, timedelta from flask import url_for, request, flash, redirect from flask_login import current_user from flask_rauth import RauthOAuth2, RauthOAuth1 from flaskext.babel import lazy_gettext as _ from ..models import db, Key, User from ..views import auth class AbstractRAuth(object): ...
0.45181
0.052887
from common.spatial_func import SPoint, distance import networkx as nx import math def find_shortest_path(rn, prev_candi_pt, cur_candi_pt, weight='length'): if nx.is_directed(rn): return find_shortest_path_directed(rn, prev_candi_pt, cur_candi_pt, weight) else: return find_shortest_path_undire...
map_matching/utils.py
from common.spatial_func import SPoint, distance import networkx as nx import math def find_shortest_path(rn, prev_candi_pt, cur_candi_pt, weight='length'): if nx.is_directed(rn): return find_shortest_path_directed(rn, prev_candi_pt, cur_candi_pt, weight) else: return find_shortest_path_undire...
0.419767
0.288281
import sys import shutil import os import unittest import time from riboSeed.shared_methods import md5 from argparse import Namespace sys.path.append(os.path.join( os.path.dirname(os.path.dirname(__file__)), "riboSeed")) from riboSeed.riboSketch import makeContigMoverCmds, findBestAlignments, \ parseBackbon...
tests/test_riboSketch.py
import sys import shutil import os import unittest import time from riboSeed.shared_methods import md5 from argparse import Namespace sys.path.append(os.path.join( os.path.dirname(os.path.dirname(__file__)), "riboSeed")) from riboSeed.riboSketch import makeContigMoverCmds, findBestAlignments, \ parseBackbon...
0.245899
0.218888
load("//cc/private/rules_impl:cc_flags_supplier.bzl", _cc_flags_supplier = "cc_flags_supplier") load("//cc/private/rules_impl:compiler_flag.bzl", _compiler_flag = "compiler_flag") _MIGRATION_TAG = "__CC_RULES_MIGRATION_DO_NOT_USE_WILL_BREAK__" def _add_tags(attrs): if "tags" in attrs and attrs["tags"] != None: ...
maistra/vendor/rules_cc/cc/defs.bzl
load("//cc/private/rules_impl:cc_flags_supplier.bzl", _cc_flags_supplier = "cc_flags_supplier") load("//cc/private/rules_impl:compiler_flag.bzl", _compiler_flag = "compiler_flag") _MIGRATION_TAG = "__CC_RULES_MIGRATION_DO_NOT_USE_WILL_BREAK__" def _add_tags(attrs): if "tags" in attrs and attrs["tags"] != None: ...
0.557604
0.1933
from typing import Iterable, List, Set from pydantic import Field from .container import Container, ContainerIO from .location import Location from .static_structure_element import StaticStructureElement, StaticStructureElementIO from .tags import Tags __all__ = ("SoftwareSystem", "SoftwareSystemIO") class Softwa...
src/structurizr/model/software_system.py
from typing import Iterable, List, Set from pydantic import Field from .container import Container, ContainerIO from .location import Location from .static_structure_element import StaticStructureElement, StaticStructureElementIO from .tags import Tags __all__ = ("SoftwareSystem", "SoftwareSystemIO") class Softwa...
0.711631
0.250353
from ...constants import Direction from ..._utils import negate_bounds as _not from ..activations.neuron.dynamic import _DynamicActivation import torch class DynamicLinear(_DynamicActivation): """Interpolated Linear""" def __init__(self, *args, **kwds): super().__init__(*args, **kwds) self.w...
lnn/neural/methods/dynamiclinear.py
from ...constants import Direction from ..._utils import negate_bounds as _not from ..activations.neuron.dynamic import _DynamicActivation import torch class DynamicLinear(_DynamicActivation): """Interpolated Linear""" def __init__(self, *args, **kwds): super().__init__(*args, **kwds) self.w...
0.848125
0.564579
from zope.component import adapter from zope.interface import Invalid, implementer from zope.schema import ValidationError from pyams_form.interfaces import IValue from pyams_form.interfaces.error import IErrorViewSnippet, IMultipleErrors from pyams_form.util import get_specification from pyams_form.value import Compu...
src/pyams_form/error.py
from zope.component import adapter from zope.interface import Invalid, implementer from zope.schema import ValidationError from pyams_form.interfaces import IValue from pyams_form.interfaces.error import IErrorViewSnippet, IMultipleErrors from pyams_form.util import get_specification from pyams_form.value import Compu...
0.785802
0.133669
from scipy import stats from scipy.constants import elementary_charge as q0, electron_mass as m0, c import numpy as np import sys import argparse def parse_arguments(): parser = argparse.ArgumentParser( description="""Tool for validating Maxwellian particle initialisation. Temperatures specified i...
src/unit_tests/particle_momentum/check_test.py
from scipy import stats from scipy.constants import elementary_charge as q0, electron_mass as m0, c import numpy as np import sys import argparse def parse_arguments(): parser = argparse.ArgumentParser( description="""Tool for validating Maxwellian particle initialisation. Temperatures specified i...
0.542863
0.317479
import sys sys.path.append('../core') import numpy as np from numpy.linalg import eig from scipy.linalg import expm from scipy.linalg import solve_discrete_are from Utils import TerminalComponents from Utils import ReplayBuffer from StabilizingController import SMPC from SafetyFilter import MPSafetyFilter from Learni...
src/tests/design_linear_controller.py
import sys sys.path.append('../core') import numpy as np from numpy.linalg import eig from scipy.linalg import expm from scipy.linalg import solve_discrete_are from Utils import TerminalComponents from Utils import ReplayBuffer from StabilizingController import SMPC from SafetyFilter import MPSafetyFilter from Learni...
0.415017
0.407216
import numpy as np from sc2.constants import ( ADEPT, ARCHON, AUTOTURRET, BANELING, BANSHEE, BATTLECRUISER, BROODLING, BROODLORD, BUNKER, CARRIER, COLOSSUS, CORRUPTOR, CYCLONE, DARKTEMPLAR, DISRUPTOR, DRONE, GHOST, HELLION, HELLIONTANK, HIG...
actions/micro/army_value_tables.py
import numpy as np from sc2.constants import ( ADEPT, ARCHON, AUTOTURRET, BANELING, BANSHEE, BATTLECRUISER, BROODLING, BROODLORD, BUNKER, CARRIER, COLOSSUS, CORRUPTOR, CYCLONE, DARKTEMPLAR, DISRUPTOR, DRONE, GHOST, HELLION, HELLIONTANK, HIG...
0.562417
0.154026
from PySide2 import QtGui, QtCore, QtXml class Node(object): def __init__(self, name, parent=None): self._name = name self._parent = parent self._children = [] self._value = None if parent is not None: parent.addChild(self) def typeInfo(self): retu...
gdesk/dicttree/node.py
from PySide2 import QtGui, QtCore, QtXml class Node(object): def __init__(self, name, parent=None): self._name = name self._parent = parent self._children = [] self._value = None if parent is not None: parent.addChild(self) def typeInfo(self): retu...
0.607663
0.168925
import os from django.core.cache import cache from django.db.models.signals import ( pre_delete, pre_save, post_save, post_delete, m2m_changed, ) from django.dispatch import receiver from django_q.tasks import async_task from django_q.models import OrmQ from projects.helpers import get_fieldset_pa...
projects/signals/handlers.py
import os from django.core.cache import cache from django.db.models.signals import ( pre_delete, pre_save, post_save, post_delete, m2m_changed, ) from django.dispatch import receiver from django_q.tasks import async_task from django_q.models import OrmQ from projects.helpers import get_fieldset_pa...
0.277963
0.068631
from typing import Dict, Any, Tuple, Optional, List from ..params.model import TIME_RANGE_TYPE from ...util.html import html_element, html_table from ...util.schema import PropertyDef, TypeDef FORWARD_MODEL_TYPE = TypeDef(object, properties=[PropertyDef('name', TypeDef(str)), ...
multiply_ui/ui/req/model.py
from typing import Dict, Any, Tuple, Optional, List from ..params.model import TIME_RANGE_TYPE from ...util.html import html_element, html_table from ...util.schema import PropertyDef, TypeDef FORWARD_MODEL_TYPE = TypeDef(object, properties=[PropertyDef('name', TypeDef(str)), ...
0.719581
0.186428
import torch from torch import nn from torch.optim import Adam class LSTMEncoderModule(nn.Module): def __init__(self, input_size): super().__init__() self.c0 = nn.Parameter(torch.zeros(256)) self.h0 = nn.Parameter(torch.zeros(256)) self.encoder = nn.Linear(input_size, 256) ...
agents/ai.py
import torch from torch import nn from torch.optim import Adam class LSTMEncoderModule(nn.Module): def __init__(self, input_size): super().__init__() self.c0 = nn.Parameter(torch.zeros(256)) self.h0 = nn.Parameter(torch.zeros(256)) self.encoder = nn.Linear(input_size, 256) ...
0.952064
0.410343