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 pprint import pformat
from six import iteritems
import re
class JobLocationInput(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, country_code=None, region_code=None, city=None):
"""
J... | smartrecruiters_python_client/models/job_location_input.py | from pprint import pformat
from six import iteritems
import re
class JobLocationInput(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, country_code=None, region_code=None, city=None):
"""
J... | 0.838878 | 0.298945 |
from kivy.app import App
from kivy.uix.stacklayout import StackLayout
from kivy.core.window import Window
from kivy.storage.jsonstore import JsonStore
from kivy.core.clipboard import Clipboard
from Crypto.PublicKey import RSA
import myrsa
import primenum
class Mainpage(StackLayout):
store = JsonStore('data.json... | main.py | from kivy.app import App
from kivy.uix.stacklayout import StackLayout
from kivy.core.window import Window
from kivy.storage.jsonstore import JsonStore
from kivy.core.clipboard import Clipboard
from Crypto.PublicKey import RSA
import myrsa
import primenum
class Mainpage(StackLayout):
store = JsonStore('data.json... | 0.30054 | 0.146057 |
import os
from reportlab.lib.pagesizes import A4
from reportlab.lib.colors import Color, HexColor
from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.enums import TA_CENTER, TA_RIGHT, TA_LEFT
from gluon import current
from core.resource.codecs.card import ... | modules/templates/DRK/idcards.py | import os
from reportlab.lib.pagesizes import A4
from reportlab.lib.colors import Color, HexColor
from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.enums import TA_CENTER, TA_RIGHT, TA_LEFT
from gluon import current
from core.resource.codecs.card import ... | 0.660282 | 0.211722 |
import shlex
from enum import Enum
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Union
class SearchFor(Enum):
"""set the test mode"""
HELP = "search for help"
PROMPT = "search for the shell prompt"
WARNING = "search for a blocking warning notifi... | tests/integration/_interactions.py | import shlex
from enum import Enum
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Union
class SearchFor(Enum):
"""set the test mode"""
HELP = "search for help"
PROMPT = "search for the shell prompt"
WARNING = "search for a blocking warning notifi... | 0.798029 | 0.241965 |
import boto3
import botocore
import json
class S3Interface():
"""Interface to the AWS S3 database."""
def __init__(self, aws_access_key_id, aws_secret_access_key, s3_region_name,
deployment_prefix):
"""Create a new interface to the AWS S3.
Remember the access key, secret acc... | perf-tests/src/s3interface.py | import boto3
import botocore
import json
class S3Interface():
"""Interface to the AWS S3 database."""
def __init__(self, aws_access_key_id, aws_secret_access_key, s3_region_name,
deployment_prefix):
"""Create a new interface to the AWS S3.
Remember the access key, secret acc... | 0.731346 | 0.235284 |
from dataclasses import dataclass
from typing import AsyncIterator, Dict, List, Optional
import betterproto
from betterproto.grpc.grpclib_server import ServiceBase
import grpclib
@dataclass(eq=False, repr=False)
class Collection(betterproto.Message):
"""Provides a Collection type for storing documents"""
# ... | python/nitricapi/nitric/document/v1/__init__.py | from dataclasses import dataclass
from typing import AsyncIterator, Dict, List, Optional
import betterproto
from betterproto.grpc.grpclib_server import ServiceBase
import grpclib
@dataclass(eq=False, repr=False)
class Collection(betterproto.Message):
"""Provides a Collection type for storing documents"""
# ... | 0.911933 | 0.229643 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('device', '0001_initial'),
]
operations = [
... | src/local/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('device', '0001_initial'),
]
operations = [
... | 0.570451 | 0.155206 |
from itertools import product
from django.test.testcases import TestCase
from server.models import Figure, Game
from .mixins import ChessCaseMixin
class TestKing(TestCase, ChessCaseMixin):
combo = product(range(3), range(3, 6))
wrong_poses = {*product(range(8), range(8))} - set(combo)
def setup_class(sel... | ChessDRF/server/models/tests/test_figures.py | from itertools import product
from django.test.testcases import TestCase
from server.models import Figure, Game
from .mixins import ChessCaseMixin
class TestKing(TestCase, ChessCaseMixin):
combo = product(range(3), range(3, 6))
wrong_poses = {*product(range(8), range(8))} - set(combo)
def setup_class(sel... | 0.500244 | 0.540681 |
from __future__ import with_statement
import os
import sys
import types
import unittest
import functools
def ensure_in_path(path):
"""
Ensure that a given path is in the sys.path array
"""
if not os.path.isdir(path):
raise RuntimeError('Tried to add nonexisting path')
def _samefile(x, y)... | specter/tests/helpers.py | from __future__ import with_statement
import os
import sys
import types
import unittest
import functools
def ensure_in_path(path):
"""
Ensure that a given path is in the sys.path array
"""
if not os.path.isdir(path):
raise RuntimeError('Tried to add nonexisting path')
def _samefile(x, y)... | 0.501465 | 0.373447 |
from itertools import chain
class MyCircularDeque:
def __init__(self, k: 'int'):
"""
Initialize your data structure here. Set the size of the deque to be k.
"""
self.capicity = k + 1
self.items = [True] * self.capicity
self.head, self.tail = 0, 0
def insertFro... | 641. Design Circular Deque/641.py | from itertools import chain
class MyCircularDeque:
def __init__(self, k: 'int'):
"""
Initialize your data structure here. Set the size of the deque to be k.
"""
self.capicity = k + 1
self.items = [True] * self.capicity
self.head, self.tail = 0, 0
def insertFro... | 0.68056 | 0.33334 |
EMSCRIPTEN_TAGS = {
"2.0.32": struct(
hash = "74646397e3c5010824ad60d1de86c6bcbe334dff",
sha_linux = "236b3954e71d3bb30d347c655b9f47f2a091aa2e61046e1912c8da90152f4ca1",
sha_mac = "6a03267574534948e3b041e5d3e31bd757751ef17912eb6e90b96a47da03afb6",
sha_win = "2f8fbf0db097d67d0c364946f... | bazel/revisions.bzl |
EMSCRIPTEN_TAGS = {
"2.0.32": struct(
hash = "74646397e3c5010824ad60d1de86c6bcbe334dff",
sha_linux = "236b3954e71d3bb30d347c655b9f47f2a091aa2e61046e1912c8da90152f4ca1",
sha_mac = "6a03267574534948e3b041e5d3e31bd757751ef17912eb6e90b96a47da03afb6",
sha_win = "2f8fbf0db097d67d0c364946f... | 0.227985 | 0.315921 |
from fastapi import APIRouter, Depends, HTTPException, Query, Path
from sqlmodel import Session, select
from sqlalchemy.exc import IntegrityError
from typing import List
import datetime as dt
from app.src.common.security import get_current_user
from app.src.common.utils import profiling_api
from app.src.models.app_us... | app/src/api/endpoints/product_type.py | from fastapi import APIRouter, Depends, HTTPException, Query, Path
from sqlmodel import Session, select
from sqlalchemy.exc import IntegrityError
from typing import List
import datetime as dt
from app.src.common.security import get_current_user
from app.src.common.utils import profiling_api
from app.src.models.app_us... | 0.60964 | 0.12638 |
from api_gateway.custom_middleware import verify_token
from clamav_scanner.common import AV_DEFINITION_PATH, create_dir
from clamav_scanner.scan import launch_scan
from database.db import get_db_session
from fastapi import (
APIRouter,
BackgroundTasks,
Body,
Depends,
File,
Response,
status,
... | api/api_gateway/routers/clamav.py | from api_gateway.custom_middleware import verify_token
from clamav_scanner.common import AV_DEFINITION_PATH, create_dir
from clamav_scanner.scan import launch_scan
from database.db import get_db_session
from fastapi import (
APIRouter,
BackgroundTasks,
Body,
Depends,
File,
Response,
status,
... | 0.345989 | 0.121686 |
import unittest
import higra as hg
import numpy as np
class TestUndirectedGraph(unittest.TestCase):
@staticmethod
def test_graph():
g = hg.UndirectedGraph(4)
g.add_edge(0, 1)
g.add_edge(1, 2)
g.add_edge(0, 2)
return g
def test_add_vertex(self):
g = hg.Und... | test/python/test_structure/test_undirected_graph.py |
import unittest
import higra as hg
import numpy as np
class TestUndirectedGraph(unittest.TestCase):
@staticmethod
def test_graph():
g = hg.UndirectedGraph(4)
g.add_edge(0, 1)
g.add_edge(1, 2)
g.add_edge(0, 2)
return g
def test_add_vertex(self):
g = hg.Und... | 0.628521 | 0.787646 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
import numpy as np
from torch.nn.utils import weight_norm
import pickle
import sys
from termcolor import colored
from modules.hierarchical_embedding import HierarchicalEmbedding
from modules.embeddings import LearnableEmbedding... | src/graph_transformer.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
import numpy as np
from torch.nn.utils import weight_norm
import pickle
import sys
from termcolor import colored
from modules.hierarchical_embedding import HierarchicalEmbedding
from modules.embeddings import LearnableEmbedding... | 0.846673 | 0.478285 |
"""Tests for input generator."""
from absl.testing import parameterized
import lingvo.compat as tf
from lingvo.core import cluster_factory
from lingvo.core import py_utils
from lingvo.core import test_helper
from lingvo.core import test_utils
from lingvo.core import tokenizers
from lingvo.tasks.mt import input_generat... | lingvo/tasks/mt/input_generator_test.py | """Tests for input generator."""
from absl.testing import parameterized
import lingvo.compat as tf
from lingvo.core import cluster_factory
from lingvo.core import py_utils
from lingvo.core import test_helper
from lingvo.core import test_utils
from lingvo.core import tokenizers
from lingvo.tasks.mt import input_generat... | 0.746786 | 0.406509 |
# <NAME>
# Demonstrates OpenGL Texture Coordinate Generation
# <EMAIL>
#
# based on Texgen.cpp
# OpenGL SuperBible
# Program by <NAME>.
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from PIL import Image
import time
ESCAPE = b'\033'
import sys
sys.path.append("../... | chapt09/texgen.py |
# <NAME>
# Demonstrates OpenGL Texture Coordinate Generation
# <EMAIL>
#
# based on Texgen.cpp
# OpenGL SuperBible
# Program by <NAME>.
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from PIL import Image
import time
ESCAPE = b'\033'
import sys
sys.path.append("../... | 0.487063 | 0.17774 |
import json
import os
import datetime
from modules import hashfunc
from modules import savegamedata
def setup_match():
""" Setup a game between two teams.
Arguments: None
While running the function, the team file is read from the 'teams' folder.
Returns:
None. Updates the match pairings
""... | src/registerformatch.py | import json
import os
import datetime
from modules import hashfunc
from modules import savegamedata
def setup_match():
""" Setup a game between two teams.
Arguments: None
While running the function, the team file is read from the 'teams' folder.
Returns:
None. Updates the match pairings
""... | 0.484868 | 0.247848 |
import _pickle as Pickle
import gzip
# Third-party libraries
import numpy as np
def load_data():
"""Return the MNIST data as a tuple containing the training data,
the validation data, and the test data."""
"""The ``training_data`` is returned as a tuple with two entries.
The first entry contains the... | mnist_loader.py | import _pickle as Pickle
import gzip
# Third-party libraries
import numpy as np
def load_data():
"""Return the MNIST data as a tuple containing the training data,
the validation data, and the test data."""
"""The ``training_data`` is returned as a tuple with two entries.
The first entry contains the... | 0.891652 | 0.844985 |
import time
def _clamp(value, limits):
lower, upper = limits
if value is None:
return None
elif (upper is not None) and (value > upper):
return upper
elif (lower is not None) and (value < lower):
return lower
return value
try:
scale = 1e9
def _to_s():
ret... | circuitpy/PID_CPY.py | import time
def _clamp(value, limits):
lower, upper = limits
if value is None:
return None
elif (upper is not None) and (value > upper):
return upper
elif (lower is not None) and (value < lower):
return lower
return value
try:
scale = 1e9
def _to_s():
ret... | 0.675122 | 0.37958 |
from tensorflow.keras import layers, Model, Sequential
def _make_divisible(ch, divisor=8, min_ch=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/maste... | deep-learning-for-image-processing-master/tensorflow_classification/ConfusionMatrix/model.py | from tensorflow.keras import layers, Model, Sequential
def _make_divisible(ch, divisor=8, min_ch=None):
"""
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/blob/maste... | 0.953837 | 0.445168 |
import logging
from genie.harness.base import Trigger
from pyats import aetest
from pyats.async_ import pcall
log = logging.getLogger(__name__)
class SaveDeviceConfigurationToFile(Trigger):
""" Trigger to save the running configuration of a device to a file """
@aetest.test
def saving_config(self, steps... | save_running_config_to_file/triggers/triggers.py | import logging
from genie.harness.base import Trigger
from pyats import aetest
from pyats.async_ import pcall
log = logging.getLogger(__name__)
class SaveDeviceConfigurationToFile(Trigger):
""" Trigger to save the running configuration of a device to a file """
@aetest.test
def saving_config(self, steps... | 0.678753 | 0.134861 |
import pytest
from decoy import Decoy, matchers
from typing import List, cast
from opentrons_shared_data.protocol.dev_types import JsonProtocol as JsonProtocolDict
from opentrons.hardware_control import API as HardwareAPI
from opentrons.protocols.api_support.types import APIVersion
from opentrons.protocols.models imp... | api/tests/opentrons/protocol_runner/test_protocol_runner.py | import pytest
from decoy import Decoy, matchers
from typing import List, cast
from opentrons_shared_data.protocol.dev_types import JsonProtocol as JsonProtocolDict
from opentrons.hardware_control import API as HardwareAPI
from opentrons.protocols.api_support.types import APIVersion
from opentrons.protocols.models imp... | 0.865722 | 0.287755 |
from ....dyn.form.component.check_box import CheckBox as CheckBox
from ....dyn.form.component.combo_box import ComboBox as ComboBox
from ....dyn.form.component.command_button import CommandButton as CommandButton
from ....dyn.form.component.currency_field import CurrencyField as CurrencyField
from ....dyn.form.componen... | ooobuild/cssdyn/form/component/__init__.py | from ....dyn.form.component.check_box import CheckBox as CheckBox
from ....dyn.form.component.combo_box import ComboBox as ComboBox
from ....dyn.form.component.command_button import CommandButton as CommandButton
from ....dyn.form.component.currency_field import CurrencyField as CurrencyField
from ....dyn.form.componen... | 0.453746 | 0.083853 |
import email
import imaplib
import json
import smtplib, ssl
from mailbox import Message
from typing import Union, List
from classifier import Classifier
from model.addressee import Addressee
from model.mail import Mail
class ApiMail:
def __init__(self, user: str, password: str, server_name: str, port: int) -> N... | project/api_mail.py | import email
import imaplib
import json
import smtplib, ssl
from mailbox import Message
from typing import Union, List
from classifier import Classifier
from model.addressee import Addressee
from model.mail import Mail
class ApiMail:
def __init__(self, user: str, password: str, server_name: str, port: int) -> N... | 0.374448 | 0.110567 |
from sklearn.metrics import f1_score, accuracy_score
from sklearn.metrics import confusion_matrix
import numpy as np
from sklearn.model_selection import train_test_split, StratifiedKFold
from ..formatting.format_util import y_to_categorical
def get_scores(y_true, y_pred):
if y_true.ndim > 1:
y_true = np.a... | minder_utils/evaluate/eval_utils.py | from sklearn.metrics import f1_score, accuracy_score
from sklearn.metrics import confusion_matrix
import numpy as np
from sklearn.model_selection import train_test_split, StratifiedKFold
from ..formatting.format_util import y_to_categorical
def get_scores(y_true, y_pred):
if y_true.ndim > 1:
y_true = np.a... | 0.693058 | 0.792103 |
from stuff import *
import numpy as np
from math import exp,log,sqrt
from scipy.stats import kendalltau
mindate='0000-00-00'
maxdate='9999-99-99'
mincount=10
prlevel=1
if len(sys.argv)>1: mindate=sys.argv[1]
if len(sys.argv)>2: maxdate=sys.argv[2]
if len(sys.argv)>3: mincount=int(sys.argv[3])
print("Using date range"... | VOCgrowth/rankcorrgrowth-gentimes.py |
from stuff import *
import numpy as np
from math import exp,log,sqrt
from scipy.stats import kendalltau
mindate='0000-00-00'
maxdate='9999-99-99'
mincount=10
prlevel=1
if len(sys.argv)>1: mindate=sys.argv[1]
if len(sys.argv)>2: maxdate=sys.argv[2]
if len(sys.argv)>3: mincount=int(sys.argv[3])
print("Using date range"... | 0.242026 | 0.14885 |
from flask import render_template, flash, redirect, url_for, request, current_app, jsonify
from flask_login import current_user, login_required
from flask_babel import _, get_locale
from app import db
from app.models import Cases
from app.case_new.scraper.cp_case_scraper import CPCaseScraper
from app.case_his import b... | app/case_his/routes.py | from flask import render_template, flash, redirect, url_for, request, current_app, jsonify
from flask_login import current_user, login_required
from flask_babel import _, get_locale
from app import db
from app.models import Cases
from app.case_new.scraper.cp_case_scraper import CPCaseScraper
from app.case_his import b... | 0.20834 | 0.065845 |
__author__ = '<EMAIL> (<NAME>)'
import random
import re
import socket
import sys
import time
# external dependencies (from nb_third_party)
import dns.exception
import dns.message
import dns.name
import dns.query
import dns.rcode
import dns.rdataclass
import dns.rdatatype
import dns.resolver
import dns.reversename
imp... | libnamebench/nameserver.py | __author__ = '<EMAIL> (<NAME>)'
import random
import re
import socket
import sys
import time
# external dependencies (from nb_third_party)
import dns.exception
import dns.message
import dns.name
import dns.query
import dns.rcode
import dns.rdataclass
import dns.rdatatype
import dns.resolver
import dns.reversename
imp... | 0.426322 | 0.085404 |
import discord
from discord.ext import commands
import config
import MySQLdb
#Discord API
discordToken = config.discord["key"]
bot = discord.Client()
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), description='Saves a user\'s astrology information')
#Variables
conn = MySQLdb.connect(user="root", p... | main.py | import discord
from discord.ext import commands
import config
import MySQLdb
#Discord API
discordToken = config.discord["key"]
bot = discord.Client()
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), description='Saves a user\'s astrology information')
#Variables
conn = MySQLdb.connect(user="root", p... | 0.375936 | 0.078678 |
from __future__ import print_function
import sys
import requests
import json
import os
import multiprocessing
def update(launchtype, session, headers, endpoint, HOST, projectId, machinelist, dryrun, serverlist):
if launchtype == "test" or launchtype == "cutover":
try:
b = requests.g... | source/CE-Integration/UpdateBlueprint.py |
from __future__ import print_function
import sys
import requests
import json
import os
import multiprocessing
def update(launchtype, session, headers, endpoint, HOST, projectId, machinelist, dryrun, serverlist):
if launchtype == "test" or launchtype == "cutover":
try:
b = requests.g... | 0.168549 | 0.082809 |
import os
import logging
import secrets
import shutil
from ..rpc import get_default_datadir, RPC_PORTS
from ..specter_error import SpecterError
from ..persistence import write_node, delete_file
from ..helpers import alias, load_jsons
from ..node import Node
from ..internal_node import InternalNode
from ..util.bitcoind... | src/cryptoadvance/specter/managers/node_manager.py | import os
import logging
import secrets
import shutil
from ..rpc import get_default_datadir, RPC_PORTS
from ..specter_error import SpecterError
from ..persistence import write_node, delete_file
from ..helpers import alias, load_jsons
from ..node import Node
from ..internal_node import InternalNode
from ..util.bitcoind... | 0.375134 | 0.119408 |
from sage.structure.sage_object import SageObject
class MethodDecorator(SageObject):
def __init__(self, f):
"""
EXAMPLE::
sage: from sage.misc.method_decorator import MethodDecorator
sage: class Foo:
... @MethodDecorator
... def bar(self, ... | src/sage/misc/method_decorator.py | from sage.structure.sage_object import SageObject
class MethodDecorator(SageObject):
def __init__(self, f):
"""
EXAMPLE::
sage: from sage.misc.method_decorator import MethodDecorator
sage: class Foo:
... @MethodDecorator
... def bar(self, ... | 0.867008 | 0.362715 |
import os
import sys
import json
import pytest
from click.testing import CliRunner
from chalice.cli import newproj
try:
from aws_cdk import core as cdk
except Exception:
pytestmark = pytest.mark.skip(
"aws_cdk package needed to run CDK tests.")
@pytest.fixture
def runner():
return CliRunner()
... | tests/functional/cdk/test_construct.py | import os
import sys
import json
import pytest
from click.testing import CliRunner
from chalice.cli import newproj
try:
from aws_cdk import core as cdk
except Exception:
pytestmark = pytest.mark.skip(
"aws_cdk package needed to run CDK tests.")
@pytest.fixture
def runner():
return CliRunner()
... | 0.341034 | 0.153105 |
from __future__ import print_function
from argparse import ArgumentParser
import os
import subprocess
import re
import sys
import pipes
import tempfile
# Template values set by cuda_autoconf.
CPU_COMPILER = ('/dt7/usr/bin/gcc')
GCC_HOST_COMPILER_PATH = ('/dt7/usr/bin/gcc')
NVCC_PATH = '/usr/local/cuda-10.0/bin/nvcc'... | third_party/toolchains/preconfig/ubuntu16.04/gcc7_manylinux2010-nvcc-cuda10.0/windows/msvc_wrapper_for_nvcc.py | from __future__ import print_function
from argparse import ArgumentParser
import os
import subprocess
import re
import sys
import pipes
import tempfile
# Template values set by cuda_autoconf.
CPU_COMPILER = ('/dt7/usr/bin/gcc')
GCC_HOST_COMPILER_PATH = ('/dt7/usr/bin/gcc')
NVCC_PATH = '/usr/local/cuda-10.0/bin/nvcc'... | 0.509032 | 0.086555 |
from __future__ import absolute_import
import pytest
from django.conf import settings
from django.test import RequestFactory
from django.dispatch import receiver
from importlib import import_module
from django_cas_ng.models import SessionTicket
from django_cas_ng.backends import CASBackend
from django_cas_ng.signals ... | tests/test_signals.py | from __future__ import absolute_import
import pytest
from django.conf import settings
from django.test import RequestFactory
from django.dispatch import receiver
from importlib import import_module
from django_cas_ng.models import SessionTicket
from django_cas_ng.backends import CASBackend
from django_cas_ng.signals ... | 0.560493 | 0.302803 |
# Common Python library imports
# Pip package imports
import pytest
from flask import url_for
from flask_login import current_user
# Internal package imports
@pytest.mark.usefixtures('user')
class TestLogin:
def test_html_get_login(self, client, templates):
r = client.get(url_for('security.login'))
... | tests/security/views/test_login.py |
# Common Python library imports
# Pip package imports
import pytest
from flask import url_for
from flask_login import current_user
# Internal package imports
@pytest.mark.usefixtures('user')
class TestLogin:
def test_html_get_login(self, client, templates):
r = client.get(url_for('security.login'))
... | 0.52829 | 0.33516 |
import numpy as np
import mindspore as ms
import mindspore.context as context
from mindspore.common.api import _executor
from mindspore import Tensor, Parameter
import mindspore.nn as nn
from mindspore.nn import Cell, TrainOneStepCell, Momentum
from mindspore.ops import operations as P
class TwoInputBpropOperator(Ce... | tests/ut/python/parallel/test_mul_div_bn.py |
import numpy as np
import mindspore as ms
import mindspore.context as context
from mindspore.common.api import _executor
from mindspore import Tensor, Parameter
import mindspore.nn as nn
from mindspore.nn import Cell, TrainOneStepCell, Momentum
from mindspore.ops import operations as P
class TwoInputBpropOperator(Ce... | 0.756447 | 0.317281 |
import argparse
import math
import os
import platform
import re
import select
import socket
import string
import struct
import subprocess
import sys
import tempfile
from timeit import default_timer as timer
try:
import serial
except:
print("Please install pyserial")
exit(1)
try:
import readline
except:... | term/term.py |
import argparse
import math
import os
import platform
import re
import select
import socket
import string
import struct
import subprocess
import sys
import tempfile
from timeit import default_timer as timer
try:
import serial
except:
print("Please install pyserial")
exit(1)
try:
import readline
except:... | 0.274449 | 0.112893 |
import unittest
from concurrent import futures
import grpc
from testutils import getZserioApi, TEST_ARGS
def _convertRgbToCmyk(rgb):
# see https://www.rapidtables.com/convert/color/rgb-to-cmyk.html
rr = rgb[0] / 255. * 100
gg = rgb[1] / 255. * 100
bb = rgb[2] / 255. * 100
k = 100. - max(rr, gg, b... | test/language/service_types/python/ComplexTypesServiceTest.py | import unittest
from concurrent import futures
import grpc
from testutils import getZserioApi, TEST_ARGS
def _convertRgbToCmyk(rgb):
# see https://www.rapidtables.com/convert/color/rgb-to-cmyk.html
rr = rgb[0] / 255. * 100
gg = rgb[1] / 255. * 100
bb = rgb[2] / 255. * 100
k = 100. - max(rr, gg, b... | 0.614625 | 0.144964 |
from pathlib import Path
import numpy as np
from alphaex.sweeper import Sweeper
class Result:
def __init__(self, config_filename, datapath, num_runs):
self.config_filename = config_filename
self.datapath = datapath
self.sweeper = Sweeper(
Path(__file__).parents[1] / "configs" ... | analysis/results.py | from pathlib import Path
import numpy as np
from alphaex.sweeper import Sweeper
class Result:
def __init__(self, config_filename, datapath, num_runs):
self.config_filename = config_filename
self.datapath = datapath
self.sweeper = Sweeper(
Path(__file__).parents[1] / "configs" ... | 0.777131 | 0.316792 |
import unittest
from mock import Mock, patch
from datawinners.project import helper
from datawinners.project.models import delete_datasenders_from_project
from mangrove.datastore.database import DatabaseManager
from mangrove.errors.MangroveException import FormModelDoesNotExistsException
from mangrove.form_model.fie... | datawinners/project/tests/test_helper.py |
import unittest
from mock import Mock, patch
from datawinners.project import helper
from datawinners.project.models import delete_datasenders_from_project
from mangrove.datastore.database import DatabaseManager
from mangrove.errors.MangroveException import FormModelDoesNotExistsException
from mangrove.form_model.fie... | 0.47317 | 0.393968 |
from tunguska import gfdb, receiver, seismosizer, source, config
from pyrocko import orthodrome
from subprocess import call, Popen, PIPE
import numpy as num
import sys, time, signal
import logging
from os.path import join as pj
logformat = '[%(asctime)s] %(levelname)-8s %(message)s'
dateformat = '%Y-%m-%d %H:%M:%S'... | benchmark/kiwibench.py | from tunguska import gfdb, receiver, seismosizer, source, config
from pyrocko import orthodrome
from subprocess import call, Popen, PIPE
import numpy as num
import sys, time, signal
import logging
from os.path import join as pj
logformat = '[%(asctime)s] %(levelname)-8s %(message)s'
dateformat = '%Y-%m-%d %H:%M:%S'... | 0.170163 | 0.09343 |
import os
import csv
# sets up my variable election data and tells computer where to find this file
csv_file_path = os.path.join("py_poll_resources", "election_data.csv")
print(csv_file_path)
# define and initialize variables
total_votes = 0
# Opens the file as a csv type
with open(csv_file_path) as csv_file... | py_poll/py_poll_mail.py | import os
import csv
# sets up my variable election data and tells computer where to find this file
csv_file_path = os.path.join("py_poll_resources", "election_data.csv")
print(csv_file_path)
# define and initialize variables
total_votes = 0
# Opens the file as a csv type
with open(csv_file_path) as csv_file... | 0.08752 | 0.201165 |
# Copyright 2021 <NAME> (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import division
from __future__ import print_function
import argparse
from distutils.util import strtobool
import multiprocessing as mp
import os
import sys
import numpy as np
import soundfile as ... | src/bin/proc_wav_pqmf.py |
# Copyright 2021 <NAME> (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import division
from __future__ import print_function
import argparse
from distutils.util import strtobool
import multiprocessing as mp
import os
import sys
import numpy as np
import soundfile as ... | 0.410047 | 0.141756 |
from __future__ import unicode_literals
import fnmatch
import logging
import signal
import sys
import time
import multiprocessing
import threading
from .signals import consumer_started, consumer_finished
from .exceptions import ConsumeLater, DenyConnection
from .message import Message
from .utils import name_that_thi... | channels/worker.py | from __future__ import unicode_literals
import fnmatch
import logging
import signal
import sys
import time
import multiprocessing
import threading
from .signals import consumer_started, consumer_finished
from .exceptions import ConsumeLater, DenyConnection
from .message import Message
from .utils import name_that_thi... | 0.464173 | 0.077274 |
from django.http import JsonResponse
from django.core.cache import cache
import requests
from django.contrib.auth.models import User
from game.models.player.player import Player
from random import randint
def receive_code(request):
data = request.GET
if "err _code" in data:
return JsonResponse({
... | game/views/settings/acwing/acapp/receive_code.py | from django.http import JsonResponse
from django.core.cache import cache
import requests
from django.contrib.auth.models import User
from game.models.player.player import Player
from random import randint
def receive_code(request):
data = request.GET
if "err _code" in data:
return JsonResponse({
... | 0.258981 | 0.101189 |
import collections
import json
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from dtf.validators import JSONSchemaValidator
class Membership(models.Model):
user = models.ForeignKey(
User,
null=False,
blank=False,
related... | dtf/models.py | import collections
import json
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from dtf.validators import JSONSchemaValidator
class Membership(models.Model):
user = models.ForeignKey(
User,
null=False,
blank=False,
related... | 0.511473 | 0.157687 |
"""Contains definitions of RevNet."""
from typing import Any, Callable, Dict, Optional
# Import libraries
import tensorflow as tf
from official.modeling import tf_utils
from official.vision.beta.modeling.backbones import factory
from official.vision.beta.modeling.layers import nn_blocks
# Specifications for differen... | official/vision/beta/modeling/backbones/revnet.py | """Contains definitions of RevNet."""
from typing import Any, Callable, Dict, Optional
# Import libraries
import tensorflow as tf
from official.modeling import tf_utils
from official.vision.beta.modeling.backbones import factory
from official.vision.beta.modeling.layers import nn_blocks
# Specifications for differen... | 0.97736 | 0.560012 |
"""Provides interfaces to various commands provided by diffusion toolkit
"""
import os
import re
from ...utils.filemanip import fname_presuffix, split_filename, copyfile
from ..base import (TraitedSpec, File, traits, CommandLine,
CommandLineInputSpec, isdefined)
__docformat__ = 'restructuredtext'
... | nipype/interfaces/diffusion_toolkit/odf.py | """Provides interfaces to various commands provided by diffusion toolkit
"""
import os
import re
from ...utils.filemanip import fname_presuffix, split_filename, copyfile
from ..base import (TraitedSpec, File, traits, CommandLine,
CommandLineInputSpec, isdefined)
__docformat__ = 'restructuredtext'
... | 0.642545 | 0.362715 |
import sys
import logging
import datetime
import os
import pyramid_dogpile_cache
import transaction
from gengine.base.util import dt_ago, dt_now
from sqlalchemy.sql.expression import and_
from zope.sqlalchemy.datamanager import mark_changed
from gengine.app.cache import init_caches
from pyramid.config import Configur... | gengine/maintenance/scripts/scheduler_beat.py | import sys
import logging
import datetime
import os
import pyramid_dogpile_cache
import transaction
from gengine.base.util import dt_ago, dt_now
from sqlalchemy.sql.expression import and_
from zope.sqlalchemy.datamanager import mark_changed
from gengine.app.cache import init_caches
from pyramid.config import Configur... | 0.219254 | 0.105165 |
# coding: utf-8
"""
Polyaxon SDKs and REST API specification.
Polyaxon SDKs and REST API specification. # noqa: E501
The version of the OpenAPI document: 1.18.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except ImportError:
... | python/http_client/v1/polyaxon_sdk/models/v1_event_kind.py |
# coding: utf-8
"""
Polyaxon SDKs and REST API specification.
Polyaxon SDKs and REST API specification. # noqa: E501
The version of the OpenAPI document: 1.18.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except ImportError:
... | 0.524638 | 0.076408 |
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev
import sys
import os
import crc16
# Initialize GPIOs
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Define the pipes that will be used to send the data from one transceiver to the other
pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc... | qm-send-complete.py |
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev
import sys
import os
import crc16
# Initialize GPIOs
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Define the pipes that will be used to send the data from one transceiver to the other
pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc... | 0.471467 | 0.311662 |
import shutil
import os
import json
import tarfile
from uuid import uuid4
from datetime import datetime
from flask_securest.rest_security import SecuredResource
from flask_restful_swagger import swagger
from flask import request
from manager_rest import resources
from manager_rest.resources import (marshal_with,
... | rest-service/manager_rest/resources_v2.py | import shutil
import os
import json
import tarfile
from uuid import uuid4
from datetime import datetime
from flask_securest.rest_security import SecuredResource
from flask_restful_swagger import swagger
from flask import request
from manager_rest import resources
from manager_rest.resources import (marshal_with,
... | 0.59514 | 0.113875 |
import os
def read_columnar_data(filename, number_columns=0, comment_character='#'):
"""
Read in a file containing variable number of columns
Lines beginning with comment_character are ignored
"""
if not os.path.exists(filename):
raise IOError("Data file %s not found" % filename)
resul... | brownies/BNL/plot_evaluation/plotio.py | import os
def read_columnar_data(filename, number_columns=0, comment_character='#'):
"""
Read in a file containing variable number of columns
Lines beginning with comment_character are ignored
"""
if not os.path.exists(filename):
raise IOError("Data file %s not found" % filename)
resul... | 0.290578 | 0.276311 |
""" Tests for Network ACLs in VPC
"""
#Import Local Modules
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin.integration.lib.utils import *
from marvin.integration.lib.base import *
from marvin.integration.lib.common import *
from nose.plugins.attrib import attr
class TestPrivate... | test/integration/smoke/test_privategw_acl.py | """ Tests for Network ACLs in VPC
"""
#Import Local Modules
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin.integration.lib.utils import *
from marvin.integration.lib.base import *
from marvin.integration.lib.common import *
from nose.plugins.attrib import attr
class TestPrivate... | 0.322633 | 0.138316 |
from unittest import TestCase
from faker import Faker
from logzero import logger
from sqlalchemy import MetaData
from covigator.database.database import Database
from covigator.database.model import VariantCooccurrence, SampleEna, Sample, JobEna, JobGisaid, VariantObservation, \
SampleGisaid, SubclonalVariantObser... | covigator/tests/unit_tests/abstract_test.py | from unittest import TestCase
from faker import Faker
from logzero import logger
from sqlalchemy import MetaData
from covigator.database.database import Database
from covigator.database.model import VariantCooccurrence, SampleEna, Sample, JobEna, JobGisaid, VariantObservation, \
SampleGisaid, SubclonalVariantObser... | 0.754192 | 0.384161 |
from datetime import datetime
import requests
import json
import os
from dateutil import parser
# While true to get a actual link
from loguru import logger
def fetch_info(url=""):
try:
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36'
... | shopifychecker.py | from datetime import datetime
import requests
import json
import os
from dateutil import parser
# While true to get a actual link
from loguru import logger
def fetch_info(url=""):
try:
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36'
... | 0.453504 | 0.175044 |
import aiohttp
import asyncio
import async_timeout
from yarl import URL
from xml.parsers.expat import ExpatError
from typing import Any
from .__version__ import __version__
from .const import (
DEFAULT_PORT,
DEFAULT_TIMEOUT,
)
from .exceptions import (
SolarEnergyError,
SolarEnergyConnectionError,
... | pysolarenergy/inverter.py | import aiohttp
import asyncio
import async_timeout
from yarl import URL
from xml.parsers.expat import ExpatError
from typing import Any
from .__version__ import __version__
from .const import (
DEFAULT_PORT,
DEFAULT_TIMEOUT,
)
from .exceptions import (
SolarEnergyError,
SolarEnergyConnectionError,
... | 0.786295 | 0.117294 |
import os
import pymongo
import virtool.subtractions.db
import virtool.jobs.job
import virtool.jobs.utils
import virtool.subtractions.utils
import virtool.utils
class Job(virtool.jobs.job.Job):
"""
A subclass of :class:`.Job` that adds a new host to Virtool from a passed FASTA file.
"""
def __init... | virtool/jobs/create_subtraction.py | import os
import pymongo
import virtool.subtractions.db
import virtool.jobs.job
import virtool.jobs.utils
import virtool.subtractions.utils
import virtool.utils
class Job(virtool.jobs.job.Job):
"""
A subclass of :class:`.Job` that adds a new host to Virtool from a passed FASTA file.
"""
def __init... | 0.630799 | 0.266936 |
from programytest.parser.pattern.matching.base import PatternMatcherBaseClass
class PatternMatcherTests(PatternMatcherBaseClass):
def test_star_tree_matching_single(self):
self.add_pattern_to_graph(pattern="*", topic="X", that="Y", template="1")
context = self.match_sentence("A B D", topic="X",... | dialogue-engine/test/programytest/parser/pattern/matching/test_star.py | from programytest.parser.pattern.matching.base import PatternMatcherBaseClass
class PatternMatcherTests(PatternMatcherBaseClass):
def test_star_tree_matching_single(self):
self.add_pattern_to_graph(pattern="*", topic="X", that="Y", template="1")
context = self.match_sentence("A B D", topic="X",... | 0.774498 | 0.738834 |
import os
import slash
from ....lib.gstreamer.encoderbase import BaseEncoderTest
from ....lib.gstreamer.util import have_gst_element
from ....lib.gstreamer.msdk.util import using_compatible_driver, mapprofile, map_best_hw_format, mapformat, mapformatu
from ....lib.common import get_media
@slash.requires(*have_gst_el... | lib/gstreamer/msdk/encoder.py |
import os
import slash
from ....lib.gstreamer.encoderbase import BaseEncoderTest
from ....lib.gstreamer.util import have_gst_element
from ....lib.gstreamer.msdk.util import using_compatible_driver, mapprofile, map_best_hw_format, mapformat, mapformatu
from ....lib.common import get_media
@slash.requires(*have_gst_el... | 0.232397 | 0.09709 |
from django.test import TestCase, RequestFactory
from django.http import HttpResponse
from django.utils import timezone
from .loggers.base import BaseLogger
from .loggers.request import RequestLogger
from .loggers.process import ProcessLogger
from .backends.base import BaseDataBackend
from .backends.database import Da... | logexpose/tests.py | from django.test import TestCase, RequestFactory
from django.http import HttpResponse
from django.utils import timezone
from .loggers.base import BaseLogger
from .loggers.request import RequestLogger
from .loggers.process import ProcessLogger
from .backends.base import BaseDataBackend
from .backends.database import Da... | 0.439266 | 0.134463 |
from typing import List, Optional
import numpy as np
from ax.core.observation import ObservationData, ObservationFeatures
from ax.core.search_space import SearchSpace
from ax.core.types import TConfig
from ax.modelbridge.transforms.base import Transform
from ax.modelbridge.transforms.utils import get_data
from ax.uti... | ax/modelbridge/transforms/winsorize.py |
from typing import List, Optional
import numpy as np
from ax.core.observation import ObservationData, ObservationFeatures
from ax.core.search_space import SearchSpace
from ax.core.types import TConfig
from ax.modelbridge.transforms.base import Transform
from ax.modelbridge.transforms.utils import get_data
from ax.uti... | 0.955183 | 0.565299 |
import json
import os
import time
import uuid
from eth_utils import remove_0x_prefix, add_0x_prefix
from web3 import Web3
from eth_account import Account
from web3.datastructures import AttributeDict
from aquarius.events.util import get_metadata_contract, deploy_datatoken
from aquarius.events.constants import EVENT_M... | tests/helpers.py | import json
import os
import time
import uuid
from eth_utils import remove_0x_prefix, add_0x_prefix
from web3 import Web3
from eth_account import Account
from web3.datastructures import AttributeDict
from aquarius.events.util import get_metadata_contract, deploy_datatoken
from aquarius.events.constants import EVENT_M... | 0.275519 | 0.108732 |
import matplotlib.pyplot as plt
import pandas
# calculate the number of positive and negetive samples of each attribute
def stat_attr(file_path):
pos_samples = [0 for i in range(40)]
neg_samples = [0 for i in range(40)]
#attri_id = [i + 1 for i in range(40)]
#attr_name = []
with open(file_path) ... | data_analysis/analysis_attr.py | import matplotlib.pyplot as plt
import pandas
# calculate the number of positive and negetive samples of each attribute
def stat_attr(file_path):
pos_samples = [0 for i in range(40)]
neg_samples = [0 for i in range(40)]
#attri_id = [i + 1 for i in range(40)]
#attr_name = []
with open(file_path) ... | 0.305594 | 0.469642 |
import enum
import json
import os
from chalice import Chalice
from chalice.app import S3Event
import boto3
import yaml
from typing import TYPE_CHECKING
app = Chalice(app_name="cfn__resource_injection")
class CfnType(enum.Enum):
YAML = 0
JSON = 1
# The Role name is used to check if the lambda has already... | pacu/modules/cfn__resource_injection/cfn__resource_injection_lambda/app.py | import enum
import json
import os
from chalice import Chalice
from chalice.app import S3Event
import boto3
import yaml
from typing import TYPE_CHECKING
app = Chalice(app_name="cfn__resource_injection")
class CfnType(enum.Enum):
YAML = 0
JSON = 1
# The Role name is used to check if the lambda has already... | 0.23014 | 0.155142 |
import argparse
import logging
import re
import collections
import sqlite3
import os
import sys
this_dir = os.path.dirname(os.path.realpath(__file__))
base_dir = os.path.join(this_dir, '..', '..', '..')
sys.path.append(base_dir)
import spar_python.report_generation.ta2.ta2_database as ta2_database
import spar_python.... | spar_python/analytics/ta2/parse_circuit_log.py |
import argparse
import logging
import re
import collections
import sqlite3
import os
import sys
this_dir = os.path.dirname(os.path.realpath(__file__))
base_dir = os.path.join(this_dir, '..', '..', '..')
sys.path.append(base_dir)
import spar_python.report_generation.ta2.ta2_database as ta2_database
import spar_python.... | 0.156041 | 0.131006 |
import os
import sys
import pytest
import importlib
import numpy as np
from pandas import DataFrame
from pandas.util.testing import assert_frame_equal
import taxcalc
from taxcalc.decorators import *
def test_create_apply_function_string():
ans = create_apply_function_string(['a', 'b', 'c'], ['d', 'e'], [])
e... | Tax-Calculator-2.9.0/taxcalc/tests/test_decorators.py |
import os
import sys
import pytest
import importlib
import numpy as np
from pandas import DataFrame
from pandas.util.testing import assert_frame_equal
import taxcalc
from taxcalc.decorators import *
def test_create_apply_function_string():
ans = create_apply_function_string(['a', 'b', 'c'], ['d', 'e'], [])
e... | 0.41561 | 0.47792 |
import difflib
import os
import re
import shutil
import subprocess
import sys
import unittest
from unittest.mock import patch
import mys.cli
from mys.transpiler import Source
from mys.transpiler import TranspilerError
from mys.transpiler import transpile
class TestCase(unittest.TestCase):
maxDiff = None
de... | tests/utils.py | import difflib
import os
import re
import shutil
import subprocess
import sys
import unittest
from unittest.mock import patch
import mys.cli
from mys.transpiler import Source
from mys.transpiler import TranspilerError
from mys.transpiler import transpile
class TestCase(unittest.TestCase):
maxDiff = None
de... | 0.328314 | 0.299018 |
import os
import json
import math
import pika
import requests
import pytz
import datetime
import dateutil.parser as iso_parser
from tqdm import tqdm
ENV = [
'COUCH_HOST',
'RABBIT_HOST',
'RABBIT_USER',
'RABBIT_PASS'
]
COUCHDB = ''
PROPERTIES = pika.BasicProperties(delivery_mode=2,)
DBs = {}
def han... | support/scripts/couchdb_to_titan.py | import os
import json
import math
import pika
import requests
import pytz
import datetime
import dateutil.parser as iso_parser
from tqdm import tqdm
ENV = [
'COUCH_HOST',
'RABBIT_HOST',
'RABBIT_USER',
'RABBIT_PASS'
]
COUCHDB = ''
PROPERTIES = pika.BasicProperties(delivery_mode=2,)
DBs = {}
def han... | 0.242475 | 0.074131 |
from contextlib import contextmanager
from flask import flash, session
from markupsafe import Markup, escape
from sqlalchemy.orm import joinedload
from indico.core.db import db
from indico.core.db.sqlalchemy.links import LinkType
from indico.util.i18n import _, ngettext
from indico.util.struct.iterables import mater... | indico/modules/events/management/util.py |
from contextlib import contextmanager
from flask import flash, session
from markupsafe import Markup, escape
from sqlalchemy.orm import joinedload
from indico.core.db import db
from indico.core.db.sqlalchemy.links import LinkType
from indico.util.i18n import _, ngettext
from indico.util.struct.iterables import mater... | 0.658527 | 0.089494 |
import collections
from ast import literal_eval
from sysinv.common import constants
from sysinv.common import device as dconstants
from sysinv.puppet import base
from sysinv.puppet import quoted_str
class DevicePuppet(base.BasePuppet):
"""Class to encapsulate puppet operations for device configuration"""
... | sysinv/sysinv/sysinv/sysinv/puppet/device.py |
import collections
from ast import literal_eval
from sysinv.common import constants
from sysinv.common import device as dconstants
from sysinv.puppet import base
from sysinv.puppet import quoted_str
class DevicePuppet(base.BasePuppet):
"""Class to encapsulate puppet operations for device configuration"""
... | 0.37777 | 0.099689 |
import logging
import pytest
import sdk_auth
import sdk_cmd
import sdk_hosts
import sdk_install
import sdk_security
import sdk_utils
from security import kerberos as krb5
from tests import auth
from tests import client
from tests import config
pytestmark = [pytest.mark.skipif(sdk_utils.is_open_dcos(),
... | frameworks/kafka/tests/test_zookeeper_auth.py | import logging
import pytest
import sdk_auth
import sdk_cmd
import sdk_hosts
import sdk_install
import sdk_security
import sdk_utils
from security import kerberos as krb5
from tests import auth
from tests import client
from tests import config
pytestmark = [pytest.mark.skipif(sdk_utils.is_open_dcos(),
... | 0.324985 | 0.168104 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetHubResult',
'AwaitableGetHubResult',
'get_hub',
'get_hub_output',
]
@pulumi.output_type
class GetHubResult:
def... | sdk/python/pulumi_google_native/networkconnectivity/v1/get_hub.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetHubResult',
'AwaitableGetHubResult',
'get_hub',
'get_hub_output',
]
@pulumi.output_type
class GetHubResult:
def... | 0.838349 | 0.100613 |
from Exceptions import *
from SubversionDumpData import SVNDumpData
class SVNDumpFileWriter:
""" Writes a dump file from the data created by SVNDumpFileParser """
def __init__(self, dump):
self.dump = dump
def writeFile(self, file_path):
# open the file
self.... | src/SubversionDumpWriter.py | from Exceptions import *
from SubversionDumpData import SVNDumpData
class SVNDumpFileWriter:
""" Writes a dump file from the data created by SVNDumpFileParser """
def __init__(self, dump):
self.dump = dump
def writeFile(self, file_path):
# open the file
self.... | 0.469277 | 0.121165 |
from spack import *
import os
class SeissolEnv(BundlePackage):
"""Seissol - A scientific software for the numerical simulation of seismic wave phenomena and earthquake dynamics.
This package only provides all necessary libs for seissol installation.
"""
homepage = "http://www.seissol.org"
versio... | spack/packages/seissol-env/package.py |
from spack import *
import os
class SeissolEnv(BundlePackage):
"""Seissol - A scientific software for the numerical simulation of seismic wave phenomena and earthquake dynamics.
This package only provides all necessary libs for seissol installation.
"""
homepage = "http://www.seissol.org"
versio... | 0.489015 | 0.174762 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | tests/ops/qubit/test_arithmetic_ops.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | 0.914324 | 0.681528 |
# N.B. allCountries.sorted.txt and alternateNames.sorted.txt are pre-sorted as follows:
#
# sort -n allCountries.txt > allCountries.sorted.txt
# sort -k2 -n alternateNames.txt > alternateNames.sorted.txt
from core import Dump, tab_file, transliterate
columns = {
"geoname": ["geoname_id", "name", "ascii_na... | etl/parser/geonames.py |
# N.B. allCountries.sorted.txt and alternateNames.sorted.txt are pre-sorted as follows:
#
# sort -n allCountries.txt > allCountries.sorted.txt
# sort -k2 -n alternateNames.txt > alternateNames.sorted.txt
from core import Dump, tab_file, transliterate
columns = {
"geoname": ["geoname_id", "name", "ascii_na... | 0.274157 | 0.274222 |
import os
import re
import json
import copy
from lxml import etree
from xml_rnc2json import Xml_Rnc2JSON
class Tmx2JSON(Xml_Rnc2JSON):
"""
Contains methods to make JSONs ready for indexing from aligned
parallel tmx files in the format used e.g. in Tyumen learner coprora
and a csv with meta... | src_convertors/tmx2json.py | import os
import re
import json
import copy
from lxml import etree
from xml_rnc2json import Xml_Rnc2JSON
class Tmx2JSON(Xml_Rnc2JSON):
"""
Contains methods to make JSONs ready for indexing from aligned
parallel tmx files in the format used e.g. in Tyumen learner coprora
and a csv with meta... | 0.241132 | 0.115761 |
import sys
import traceback
from re import findall
import requests
from requests.exceptions import ConnectionError
class ScrapperException(BaseException):
pass
class Proxies(object):
"""
Proxies is the response data type of getProxies function
"""
def __init__(self, proxies, category):
... | libs/Proxy_List_Scrapper/__init__.py | import sys
import traceback
from re import findall
import requests
from requests.exceptions import ConnectionError
class ScrapperException(BaseException):
pass
class Proxies(object):
"""
Proxies is the response data type of getProxies function
"""
def __init__(self, proxies, category):
... | 0.406744 | 0.217504 |
import numpy as np
import tensorflow as tf
from timeit import default_timer as timer
from keras import backend as K
from PedestrianDetectionFunc.PedestrianDetectionModel import PedestrianModel
class Pedestrian(object):
def __init__(self):
K.clear_session()
self.GPU_config = tf.ConfigProto()
... | PedestrianDetectionFunc/PedestrianDetectionClass.py | import numpy as np
import tensorflow as tf
from timeit import default_timer as timer
from keras import backend as K
from PedestrianDetectionFunc.PedestrianDetectionModel import PedestrianModel
class Pedestrian(object):
def __init__(self):
K.clear_session()
self.GPU_config = tf.ConfigProto()
... | 0.618204 | 0.157169 |
import sqlalchemy
from contextlib import contextmanager
from typing import List, Iterator, Optional, Union, Tuple
import logging
from google.cloud.bigquery.dbapi.connection import Connection
from google.cloud.bigquery.client import Client
from google.cloud.bigquery.job import ExtractJobConfig
from records_mover.db.unlo... | records_mover/db/bigquery/unloader.py | import sqlalchemy
from contextlib import contextmanager
from typing import List, Iterator, Optional, Union, Tuple
import logging
from google.cloud.bigquery.dbapi.connection import Connection
from google.cloud.bigquery.client import Client
from google.cloud.bigquery.job import ExtractJobConfig
from records_mover.db.unlo... | 0.73848 | 0.10618 |
import ctypes
import threading
from nifake._visatype import * # noqa: F403,H303
import nifake.custom_struct as custom_struct # noqa: F401
class Library(object):
'''Library
Wrapper around driver library.
Class will setup the correct ctypes information for every function on first call.
'''
de... | generated/nifake/_library.py |
import ctypes
import threading
from nifake._visatype import * # noqa: F403,H303
import nifake.custom_struct as custom_struct # noqa: F401
class Library(object):
'''Library
Wrapper around driver library.
Class will setup the correct ctypes information for every function on first call.
'''
de... | 0.569613 | 0.074703 |
import os
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1' #Comment to Enable GPU, disable CUDA cores
import numpy as np
from numpy.random import seed #fix random seed for reproducibility (numpy)
seed(1)
from tensorflow import set_random_seed # fix random seed for reproducibility (tensorflow backend)
set_random_seed(2... | Lee_et_Kwon_2016.py | import os
#os.environ['CUDA_VISIBLE_DEVICES'] = '-1' #Comment to Enable GPU, disable CUDA cores
import numpy as np
from numpy.random import seed #fix random seed for reproducibility (numpy)
seed(1)
from tensorflow import set_random_seed # fix random seed for reproducibility (tensorflow backend)
set_random_seed(2... | 0.591487 | 0.315756 |
import json
import sys
import traceback
import logging
from urllib.parse import parse_qsl
global logger
logger = logging.getLogger("wave-api-handler")
class ApiHandler:
def __init__(self, web_root):
self._web_root = web_root
def set_headers(self, response, headers):
if not isinstance(respo... | tools/wave/network/api/api_handler.py |
import json
import sys
import traceback
import logging
from urllib.parse import parse_qsl
global logger
logger = logging.getLogger("wave-api-handler")
class ApiHandler:
def __init__(self, web_root):
self._web_root = web_root
def set_headers(self, response, headers):
if not isinstance(respo... | 0.277179 | 0.07889 |
import json
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import base64
import requests
import tenacity
from ironic.common import exception
from ironic.common.i18n import _
from ironic.common import swift
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
def save_configu... | ironic/common/molds.py |
import json
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import base64
import requests
import tenacity
from ironic.common import exception
from ironic.common.i18n import _
from ironic.common import swift
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
def save_configu... | 0.490236 | 0.127625 |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
install_requires = [
"wheezy.core>=0.1.131",
"wheezy.caching>=0.1.106",
"wheezy.html>=0.1.140",
"wheezy.http>=0.1.314",
"wheezy.routing>=0.1.153",
"wheezy.security>=0.1.61",
... | demos/template/setup.py |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read()
install_requires = [
"wheezy.core>=0.1.131",
"wheezy.caching>=0.1.106",
"wheezy.html>=0.1.140",
"wheezy.http>=0.1.314",
"wheezy.routing>=0.1.153",
"wheezy.security>=0.1.61",
... | 0.341473 | 0.216012 |
from collections import OrderedDict
from typing import Type
from django.db.models.base import Model
from django.db.models.fields import DateField, DateTimeField
from django.db.models.fields.related import ForeignKey
from django.db.models.fields.reverse_related import (
ManyToManyRel, ManyToOneRel, OneToOneRel,
)
f... | mypy_django_plugin/transformers/models.py | from collections import OrderedDict
from typing import Type
from django.db.models.base import Model
from django.db.models.fields import DateField, DateTimeField
from django.db.models.fields.related import ForeignKey
from django.db.models.fields.reverse_related import (
ManyToManyRel, ManyToOneRel, OneToOneRel,
)
f... | 0.729809 | 0.104158 |
import sys
from sympy.external import import_module
matchpy = import_module("matchpy")
if not matchpy:
#bin/test will not execute any tests now
disabled = True
if sys.version_info[:2] < (3, 6):
disabled = True
from sympy.integrals.rubi.parsetools.parse import (rubi_rule_parser,
get_default_values, ad... | venv/lib/python2.7/site-packages/sympy/integrals/rubi/parsetools/tests/test_parse.py | import sys
from sympy.external import import_module
matchpy = import_module("matchpy")
if not matchpy:
#bin/test will not execute any tests now
disabled = True
if sys.version_info[:2] < (3, 6):
disabled = True
from sympy.integrals.rubi.parsetools.parse import (rubi_rule_parser,
get_default_values, ad... | 0.439988 | 0.546859 |
import sys
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.layers import Activation, Conv2D, MaxPooling2D, UpSampling2D
from tensorflow.keras.preprocessing.image import load_img
# Set base filepath. Import helper functions.
path = '/content/drive/My Drive/finding-houses/'
sys.path... | train.py |
import sys
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.layers import Activation, Conv2D, MaxPooling2D, UpSampling2D
from tensorflow.keras.preprocessing.image import load_img
# Set base filepath. Import helper functions.
path = '/content/drive/My Drive/finding-houses/'
sys.path... | 0.828766 | 0.451327 |
import six
import os
from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2common.util import jinja as jinja_utils
class FormatResultAction(Action):
def __init__(self, config=None, action_service=None):
super(FormatResultAction, self).__init__(config=config, actio... | contrib/chatops/actions/format_execution_result.py | import six
import os
from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2common.util import jinja as jinja_utils
class FormatResultAction(Action):
def __init__(self, config=None, action_service=None):
super(FormatResultAction, self).__init__(config=config, actio... | 0.379263 | 0.066236 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_in... | webshell_sdk/model/container/service_spec_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_in... | 0.192122 | 0.080249 |
import argparse
import logging
import traceback
import westpa
import westpa.work_managers as work_managers
from westpa.work_managers import make_work_manager
log = logging.getLogger('w_run')
def entry_point():
parser = argparse.ArgumentParser('w_run', 'start/continue a WEST simulation')
westpa.rc.add_args(... | src/westpa/cli/core/w_run.py | import argparse
import logging
import traceback
import westpa
import westpa.work_managers as work_managers
from westpa.work_managers import make_work_manager
log = logging.getLogger('w_run')
def entry_point():
parser = argparse.ArgumentParser('w_run', 'start/continue a WEST simulation')
westpa.rc.add_args(... | 0.546012 | 0.092074 |
from __future__ import absolute_import
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
def test_varnewaxis_1():
array = ak.Array(
[
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]],
[[15, 16, 17, 18, 19], [20, 21, 22, 23, 24... | tests/test_0693-fixes-for-scipy-prep.py |
from __future__ import absolute_import
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
def test_varnewaxis_1():
array = ak.Array(
[
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]],
[[15, 16, 17, 18, 19], [20, 21, 22, 23, 24... | 0.654122 | 0.582343 |
import time
import holdem_calc.holdem_functions as holdem_functions
import holdem_calc.holdem_argparser as holdem_argparser
def main():
hole_cards, num, exact, board, file_name = holdem_argparser.parse_args()
run(hole_cards, num, exact, board, file_name, True)
def calculate(board, exact, num, input_file, hol... | holdem_calc/holdem_calc.py | import time
import holdem_calc.holdem_functions as holdem_functions
import holdem_calc.holdem_argparser as holdem_argparser
def main():
hole_cards, num, exact, board, file_name = holdem_argparser.parse_args()
run(hole_cards, num, exact, board, file_name, True)
def calculate(board, exact, num, input_file, hol... | 0.526586 | 0.273172 |
import numpy as np
import tensorflow as tf
"""
Utility functions for capsule networks.
"""
def conv(x, scope, *, nf, rf, stride, pad='VALID', init_scale=1.0, data_format='NHWC', one_dim_bias=False):
if data_format == 'NHWC':
channel_ax = 3
strides = [1, stride, stride, 1]
bshape = [1, ... | caps/capsule/utils.py | import numpy as np
import tensorflow as tf
"""
Utility functions for capsule networks.
"""
def conv(x, scope, *, nf, rf, stride, pad='VALID', init_scale=1.0, data_format='NHWC', one_dim_bias=False):
if data_format == 'NHWC':
channel_ax = 3
strides = [1, stride, stride, 1]
bshape = [1, ... | 0.68742 | 0.571288 |
import unittest
from unittest import mock
from libpurecool.dyson_pure_cool import DysonPureCool
from libpurecool.dyson_pure_cool_link import DysonPureCoolLink
from homeassistant.components import dyson as dyson_parent
from homeassistant.components.dyson import sensor as dyson
from homeassistant.const import (
STA... | tests/components/dyson/test_sensor.py | import unittest
from unittest import mock
from libpurecool.dyson_pure_cool import DysonPureCool
from libpurecool.dyson_pure_cool_link import DysonPureCoolLink
from homeassistant.components import dyson as dyson_parent
from homeassistant.components.dyson import sensor as dyson
from homeassistant.const import (
STA... | 0.740644 | 0.476762 |
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
c... | twilio/rest/verify/v2/service/verification_check.py | r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
c... | 0.86421 | 0.235306 |
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from .serializers import PostSerializer, CommentSerializer, AuthorSerializer, StoryFeedSerializer, StoryViewerSerializer,StorySerializer
from rest_framework import permissions, generics, status
... | post/views.py | from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from .serializers import PostSerializer, CommentSerializer, AuthorSerializer, StoryFeedSerializer, StoryViewerSerializer,StorySerializer
from rest_framework import permissions, generics, status
... | 0.566498 | 0.086016 |