id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1701094 | class FeatureRetriever:
"""FeatureRetriever is responsible for retrieving feature vectors for
beats.
"""
def __init__(self):
self.mapping = None
self.features = None
def get_feature_vector(self, file_path):
"""Get the feature vector associated to a file path.
:para... |
1701107 | from django.conf import settings
FAVICON_PATH = getattr(settings, 'FAVICON_PATH', '%sfavicon.ico' % settings.STATIC_URL)
|
1701142 | import logging
from volcengine_ml_platform.openapi.base_client import BaseClient
from volcengine_ml_platform.openapi.base_client import define_api
define_api("CreateCustomTask")
define_api("GetCustomTask")
define_api("ListCustomTasks")
define_api("StopCustomTask")
define_api("DeleteCustomTask")
define_api("ListCustom... |
1701153 | import requests_mock
import pandas as pd
import numpy as np
from tests import add_mock_request_queue, add_mock_request_get_success
from tests import fix_client, fix_report_definition # imports are used
def test_queue_reports(fix_client, fix_report_definition):
from adobe_analytics.reports.utils import _queue_r... |
1701155 | from PIL import Image
import numpy
image_path = "0001/0001_c1s1_001051_00.jpg"
original_im = Image.open("/home/zzd/Market/pytorch/query/" + image_path)
original_im = original_im.resize((128,256))
attack_im = Image.open("../attack_query/pytorch/query/" + image_path)
diff = numpy.array(original_im, dtype=float) - nu... |
1701159 | from rest_framework import serializers
from node.blockchain.models import Node
class NodeSerializer(serializers.ModelSerializer):
# TODO(dmu) HIGH: Instead of redefining serializer fields generate serializer from
# Node model metadata
identifier = serializers.CharField()
addresses = ... |
1701187 | import ldnlib
import argparse
import json
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="""For a provided web
resource, discover an ldp:inbox and GET the notifications from
that inbox, if one exists""")
parser.add_argument("target", help="The IRI of the target web re... |
1701202 | From 9934ce31b8447667f71c211e559a8de71e8263db Mon Sep 17 00:00:00 2001
From: <NAME> <<EMAIL>>
Date: Mon, 4 Jan 2016 23:14:06 +1100
Subject: [PATCH] Check bytecode file actually exists and tests
Should solve issue 20397, where using the --record argument results
in files that failed to generate bytecode files are added... |
1701262 | from selenium import webdriver
import time, unittest, config
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
class test_account(unittest.TestCase):
def setUp(self):
if (config.local):
self.wd = webdriver.Firefox()
... |
1701301 | from src import view
from model.geotechnic import surcharge_load
from model.utils import plot
import cherrypy
class Surcharge_Load:
def __init__(self):
pass
def point(self, **var):
# Prepare view & model object
template = view.lookup.get_template('geotechnic/surcharge_point.... |
1701302 | import regex as re
def modify_longvowel_errors(line, idx_yomi=None):
line[idx_yomi] = line[idx_yomi]\
.replace("ーィ","ウィ")\
.replace("ーェ","ウェ")\
.replace("ーォ","ウォ")
return line
def modify_yomi_of_numerals(line, idx_surface=None, idx_yomi=None):
"""
数値の読みを簡易的に修正する(完全なものではない)
... |
1701359 | import os
import numpy as np
import sys
import inspect
import functools
from collections import defaultdict
#pylint:disable=no-member,too-many-function-args
class Device: CPU, GPU = 0, 1
DEFAULT_DEVICE = Device.CPU if os.environ.get('GPU', 0) !=1 else Device.GPU
try:
import pyopencl as cl
# TODO: move this... |
1701368 | from django.urls import include, re_path
from .views import RootView
urlpatterns = [
re_path(r'^api/', include('knox.urls')),
re_path(r'^api/$', RootView.as_view(), name="api-root"),
]
|
1701392 | import pytest
pytestmark = [
pytest.mark.django_db,
pytest.mark.usefixtures('purchase'),
]
def test_patch(api, answer):
api.patch(f'/api/v2/homework/answers/{answer.slug}/', {'text': 'test'}, expected_status_code=405)
def test_put(api, answer):
api.put(f'/api/v2/homework/answers/{answer.slug}/', {'... |
1701467 | import ocaml
ocaml.add_dir("../../api/.ocaml_in_python_api.objs/byte/")
ocaml.add_dir(".nested_modules.objs/byte/")
ocaml.Dynlink.loadfile("nested_modules.cmxs")
from ocaml import Nested_modules
print(Nested_modules.A.c)
Nested_modules.A.f(Nested_modules.A.c)
|
1701471 | import io
import json
import os
from random import randint
import aiohttp
from loguru import logger
class InvalidFileIO(Exception):
pass
class DataIO():
def __init__(self):
self.logger = logger
async def download_link(self, ctx, url, filename):
async with aiohttp.ClientSession() as sess... |
1701481 | import click
from ...arguments import identifiers_argument, identifiers_help
from .base import cluster_command
@cluster_command.command(
context_settings=dict(ignore_unknown_options=True),
help=f'''Get the status of the connected Kubernetes cluster. {identifiers_help}''',
)
@click.pass_context
@identifiers_argum... |
1701519 | from unittest import TestCase
import os
import numpy as np
from bladex import NacaProfile, Shaft, Propeller, Blade
from smithers.io.obj import ObjHandler
from smithers.io.stlhandler import STLHandler
def create_sample_blade_NACApptc():
sections = np.asarray([NacaProfile('5407') for i in range(13)])
radii=np.a... |
1701533 | import itertools
from typing import TextIO
def read_range(data: TextIO) -> range:
a, b = next(data).split('-')
return range(int(a), int(b) + 1) # plus one because inclusive
def valid(number: int, strict: bool) -> bool:
s = str(number)
prev = '/' # is smaller than '0'
has_group = False
if... |
1701597 | import asyncio
import logging
import botocore.exceptions
from .bases import BaseSQSClient
from loafer.exceptions import ProviderError
from loafer.providers import AbstractProvider
logger = logging.getLogger(__name__)
class SQSProvider(AbstractProvider, BaseSQSClient):
def __init__(self, queue_name, options=No... |
1701601 | import os.path
from easydict import EasyDict as ezdict
import socket
class Paths(object):
def __init__(self, root=None):
# decide root based on input and machine name
if root is None:
hostname = socket.gethostname()
if hostname == 'cashew':
self.dsetroot = ... |
1701606 | from User import User
from User_manager import User_manager
class Register_controller:
def GetRegisterData(self, Fname, Lname, Email, Pass, Relationship, Sex, Bday, Route_visible,Pics_visible,User_ID=0 ):
user = User(Fname,Lname,Email,Pass,Relationship,Sex,Bday,Route_visible,Pics_visible,User_ID)
... |
1701622 | import numpy as np
import math
import sys
import scipy.ndimage
import pickle
import graph as splfy
import code
import random
import showTOPO
from rtree import index
from time import time
from hopcroftkarp import HopcroftKarp
from sets import Set
from subprocess import Popen
def latlonNorm(p1, lat = 40):
p11 = p... |
1701629 | import unittest
import os
import tempfile
from filecmp import cmp
from subprocess import call
import sys
import py_compile
#python -m unittest tests/test_coverage_filter.py
class CoverageFilterTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
#locate the bin and test_data directories
... |
1701641 | from . import BaseExtractor
class KDramaindo(BaseExtractor):
tag = "movie"
host = "https://k.dramaindo.my.id"
def extract_meta(self, id: str) -> dict:
"""
Ambil semua metadata dari halaman web
Args:
id: type 'str'
"""
raw = self.session.get(f"{self.... |
1701642 | from datetime import datetime, timedelta, timezone
import pytest
import dynamo
def test_put_subscription(tables):
subscription = {
'job_definition': {
'job_type': 'RTC_GAMMA',
'name': 'sub1',
},
'search_parameters': {
'start': '2020-01-01T00:00:00+00:0... |
1701654 | import zipfile
from kaitaistruct import KaitaiStructError
from .fileutils import Tempfile
from .kaitai.parser import KaitaiParser
from .kaitai.parsers.zip import Zip
from .kaitaimatcher import ast_to_matches
from .polyfile import InvalidMatch, Match, submatcher
@submatcher("application/zip")
class ZipFile(Match):
... |
1701701 | from __future__ import division
import os
import os.path
import os.path
import random
import math
import glob
import torch
import torch.utils.data as data
from .dataset_utils.util_func import *
from .dataset_utils import frame_utils
from . import dataset_read
class FolderImage(data.Dataset):
... |
1701703 | import time
from slackclient import SlackClient as _SlackClient
from conversations import ConversationManager
from commands import CommandManager
class SlackClient(_SlackClient):
# I'm not sure if it's my local environment, but the Slack Client
# swallows an error where the websocket client beneath can't find... |
1701747 | import numpy as np
import cv2
black_image = np.zeros((300,300,3), dtype='uint8')
red = (0, 0, 255)
black_image = cv2.line(black_image, (0, 0), (300, 300), red, 3)
cv2.imshow('Red line', black_image)
cv2.waitKey(0)
green = (0, 255, 0)
black_image = cv2.rectangle(black_image, (10, 10), (50, 50), green, -1)
cv2.imshow(... |
1701748 | from scipy import sparse
from autosklearn.pipeline.components.data_preprocessing.imputation.numerical_imputation\
import NumericalImputation
from autosklearn.pipeline.util import _test_preprocessing, PreprocessingTestCase
class NumericalImputationTest(PreprocessingTestCase):
def test_default_configuration(se... |
1701770 | import unittest
import orca
import os.path as path
from setup.settings import *
from pandas.util.testing import *
def _create_odf_csv(data, dfsDatabase):
# call function default_session() to get session object
s = orca.default_session()
dolphindb_script = """
login("admin", "<PASSWORD>")
dbPath="d... |
1701785 | import torch
import torchvision
import argparse
class EncoderCNNBackbone(torch.nn.Module):
def __init__(self):
super(EncoderCNNBackbone, self).__init__()
resnet_children = list(torchvision.models.resnet50(pretrained=True).children())[:-2]
self.layers = torch.nn.Sequential(*resnet_c... |
1701807 | from ..number import Number
from cake.abc import FloatType
import cake
import typing
class Irrational(Number):
"""
A class representing an irrational number, subclass of :class:`~cake.core.number.Number`
If the value is not a float/real it returns a :class:`~cake.core.number.Number`.
If it is not irr... |
1701824 | from __future__ import division
import glob
import numpy as NP
from functools import reduce
import numpy.ma as MA
import progressbar as PGB
import h5py
import healpy as HP
import warnings
import copy
import astropy.cosmology as CP
from astropy.time import Time, TimeDelta
from astropy.io import fits
from astropy import ... |
1701993 | import pytest
from bocadillo import configure, create_client, settings
def test_cannot_reconfigure(app):
with pytest.raises(RuntimeError):
configure(app)
def test_must_be_configured_to_serve(raw_app):
@raw_app.route("/")
async def index(req, res):
pass
with pytest.raises(RuntimeErr... |
1702001 | from __future__ import print_function
import os
import argparse
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from data import cfg
from layers.functions.prior_box import PriorBox
from utils.nms_wrapper import nms
#from utils.nms.py_cpu_nms import py_cpu_nms
import cv2
from models.faceboxes import... |
1702016 | import os
import shutil
import unittest
import uuid
import pyodbc
from ..pyodbc_helpers import *
class Test_pyodbc(unittest.TestCase):
@classmethod
def setUpClass(cls):
shutil.rmtree(cls.fix_tmproot())
@staticmethod
def fix_tmproot():
return os.path.realpath(os.path.j... |
1702028 | import torch.utils.data as data
import torch
from .human_parse_labels import get_label_map
from PIL import Image
import numpy as np
import cv2
import torchvision.transforms as transforms
import torch
import copy, os, collections
import json
import random
def listdir(root):
all_fns = []
for fn in os.listdir(roo... |
1702040 | class Clock:
def __init__(self,area):
self.area=area
def clock(self,feature):
if 'geometries' in feature:
feature['geometries'] = map(self.clock_geometry,feature['geometries'])
elif 'geometry' in feature:
feature['geometry']=self.clock_geometry(feature['geo... |
1702058 | from collections import OrderedDict
import numpy as np
import pandas as pd
from karura.core.dataframe_extension import DataFrameExtension
from karura.core.insight import InsightIndex
from karura.core.analysis_stop_exception import AnalysisStopException
from karura.core.predictor import PredictorConvertible
class Anal... |
1702068 | import asyncio
import pulumi
output = pulumi.Output.from_input(asyncio.sleep(1, "magic string"))
output.apply(print)
|
1702125 | from a2ml.api.base_a2ml import BaseA2ML
from a2ml.api.utils.show_result import show_result
class A2MLExperiment(BaseA2ML):
"""Contains the experiment operations that interact with provider."""
def __init__(self, ctx, provider=None):
"""Initializes a new a2ml experiment.
Args:
ctx (... |
1702163 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .architecture import VGG19, VGGFace19
# Defines the GAN loss which uses either LSGAN or the regular GAN.
# When LSGAN is used, it is basically same as MSELoss,
# but it abstracts away the need to create the target label tensor
# that has the same... |
1702194 | from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^tools/(?P<app_name>.*)/$', views.scan_tools, name='scan_tools'),
url(r'^all-app/$', views.all_app, name='all_app'),
url(r'^all-tool/(?P<app_name>.*)/$', views.all_tool, name='all_tool'),
... |
1702216 | from osrf_pycommon.process_utils import AsyncSubprocessProtocol
def create_protocol():
class CustomProtocol(AsyncSubprocessProtocol):
def __init__(self, *args, **kwargs):
self.stdout_buffer = b""
self.stderr_buffer = b""
AsyncSubprocessProtocol.__init__(self, *args, **k... |
1702227 | from .lstm import LSTM
from .layer_norm_lstm import LayerNormLSTM
from .gru import GRU
from .nbrc import NBRC
|
1702251 | from .dataloader import VisualQueryDatasetMapper
from .dataset import (
register_visual_query_datasets,
)
from .feature_retrieval import perform_retrieval
from .predictor import SiamPredictor
from .utils import (
create_similarity_network,
convert_annot_to_bbox,
convert_image_np2torch,
get_clip_name... |
1702257 | import albumentations as A
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch.utils.data import DataLoader
from mobile_seg.const import EXP_DIR
from mobile_seg.dataset import load_df, MaskDataset, split_df
from mobile_seg.modules.net import load_trained_model
from mobile_seg.params import DataP... |
1702260 | import os
import random
import socket
import typing
import pymongo
import pytest
import _pytest
from data import models
def local_mongo_is_running() -> bool:
if 'CIRCLECI' in os.environ:
return True
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.bind(("127.0.0.1", 2701... |
1702261 | import gi
gi.require_version('Gdk', '3.0')
from todoistext.TodoistExtension import TodoistExtension
if __name__ == '__main__':
TodoistExtension().run()
|
1702269 | rendererLineStart = ".renderer(() -> "
allTileEntities = "../src/main/java/com/simibubi/create/AllTileEntities.java"
lines = []
file = open(allTileEntities)
for line in file:
if rendererLineStart in line:
if "//" in line:
lines.append(line)
continue
toReplace = line.split(ren... |
1702296 | import pybullet as p
p.connect(p.GUI)
cube = p.loadURDF("cube.urdf")
frequency = 240
timeStep = 1./frequency
p.setGravity(0,0,-9.8)
p.changeDynamics(cube,-1,linearDamping=0,angularDamping=0)
p.setPhysicsEngineParameter(fixedTimeStep = timeStep)
for i in range (frequency):
p.stepSimulation()
pos,orn = p.getBasePositio... |
1702300 | from twilio.rest import Client
from SensoryData import SensoryData
from SensoryDashboard import SensoryDashboard
from gpiozero import Button
from time import time, sleep
class SecurityDashboardDist:
account_sid = ''
auth_token = ''
time_sent = 0
from_phonenumber=''
test_env = True
switch ... |
1702371 | import numpy as np
from FTOCP import FTOCP
from LMPC import LMPC
import pdb
import dill
import matplotlib.pyplot as plt
from tempfile import TemporaryFile
import copy
import datetime
import os
from casadi import *
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import rc
rc('font... |
1702389 | import sys
import numpy as np
from plyfile import PlyData
from matplotlib import pyplot as plt
from tomasi_kanade import TomasiKanade
from visualization import plot3d, plot_result
import rigid_motion
def read_object(filename):
"""Read a 3D object from a PLY file"""
ply = PlyData.read(filename)
vertex... |
1702401 | import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.transforms import ToTensor
from model_super_resolution import Net
from super_resolution_data_loader import *
import os
from os import listdir
from math import log10
from PIL import Image
... |
1702409 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.serialized_test.serialized_test_util as serial
from hypothesis import... |
1702465 | from topicdb.core.store.ontologymode import OntologyMode
from slugify import slugify
from topicdb.core.store.topicstore import TopicStore
from topicdb.core.models.attribute import Attribute
from topicdb.core.models.datatype import DataType
from topicdb.core.models.occurrence import Occurrence
from topicdb.core.models... |
1702472 | import argparse
from pathlib import Path
from typing import Tuple, Dict, Any
import torch
from models.fatchord_version import WaveRNN
from models.tacotron import Tacotron
from utils.display import simple_table
from utils.dsp import DSP
from utils.files import read_config
from utils.paths import Paths
from utils.text.... |
1702479 | from .base import rpartial, root, BaseLoadCase, BaseSaveCase
from .cv2 import cv2
class LoadCase(BaseLoadCase):
def runner(self):
cv2.imread(root('resources', self.filename),
flags=cv2.IMREAD_UNCHANGED)
class SaveCase(BaseSaveCase):
def create_test_data(self):
im = cv2.imr... |
1702534 | from typing import Iterable, Sequence
import numpy as np
from ..layout import Flat
from ..io import PathLike
@np.deprecate(message='This function is deprecated in favor of `dpipe.layout.Flat`')
def flat(split: Iterable[Sequence], config_path: PathLike, experiment_path: PathLike,
prefixes: Sequence[str] = (... |
1702551 | import numpy as np
from statsmodels.tools.testing import MarginTableTestBunch
est = dict(
rank=7,
N=17,
ic=6,
k=7,
k_eq=1,
k_dv=1,
converged=1,
rc=0,
k_autoCns=0,
ll=-28.46285727296058,
k_eq_model=... |
1702564 | import json
import os
import sys
from selenium.webdriver.firefox.firefox_profile import AddonFormatError
class FirefoxProfileWithWebExtensionSupport(webdriver.FirefoxProfile):
def _addon_details(self, addon_path):
try:
return super()._addon_details(addon_path)
except AddonFormatError:... |
1702579 | from whoosh.lang.snowball.english import EnglishStemmer
from whoosh.lang.snowball.french import FrenchStemmer
from whoosh.lang.snowball.finnish import FinnishStemmer
from whoosh.lang.snowball.spanish import SpanishStemmer
def test_english():
s = EnglishStemmer()
assert s.stem("hello") == "hello"
assert s.... |
1702660 | from importlib import import_module
from multiprocessing import Process
from os import kill, makedirs
from os.path import exists
from time import sleep
from setproctitle import setproctitle
from core import logger, common, storage
PROCESSES = [
"watcher",
"cleaner",
"reporter"
]
MODULES = {
"watcher":... |
1702662 | import cPickle as pkl
import h5py
from tqdm import tqdm
import os
train_h5_path = '../data/train36.hdf5'
val_h5_path = '../data/val36.hdf5'
train_id_path = '../data/train36_imgid2idx.pkl'
val_id_path = '../data/val36_imgid2idx.pkl'
save_obj_path = '../data/coco_obj'
train_obj_path = os.path.join(save_obj_p... |
1702673 | from logging import Formatter
from logging import Logger
from logging import StreamHandler
from logging import getLogger
from sys import stdout
from faceanalysis.settings import LOGGING_LEVEL
def get_logger(module_name: str) -> Logger:
logger = getLogger(module_name)
logger.setLevel(LOGGING_LEVEL)
strea... |
1702719 | from ..advans import *
@ti.data_oriented
class ToneMapping:
def __init__(self, res):
self.res = res
@ti.kernel
def apply(self, image: ti.template()):
for I in ti.grouped(image):
image[I] = aces_tonemap(image[I])
|
1702752 | from setuptools import setup
setup(
name="rubikscolorresolver",
version="1.0.0",
description="Resolve rubiks cube RGB values to the six cube colors",
keywords="rubiks cube color",
url="https://github.com/dwalton76/rubiks-color-resolver",
author="dwalton76",
author_email="<EMAIL>",
lice... |
1702849 | import csv
from itertools import zip_longest
from os import PathLike
from typing import Dict
from typing import List
from typing import Optional
from pydantic import BaseModel
from pydantic import Field
class PageData(BaseModel):
"""Representation for data from a webpage
Examples:
>>> from extract_... |
1702895 | import wx
import os
def file_open_dialog():
dialog_style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST
dialog = wx.FileDialog(
None, message='Open',
defaultDir=os.getcwd(),
defaultFile='', style=dialog_style)
return dialog
def file_save_dialog(title):
dialog_style = wx.FD_SAVE
... |
1702899 | from django.conf.urls import url
from . import views
urlpatterns = [
# url(r'^login/$', views.user_login, name='login'),
url(r'^$', views.dashboard, name='dashboard'),
url(r'^register/$', views.register, name='register'),
url(r'^edit/$', views.edit, name='edit'),
# login / logout urls
url(r'... |
1702905 | import inspect
import logging
from functools import partial, update_wrapper
from django.conf import settings
from django.contrib import messages
from django.contrib.admin.templatetags.admin_urls import admin_urlname
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from... |
1702906 | from selenium.webdriver.common.by import By
from util.conf import BAMBOO_SETTINGS
class UrlManager:
def __init__(self, build_plan_id=None):
self.host = BAMBOO_SETTINGS.server_url
self.login_params = '/userlogin!doDefault.action?os_destination=%2FallPlans.action'
self.logout_params = '/use... |
1702910 | import tensorflow as tf
from onnx_tf.handlers.backend_handler import BackendHandler
from onnx_tf.handlers.handler import onnx_op
from onnx_tf.common import sys_config
from onnx_tf.common import exception
import onnx_tf.common.data_type as data_type
@onnx_op("Gemm")
class Gemm(BackendHandler):
cast_map = {}
suppo... |
1702914 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from dgl.nn.pytorch.softmax import edge_softmax
import dgl
import dgl.function as fn
from dgl.nn.pytorch import GraphConv
import torch.nn.functional as F
from geomloss import SamplesLoss
def loss_fn_k... |
1702938 | from __future__ import absolute_import
import hyperopt
import mjolnir.training.tuning
import mjolnir.training.xgboost
from pyspark.sql import functions as F
import pytest
def test_split(spark):
df = (
spark
.range(1, 100 * 100)
# convert into 100 "queries" with 100 values each. We need a
... |
1702952 | import json
import os
import torch
from PIL import Image
class ImageDataset_Adv(torch.utils.data.Dataset):
def __init__(self, data_dir, transform=None):
self.data_dir = data_dir
self.transform = transform
self._indices = []
for line in open(os.path.join(os.path.dirname(os.path.ab... |
1703020 | valor_um = int(input("Digite um valor:"))
valor_dois = int(input("Digite outro valor:"))
resultado = valor_um + valor_dois
print(f"A soma entre {valor_um} e {valor_dois} é igual a {resultado}") |
1703041 | from __future__ import absolute_import
from tornado.web import RequestHandler
class BaseRequestHandler(RequestHandler):
"""
The base class for Tornado request handlers
"""
def get_current_user(self):
"""
Returns the current user for the request
:return: The current user for t... |
1703044 | import torch as tc
import numpy as np
import torch.nn.functional as F
from deeprobust.graph.data import Dataset
from deeprobust.graph.defense import GCN
from deeprobust.graph.global_attack import Metattack , MetaApprox
from deeprobust.graph.utils import sparse_mx_to_torch_sparse_tensor
import pdb
import dgl
import os
i... |
1703075 | from tests.utils import W3CTestCase
class TestDeleteBlockInInlinesEnd(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'delete-block-in-inlines-end-'))
|
1703105 | from PIL import Image
import matplotlib.pyplot as plt
def format_results(images, dst):
fig = plt.figure()
for i, image in enumerate(images):
text, img = image
fig.add_subplot(1, 3, i + 1)
plt.imshow(img)
plt.tick_params(labelbottom='off')
plt.tick_params(labelleft='off')... |
1703207 | from django.db import models
# Create your models here.
class Word(models.Model):
"""
单词Model
"""
name = models.CharField(max_length=20, verbose_name="名称")
explain = models.CharField(max_length=50, verbose_name="释义")
class Meta:
verbose_name = "单词"
verbose_name_plural = "单词们"... |
1703216 | import six
from .html_elements import HTMLElement
from ..meta_elements import MetaHTMLElement
from ..user_editable import UserEditable
@six.add_metaclass(MetaHTMLElement)
class TextArea(UserEditable, HTMLElement):
ATTRIBUTES = ['value']
|
1703219 | import cv2
import numpy as np
from PIL import Image
import os, glob
import characters as cd
# 画像が保存されているルートディレクトリのパス
root_dir = "../learning_data"
# キャラクター名一覧
characters = cd.characters_name_mask
# 画像データ用配列
X = []
# ラベルデータ用配列
Y = []
# 画像データごとにadd_sample()を呼び出し、X,Yの配列を返す関数
def make_sample(files):
global X, Y
... |
1703250 | from mu.harness.project import StoreUpdate
from mu.harness.sub_sim import SubSim
from mu.protogen import stores_pb2
from mu.protogen import mcp2515_pb2
MCP2515_KEY = (stores_pb2.MuStoreType.MCP2515, 0)
class Mcp2515(SubSim):
def handle_store(self, store, key):
if key[0] == stores_pb2.MuStoreType.MCP2515:... |
1703268 | from redis import Redis
from redisprob import RedisHashFreqDist, RedisConditionalHashFreqDist
if __name__ == '__channelexec__':
host, fd_name, cfd_name = channel.receive()
r = Redis(host)
fd = RedisHashFreqDist(r, fd_name)
cfd = RedisConditionalHashFreqDist(r, cfd_name)
for data in channel:
if data == 'done':... |
1703282 | import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv')
app = dash.Dash()
app.layout = html.Div(className='container', children=[
html.H... |
1703301 | import numpy as np
import pandas as pd
import geopandas as gpd
from datetime import datetime
from operator import itemgetter
from ...utils import constants
from ...utils.constants import UID, DATETIME, LATITUDE, LONGITUDE, GEOLIFE_SAMPLE
from ...core.trajectorydataframe import TrajDataFrame
from ...core.flowdataframe i... |
1703303 | import torch
import cargan
class Autoregressive(torch.nn.Module):
def __init__(self):
super().__init__()
model = [
torch.nn.Linear(cargan.AR_INPUT_SIZE, cargan.AR_HIDDEN_SIZE),
torch.nn.LeakyReLU(.1)]
for _ in range(3):
model.extend([
... |
1703309 | from copy import deepcopy
from sklearn.model_selection import ParameterGrid
from yaglm.config.base import Config
from yaglm.autoassign import autoassign
class ParamConfig(Config):
"""
Base class for tunable parameter configs.
"""
def tune(self):
"""
Returns the initialized tuning obje... |
1703337 | import argparse
def get_args():
parser = argparse.ArgumentParser(description='Multimodal Emotion Recognition')
# Training hyper-parameters
parser.add_argument('-bs', '--batch-size', help='Batch size', type=int, required=True)
parser.add_argument('-lr', '--learning-rate', help='Learning rate', type=flo... |
1703341 | import numpy as np
import pytest
from probnum import randprocs
from tests.test_randprocs.test_markov.test_discrete import test_linear_gaussian
class TestLTIGaussian(test_linear_gaussian.TestLinearGaussian):
# Replacement for an __init__ in the pytest language. See:
# https://stackoverflow.com/questions/2143... |
1703370 | from insights.parsr.examples.multipath_conf import loads
EXAMPLE = """
# This is a basic configuration file with some examples, for device mapper
# multipath.
#
# For a complete list of the default configuration values, run either
# multipath -t
# or
# multipathd show config
#
# For a list of configuration options wi... |
1703398 | import komand
from .schema import SubmitFileInput, SubmitFileOutput
# Custom imports below
import base64
import io
import pyldfire
from komand.exceptions import PluginException
class SubmitFile(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="submit_file",
... |
1703410 | import logging
from django.conf import settings
from django.core.mail import send_mail
from django.db.models import Exists
from django.db.models.expressions import OuterRef
from django.db.models.functions import Now
from django.template.loader import render_to_string
from django_cron import CronJobBase, Schedule
from ... |
1703417 | import os
import subprocess
################################################################################################
# Service DTO
class ServiceDTO:
# Class Constructor
def __init__(self, port, name, description):
self.description = description
self.port = port
self.name = nam... |
1703419 | from django.core.management.base import BaseCommand
from django.core.management.color import no_style
from django.db import connection
from nautobot.circuits.models import CircuitTermination
from nautobot.dcim.models import (
CablePath,
ConsolePort,
ConsoleServerPort,
Interface,
PowerFeed,
Powe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.