id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3353895 | import functools
from .. import errors
from . import utils
def minimum_version(version):
def decorator(f):
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
if utils.version_lt(self._version, version):
raise errors.InvalidVersion(
'{0} is not ... |
3353905 | from django.test.utils import override_settings
from cms.api import add_plugin, create_page
from cms.models import CMSPlugin
from cms.plugin_rendering import (
ContentRenderer,
LegacyRenderer,
StructureRenderer,
)
from cms.test_utils.testcases import CMSTestCase
class TestStructureRenderer(CMSTestCase):
... |
3353931 | import numpy as np
import torch
import math
import torch.utils.data as Data
from torch.autograd import Variable
from EvalBox.Evaluation.evaluation import Evaluation
from EvalBox.Evaluation.evaluation import MIN_COMPENSATION
class NBC(Evaluation):
def __init__(self, outputs_origin,outputs_adv, device, model, **kwa... |
3354005 | from selenium import webdriver
from selenium.webdriver.common.by import By
import time
class ClickAndSendKeys():
def test(self):
baseUrl = "https://letskodeit.teachable.com"
driver = webdriver.Firefox()
driver.maximize_window()
driver.get(baseUrl)
driver.implicitly_wait(10)... |
3354019 | import pytest
import unittest
from exam import Exam
from lxml import etree, html
from lxml.cssselect import CSSSelector
from toronado import (
Properties,
Rule,
compress_box_property,
expand_shorthand_box_property,
from_string,
inline,
warn_unsupported_shorthand_property,
)
try:
from ... |
3354029 | import webapp2
class Redirect(webapp2.RequestHandler):
def get(self, path):
self.redirect(uri='https://www.webcomponents.org/%s' % path, permanent=True)
# pylint: disable=invalid-name
app = webapp2.WSGIApplication([
webapp2.Route(r'/<path:.*>', handler=Redirect),
], debug=True)
|
3354036 | import numpy as np
import ast
import sys
import json
from auxiliary_functions import SampleListToArray
import matplotlib
from matplotlib import rc
rc('text', usetex=True)
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
matplotlib.rc('xtick', labelsize=30)
matplotlib.rc('ytick', labelsize=30)
imp... |
3354041 | import warnings
from amuse.rfi.channel import *
warnings.warn("amuse.support.codes.channel has moved to amuse.rfi.channel", DeprecationWarning)
|
3354046 | import asyncio
import functools
import json
import logging
import math
import prometheus_client
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import aliased, defer, joinedload
import tempfile
from tornado.concurrent import Future
import tornado.log
from tornado.web import MissingArgumentError, HTTPError... |
3354062 | import unittest
from adk.fortune import Voronoi, Point, Arc
import random
class TestFortuneMethods(unittest.TestCase):
def perturb(self, points):
for i in range(len(points)):
pt = points[i]
points[i] = (pt[0] + random.random(), pt[1] + random.random())
def valid(s... |
3354073 | import torch
import pdb
def dot(b1, b2, dim=-1):
return (b1*b2).sum(dim=dim)
def add_eps(b, eps):
mask = (b == 0).double()
return b*(1-mask) + mask*(b + eps)
def batch_cosine_distance(b1, b2, dim=-1, eps=1e-10):
b1 = add_eps(b1, eps)
b2 = add_eps(b2, eps)
return dot(b1, b2, dim=dim)/(dot(b1, b1, dim=dim)... |
3354084 | from setuptools import setup, Extension
import numpy
import numpy.distutils
try:
from Cython.Build import cythonize
use_cython = True
except ImportError:
use_cython = False
if use_cython:
ext_modules = cythonize([Extension('pyhacrf.algorithms',
['pyhacrf/algorith... |
3354119 | import os
from pynif3d.log.log_funcs import func_logger
from pynif3d.models import ConvolutionalOccupancyNetworksModel, PointNet_LocalPool
from pynif3d.pipeline import BasePipeline
from pynif3d.renderer import PointRenderer
from pynif3d.sampling import FeatureSampler2D
class ConvolutionalOccupancyNetworks(BasePipeli... |
3354147 | import pytest
import xml.etree.ElementTree as ET
from panos.base import ENTRY, Root
from panos.base import VersionedPanObject, VersionedParamPath
from panos.firewall import Firewall
class FakeObject(VersionedPanObject):
"""Fake object for testing."""
SUFFIX = ENTRY
ROOT = Root.VSYS
def _setup(self)... |
3354166 | import numpy as np
from numpy.testing import *
from supreme.resolve.ordering import *
import scipy.sparse as sparse
def test_basic():
A = sparse.csr_matrix([[0, 1, 0, 2],
[2, 0, 1, 1],
[0, 0, 0, 1],
[0, 0, 1, 0],
... |
3354249 | import csv
import time
import usaddress
from processors.get_sam_data import SamData
def get_address(record):
results = {}
results['address1'] = record['docvendor.address1']
results['address2'] = record['docvendor.address2']
results['address3'] = record['docvendor.address3']
results['city'] = recor... |
3354288 | from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.environment.adapters.indexentries import IndexEntries
class DPYStandaloneHTMLBuilder(StandaloneHTMLBuilder):
# This is mostly copy pasted from Sphinx.
def write_genindex(self) -> None:
# the total count of lines for each index let... |
3354358 | import socket
import time
def check_used(port: int) -> bool:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1', port))
if result == 0:
sock.close()
return True
else:
return False
def alloc(start_from: int = 7000) -> int:
while ... |
3354387 | import time
import numpy as np
from PIL import Image
from skimage.data import camera
import tensorflow as tf
from tfkbnufft import kbnufft_forward, kbnufft_adjoint
from tfkbnufft.kbnufft import KbNufftModule
def profile_tfkbnufft(
image,
ktraj,
im_size,
device,
):
if device =... |
3354481 | from http import HTTPStatus
from pytest import mark
from freddie.viewsets.dependencies import Paginator
from .app import Item, test_item, test_items_seq
from .utils import WithClient
pytestmark = mark.asyncio
api_prefixes = {
'argnames': 'prefix',
'argvalues': ['/unvalidated', '/validated', '/sync'],
'i... |
3354497 | import random
import sys
import time
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication
from ARui import ArMainwindow
from voicecontrollermodel.voicecontroller import Controller as VoiceController
from Navigation_system import Navigationsys
from voicecontrollermodel.voice_and_text import Text2voi... |
3354499 | import FWCore.ParameterSet.Config as cms
process = cms.Process("ExREG")
process.load("Configuration.StandardSequences.Services_cff")
process.load('Configuration.StandardSequences.Geometry_cff')
process.load('Configuration/StandardSequences/MagneticField_38T_cff')
process.load('Configuration/StandardSequences/FrontierC... |
3354531 | import os
import sys
from pprint import pprint
from notion_client import Client
try:
from dotenv import load_dotenv
except ModuleNotFoundError:
print("Could not load .env because python-dotenv not found.")
else:
load_dotenv()
NOTION_TOKEN = os.getenv("NOTION_TOKEN", "")
while NOTION_TOKEN == "":
pri... |
3354581 | import logging
from bson.timestamp import Timestamp
from multiprocessing import Event
from time import time, sleep
from TailThread import TailThread
from mongodb_consistent_backup.Common import MongoUri
from mongodb_consistent_backup.Errors import OperationError
from mongodb_consistent_backup.Oplog import OplogState
... |
3354585 | import os
# if DISPLAY is not defined
if 'DISPLAY' not in os.environ:
import matplotlib
matplotlib.use('Agg') # Use a different backend
from tensorflow.examples.tutorials.mnist import input_data
from models.models import *
# Load dataset
data = input_data.read_data_sets('datasets/mnist/', one_hot=True)
... |
3354609 | import numpy as np
import torch
import torch.utils.data
from sklearn.metrics import cohen_kappa_score, accuracy_score
from sklearn.metrics import confusion_matrix
from tqdm import tqdm
def testing(epoch, net, testloader, criterion):
# global bestAcc, inputs, aa
net.eval()
testLoss = 0
batchSize = t... |
3354631 | import fsspec
import json
import logging
import os
from mapchete.io._path import fs_from_path, path_exists
from mapchete.io._misc import get_boto3_bucket
logger = logging.getLogger(__name__)
def write_json(path, params, fs=None, **kwargs):
"""Write local or remote."""
logger.debug(f"write {params} to {path... |
3354632 | import numpy as np
import theano
import theano.tensor as T
try:
import cPickle as pickle
except:
import pickle
import sys
#list for converting index to character
dic = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',\
'A','B','C','D','E','F','G','H',... |
3354637 | import os
import sys
import time
import math
import torch.nn.functional as F
from datetime import datetime
import random
import logging
from collections import OrderedDict
import numpy as np
import cv2
import torch
from torchvision.utils import make_grid
from shutil import get_terminal_size
from utils.Demosaicing_malva... |
3354648 | from django.db import models
from datetime import datetime
class Site(models.Model):
"""外部站点(用于文章来源)"""
name = models.CharField(max_length=20, null=True, blank=True, verbose_name="站点名称")
url = models.URLField(null=True, blank=True, verbose_name="URL")
class Meta:
verbose_name = "外部站点"
... |
3354710 | import numpy as np
from sklearn.preprocessing import minmax_scale
def normalizer(data_x):
"""
:param data_x: the whole set of data for the sequence
:return: data_x
Description
----
This normalizes the whole data for each channel.
Params
----
"""
placeholder = None
data_sh... |
3354764 | import SimpleITK as sitk
import numpy as np
def calculate_origin_offset(new_spacing, old_spacing):
return np.subtract(new_spacing, old_spacing)/2
def sitk_resample_to_spacing(image, new_spacing=(1.0, 1.0, 1.0), interpolator=sitk.sitkLinear, default_value=0.):
# "zoom_factor" la shape moi / shape cu
zoom... |
3354766 | import csv
from collections import defaultdict, Counter
with open('data/survey_results_public.csv') as f:
csv_reader = csv.DictReader(f)
dev_type_info = {}
for line in csv_reader:
dev_types = line['DevType'].split(';')
for dev_type in dev_types:
dev_type_info.setdefault(dev_t... |
3354798 | from polyphony import pure
from polyphony import testbench
value = 12345
@pure
def f():
return value
def pure05():
return f()
@testbench
def test():
assert value == pure05()
test()
|
3354822 | class ServiceSnapshot(object):
def __init__(self, service, status, limit):
self.service = service
self.status = status
self.limit = limit
def as_header(self):
return "{0}={1}:{2}".format(self.service, self.status, self.limit)
def as_dict(self):
return {self.service:... |
3354876 | from arbol import aprint
from dexp.datasets.operations.demo.demo_stabilize import _demo_stabilize
from dexp.utils.backends import CupyBackend
# def test_stabilize_numpy():
# with NumpyBackend():
# _demo_stabilize(display=False)
def test_stabilize_cupy():
try:
with CupyBackend():
... |
3354878 | def f(*a):
print a
def g(x, *a):
print x, a
def h(x, y, *a):
print x, y, a
def i(x, y=4, *a):
print x, y, a
f()
f(1)
f(1, 2, 3)
g(1)
g(1, 2, 3)
h(1, 2)
h(1, 2, 3)
h(1, 2, 3, 4)
i(1)
i(1, 2, 3)
i(1, 2, 3, 4)
|
3354924 | import typing as t
from abc import ABCMeta, abstractmethod
T = t.TypeVar('T')
class Redirect(t.Generic[T]):
__metaclass__ = ABCMeta
@abstractmethod
def do_redirect(self):
# type: () -> T
raise NotImplementedError
@abstractmethod
def do_js_redirect(self):
# type: () -> T
... |
3354939 | from typing import Iterable
from modelforge import Model
from ast2vec import Model2Base
class Model2BaseSplit(Model2Base):
"""
Class to split the model content and save it in a new model.
`Model2Base.MODEL_FROM` should be iterable and iterator returns will be called model objects.
For example, one ca... |
3354940 | import datetime
import great_expectations as ge
import great_expectations.jupyter_ux
from great_expectations.checkpoint import LegacyCheckpoint
from great_expectations.data_context.types.resource_identifiers import ValidationResultIdentifier
context = ge.data_context.DataContext()
# Feel free to change the name of yo... |
3354966 | from dataclasses import dataclass
from dataclasses_json import dataclass_json
from typing import Optional
from .texture_info import TextureInfo
@dataclass_json
@dataclass
class NormalTextureInfo(TextureInfo):
"""
Material Normal Texture Info
Properties:
index (integer) The index of the texture. (Requ... |
3355000 | from django.db import models
from django.contrib.auth.models import User
import uuid
from django.conf import settings
class Professor(models.Model) :
name = models.CharField(max_length=75)
departmentCode = models.CharField(max_length=10)
website = models.URLField()
designation = models.CharField(max_l... |
3355010 | import itertools
import numpy
import pytest
from helpers import *
from reikna.helpers import product
from reikna.dht import DHT, harmonic, get_spatial_grid
import reikna.cluda.dtypes as dtypes
class FunctionHelper:
"""
Encapsulates creation of functions in mode and coordinate space used for DHT tests.
"... |
3355012 | from django.test import TestCase
from wagtail.tests.utils import WagtailTestUtils
from wagtail.core.models import Page
from tests.app.models import FacebookPage
from wagtail_meta_preview.utils import FacebookSettings
from wagtail_meta_preview import meta_settings
class TestMetaPreviewFacebookAdminView(TestCase, Wag... |
3355019 | import networkx as nx
import numpy as np
from ...Fragment.FragmentChain import FragmentChain
from ..AssemblyMixError import AssemblyMixError
class ConstructsMixin:
"""Mixin for AssemblyMix"""
def compute_random_circular_fragments_sets(
self, staling_cutoff=100, fragments_sets_filters=()
):
... |
3355029 | import os
import sys
import json
import yaml
import pandas as pd
from ananke.graphs import ADMG
from networkx import DiGraph
from optparse import OptionParser
sys.path.append(os.getcwd())
sys.path.append('/root')
from src.causal_model import CausalModel
from src.generate_params import GenerateParams
def config_optio... |
3355071 | from drawable import Drawable
from polygon import Polygon
from opengraph import OpenGraph
from scalable import Scalable
from background import Background
from arrow import Arrow
from text import Text
class DrawingBackend(object):
DEFAULT_SCALE = 1
DEFAULT_PIXELS_PER_UNIT = 20
DEFAULT_SHADOW_TRANSLATION = ... |
3355156 | def main(request, response):
"""
Check that headers sent to navigate here *do not* contain the device-memory client
hint, and report success/failure in a way compatible with
verify_subresource_state() in accept-ch-test.js
"""
if b"device-memory" in request.headers:
result = u"FAIL"
el... |
3355204 | import logging
from typing import Optional
from normality import collapse_spaces, stringify
from fingerprints.constants import BRACKETED, WS
from fingerprints.replacers import replace_types
from fingerprints.cleanup import clean_entity_name, clean_strict
log = logging.getLogger(__name__)
def generate(
text: Opt... |
3355235 | import sys
import urllib
import django
PY3 = sys.version_info[0] == 3
if PY3:
from urllib import parse as urlparse
def to_string(s):
if isinstance(s, str):
return s
return str(s, 'latin1')
def to_wsgi_safe_string(s):
return urlparse.quote(to_string(s))
def from_... |
3355243 | from houdini import IWaddle
class CardJitsuWaterLogic(IWaddle):
room_id = 995
def __init__(self, waddle):
super().__init__(waddle)
class WaterSenseiLogic(CardJitsuWaterLogic):
def __init__(self, waddle):
super().__init__(waddle)
|
3355279 | from typing import Dict
from dataclasses import dataclass
from typhoon.core.dags import TaskDefinition
from typhoon.core.templated import Templated
from typhoon.core.transpiler.transpiler_helpers import expand_function, camel_case, \
extract_imports, ImportsTemplate, render_args
@dataclass
class TaskTemplate(Te... |
3355285 | import json
import os
import horovod.tensorflow as hvd
hvd.init()
with open('/opt/ml/model/local-rank-%s-rank-%s' % (hvd.local_rank(), hvd.rank()), 'w+') as f:
basic_info = {'local-rank': hvd.local_rank(), 'rank': hvd.rank(), 'size': hvd.size()}
print(basic_info)
json.dump(basic_info, f)
val = os.enviro... |
3355324 | import argparse
import os
import sys
import shutil
import time
import numpy as np
from PIL import Image
import json
import logging
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as... |
3355354 | import torch.nn as nn
import ipdb
class Bottleneck(nn.Module):
expansion = 4
only_2D = False
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
self.bn1... |
3355373 | import dlib # 人脸识别的库dlib
import numpy as np # 数据处理的库numpy
import cv2 # 图像处理的库OpenCv
# dlib预测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
# 读取图像
path = "F:/code/python/P_Dlib_face_cut/pic/"
img = cv2.imread(path+"test_faces_6.... |
3355458 | from . import tour
from . import tour_config
def get_priority():
return tour_config.priority
def run_module():
return (tour.generate_tour(), tour_config.module_name) |
3355477 | from sklearn import datasets
from sklearn.tree import DecisionTreeRegressor
def compute_tree_complexity(tree, complexity_measure='num_rules'):
"""Calculate number of non-leaf nodes
"""
children_left = tree.children_left
children_right = tree.children_right
# num_split_nodes = 0
complexity = 0
... |
3355478 | import os
from setuptools import setup, find_packages
from pipshow import __version__, __description__, __author__, __email__, __license__
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="pipshow",
version=__version__,
license=__license__,
description... |
3355490 | from .utils import *
class Group(unittest.TestCase):
def setUp(self):
"""Inicia novo objeto em todo os testes """
self.ufrn_data = ODUFRNDownloader()
def test_can_print_groups(self):
"""Verifica se a lista de grupos é impressa na tela """
assert_console(self.ufrn_data.print_gr... |
3355593 | import argparse
import os
import pytest
from shutil import rmtree, copytree
from afdko.makeinstancesufo import (
main as mkinstufo,
get_options,
_split_comma_sequence,
updateInstance,
)
from runner import main as runner
from differ import main as differ
from test_utils import get_input_path
TOOL = 'ma... |
3355617 | from .multiclass_classification import MultiClassClassificationDataset
LABELS = ["airplane", "airport_runway", "artificial_grassland", "avenue", "bare_land", "bridge", "city_building",
"coastline", "container", "crossroads", "dam", "desert", "dry_farm", "forest", "green_farmland", "highway",
"hirs... |
3355672 | from scrounger.core.module import BaseModule
# helper functions / modules
from scrounger.modules.misc.android.app.manifest import Module as ManifestModule
from scrounger.utils.config import Log
class Module(BaseModule):
meta = {
"author": "RDC",
"description": "Checks if the application requires d... |
3355682 | from .version import version as __version__
from .GaussianProcess import GaussianProcess
try:
from .GaussianProcessGPU import GaussianProcessGPU
from .GaussianProcessGPU import GPUUnavailableError
except:
pass
from .MultiOutputGP import MultiOutputGP
from .fitting import fit_GP_MAP
from .MeanFunction impor... |
3355711 | import argparse
import tensorflow as tf
from os.path import join
from tensorflow.python import pywrap_tensorflow
def main(args):
"""
restores first source graph and (if exists) checkpoints
restores selected variables from target graph with checkpoint weights
selected variables of target graph will ... |
3355717 | def multiply(a,b):
return a*b
def print_args(a,b,c,d,e):
t = (a,b,c,d,e)
if t != ((4, 5), {'a': 3.14, 'b': 2.123}, True, {'ACGT'}, [['abc'], ['1.1', '2.2'], []]):
raise ValueError('TEST FAILED!')
return ({'a': 3.14, 'b': 2.123}, (222, 3.14))
def print_args_var(a,b,c=1,*args,**kwargs):
retu... |
3355722 | from django import forms
from crispy_forms_gds.helper import FormHelper
from crispy_forms_gds.layout import HTML, Button, Field, Hidden, Layout
class TextareaForm(forms.Form):
description = forms.CharField(
label="Can you provide more detail?",
widget=forms.Textarea,
help_text="Do not in... |
3355728 | import requests
import json
from dateutil import parser as dateutilParser
from bs4 import BeautifulSoup
import re
from coincrawler.blockchain.bitcoin import BitcoinAccess
from coincrawler.blockchain.ethereum import EthereumAccess
from coincrawler.blockchain.monero import MoneroAccess
from coincrawler.utils.network impo... |
3355735 | import copy
import unittest
from constants.globals import SLASH_POINTS_NOTIFICATION_THRESHOLD_DEFAULT
from handlers.settings_handlers import set_slash_points_threshold
from jobs.thorchain_node_jobs import build_notification_message_for_active_node
from service.utils import get_slash_points_threshold
from unit_tests.he... |
3355767 | from FWCore.Modules.logErrorFilter_cfi import *
logerrorseq=cms.Sequence(logErrorSkimFilter)
logerrormonitorseq=cms.Sequence(logErrorFilter)
|
3355789 | from InterpreteF2.Valor.Valor import Valor
class Simbolo():
def __init__(self, id, tipo, valor):
self.id = id
self.tipo = tipo
self.valor:Valor = valor
self.temporal = ""
def setTemp(self, tmp):
self.temporal = str(tmp)
def getTemp(self):
return str(self.t... |
3355836 | from tkinter import (
Frame,
font
)
class Section(Frame):
def __init__(self, master, x, y, height, width):
super(Section, self).__init__(master)
self.place(x=x, y=y, height=height, width=width)
self.add_widgets()
def add_attribute(self, **kwargs):
for i in kwargs.k... |
3355844 | from rtamt.exception.stl.exception import STLException
from rtamt.exception.stl.exception import STLParseException
from rtamt.exception.stl.exception import STLOfflineException
from rtamt.exception.stl.exception import STLSpecificationException
from rtamt.exception.stl.exception import STLNotImplementedException
from r... |
3355864 | import re
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import Any, Optional
# =====================================
# Schema for:
# * 'show avc sd-service info summary'
# =====================================
class ShowAvcSdServiceInfoSummarySchema(MetaParser):
"""Schema for s... |
3355868 | import unittest
from pathlib import Path
from sklearn.ensemble import RandomForestClassifier
from explainerdashboard import ClassifierExplainer, ExplainerDashboard
from explainerdashboard.datasets import titanic_survive, titanic_names
from explainerdashboard.custom import ShapDependenceComposite
class DashboardTest... |
3355879 | import logging
from collections import defaultdict
from django.utils.module_loading import import_string
from product_details.utils import settings_fallback
class MissingJSONData(IOError):
pass
__version__ = "1.0.3"
__all__ = ["__version__", "product_details", "version_compare"]
log = logging.getLogger("prod... |
3355881 | from internal import utility
class CityHeader:
def __init__(self, city):
self.city = city
x, y = self.get_position()
self.name_id = self.city.parent.canvas.create_text(x, y - utility.CELL_SIZE * 4, text='{} ({})'.format(self.city.name, self.city.population))
self.food_indicator_i... |
3355890 | def doLoginAction(self):
"""Try to actually log the user in."""
class PasswordAccepted(Exception): pass
try:
if check_password(): # This may raise KeyError.
raise PasswordAccepted
do_more_expensive_work()
and_even_more_expensive_work()
if check_other_passwo... |
3355909 | from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import sys, os, string
characters = string.printable
char_indices = dict((c, i) for i, c in enumerate(characters))
indices_char = dict((i, c) for i, c in enumerate(characters))
INPUT_VOCAB_SIZE = len(characters)
def encode_one_hot(... |
3355919 | import re
import lxml, lxml.html
from pupa.scrape import Scraper
from pupa.scrape.helpers import Legislator, Organization
class PersonScraper(Scraper):
COUNTY_BOARD_URL = 'http://www.arlingtonva.us/Departments/CountyBoard/meetings/members/CountyBoardMeetingsMembersMain.aspx'
def scrape(self):
board... |
3355962 | import re
from util import web
from util.hook import *
@hook(cmds=['kernel', 'kern'])
def kernel(code, input):
""" kernel - Gets the latest kernel versions from kernel.org """
data = web.text('https://www.kernel.org/finger_banner')
data = re.findall(r'The latest (.*?) version of the Linux kernel is: (.*)'... |
3355997 | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.conf import settings
from accounts.models import UserAttributes, UserInstance, UserSSHKey
from django.contrib.auth.models import Permission
from logs.models import Logs
import uuid
try:
from ldap3 import S... |
3355999 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import json
import cv2
import numpy as np
from progress.bar import Bar
import torch
import math
from opts import opts
from logger import Logger
from datasets.dataset_factory impor... |
3356006 | from .Ball3D import Ball3D
import numpy as np
from numpy.matlib import repmat
from numpy import zeros, eye, ones, matrix
from numpy import cos, sin, arccos, sqrt, pi, arctan2
class HumanBall3D(Ball3D):
"""
This the passive human 3D ball model. We assume a ball is control by human.
The human has no respons... |
3356008 | import sys
from glados.es.ws2es.denormalization import DenormalizationHandler
class DrugDenormalizationHandler(DenormalizationHandler):
RESOURCE = DenormalizationHandler.AVAILABLE_RESOURCES.DRUG
def __init__(self):
super().__init__()
self.compound_dict = {}
def handle_doc(self, es_doc: ... |
3356009 | from ..broker import Broker
class CollectionScheduleBroker(Broker):
controller = "collection_schedules"
def index(self, **kwargs):
"""Lists the available collection schedules. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the various ways to query lists,... |
3356020 | from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
from tests import pyunit_utils
import h2o
import random
from h2o.utils.typechecks import assert_is_type
from h2o.frame import H2OFrame
def h2ocreate_frame():
"""
Python API test: h2o.create_frame(frame_id=None, rows=10000, cols=10,... |
3356025 | from datahub.configuration.common import AllowDenyPattern
def test_allow_all() -> None:
pattern = AllowDenyPattern.allow_all()
assert pattern.allowed("foo.table")
def test_deny_all() -> None:
pattern = AllowDenyPattern(allow=[], deny=[".*"])
assert not pattern.allowed("foo.table")
def test_single_... |
3356040 | import ee
from ee_plugin import Map
# Simple regression of year versus NDVI.
# Define the start date and position to get images covering Montezuma Castle,
# Arizona, from 2000-2010.
start = '2000-01-01'
end = '2010-01-01'
lng = -111.83533
lat = 34.57499
region = ee.Geometry.Point(lng, lat)
# Filter to Landsat 7 im... |
3356120 | import io
import pytest
from mitmproxy import exceptions
from mitmproxy.net import tls
from mitmproxy.net.tcp import TCPClient
from test.mitmproxy.net.test_tcp import EchoHandler
from . import tservers
CLIENT_HELLO_NO_EXTENSIONS = bytes.fromhex(
"03015658a756ab2c2bff55f636814deac086b7ca56b65058c7893ffc6074f5245f... |
3356123 | import os
import cv2
import numpy as np
import scipy.misc as sm
import scipy.ndimage as nd
import itertools as it
from pyKinectTools.utils.DepthUtils import skel2depth, depthIm_to_colorIm#world2depth, depthIm2XYZ, depth2world
from pyKinectTools.utils.SkeletonUtils import msr_to_kinect_skel
from pyKinectTools.algs.Backg... |
3356162 | import pytz
import hashlib
import uuid
import datetime
from furs_fiscal.base_api import FURSBaseAPI
TYPE_MOVABLE_PREMISE_A = 'A'
TYPE_MOVABLE_PREMISE_B = 'B'
TYPE_MOVABLE_PREMISE_C = 'C'
NUMBERING_STRUCTURE_CENTRAL = 'C'
NUMBERING_STRUCTURE_DEVICE = 'B'
REGISTER_BUSINESS_UNIT_PATH = 'v1/cash_registers/invoices/reg... |
3356163 | import numpy as np
import torch
import torch.utils.data
class TrainSampler(torch.utils.data.Sampler):
def __init__(self, batch_size, filelists):
self.filelists = filelists
self.batch_size = batch_size
self.indexes = []
total = 0
for filelist in self.filelists:
in... |
3356176 | import random
from collections import Counter
import pytest
from agents.DQN_agents.DQN_HER import DQN_HER
from agents.DQN_agents.DDQN import DDQN
from agents.DQN_agents.DDQN_With_Prioritised_Experience_Replay import DDQN_With_Prioritised_Experience_Replay
from agents.DQN_agents.DQN_With_Fixed_Q_Targets import DQN_Wit... |
3356214 | from typing import List
from app import db
from app.responses.models import Response, Answer, ResponseTag
from app.applicationModel.models import ApplicationForm, Question, Section
from app.users.models import AppUser
from sqlalchemy import func, cast, Date
import itertools
class ResponseRepository():
@staticme... |
3356234 | params = {}
params["img_shape"] = (256, 256, 3)
params["batch_size"] = 2
params["epochs"] = 1
params["learning_rate"] = 0.001
params["continuing_training"] = False
params["data_dir"] = "./data"
params["save_path"] = "./output"
params["loss_function"] = "dice_loss"
params["n_filters"] = 32
params["batchnorm"] = True
par... |
3356269 | import yaml
import sys
import itertools
import os
import json
yaml_filename = 'sprint-5.yaml'
def run_relative_perturbation(compound_series, transformation_index, microstate_sdf_filename, tidy=True):
"""
Set up a relative transformation
"""
transformation = compound_series.transformations[transformat... |
3356306 | import numpy as np
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
from utils.data_paths import SUBMISSIONS_DIR_PATH
OUTPUT_FILE_PATH = os.path.join(SUBMISSIONS_DIR_PATH, 'simple_blend.dta')
PREDICTION_FILE_PATHS = [os.path.join(SUBMISSIONS_DIR_PATH, 'predictions1.dt... |
3356314 | from app.models.account import StudentModel, SignupWaitingModel
from tests.v2.views import TCBase
class TestIDVerification(TCBase):
"""
ID 중복체크를 테스트합니다.
"""
def __init__(self, *args, **kwargs):
super(TestIDVerification, self).__init__(*args, **kwargs)
self.method = self.client.post
... |
3356353 | from setuptools import setup, find_packages
try:
README = open('README.rst').read()
except Exception:
README = None
setup(
author='<NAME>',
author_email='<EMAIL>',
classifiers=['Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Frame... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.