id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9956207 | import logging
from django.http import HttpResponse
logger = logging.getLogger(__name__)
def test_view(request):
logger.debug("A wild log message appears!")
return HttpResponse('ok')
async def test_async_view(request):
logger.debug("An async log message appears")
return HttpResponse('ok')
|
9956210 | import text2text as t2t
class Variator(t2t.Translator):
def transform(self, input_lines, src_lang='en', **kwargs):
input_lines = t2t.Transformer.transform(self, input_lines, src_lang=src_lang, **kwargs)
output_lines = []
src_lang = src_lang
for tgt_lang in self.__class__.LANGUAGES:
translated =... |
9956224 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
"""
MXNet Protobuf to IR converter &
IR to MXNet net converter
To run this, you will need to have MXNet installed as well.
"""
import os
import sys
sys.path.append('./.... |
9956275 | from rest_framework import serializers
from api.model.ingredient import Ingredient
from api.model.ateIngredient import AteIngredient
from api.serializer.ingredient import IngredientSerializer
from django.contrib.auth.models import User
class AteIngredientSerializer(serializers.ModelSerializer):
user = serialize... |
9956282 | import torch
import torch.nn as nn
class SDT(nn.Module):
"""Fast implementation of soft decision tree in PyTorch.
Parameters
----------
input_dim : int
The number of input dimensions.
output_dim : int
The number of output dimensions. For example, for a multi-class
classification... |
9956305 | from nornir import InitNornir
from nornir_utils.plugins.tasks.data import load_yaml
from nornir_jinja2.plugins.tasks import template_string
ACL_TEMPLATE = """{%- for acl, rules in acls.items() %}
{%- for entry in rules %}
set firewall family inet filter {{ acl }} term {{ entry['term_name'] }} from protocol {{ entr... |
9956308 | from collections import MutableMapping
import ruamel.yaml
from python.common_components import CORENLP, YAML, DBPEDIA, DBPEDIA_SPOTLIGHT
from python.common_components.dbpedia import DbPedia
from python.common_components.dbpedia_spotlight import DbPediaSpotlight
from python.pipeline import ComponentBase
from python.co... |
9956324 | from multiprocessing import cpu_count
from tqdm.auto import tqdm
from mpire.pool import WorkerPool
|
9956366 | from __future__ import absolute_import
from .sparse import *
from .utils import *
from .geometry import *
from .eigen import *
from .check_derivatives import *
|
9956375 | from django.test import TestCase
from django.urls import reverse
from conf_site.accounts.tests import AccountsTestCase
from conf_site.core.views import CsvView
class CsvViewTestCase(TestCase):
view_class = CsvView
def test_status_code(self):
response = self.view_class().get()
self.assertEqua... |
9956389 | import json
import os
import unittest
from collections import OrderedDict
from tempfile import NamedTemporaryFile
from unittest import TestCase
import networkx as nx
from lucid_ml.utils.thesaurus_reader import ThesaurusReader
class ThesaurusReaderTest(TestCase):
def setUp(self):
self.thes_path = make_thes... |
9956390 | from distutils.core import setup
setup(
name='screenutils',
version='0.0.1.6.2',
packages=['screenutils',],
license='GNU Public License >=2 (ask me if you want other)',
author="<NAME>",
author_email="@Christophe31",
url="http://github.com/Christophe31/screenutils",
description =
"li... |
9956402 | import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import argparse
# (Optional) command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--data_loc', type=str, default='/home/nkilloran/Desktop/Max_pipeline/2017.05.30-17h52m42s_pcnathan/gen_edit_d... |
9956413 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
import PIL
import os
import os.path
import pickle
import ra... |
9956423 | import os
from pathlib import Path
from src import OUTPUT_PATH
from src.schemas import retrosheet_metadata, baseballdatabank_metadata, all_metadata
from src.ddl_factories import all_factories
from src.parquet import write_files, PARQUET_PREFIX
os.chdir(Path("/tmp/boxball"))
class TestSchemas:
def test_schemas_... |
9956437 | class Kaldi():
def __init__(self, context):
context.tokens = []
context.last_segment = None
context.text = ""
context.final_transcript = False
def middleware(self, nxt):
def handle(context):
msg = context.msg
if 'result' in msg:
... |
9956476 | from subprocess import check_output
from slackclient import SlackClient
import os
import re
import time
import json
class SpotifySlackBot():
def __init__(self, api_key, broadcast_channel):
self.broadcast_channel = broadcast_channel
self.sc = SlackClient(api_key)
# Get the user list
... |
9956492 | import tkinter as tk
# --- functions ---
def select_button(widget):
global previously_clicked
if previously_clicked:
previously_clicked['bg'] = widget['bg']
previously_clicked['activebackground'] = widget['activebackground']
previously_clicked['relief'] = widget['relief']
widget[... |
9956504 | import pytest
from django.urls import reverse
users = (
('owner', 'owner'),
('manager', 'manager'),
('author', 'author'),
('guest', 'guest'),
('api', 'api'),
('user', 'user'),
('site', 'site'),
('anonymous', None),
)
view_questionset_permission_map = {
'owner': [1, 2, 3, 4, 5],
... |
9956525 | import pandas as pd
sales=pd.read_csv('train_data.csv',sep='\s*,\s*',engine='python') #读取CSV
X=sales['X'].values #存csv的第一列
Y=sales['Y'].values #存csv的第二列
#初始化赋值
s1 = 0
s2 = 0
s3 = 0
s4 = 0
n = 4 ####你需要根据的数据量进行修改
#循环累加
for i in range(n):
s1 = s1 + X[i]*Y[i]
s2 = s2 + X[i]
s3 = s3 + Y[i]
s4 = s4 + X[i... |
9956560 | from __future__ import print_function
import time
def fib(n):
if n < 2: return n
return fib(n - 1) + fib(n - 2)
for i in range(0, 5):
print(fib(28))
|
9956625 | clue = 'payzgmuujurjigkygxiovnkxlcgihubb'
for i in range(26):
cand = ''
for c in clue:
cand += chr(0x61 + (ord(c.lower()) + i - 0x61) % 26)
print('Shift %d: %s' % (i, cand))
|
9956628 | from dataknead import Knead
# Convert from JSON to TOML
Knead("input/entity.json").write("output/entity.toml")
# Convert from TOML to JSON
Knead("input/example.toml").write("output/toml_example.json", indent = 4, default = str) |
9956640 | import unittest
from Skoarcery import langoids, terminals, nonterminals, dragonsets
from Skoarcery.langoids import Terminal
class Not_LL_1(Exception):
pass
M = None
#
# Dragon Spell: 4.4 Construction of a predictive parsing table
#
def init():
from collections import defaultdict
from Skoarcery.dragonse... |
9956668 | r"""`fast_rl.layers` provides essential functions to building and modifying `model` architectures"""
from math import ceil
from fastai.torch_core import *
from fastai.tabular import TabularModel
def init_cnn(mod: Any):
r""" Utility for initializing cnn Modules. """
if getattr(mod, 'bias', None) is not None: nn.ini... |
9956715 | from ds2.stack import ListStack
class BadStack(ListStack):
def push(self, item):
self._L.insert(0, item)
def pop(self):
return self._L.pop(0)
def peek(self):
return self._L[0]
|
9956789 | import torch
import numpy as np
from nes.ensemble_selection.containers import Baselearner
from nes.ensemble_selection.config import model_seeds
from nes.ensemble_selection.utils import get_dataloaders_and_classes
from nes.darts.baselearner_train.model import DARTSByGenotype as model_cifar
from nes.darts.baselearner_tr... |
9956810 | from __future__ import print_function
import argparse
import os
import shutil
import time
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data as data
import torchvision.transforms as trans... |
9956856 | import pygame as pg
black, white, grey, red, alpha = (
pg.Color(20, 20, 20),
pg.Color(255, 255, 255),
pg.Color(50, 50, 50),
pg.Color(150, 0, 0),
pg.Color(0, 0, 0, 0),
)
|
9956861 | import os
import numpy as np
import cv2
import torch
from model import S3D
def main():
''' Output the top 5 Kinetics classes predicted by the model '''
path_sample = './sample'
file_weight = './S3D_kinetics400.pt'
class_names = [c.strip() for c in open('./label_map.txt')]
num_class = 400
model... |
9956886 | import os, requests, os.path
from colorama import Fore
os.system('cls' if os.name == 'nt' else 'clear')
statuechangertitle()
print(f"""{y}[{w}+{y}]{w} Enter your token""")
usertoken = str(input(f"""{y}[{b}#{y}]{w} Token: """))
print(f"""\n{y}[{w}+{y}]{w} Choose Custom Status""")
status = input(f"""{y}[{b}#{y}]... |
9956975 | import time
from datetime import datetime
from unittest import mock
from freezegun import freeze_time
from looker_sdk.sdk.api31.models import (
Dashboard,
DashboardElement,
LookmlModelExplore,
LookmlModelExploreField,
LookmlModelExploreFieldset,
LookmlModelExploreJoins,
Query,
)
from datah... |
9957007 | import unittest
import numpy as np
from feastruct.fea.node import Node
from feastruct.pre.material import Steel
from feastruct.fea.fea import FiniteElement
from feastruct.fea.cases import AnalysisCase
class TestFiniteElement(unittest.TestCase):
"""Tests the functionality of the FiniteElement class"""
def set... |
9957013 | import sys
f = open(sys.argv[1], 'r')
print('opening %s' % sys.argv[1])
stats = {}
filenames = {}
for l in f:
if l.startswith('#'):
filenum, filename = l[1:].strip().split(' ')
filenames[int(filenum)] = filename
continue
time, offset, end, rw, f = l.split('\t')
size = int(end) - int(offset)
f = int(f.s... |
9957065 | from WhatsAppManifest.consts import _PACKAGE_NAME_
from WhatsAppManifest.manifest.android.keyevents import KeyEvents
from WhatsAppManifest.adb.base import WhatsAppManifest
from WhatsAppManifest.manifest.whatsapp.sys import SysCommands
from WhatsAppManifest.manifest.android.category import AndroidCategoryBrowsable, Andr... |
9957073 | import datetime
from dateutil.tz import tzutc, tzoffset
from atoma.atom import (
AtomFeed, AtomEntry, AtomTextConstruct, AtomTextType, AtomPerson, AtomLink,
AtomGenerator, parse_atom_file
)
def test_rfc_more_extensive():
expected_entry = AtomEntry(
title=AtomTextConstruct(text_type=AtomTextType.... |
9957093 | from wagtail.contrib.modeladmin.options import (
ModelAdmin,
ModelAdminGroup,
modeladmin_register,
)
from .models import Subscription, Newsletter
class SubscriptionAdmin(ModelAdmin):
model = Subscription
menu_icon = "mail"
class NewsletterAdmin(ModelAdmin):
model = Newsletter
menu_icon ... |
9957140 | from model_mommy import mommy
from django.contrib.gis.geos import Point
from rest_framework.exceptions import ValidationError
from common.tests.test_models import BaseTestCase
from ..models import (
GeoCodeSource, GeoCodeMethod, FacilityCoordinates, WorldBorder)
class TestWorldBoundaryModel(BaseTestCase):
d... |
9957157 | import FWCore.ParameterSet.Config as cms
eleIsoFromDepsTk = cms.EDProducer("CandIsolatorFromDeposits",
deposits = cms.VPSet(cms.PSet(
mode = cms.string('sum'),
src = cms.InputTag("eleIsoDepositTk"),
weight = cms.string('1'),
deltaR = cms.double(0.3),
vetos = cms.vstring('Rec... |
9957204 | from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING:
from dataclasses import dataclass, field
else:
from reloadium.vendored.dataclasses import dataclass, field
dataclass = dataclass(repr=False) # type: ignore
__all__ = [
"Object",
"Variable",
"All",
"Dic... |
9957217 | import os
import sys
import unittest
import xmlrunner
CWD = os.path.dirname(os.path.abspath(__file__))
INVERSE_DESIGN_DIR = os.path.join(CWD, "..")
sys.path.insert(0, INVERSE_DESIGN_DIR)
TestCase = unittest.TestCase
def run(filenames):
for filename in filenames:
os.chdir(os.path.abspath(os.path.dirname(... |
9957251 | from marshmallow import fields, INCLUDE
from marshmallow.schema import Schema
from platypush.schemas import StrippedString
class SlackMessageBlockSchema(Schema):
class Meta:
unknown = INCLUDE
type = fields.String(required=True, metadata=dict(description='Message block type'))
block_id = fields.S... |
9957261 | from collections import OrderedDict
import random
from sentence_transformers.util import pytorch_cos_sim
from torch.utils.data import Dataset, Sampler
from typing import List, Optional
import torch
import numpy as np
from tqdm import tqdm
class EncodeDataset(Dataset):
def __init__(self,
sentences... |
9957281 | CONFIG = """
{
"dataset_reader" : {
"type": "classification-tsv",
"token_indexers": {
"tokens": {
"type": "single_id"
}
}
},
"train_data_path": "quick_start/data/movie_review/train.tsv",
"validation_data_path": "quick_start/data/movie_revie... |
9957291 | from django.contrib import admin
from django.urls import path, include
from products.api.views import ProductListAPIView, ProductCreateAPIView
urlpatterns = [
path("list/", ProductListAPIView.as_view(), name="product-list"),
path("create/", ProductCreateAPIView.as_view(), name="product-create"),
]
|
9957335 | import torch
import torch.nn as nn
class Bottleneck(nn.Module):
def __init__(self, latent_dim):
super(Bottleneck, self).__init__()
self.latent_dim = latent_dim
def forward(self, encoded):
"""Calculate latent code and loss."""
raise NotImplementedError
def _loss(self, *arg... |
9957367 | import os
import argparse
from os.path import join
parser = argparse.ArgumentParser()
parser.add_argument("--model_root_dir", type=str, default="/home/ubuntu/ShapeNetV1/ShapeNetCore.v1", help="path to ShapeNet mesh model")
parser.add_argument("--blender_path", type=str, default="/usr/local/blender-2.79b-linux-glibc219... |
9957387 | import unittest
from propnet.dbtools.aflow_ingester import AflowIngester
from propnet.dbtools.aflow_ingester_defaults import default_query_configs, default_files_to_ingest
from propnet.symbols import add_builtin_symbols_to_registry
from propnet.core.registry import Registry
from maggma.stores import MemoryStore
from af... |
9957389 | import os
import json
import logging
def read(config_path):
with open(config_path, "r") as f:
return json.load(f)
def welcome(message, url, time):
logging.basicConfig(level = logging.INFO)
logging.info(message)
logging.info(f"商品链接为 : {url}")
logging.info(f"抢购时间为 : {time}")
|
9957446 | from typing import List, Set
from requests import HTTPError
from keycloak_scanner.logging.vuln_flag import VulnFlag
from keycloak_scanner.scan_base.scanner import Scanner
from keycloak_scanner.scan_base.types import Realm, Client, ClientConfig
from keycloak_scanner.scan_base.wrap import WrapperTypes
class ClientSca... |
9957447 | from .states import (
STATES,
STATES_CONTIGUOUS,
STATES_CONTINENTAL,
TERRITORIES,
STATES_AND_TERRITORIES,
OBSOLETE,
)
from .unitedstatesofamerica import * # noqa
|
9957537 | from .argparse import *
from .errors import *
__title__ = "discord_argparse"
__author__ = "lukeciel"
__version__ = "1.0.1"
|
9957550 | from typing import Tuple
import time
import traceback
import random
from termcolor import colored
from tqdm import tqdm
import numpy as np
import tvm
import tvm.testing
from tvm import tir
from . import report, error, seed, oracle
from .config import Config
from .pass_fuzz.pass_mutator import SimplePassMutator
from .... |
9957569 | import copy
from hash_map import *
class block:
def __init__(self):
self.type = ""
self.name = ""
self.attr = {}
self.data = {}
self.data_ordered = []
def depend(obj, macro):
if "depend" in obj.attr:
return macro.query(obj.attr["depend"])
else:
retur... |
9957669 | import geonumpy.io as gio
import matplotlib.pyplot as plt
if __name__ == '__main__':
gdf = gio.read_shp('../data/shape/shandong.shp')
print(gdf)
gdf.plot()
plt.show()
print('read modis hdf data:')
modis = gio.read_hdf('../data/modis/MOD09Q1.A2019017.h28v05.006.2019030120612.hdf', 0)
p... |
9957695 | from functools import partial, update_wrapper
def named_partial(func, *args, **kwargs):
"""
__name__ and __doc__ attributes are not created automatically for partial.
Use that function to propagate these properties from the original function.
"""
partial_func = partial(func, *args, **kwargs)
u... |
9957706 | input = """
1 511 2 0 452 44
1 452 2 0 511 61
1 452 2 0 381 61
1 381 3 0 22 81 57
1 1 2 1 511 65
1 1 2 1 452 44
1 1 2 1 381 53
6 0 45 24 23 22 26 29 32 33 36 40 44 50 53 57 61 65 74 77 81 85 89 98 101 105 109 113 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 1 1 1 1 1 1 1 1 1 1 1 1... |
9957740 | import unittest
from typing import Set
import numpy as np
import xarray as xr
from xcube.core.new import new_cube
from xcube.core.timeseries import get_time_series
POINT_GEOMETRY = dict(type='Point', coordinates=[20.0, 10.0])
POLYGON_GEOMETRY = dict(type='Polygon', coordinates=[[[20.0, 10.0],
... |
9957745 | from cartographer.field_types import SchemaAttribute
class BoolAttribute(SchemaAttribute):
@classmethod
def format_value_for_json(cls, value):
return bool(value)
def from_json(self, serialized_value):
return bool(str(serialized_value).lower() not in ['false', '0'])
|
9957747 | import ipywidgets as widgets
import numpy as np
import plotly.graph_objects as go
import pynwb
import trimesh
from .base import df_to_hover_text
def make_cylinder_mesh(
radius, height, sections=32, position=(0, 0, 0), direction=(1, 0, 0), **kwargs
):
new_normal = direction / np.linalg.norm(direction)
cos... |
9957751 | import numpy as np
import torch
import torch.nn as nn
from collections import OrderedDict
from torchvision.models.densenet import _DenseBlock, _Transition
class DenseYOLO(nn.Module):
def __init__(
self,
img_channels,
out_channels,
growth_rate=16,
block_config=(2, 6, 4, 12,... |
9957770 | from pathlib import Path
from typing import Optional
from starlette.config import Config
from starlette.datastructures import CommaSeparatedStrings, Secret
from ..models.pydantic.database import DatabaseURL
p: Path = Path(__file__).parents[2] / ".env"
config: Config = Config(p if p.exists() else None)
DATABASE: str... |
9957801 | import cPickle as pickle
import numpy as np
import tensorflow as tf
from ch02.util.matplot_util import draw_plot
from util import accuracy
pickle_file = 'notMNIST.pickle'
image_size = 28
num_of_labels = 10
def reformat(dataset, labels):
dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float3... |
9957823 | from tests.utils_testing import *
@pytest.fixture
def X_converted():
return GeneticTree._check_X(GeneticTree(), X, True)
def test_observations_creation(X_converted):
obs = Observations(X_converted, y, sample_weight)
@pytest.fixture
def obs(X_converted):
return Observations(X_converted, y, sample_weigh... |
9957825 | from elasticsearch import Elasticsearch
import argparse
import os
import json
import re
def ExportDashboards(es, beat, kibana_index, output_directory):
res = es.search(
index=kibana_index,
doc_type="dashboard",
size=1000)
reg_exp = re.compile(beat + '*', re.IGNORECASE)
for doc in... |
9957856 | import unittest
from collections import defaultdict
import numpy as np
import pandas as pd
import numpy.testing as np_test
from scipy.sparse import coo_matrix
from dummyPy import Encoder, OneHotEncoder
class TestEncoder(unittest.TestCase):
def test_class(self):
encoder = Encoder()
self.assertEqu... |
9957888 | def test_vcf(filename):
with open(filename, encoding='utf-8') as handle:
for index, line in enumerate(handle):
line = line.replace('\n', '')
# Already read meta and header in self.__init__
if line.startswith('#'):
continue
list_line = line.spli... |
9957905 | from ida_migrator.plugin import IdaMigratorPlugin
def PLUGIN_ENTRY(*args, **kwargs):
return IdaMigratorPlugin(*args, **kwargs)
|
9957947 | import os
from mock import MagicMock
from bxcommon.services.transaction_service import TransactionService
from bxcommon.test_utils import helpers
from bxcommon.utils import convert
from bxcommon.utils.object_hash import Sha256Hash, SHA256_HASH_LEN
from bxgateway.messages.eth.protocol.new_block_eth_protocol_message im... |
9958014 | from dataclasses import dataclass
import numpy as np
@dataclass
class SurvivePose:
Pos: np.array = np.array((0, 0, 0))
Rot: np.array = np.array((1, 0, 0, 0))
@dataclass
class SurviveAxisAnglePose:
Pos: np.array = np.array((0., 0., 0))
AxisAngleRot: np.array = np.array((0, 0, 0))
@dataclass
class Sur... |
9958018 | from .base import *
from .crd_transform import *
from .dynamics import *
from .estimator import *
from .stochastic import *
from .transformer import *
from .affine import *
from .coupling import *
from .funnel import FunnelFlow
from .spline import LinearSplineFlow
from .kronecker import KroneckerProductFlow
from .sequ... |
9958037 | import os
import typer
from cli.version_detectors import DETECTORS
from cli.vulnerablity_detectors import detect_vulnerablities
from cli.formatters import format_report
from cli.utils import normalized_version
from cli.utils import blue_str
def _main():
versions_by_component = {}
for component_name, detecto... |
9958049 | import json
import pathlib
import re
import aiofiles
import pytest
from baguette.headers import Headers
from baguette.httpexceptions import NotFound
from baguette.responses import (
EmptyResponse,
FileResponse,
HTMLResponse,
JSONResponse,
PlainTextResponse,
RedirectResponse,
Response,
... |
9958088 | from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def can_paginate(self, operation_name: str = None):
"""
C... |
9958159 | from PyQt5.QtCore import QObject, QBuffer, QIODevice, Qt
from PyQt5.QtGui import QImage, QPainter, QCursor
import socket
import struct
from threading import Thread
from mss import mss
import zlib
import logging
from Module.Packages import RemoteSpyFlag
class RemoteSpy(QObject):
socket_ip = None
socket_port = ... |
9958183 | import datetime as dt
import math
import time
import requests
from .utils import to_dataframe
class AtlasTrendsQuery:
def __init__(self, resource, msm_id, prb_id, start_dt=None, stop_dt=None, subresource=None):
self.resource = resource
self.subresource = subresource
self.msm_id = msm_id... |
9958219 | from os.path import dirname, join
from . import (test_blas_low_level, test_blas, test_fft, test_rand,
test_sorting, test_sparse)
test_cases = (
test_blas_low_level.test_cases +
test_blas.test_cases +
test_fft.test_cases +
test_rand.test_cases +
test_sorting.test_cases +
test_spar... |
9958223 | from collections import defaultdict
import numpy
from OpenGL.GL import *
from btypes.big_endian import *
import gx
from j3d.opengl import *
import logging
logger = logging.getLogger(__name__)
class Header(Struct):
magic = ByteString(4)
section_size = uint32
attribute_format_offset = uint32
position_o... |
9958234 | import pandas as pd
from pandas_profiling.config import Settings
from pandas_profiling.model.missing import (
missing_bar,
missing_dendrogram,
missing_heatmap,
missing_matrix,
)
from pandas_profiling.visualisation.missing import (
plot_missing_bar,
plot_missing_dendrogram,
plot_missing_heat... |
9958278 | from django.apps import apps as djapps
settings = djapps.get_app_config('debug_informer')
__all__ = (
'DebugInformerHeadersMiddleware',
)
class DebugInformerHeadersMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self... |
9958389 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
def huber_loss(labels, predictions, delta=1.0):
residual = tf.abs(predictions - labels)
def f1(): return 0.5 * tf.square(residual)
def f2(): return delta * residual - 0.5 * tf.square(delta)
return tf.cond(residual < delta, f1, f2)... |
9958404 | from flask import Flask, render_template
#
# Our WSGI application .. in this case Flask based
#
app = Flask(__name__)
app.config.seq = 0
@app.route('/')
def page_home():
app.config.seq += 1
return render_template('index.html',
message="Hello from Crossbar.io",
... |
9958437 | import numpy as np
try:
from numpy import nanmean
except ImportError:
# obsolete location
from scipy.stats import nanmean
# initial implementation 90ms for 1132 sample window,
# compared to 0.258ms for holey_psd
# changing to nanmean -> 6ms.
# mean takes just 3ms.
def nan_detrend(x,order=1):
valid=np.... |
9958445 | import logging
from glob import glob
from pathlib import Path
import cv2
import numpy as np
from imgaug import augmenters as iaa
from imgaug.augmentables import BoundingBox, BoundingBoxesOnImage, Keypoint, KeypointsOnImage
from omegaconf.listconfig import ListConfig
from PIL import Image
from pycocotools.coco import C... |
9958468 | import argparse
import importlib
import json
import os
import matplotlib
import numpy as np
import tensorflow as tf
import utils
from config_rnn import defaults
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import gridspec
def plot_anomaly(config_name, n_sequences, n_ignore=8):
configs_... |
9958497 | import sys
from os import listdir, getcwd
from os.path import abspath, isdir, join, dirname, basename
from argparse import ArgumentParser
sys.path.append(abspath("scripts"))
from generate_imports_helper import comment, get_importable_lines
import_line_format = "\t_ \"{beat_path}/{module}/{name}\""
import_template = ... |
9958546 | from .Cat import Cat
from .Dog import Dog
from .Error import Error
from .Owner import Owner
from .Pet import Pet
from .Shop import Shop
|
9958550 | import sqlalchemy as sa
Book = sa.table(
"book",
sa.column("id", sa.Integer),
sa.column("name", sa.String),
)
Book.append_column(sa.column("other"))
Book.corresponding_column(Book.c.id)
value_expr = sa.values(
sa.column("id", sa.Integer), sa.column("name", sa.String), name="my_values"
).data([(1, "nam... |
9958558 | import numpy as np
from iter_solver import calculate_distance_matrix, auto_solver, plot_route
coords = []
for _ in range(50):
coords.append(np.random.random(2))
coords = np.array(coords)
distance_matrix = calculate_distance_matrix(coords)
d, r = auto_solver(distance_matrix, n_iter=1000, local_search_iter=100,
... |
9958564 | import numpy as np
class Softmax:
'''
A standar fully-connected layer with softmax activation
'''
def __init__(self, input_len, nodes):
# (.../input_len) to reduce the variance of our initial values
self.weights = np.random.randn(input_len, nodes) / input_len
self.biases = np... |
9958582 | import unittest
import logging
import sys
from .test_endpoint_ignore import EndpointIgnoreTestCase
from .test_measurement import MeasurementTest
from .test_measure_endpoint import EndpointMeasurementTest, EndpointMeasurementTest2
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
def suite():
suite = ... |
9958598 | try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
from mse.constants import *
from mse.charset import fix_charset_collation
class EqualityMixin:
def __eq__(self, other):
return (type(other) is type(self)) and self.__dict__ == other.__dict__
def _... |
9958604 | import json
import os
import sys
import time
from datetime import datetime
from time import gmtime, strftime
from urllib.parse import parse_qs, urlparse
import boto3
import numpy as np
import requests
from chalice import Chalice
# Global Varibale from model
content_type = "application/json"
accept = "Accept"
min_serv... |
9958620 | import contextlib
import logging
from threading import RLock
# from bottle import Bottle, HTTPError, redirect
import bottle
from ..nodes import Manager as NodesManager
from ..proxy import Proxy
from ..session import SessionManager, Session, make_short_id
from ..utils import AttributedDict
from ..version import Versio... |
9958622 | from typing import Dict
from mee6_py_api.config import API_BASE_URL, GUILD_ID
from mee6_py_api.constants import HTTP_STATUS_SUCCESS
from mee6_py_api.exceptions import HTTPRequestError, BadRequestError, UnauthorizedError, TooManyRequestsError
from pprint import pprint
import asyncio
import aiohttp
from mee6_py_api.plu... |
9958628 | from trakt.mapper.comment import CommentMapper
from trakt.mapper.list import ListMapper
from trakt.mapper.list_item import ListItemMapper
from trakt.mapper.search import SearchMapper
from trakt.mapper.summary import SummaryMapper
from trakt.mapper.sync import SyncMapper
__all__ = [
'CommentMapper',
... |
9958657 | import logging
from .Defaults import *
class Ssl(object):
def delete_ssl_certchain(self):
pass
def download_csr(self):
pass
def generate_csr(self):
pass
def show_cert(self):
pass
def upload_signed_cert(self):
pass
def upload_cert_chain(self):
pass
|
9958710 | from enum import Enum
import json
import logging
from typing import List, Optional, Union
from uuid import uuid4
import channels.layers
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from django.db import connections
from datetime import datetime
from pydantic.main impo... |
9958760 | import numpy as np
import sys
filename = sys.argv[1]
a = np.loadtxt(filename, delimiter=',')
#mean0 = np.mean(a, axis=1)
#maxidx = np.argsort(mean0)[3:]
#a = a[maxidx, :]
print('------ show mean(std) ----------')
mean = np.mean(a, axis=0)
std = np.std(a, axis=0)
print('{:0.2f}({:0.2f}) / {:0.2f}({:0.2f}) / {:0.2f... |
9958781 | import copy
THREE_TASKS_THREE_NEWS = [
{
u'task_id': 1,
u'task_name': u'notification.fake.task_1',
u'task_status': 'SUCCESS',
u'user': 'admin',
u'arguments': 'Database: fake_database_name_1, New Disk Offering: Micro',
u'updated_at': 1501177162,
u'is_new': 1,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.