id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
170770 | import os
import sys
import argparse
import tensorflow as tf
import numpy as np
from PIL import Image
from reader import Reader
from source.anchor_filter import AnchorFilter
import logging
import random
import time
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
class VS3D(object):
def __init__(self, k... |
170790 | import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def initialize(self):
self.SUPPORTED_METHODS = ("GET", "POST", "PURGE")
def get(self):
self.write("Hello, world")
def post(self):
print ("processing body: %s" % self.request.body)
s... |
170799 | import numpy as np
import unittest
import pytest
from mvc.misc.batch import make_batch
class MakeBatchTest(unittest.TestCase):
def test_success(self):
batch_size = np.random.randint(32) + 1
data_size = batch_size * np.random.randint(10) + 1
data = {
'test1': np.random.random((... |
170808 | import json
import pytest
from lxml import etree
import numpy as np
import xarray as xr
import pandas as pd
import finch
import finch.processes
from finch.processes.wps_xclim_indices import XclimIndicatorBase
from finch.processes.wps_base import make_xclim_indicator_process
from . utils import execute_process, wps_inp... |
170814 | import numpy as np
import matplotlib.pyplot as plt
from tools import get_array, dags
data = dags[0]
find_or_add_index = get_array(data, "find_or_add index")
find_or_add_add = get_array(data, "find_or_add add")
find_or_add_level = get_array(data, "find_or_add level")
plt.xlabel("index")
plt.ylabel("num")
indices_add... |
170825 | import pycristoforo.utils.utils as utils_py
import pycristoforo.geo.key_value_pair as keyvaluepair_py
class CountryList:
def __init__(self, full_path):
"""
Constructor method that builds the country dictionary with 'key','value' pair
:param full_path: path where the geojson is stored
... |
170867 | import kdtree
def nonmaximalsuppression(tensor, threshold):
pred_data = tensor.storage()
offset = tensor.storage_offset()
stride = int(tensor.stride()[0])
numel = tensor.numel()
points = []
# Corners
val = pred_data[0 + offset]
if val >= threshold and val >= pred_data[1 + offset] and v... |
170881 | import timeit
import argparse
import numpy as np
from core.bamnet.bamnet import BAMnetAgent
from core.matchnn.matchnn import MatchNNAgent
from core.bow.bow import BOWnetAgent
from core.bow.pbow import PBOWnetAgent
from core.build_data.utils import vectorize_data
from core.utils.utils import *
from core.config import *... |
170882 | import re
import xml.etree.ElementTree as ET
from os import path
from collections import Counter
import argparse
import csv
import json
import os
import random
# package local imports
import sys
import uuid
import matplotlib.pyplot as plt
import math
from dateutil.parser import parse
from tdigest import TDigest
impo... |
170894 | from . import model_zoo
from .resnet import *
from .fcn import *
from .pspnet import *
from .deeplab import *
|
170936 | import httpretty
from nose.tools import raises
from tests import FulcrumTestCase
class PhotoTest(FulcrumTestCase):
@httpretty.activate
def test_records_from_form_via_url_params(self):
httpretty.register_uri(httpretty.GET, self.api_root + '/photos/abc-123',
body='{"photo": {"id": "abc-123"... |
170952 | import re
from src.commons.exceptions import ParameterValidationException
class WrongDatasetNameException(Exception):
pass
class WrongProjectNameException(Exception):
pass
class WrongWriteDispositionException(Exception):
pass
class WrongCreateDispositionException(Exception):
pass
project_id_p... |
170985 | import pyhecdss
import pandas as pd
import numpy as np
import os
def test_read_write_cycle_rts():
'''
Test reading and writing of period time stamped data so
that reads and writes don't result in shifting the data
'''
fname = "test2.dss"
if os.path.exists(fname):
os.remove... |
170999 | import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY2:
from httplib import HTTPConnection, HTTPSConnection
if PY3:
from http.client import HTTPConnection, HTTPSConnection
def basic():
conn = HTTPConnection('example.com')
conn.request('GET', '/path')
def indirect_caller():
... |
171004 | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-15, 15, 0.5)
X, Y = np.meshgrid(x, y)
sigma = 4
Z = np.exp(-(X**2 + Y**2)/(2*sigma**2)) / (2*np.pi*sigma**2)
ax.plot_s... |
171037 | import os
from random import seed
import numpy as np
from hyperopt import hp, tpe, rand
import pytest
from sklearn.metrics import mean_squared_error as mse, roc_auc_score as roc
from fedot.core.data.data import InputData
from fedot.core.data.data_split import train_test_data_setup
from fedot.core.pipelines.node impor... |
171042 | from functools import lru_cache
from typing import List, Set, Union, Optional
import yaml
from .root import HConfig
from .options import options_for
class Host:
"""
A host object is a convenient way to loading host inventory
items into a single object.
The default is to load "hostname", "os", and "... |
171050 | from pathlib import Path
import shutil
import glob
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pyarrow.dataset
import vaex
path = Path(__file__).parent.parent
data_path = path / 'data'
countries = ['US', 'US', 'NL', 'FR', 'NL', 'NL']
years = [2020, 2021, 2020, 2020, 2019, 2020]
val... |
171064 | import math
from maya import OpenMaya, OpenMayaMPx
class Circler(OpenMayaMPx.MPxNode): #(1)
def compute(self, *args):
pass
def create(): #(2)
return OpenMayaMPx.asMPxPtr(Circler())
def init(): #(3)
return
nodeName = 'circler' #(4)
nodeTypeID = OpenMaya.MTypeId(0x60005) #(5)
def _toplugin(mobjec... |
171067 | import random
from random import choice
import numpy as np
import pandas as pd
from pyspark.sql import SparkSession
from ydot.spark import smatrices
random.seed(37)
np.random.seed(37)
def get_spark_dataframe(spark):
n = 100
data = {
'a': [choice(['left', 'right']) for _ in range(n)],
'b': [... |
171081 | from threading import Thread, Lock
c = 0
lock = Lock()
def count_300():
global c
lock.acquire()
try:
while c < 30000:
c += 1
print(c)
finally:
lock.release()
def count_10000():
global c
x = 340
while c < 100000:
c += 1
print(c)
t_0 = Thr... |
171101 | from Rules.RuleTextTooBigCompWords import RuleTextTooBigCompWords
from Rules.RuleVisionBoxHasSoManyInvalidTexts import RuleVisionBoxHasSoManyInvalidTexts
from Rules.RuleBaseOnNeighbour import RuleBaseOnNeighbour
from Rules.RuleAlignVertically import RuleAlignVertically
from Rules.RuleBigLotChildren import RuleBigLotChi... |
171106 | import asyncio
from multiprocessing.util import register_after_fork
from queue import Queue
from threading import (
Barrier,
BoundedSemaphore,
Condition,
Event,
Lock,
RLock,
Semaphore,
)
from aioprocessing.locks import _ContextManager
from .executor import _ExecutorMixin
from .mp import man... |
171181 | from django.conf import settings
from django.core.management.base import BaseCommand
from qfieldcloud.core import geodb_utils, utils
class Command(BaseCommand):
help = "Check qfieldcloud status"
def handle(self, *args, **options):
results = {}
results["redis"] = "ok"
# Check if redis... |
171187 | import matplotlib.pyplot as plt
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
import numpy as np
import skimage.io as io
import ipdb;pdb=ipdb.set_trace
from collections import OrderedDict
# markdown format output
def _print_name_value(name_value, full_arch_name):
names = name_value.ke... |
171199 | from .single_stage import SingleStageDetectorWraper
from .two_stage import TwoStageDetectorWraper
__all__ = ['SingleStageDetectorWraper', 'TwoStageDetectorWraper']
|
171226 | import getpass
import logging
import os
import pathlib
import pytest
from libtmux import exc
from libtmux.server import Server
from libtmux.test import TEST_SESSION_PREFIX, get_test_session_name, namer
logger = logging.getLogger(__name__)
@pytest.fixture(autouse=True, scope="session")
def home_path(tmp_path_factor... |
171259 | import asyncio
import logging
from typing import Dict, Callable, List, Optional, Union, Pattern
from .command import Command
from .lexer import Lexer
from .parser import Parser
from .. import AsyncRunnable, MessageTypes, EventTypes # interfaces & basics
from .. import Cert, HTTPRequester, WebhookReceiver, WebsocketRe... |
171298 | import requests
import rdflib
from whyis import nanopub
import datetime
import pytz
import dateutil.parser
from dateutil.tz import tzlocal
from werkzeug.datastructures import FileStorage
from werkzeug.http import http_date
from setlr import FileLikeFromIter
import re
import os
from requests_testadapter import Resp
impo... |
171324 | input_data = '1901,12.3\n1902,45.6\n1903,78.9'
print('input data is:')
print(input_data)
as_lines = input_data.split('\n')
print('as lines:')
print(as_lines)
for line in as_lines:
fields = line.split(',')
year = int(fields[0])
value = float(fields[1])
print(year, ':', value)
|
171350 | from __future__ import division
from __future__ import print_function
import json
import pdb
import math
all_params = json.load(open('config.json'))
dataset_name = all_params['dataset_name']
locals().update(all_params['experiment_setup'])
locals().update(all_params[dataset_name])
tcn_params['model_params']['encod... |
171360 | import zmq.backend.cython._device
import zmq.backend.cython._poll
import zmq.backend.cython._version
import zmq.backend.cython.constants
import zmq.backend.cython.context
import zmq.backend.cython.error
import zmq.backend.cython.message
import zmq.backend.cython.socket
import zmq.backend.cython.utils
import zmq.devices... |
171406 | from .light_frontend import LightFrontend
from .full_frontend import FullFrontend
from .hybrid_frontend import HybridFrontend
from .composite_frontend import CompositeFrontend
from .replacement_frontend import ReplacementFrontend
|
171429 | from django.db import models
class CustomField(models.Field):
description = "A custom field type"
class DescriptionLackingField(models.Field):
pass
|
171432 | from autogoal.contrib import find_classes
from autogoal.kb import (
algorithm,
Sentence,
Seq,
Word,
Stem,
build_pipeline_graph,
Supervised,
Label,
)
from autogoal.grammar import generate_cfg, Symbol
class Algorithm:
def __init__(
self,
tokenizer: algorithm(Sentence,... |
171446 | class Pipeline:
def __init__(self, ready):
self._queue = []
self._ready = ready
@property
def empty(self):
return not self._queue
def queue(self, task):
print("queued")
self._queue.append(task)
task.add_done_callback(self._task_done)
def _task_don... |
171480 | from MiscUtils.DataTable import DataTable
from MiscUtils.Funcs import hostName as HostName
from SitePage import SitePage
class SelectDatabase(SitePage):
def writeSideBar(self):
self.writeln('<a href="?showHelp=1" class="SideBarLink">Help</a>')
def writeContent(self):
self.saveFieldsToCookies... |
171505 | class EventRecorder(object):
def __init__(self):
super(EventRecorder, self).__init__()
self.events = {}
self.timestamp = 0
def record(self, event_name, **kwargs):
assert event_name not in self.events, "Event {} already recorded".format(event_name)
self.timestamp += 1
... |
171516 | from sqlalchemy import *
import sqlalchemy.schema
import uuid
from sqlalchemy.sql import select
from migrate import *
import migrate.changeset
from migrate.changeset.constraint import ForeignKeyConstraint, PrimaryKeyConstraint
metadata = MetaData()
def make_uuid():
return unicode(uuid.uuid4())
## Tables and col... |
171525 | import warnings
from pymysql.tests import base
import pymysql.cursors
class CursorTest(base.PyMySQLTestCase):
def setUp(self):
super(CursorTest, self).setUp()
conn = self.connections[0]
self.safe_create_table(
conn,
"test", "create table test (data varchar(10))",
... |
171613 | import numpy as np
def trust_region_solver(M, g, d_max, max_iter=2000, stepsize=1.0e-3):
"""Solves trust region problem with gradient descent
maximize 1/2 * x^T M x + g^T x
s.t. |x|_2 <= d_max
initialize x = g / |g| * d_max
"""
x = g / np.linalg.norm(g) * d_max
for _ in range(max_iter):
... |
171635 | class InvalidWithdrawal(Exception):
pass
raise InvalidWithdrawal("You don't have $50 in your account")
|
171657 | from datetime import timedelta
from django.core.management import call_command
from jcasts.users.factories import UserFactory
class TestNewEpisodesEmails:
def test_command(self, db, mocker):
yes = UserFactory(send_email_notifications=True)
UserFactory(send_email_notifications=False)
Use... |
171687 | from __future__ import annotations
from .abs import abs_val
def abs_min(x: list[int]) -> int:
"""
>>> abs_min([0,5,1,11])
0
>>> abs_min([3,-10,-2])
-2
>>> abs_min([])
Traceback (most recent call last):
...
ValueError: abs_min() arg is an empty sequence
"""
if len(x) ==... |
171712 | import importlib
def create_storage(app):
"""
Load specified storage and return the object.
"""
if 'STORAGE' not in app.config:
raise Exception("Missing STORAGE config key")
storage = importlib.import_module('.' + app.config['STORAGE'], __name__)
return storage.create_storage(app)
|
171735 | import http.client
import json
import subprocess
import os
tempDir = os.getenv('XDG_RUNTIME_DIR', '.')
conn = http.client.HTTPConnection('localhost', 8888)
params = """{
"level": "debug",
"media": "image/png",
"input_type": "text"
}"""
def getCaptcha():
conn.request("POST", "/v1/captcha", body=params)
respon... |
171808 | import sys, os
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CURRENT_DIR, "..", ".."))
import constants
import requests
HTTP_ERROR_CODE_START = 400
HTTP_ERROR_MESSAGE_FORMAT= "Site '%s' returned error '%d'"
REQUEST_ERROR_FORMAT = "Requesting connection to '%s' errored!"
HYP... |
171813 | from flask_login import current_user
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileField, FileRequired
import pytz
from wtforms import ValidationError
from wtforms.fields import IntegerField, SelectField, StringField
from wtforms.validators import DataRequired, NumberRange
from wtforms_com... |
171818 | from random import randint
from pynput.keyboard import Key, Listener
output = 'kld' + str(randint(0, 10000)) + '.txt'
with open(output, 'w') as f:
f.close()
def on_press(key):
with open(output, 'a') as f:
f.write('{0} pressed\n'.format(key))
f.close()
def on_release(key):
... |
171881 | import six
import json
from prompt_toolkit.application import get_app
from prompt_toolkit.filters import to_filter
from prompt_toolkit.mouse_events import MouseEventType
from prompt_toolkit.key_binding.key_bindings import KeyBindings
from prompt_toolkit.layout.containers import Window
from prompt_toolkit.layout.contro... |
171892 | import tensorflow as tf
from experiment.mapping.model.transform_both import FixSpaceModel
from experiment.utils.variables import weight_variable, bias_variable
class FixSpaceSeparateTransformationModel(FixSpaceModel):
def __init__(self, config, config_global, logger):
super(FixSpaceSeparateTransformation... |
171932 | import unittest
from common_utils import VerboseTestCase
import subprocess
class TestLinearReorder(VerboseTestCase):
def test_linear_reorder(self):
with subprocess.Popen('DNNL_VERBOSE=1 python -u linear_reorder.py', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
segmentation... |
171964 | import numpy as np
from .Layer import Layer
class Sign():
"""Sign Layer
f(x) = 1 for x > 0
f(x) = 0 for x = 0
f(x) = -1 for x < 0
Attributes:
input_shape = [N, C, H, W]: The shape of the input tensor
output_shape = [N, C, H, W]: The shape of the resulting output ... |
171972 | import dateutil.parser
import freezegun
from behaving import environment as benv
PERSONAS = {}
def before_all(context):
benv.before_all(context)
def after_all(context):
benv.after_all(context)
def before_feature(context, feature):
benv.before_feature(context, feature)
def after_feature(context, fea... |
172001 | from minos.common.testing import (
MockedDatabaseClient,
)
from minos.networks import (
BrokerPublisherQueueDatabaseOperationFactory,
)
from ..collections import (
MockedBrokerQueueDatabaseOperationFactory,
)
class MockedBrokerPublisherQueueDatabaseOperationFactory(
BrokerPublisherQueueDatabaseOperat... |
172015 | import functools
from .common import InfoExtractor
from ..utils import (
OnDemandPagedList,
traverse_obj,
unified_strdate,
)
class GronkhIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gronkh\.tv/(?:watch/)?stream/(?P<id>\d+)'
_TESTS = [{
'url': 'https://gronkh.tv/stream/536',
... |
172032 | import pytest
from munch import DefaultMunch
from market_maker.orders_manager import OrdersManager
from market_maker.gateways import gateway_interface
from market_maker.definitions import (
ApiResult,
OrderRequest,
OrderType,
OrderSide,
)
class bittest_storage():
def __init__(self):
self... |
172050 | from django.utils.translation import gettext as _
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from onadata.apps.api.models.project import Project
from onadata.apps.api.models.project_xform import ProjectXForm
from onadata.apps.logger.models.xform import XForm
from on... |
172168 | import matplotlib.pyplot as plt
import numpy as np
from keras.datasets import mnist
from keras.layers import BatchNormalization, Input, Dense, Reshape, Flatten
from keras.layers.advanced_activations import LeakyReLU
from keras.models import Sequential, Model
from keras.optimizers import Adam
def build_generator(laten... |
172201 | import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import scipy.linalg as la
def dist(A,B,C,D,alpha,beta):
"""
Parameters
----------
A
B
C
D
alpha
beta
Return
------
f
g
"""
AC=C-A
CD=D-C
BA=A-B
u0 = np.dot(AC,AC)
u4 = ... |
172215 | import logging
from colorlog import ColoredFormatter
def setup_logging():
logger = logging.getLogger()
logger.setLevel(logging.INFO)
color_formatter = ColoredFormatter(
"%(log_color)s[%(asctime)s] [%(levelname)-4s]%(reset)s - %(message)s",
datefmt='%d-%m-%y %H:%M:%S',
r... |
172263 | class ActivePlan(object):
def __init__(self, join_observer_list, on_next, on_completed):
self.join_observer_list = join_observer_list
self.on_next = on_next
self.on_completed = on_completed
self.join_observers = {}
for join_observer in self.join_observer_list:
sel... |
172318 | import cv2
import os
import numpy as np
import av
from torchvision.transforms import Compose, Resize, ToTensor
from PIL import Image
import matplotlib.pyplot as plt
import torch
from torch.utils.data import DataLoader
from dataset import MaskDataset, get_img_files, get_img_files_eval
from nets.MobileNetV2_unet import M... |
172322 | from datetime import datetime
import os.path
import functools
import collections
import copy
import re
import time
import logging
import numpy as np
import tensorflow as tf
from train_common import get_global_step, get_lr_and_max_steps, get_ops, run_op
import prune_algorithm.prune_common as pc
logging.basicConfig(l... |
172346 | COINS = (
(25, 'Quarters'),
(10, 'Dimes'),
(5, 'Nickels'),
(1, 'Pennies')
)
def loose_change(cents):
change = {'Pennies': 0, 'Nickels': 0, 'Dimes': 0, 'Quarters': 0}
cents = int(cents)
if cents <= 0:
return change
for coin_value, coin_name in COINS:
q, r = divmod(cents,... |
172367 | import mistune
from mistune import InlineLexer, BlockLexer
import re
try:
from .renderer_base import Block_Quote_Renderer, Header_Renderer
from .renderer_math import MathInlineMixin, MathRendererMixin, MathBlockMixin
except Exception:
from renderer_base import Block_Quote_Renderer, Header_Renderer
from ... |
172390 | import torch
import torch.nn as nn
import numpy as np
import sys
from sdf import SDF
import pdb
class SDFLoss(nn.Module):
def __init__(self, right_faces, left_faces, grid_size=32, robustifier=None):
super(SDFLoss, self).__init__()
self.sdf = SDF()
self.register_buffer('right_face', torch.t... |
172454 | import argparse
import json
import logging
import _jsonnet
import tqdm
# These imports are needed for registry.lookup
# noinspection PyUnresolvedReferences
from src.datasets import yahoo_dataset, ag_news_dataset
# noinspection PyUnresolvedReferences
from src.models import han
# noinspection PyUnresolvedReferences
fr... |
172486 | from mesa.datacollection import DataCollector
from mesa import Model
from mesa.time import RandomActivation
from mesa_geo.geoagent import GeoAgent, AgentCreator
from mesa_geo import GeoSpace
import random
class SchellingAgent(GeoAgent):
"""Schelling segregation agent."""
def __init__(self, unique_id, model, ... |
172509 | from .start_manifest import StartManifest
from .vod_start_manifest import VodStartManifest
from .vod_dash_start_manifest import VodDashStartManifest
from .vod_hls_start_manifest import VodHlsStartManifest
|
172583 | import torch
from torch import nn
from onconet.models.inflate import inflate_model
from onconet.models.blocks.factory import get_block
import pdb
MODEL_REGISTRY = {}
STRIPPING_ERR = 'Trying to strip the model although last layer is not FC.'
NO_MODEL_ERR = 'Model {} not in MODEL_REGISTRY! Available models are {} '
NO_... |
172593 | import gc
import numpy as np
import pandas as pd
def drop_duplicates_pharma(df):
"""
df: long-format dataframe of a patient
varref: variable reference table that contain the mean and standard deviation of values for a subset of variables
"""
df_dup = df[df.duplicated(["givenat", "pharmaid", "infu... |
172597 | import io
import os
import logging
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.filedialog as filedialog
import tkinter.messagebox as tkmessagebox
import libs.CFCrypto as CFCrypto
import libs.CFCryptoX as CFCryptoX
from libs.CFCanvas import CFCanvas
from libs.Util import set_combobox_item
from libs.Uti... |
172605 | from __future__ import division
import numpy as np
import covariance as cov
from gp import GaussianProcess
#import com.ntraft.covariance as cov
#from com.ntraft.gp import GaussianProcess
import matplotlib
# The 'MacOSX' backend appears to have some issues on Mavericks.
import sys
if sys.platform.startswith('darwin'):
... |
172635 | import torch
from torch.utils.data import Dataset
import glob
import tifffile as T
from libtiff import TIFF
import numpy as np
def range_normalize(v):
v = (v - v.mean(axis=(1, 2), keepdims=True)) / (v.std(axis=(1, 2), keepdims=True) + 1e-12)
v_min, v_max = v.min(axis=(1, 2), keepdims=True), v.max(axis=(1, 2),... |
172686 | import argparse
import numpy as np
import torch
import os, sys
import math
from subspace_inference import models, losses, posteriors, utils
# from swag.posteriors import SWAG, EllipticalSliceSampling, BenchmarkPyro, BenchmarkVIModel
from regression import run
from bayesian_benchmarks.data import get_regression_data
fr... |
172710 | import copy
import logging
import numpy
import theano
from theano import tensor
from theano.gradient import disconnected_grad
from blocks.bricks import (
Bias, Identity, Initializable, MLP, Tanh, Softmax, Random)
from blocks.bricks.attention import SequenceContentAttention
from blocks.bricks.base import applicati... |
172777 | import sqlite3
import xml.etree.ElementTree as et
from pymzml import spec
from pymzml.run import Reader
def create_database_from_file(db_name, file_path):
conn = sqlite3.connect(db_name + ".db")
Run = Reader("./tests/data/example.mzML")
with conn:
cursor = conn.cursor()
cursor.execute("CRE... |
172793 | import os
import yaml
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ConversationHandler
from commons import authentication, checkAdmin, checkId
from config import config
from translations import i18n
config = config["transmission"]
TSL_LIMIT = 'limited'
TSL_NORMAL = 'norma... |
172853 | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
from django.contrib.auth import views as auth_views
urlpatterns = [
# Examples:
# url(r'^$', 'bhr_site.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'... |
172856 | import numpy
import csb.test as test
from csb.numeric import log
from csb.statistics.pdf.parameterized import ParameterizedDensity
from csb.statistics.pdf.parameterized import ParameterValueError, ParameterizationError
from csb.statistics.pdf.parameterized import AbstractParameter, Parameter, NonVirtualParameter
c... |
172858 | import os
from click.testing import CliRunner
from twine.utils import TEST_REPOSITORY
from hatch.cli import hatch
from hatch.env import install_packages
from hatch.settings import SETTINGS_FILE, copy_default_settings, save_settings
from hatch.utils import env_vars, temp_chdir, temp_move_path
from hatch.venv import cr... |
172863 | def file_url(input_dict):
from discomll import dataset
if input_dict["range"] == "true":
urls = [url.strip() for url in input_dict["url"].split("\n") if url != ""]
else:
urls = [[url.strip()] for url in input_dict["url"].split("\n") if url != ""]
for url in urls:
if url[... |
172901 | import argparse
import os.path as osp
import random
from time import perf_counter as t
import yaml
from yaml import SafeLoader
import torch
import torch_geometric.transforms as T
import torch.nn.functional as F
import torch.nn as nn
from torch_geometric.datasets import Planetoid, CitationFull
from torch_geometric.util... |
172931 | from oidcmsg.oauth2 import AccessTokenResponse
import pytest
from oidcrp.entity import Entity
from oidcrp.util import rndstr
KEYDEF = [{"type": "EC", "crv": "P-256", "use": ["sig"]}]
class TestRP():
@pytest.fixture(autouse=True)
def create_service(self):
client_config = {
'client_id': 'c... |
173009 | import redis
import logging
from django.conf.urls import url
from django.conf import settings
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from . import consumers
logger = logging.getLogger('awx.main.routing')
class AWXProtocolTypeRouter(ProtocolTypeRou... |
173013 | from rest_framework import status
from rest_framework.reverse import reverse
from resource_tracker.models import ResourceGroupAttributeDefinition
from tests.test_resource_tracker.test_api.base_test_api import BaseTestAPI
class TestAttributeDefinitionCreate(BaseTestAPI):
def setUp(self):
super(TestAttrib... |
173071 | from social_peewee.storage import database_proxy, BaseModel, PeeweeUserMixin, \
PeeweeNonceMixin, PeeweeAssociationMixin, PeeweeCodeMixin, BasePeeweeStorage
|
173118 | import re
from nb_utils import line_macros
"""
TODO: Separation of concerns between LessonPreprocessor and MacroProcessor is
muddled. For historical reasons, LessonPreprocessor currently owns the logic for
expander macros. Eventually, would like to move all macro stuff here (and in
modules like line_macros.py)
"""
c... |
173119 | class CompressString(object):
def compress(self, string):
if string is None or not string:
return string
result = ''
prev_char = string[0]
count = 0
for char in string:
if char == prev_char:
count += 1
else:
... |
173163 | data = (
((-0.195090, 0.980785), (0.000000, 1.000000)),
((-0.382683, 0.923880), (-0.195090, 0.980785)),
((-0.555570, 0.831470), (-0.382683, 0.923880)),
((-0.707107, 0.707107), (-0.555570, 0.831470)),
((-0.831470, 0.555570), (-0.707107, 0.707107)),
((-0.923880, 0.382683), (-0.831470, 0.555570)),
((-0.980785, 0.195090), ... |
173169 | from contextlib import contextmanager
import os
from math import sqrt
from fontTools.pens.basePen import BasePen
from fontTools.pens.recordingPen import RecordingPen
from fontTools.ttLib.tables.otTables import CompositeMode, ExtendMode
import cairo
from .base import Canvas, Surface
from .sweepGradient import buildSweep... |
173194 | import click
import pathlib
import sys
import sqlalchemy as sa
from dynaconf import settings
from passlib.handlers.sha2_crypt import sha256_crypt
BASE_DIR = pathlib.Path(__file__).parent.parent
sys.path.append(str(BASE_DIR.absolute()))
from auth.models import users # noqa
@click.command()
@click.option('--login', ... |
173206 | import unittest
import numpy as np
from spn.algorithms.Inference import log_likelihood
from spn.algorithms.MPE import mpe
from spn.io.CPP import get_cpp_function, setup_cpp_bridge, get_cpp_mpe_function
from spn.io.Graphics import plot_spn
from spn.structure.Base import get_nodes_by_type
from spn.structure.leaves.para... |
173223 | class TestScheduleJobFileData:
test_job_connection = {
"Name": "TestIntegrationConnection",
"ConnectorTypeName": "POSTGRESQL",
"Host": "localhost",
"Port": 5432,
"Sid": "",
"DatabaseName": "test_pdi_integration",
"User": "postgres",
"Password": "<PASSW... |
173231 | from .mnist import MNIST, FashionMNIST
from .caltech import Caltech101, Caltech256
from .celeba import CelebA
from .cifar import CIFAR10, CIFAR100
from .cityscapes import Cityscapes
from .clevr import CLEVRClassification
from .country211 import Country211
from .coco import CocoCaptions, CocoDetection
from .dtd import D... |
173241 | import django.dispatch
#: Sent after a user has registered an account with the store.
#:
#: :param sender: The form which was submitted.
#: :type sender: ``satchmo_store.accounts.forms.RegistrationForm``
#:
#: :param contact: The contact that was saved to the database.
#: :type contact: ``satchmo_store.contact.models.... |
173243 | import os
import re
from django.conf import settings
from statsd.defaults.django import statsd
DATADOG_METRICS = False
DATADOG_TAGS = None
if settings.DATADOG_API_KEY:
from datadog import initialize
options = {
'api_key': settings.DATADOG_API_KEY,
'app_key': settings.DATADOG_APP_KEY
}
... |
173260 | import struct
import numpy
import GLWindow
import ModernGL
# This example is not working with NPOT Textures
width, height = 640, 460
pixels = numpy.round(numpy.random.rand(width, height)).astype('float32')
grid = numpy.dstack(numpy.mgrid[0:height, 0:width][::-1]).astype('int32')
wnd = GLWindow.create_window(width,... |
173298 | import argparse
import numpy as np
from pathlib import Path
import cv2
from model import get_model
from noise_model import get_noise_model
import sys
import tensorflow as tf
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
import tensorflow_datasets as tfds
def get_args()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.