id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9820246 | from __future__ import division, print_function, absolute_import
from mpl_toolkits.mplot3d import proj3d
from matplotlib.patches import FancyArrowPatch
class Annotate3D(object):
def __init__(self, fig, axes, data, labels):
self._fig = fig
self._ax = axes
self._data = data
self._la... |
9820258 | from time import time
import math as mh
import random as rd
rd.seed(20000)
t0=time()
S0=50.00;K=55.00;T=1.0
r=0.05;sigma=0.2;M=50
dt=T/M;Iter=300000
S=[]
for i in range(Iter):
path=[]
for t in range(M+1):
if t==0:
path.append(S0)
else:
z = rd.gauss(0.0,1.0)
... |
9820268 | from records_mover.db.quoting import quote_schema_and_table, quote_value
from typing import Optional
def vertica_import_sql(schema: str,
table: str,
db_engine,
gzip: bool,
delimiter: str,
trailing_nullco... |
9820314 | import logging
from contextlib import contextmanager
from ..handler import add_handler
logger = logging.getLogger(__name__)
logger = add_handler(logger)
@contextmanager
def _executor_dummy(processes=1):
yield None
@contextmanager
def _cluster_dummy(**kwargs):
yield None
@contextmanage... |
9820334 | import unittest
import numpy
import dpnp as cupy
from tests.third_party.cupy import testing
@testing.gpu
class TestFloating(unittest.TestCase):
@testing.for_all_dtypes(no_complex=True)
@testing.numpy_cupy_array_equal()
def test_signbit(self, xp, dtype):
a = testing.shaped_arange((2, 3), xp, dty... |
9820398 | from models.unet import UNet
from models.deeplabv3_plus import DeepLabV3Plus
from models.hrnet import HighResolutionNet
from models.pspnet import PSPNet
from models.fast_scnn import FastSCNN |
9820404 | import doctest
import json
from schema import Schema
from django.conf import settings
from corehq.motech.dhis2.schema import get_tracked_entity_schema
DATA_DIR = settings.BASE_DIR + '/corehq/motech/dhis2/tests/data/'
def test_tracked_entity_instance_1():
filename = DATA_DIR + 'tracked_entity_instance_1.json'
... |
9820432 | import sys
_verbose = False
def set_verbose(enabled):
global _verbose
_verbose = enabled
def print_message(message):
print(message)
def print_error_and_exit(error_string):
print('%s%s%s' % (BashColors.FAIL, error_string, BashColors.ENDC))
quit(1)
def print_error(error_string):
if _is_in... |
9820484 | class DataflowsException(Exception):
pass
class ProcessorError(DataflowsException):
def __init__(self, cause, *, processor_name, processor_object, processor_position):
self.cause = cause
self.processor_name = processor_name
self.processor_object = processor_object
self.process... |
9820500 | import time
import warnings
from abc import ABC, abstractmethod
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pkg_resources import resource_filename
|
9820529 | from django.contrib import admin
from .models import Show, ShowType, Genre, Status, Language, Country, Network, Setting
admin.site.register(Show)
admin.site.register(ShowType)
admin.site.register(Genre)
admin.site.register(Status)
admin.site.register(Language)
admin.site.register(Country)
admin.site.register(... |
9820586 | from ..models.user import User
users = [
User("<NAME>", "<EMAIL>"),
User("<NAME>", "<EMAIL>"),
]
|
9820650 | from svgpathtools import Path, Line
from svgutils import stack_paths, scan_lines
def test_stack_paths():
all_paths = [Path(*[Line(start=0, end=100), Line(start=100, end=100 + 100j),
Line(start=100 + 100j, end=100j), Line(start=100j, end=0)])]
attributes = [{"fill": "black"}]
all_p... |
9820657 | import numpy as np
def test_exercise_2_I(read_cities):
cities_locations_data = read_cities('cities_locations_large.csv')
assert len(cities_locations_data) == 15
assert 'Barcelona' in cities_locations_data
barcelona = cities_locations_data['Barcelona']
assert barcelona['idx'] == 10
assert bar... |
9820668 | import sys
sys.path.append('.')
sys.path.append('..')
from McDaily.coupon import McDailyCoupon
json = {
"rc" : 1 ,
"results" :{
"coupon" :{
"coupon_id" : 2147483647 ,
"object_info" :{
"content" : "今日已領過,明日驚喜等著你!" ,
"image" :{
... |
9820689 | def inorder(head, arr):
if head:
inorder(head.left, arr)
arr.append(head, arr)
inorder(head.right, arr)
return arr
def 2SumBST(head1, head2, summ):
arr1 = []
arr2 = []
arr1 = inorder(head1, arr1)
arr2 = inorder(head2, arr2)
i, j = 0, len(arr2)-1
while i < len(arr1) and j >= 0:
add = arr1[i] + arr2[... |
9820713 | import pytest
import numpy as np
from tests.testing_utils import DummyPhysicalSystem, DummyReferenceGenerator, DummyRewardFunction, DummyVisualization,\
DummyCallback, DummyConstraintMonitor, DummyConstraint, mock_instantiate, instantiate_dict
from gym.spaces import Tuple, Box
import gym_electric_motor
from gym_ele... |
9820718 | import numpy as np
import matplotlib.pyplot as plt
import pybullet
pybullet.connect(pybullet.GUI)
pybullet.loadURDF("r2d2.urdf")
camTargetPos = [0,0,0]
cameraUp = [0,0,1]
cameraPos = [1,1,1]
yaw = 40
pitch = 10.0
roll=0
upAxisIndex = 2
camDistance = 4
pixelWidth = 320
pixelHeight = 240
nearPlane = 0.01
farPlane = 10... |
9820730 | from django import forms
from django.contrib.contenttypes.models import ContentType
from django.template.defaultfilters import slugify
from basic.blog.models import Post
from basic.media.models import Photo
class BaseRelationshipsForm(forms.ModelForm):
relationships = forms.CharField(required=False)
hidden_r... |
9820736 | from django import forms
from django.core.exceptions import ValidationError
from django.utils.http import urlquote
from django.utils import timezone
from haystack.forms import ModelSearchForm
from floppyforms import widgets
import contacts as contact_constants
from contacts.models import (
BookOwner,
Contact,
... |
9820756 | import sys
def shift(c, k):
if(c+k < ord('A')):
return ord('Z')+1-(ord('A')-(c+k))
if(c+k > ord('Z')):
return ord('A')-1+((c+k)-ord('Z'))
return c+k
c = raw_input()
k = raw_input()
for i in range(len(k)):
sys.stdout.write(chr(shift(ord(c[i]), -(ord('A')-ord(k[i])) if i % 2 == 1 else or... |
9820833 | import logging
import sys
from uuid import UUID
import falcon
from falcon_cors import CORS
from spectree import Response, SpecTree
from analytics import settings
from analytics.docs.schemas.requests import (
DetailEventSchema,
ResultClickEventSchema,
SearchEventSchema,
SearchRatingEventSchema,
)
from ... |
9820869 | from SEAL.SplineFunction import SplineFunction
from SEAL.lib import create_interpolation_knots, create_cubic_hermite_coefficients, approximate_derivatives
def linear_spline_interpolation(parameter_values, data_values):
"""
Computes the linear spline interpolation to the given
m data points (x_i, y_i).
... |
9820908 | import cv2
detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
print("[INFO] starting video stream...")
capture = cv2.VideoCapture(0)
total = 0
while True:
ret, frame = capture.read()
faces = detector.detectMultiScale(frame,scaleFactor=1.3,minNeighbors=5)
for (x,y,w,h) in faces:
... |
9820909 | from abstract_subsystem_2 import AbstractSubsystem2
class ConcreteSubsystem2(AbstractSubsystem2):
"""Concrete implementation of AbstractSubsystem2"""
def __init__(self):
pass
def compute_age(self, abstract_subsystem_1, current_year):
return current_year - abstract_subsyst... |
9820989 | from .rman_translator import RmanTranslator
from .rman_lightfilter_translator import RmanLightFilterTranslator
from ..rman_sg_nodes.rman_sg_light import RmanSgLight
from ..rman_utils import string_utils
from ..rman_utils import property_utils
from ..rman_utils import transform_utils
from ..rman_utils import object_util... |
9821004 | from modeltranslation.translator import translator, TranslationOptions
from .models import NotificationTemplate
class NotificationTemplateTranslationOptions(TranslationOptions):
fields = ('subject', 'body', 'html_body')
translator.register(NotificationTemplate, NotificationTemplateTranslationOptions)
|
9821034 | import random
from math import log, sqrt
class Node:
def __init__(self, state):
self.state = state
self.win_value = 0
self.policy_value = None
self.visits = 0
self.parent = None
self.children = []
self.expanded = False
self.player_number = None
self.discovery_factor = 0.35
def update_win_value(se... |
9821036 | from __future__ import division, print_function
import unittest
import discretize
import properties
from SimPEG import maps
from SimPEG.electromagnetics import time_domain as tdem
from SimPEG.electromagnetics import utils
import numpy as np
import warnings
from pymatsolver import Pardiso as Solver
TOL = 1e-4
FLR = 1... |
9821066 | import numpy as np
import pandas as pd
import time
from collections import OrderedDict
import argparse
import os
import re
import pickle
import subprocess
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
... |
9821134 | import os
from setuptools import setup, find_packages
def package_files(directory):
paths = []
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
paths.append(os.path.join('..', path, filename))
return paths
with open('README.md', encoding='utf8') as... |
9821184 | import threading
import time
import os
from screepsapi import API as ScreepsAPI
from flask import Flask, render_template, json
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(e):
"""404 Page Not Found"""
return 'Sorry, nothing to see here.', 404
@app.errorhandler(500)
def application_error(e)... |
9821234 | import os
import sys
import argparse
import importlib
import numpy as np
from time import time
import tensorflow as tf
from datetime import datetime
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, 'utils'))
sys.path.append(os.path.join(BASE_DIR, 's... |
9821251 | from typing import Optional
from sortedcontainers import SortedDict
from ....errors import SimRegionMapError
from ....state_plugins import SimStatePlugin
class AddressWrapper:
"""
AddressWrapper is used in SimAbstractMemory, which provides extra meta information for an address (or a ValueSet
object) that ... |
9821350 | import opacus
from sklearn.metrics import accuracy_score, roc_auc_score
from .__head__ import *
class discriminator(nn.Module):
def __init__(self, input_size):
super(discriminator, self).__init__()
self.input_size = input_size
self.hidden = 64
self.lstm = opacus.layers.DPLSTM(sel... |
9821359 | from hsi_toolkit.util import pca
import numpy as np
def ssrx_anomaly(hsi_img, n_dim_ss, guard_win, bg_win):
"""
function ssrx_img = ssrx_anomaly(hsi_img,n_dim_ss,guard_win,bg_win)
Subspace Reed-Xiaoli anomaly detector
eliminate leading subspace as background, then
use local mean and covariance to determine pix... |
9821389 | import setka
import torch
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
import tiny_model
import test_dataset
import matplotlib.pyplot as plt
from test_metrics import dict_loss, list_loss, tensor_loss
from test_metrics import dict_acc, list_acc, tensor_acc
de... |
9821427 | class AsyncDagpiException(Exception):
"""
AsyncDagpi base exception class use this base class to catch any AsyncDagpi errors.
"""
pass
class AsyncDagpiHttpException(AsyncDagpiException):
"""
AsyncDagpi base exception class use this base class to catch any AsyncDagpi errors.
"""
... |
9821473 | import numpy as np
from PIL import Image
from anonymizer.utils import Box
from anonymizer.anonymization import Anonymizer
def load_np_image(image_path):
image = Image.open(image_path).convert('RGB')
np_image = np.array(image)
return np_image
class MockObfuscator:
def obfuscate(self, image, boxes):
... |
9821484 | import pandas as pd
import glob
import cv2
train_inp_images = glob.glob('/media/newton/newton/nitre/dataset/train/HAZY/*.png')
train_out_images = glob.glob('/media/newton/newton/nitre/dataset/train/GT/*.png')
val_inp_images = glob.glob('/media/newton/newton/nitre/dataset/val/HAZY/*.png')
val_out_images = glob.glob('... |
9821513 | import urllib.parse
from django import http
from django.conf import settings
from django.contrib.redirects.middleware import RedirectFallbackMiddleware
from django.contrib.redirects.models import Redirect
from django.contrib.sites.shortcuts import get_current_site
from django.middleware.gzip import GZipMiddleware
from... |
9821538 | import cStringIO as StringIO
import urlparse
def html_esc(s):
return s.replace('&','&').replace('<','<').replace('>','>')
def handle_request(req):
url = urlparse.urlparse(req.path)
headers = []
body = ""
try:
query = urlparse.parse_qsl(url.query, strict_parsing=True)
sta... |
9821563 | import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import random
from scipy import stats
from sklearn.metrics import mutual_info_score
np.set_printoptions(precision=4)
class Mimic(object):
"""
Usage: from mimicry import Mimic
:param domain: list of tuples containing the min and max... |
9821648 | import requests
from dbt_cloud.command.command import DbtCloudCommand
class DbtCloudAccountListCommand(DbtCloudCommand):
"""Retrieves all available accounts."""
@property
def api_url(self) -> str:
return f"{super().api_url}/accounts/"
def execute(self) -> requests.Response:
response ... |
9821655 | import hashlib
tx = "9ec4bc49e828d924af1d1029cacf709431abbde46d59554b62bc270e3b29c4b1"
p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
#r = 0xd47ce4c025c35ec440bc81d99834a624875161a26bf56ef7fdc0f5d52f843ad1
#s1 = 0x44e1ff2dfd8102cf7a47c21d5c9fd5701610d04953c6836596b4fe9dd2f53e3e
#s2 = 0x9a5f1c... |
9821712 | import random
import torch
from julius.filters import highpass_filter, lowpass_filter
class FrequencyFilter(torch.nn.Module):
def __init__(
self,
sample_rate: int,
freq_low: float,
freq_high: float,
):
super().__init__()
self.sample_rate = sample_rate
se... |
9821714 | from guillotina import schema
from guillotina.contrib.image.preview import CloudPreviewImageFileField
from guillotina.interfaces import IFile
from zope.interface import Interface
class IImageFile(IFile):
"""Image file"""
previews = schema.Dict(
title="Generated previews", key_type=schema.TextLine(), ... |
9821723 | import torch
import torch.nn as nn
import torch.nn.functional as F
import os.path as osp
from corenet import StereoUnaryUnetDyn, PadUnpad, PaddedConv2d, ResidualBlock
class SubNetwork(nn.Module):
def __init__(self, args, device):
super(SubNetwork, self).__init__()
self.net = None
self.pad... |
9821775 | import pandas as pd
from sklearn.externals import joblib
from coffeeandnoodles.core.util import get_md5_from_string
from trustworthiness.config import DeFactoConfig
from trustworthiness.definitions import OUTPUT_FOLDER
from trustworthiness.feature_extractor import FeaturesCore
config = DeFactoConfig()
if __name__ == ... |
9821805 | from . import config, datasets
from ._version import get_versions
from .base import annotate, compute, is_dask_collection, optimize, persist, visualize
from .core import istask
from .delayed import delayed
from .local import get_sync as get
versions = get_versions()
__version__ = versions["version"]
__git_revision__ =... |
9821841 | import unittest
import trace_visualizer
import os.path
class Test_wireshark(unittest.TestCase):
def test_http2_from_wireshark_wiki(self):
file_name = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Sample of HTTP2.pcap')
pdml_file = trace_visualizer.call_wireshark('3.1.0', file_name, '30... |
9821849 | def sorted(s):
stack1=[]
stack2=[]
while(s):
p=s.pop()
if len(stack1)==0:
stack1.append(p)
else:
while(len(stack1)>0 and stack1[-1]<=p):
stack2.append(stack1.pop())
stack1.append(p)
while(stack2):
stack1.... |
9821850 | import sys
from antlr4 import *
from antlr4.tree.Trees import Trees
from ResponseLexer import ResponseLexer
from ResponseParser import ResponseParser
from GenerateResponse import CustomResponse
def main(argv):
input_stream = FileStream(argv[1])
lexer = ResponseLexer(input_stream)
stream = CommonTokenStream... |
9821879 | import json
from geopy import Point
from geopy.distance import vincenty
from src.base.globalmaptiles import GlobalMercator
class Node(Point):
def __init__(self, lat=0.0, lon=0.0, osm_id=0):
super(Node, self).__new__(Point, latitude=lat, longitude=lon)
self.osm_id = osm_id
def __str__(self):
... |
9821914 | import numpy as np
import pandas as pd
import tensorflow as tf
import os
import sys
from termcolor import colored
from tensorflow.contrib.layers import fully_connected as FC_Net
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
import import_data as impt
import utils_ne... |
9821993 | from .repos import HttpServerRepo
from .responses import HttpServerResponse, HttpServersResponse
from .data import HttpServerData
from .forms import HttpServerCreateForm
|
9822011 | import os
from pathlib import Path
import pytest
from pytest_mock import MockerFixture
from inboard import start
class TestRunPreStartScript:
"""Run pre-start scripts using the method in `start.py`.
---
"""
def test_run_pre_start_script_py(
self,
mocker: MockerFixture,
monke... |
9822040 | import numpy as np
def print_cmp(inp, name=None):
print('{}: shape-{}, sum: {}, mean: {}, max: {}, min: {}'.format(name, inp.shape,
np.sum(inp), np.mean(inp),
np.max(inp), np.mi... |
9822066 | import os
import numpy as np
from rdkit import Chem, RDConfig
TYPES = np.array(['1JHC', '2JHH', '1JHN', '2JHN', '2JHC', '3JHH',
'3JHC', '3JHN'])
TYPES_MAP = {t: i for i, t in enumerate(TYPES)}
SYMBOLS = ['H', 'C', 'N', 'O', 'F']
DEGREES = [1, 2, 3, 4, 5]
HYBRIDI... |
9822075 | import os
import redis
from rq import Worker, Queue, Connection
try:
import config
redis_url = config.redis_url
print('using local config file')
except:
print('using environment variable')
redis_url = os.getenv('REDIS_URL')
listen = ['high', 'default', 'low']
conn = redis.from_url(redis_url)
i... |
9822108 | import asyncio
async def a():
print('Suspending a')
await asyncio.sleep(0)
print('Resuming a')
async def b():
print('In b')
async def main():
await asyncio.gather(a(), b())
if __name__ == '__main__':
asyncio.run(main())
|
9822122 | from __future__ import division
from unittest import TestCase
from dexpy.alias import alias_list
import dexpy.design as design
import pandas as pd
import numpy as np
class TestAliases(TestCase):
def test_two_factors(self):
"""Tests the alias list for two identical factors."""
factor_data = [
... |
9822153 | import os
import unittest
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
if __name__ == '__main__':
loader = unittest.TestLoader()
suite = loader.discover(TEST_DIR)
runner = unittest.TextTestRunner()
runner.run(suite)
|
9822200 | from kivy.app import App
class {{cookiecutter.repo_name|capitalize}}App(App):
"""Basic kivy app
Edit {{cookiecutter.repo_name}}.kv to get started.
"""
def build(self):
return self.root
|
9822223 | from ETTS.tester import ETTSInferenceModel
import argparse
import shutil
import os
import json
import numpy as np
import random
import librosa
from tqdm import tqdm
import torch
parser = argparse.ArgumentParser()
parser.add_argument('--maxlength', type=int, default=1000)
parser.add_argument('--nmels', type=int, defaul... |
9822277 | import torch
import numpy as np
from config import config
from agentEncoder import AgentEncoder
from targetEncoder import TargetEncoder
from decoder import Decoder
class Env():
def __init__(self, cfg, seed=None):
self.agent_amount = cfg.agent_amount
self.target_size = cfg.target_size
self.... |
9822291 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.m... |
9822320 | from dataclasses import dataclass, field
from typing import List
from coqpit import Coqpit
@dataclass
class Person(Coqpit):
name: str = None
age: int = None
@dataclass
class Reference(Coqpit):
name: str = "Coqpit"
size: int = 3
people: List[Person] = field(
default_factory=lambda: [
... |
9822354 | import asyncio
from pytest import fixture
from starlette.testclient import TestClient
from tmeister import core
@fixture(scope='session')
def app():
app = core.init()
loop = asyncio.get_event_loop()
loop.run_until_complete(core.pg_init())
return app
@fixture(scope='module')
def client(app):
re... |
9822385 | import sys
from os.path import join, dirname, abspath
from qtpy import uic
from qtpy.QtCore import Qt, QTimer, Slot
from qtpy.QtGui import (QStandardItemModel, QStandardItem, QImage, QPixmap,
QPalette)
from qtpy.QtWidgets import QApplication, QMainWindow
import qtawesome as qta
import qtmodern... |
9822426 | import os
# Fill the paths
DEFAULT_DATASET_DIR = "" # where the datasets folders are
DEFAULT_CKPT_DIR = "" # where the training checkpoints and logs will be saved
DEFAULT_MODEL_DIR = "" # where the pretrained models are
SSD_DIR = "" # where the HowTo100M S3D features are
HOWTO_FEATURES_PATH = os.path.join(... |
9822442 | import numpy as np
import dgramCreate as dc
import os, subprocess
try:
os.remove('data.xtc2')
except:
pass
FILE_NAME = 'data.xtc2'
NUM_ELEM = 1
def generate_event(num_elem, zero):
# data = np.array([0])*num_elem
data = [np.full((1,1), zero)]*num_elem
# data = [np.random.random((2,3,3)) for x in r... |
9822497 | import pytest
from pyramid import httpexceptions
from lms.extensions.feature_flags.views.cookie_form import CookieFormViews
class TestFeatureFlagsCookieFormViews:
def test_get_passes_the_feature_flags_to_the_template(
self, pyramid_request, FeatureFlagsCookieHelper, cookie_helper
):
views = C... |
9822526 | import numpy as np
class Record(object):
__attributes__ = []
def __eq__(self, other):
return (
type(self) == type(other)
and all(
(getattr(self, _) == getattr(other, _))
for _ in self.__attributes__
)
)
def __ne__(self, ... |
9822537 | from tir import Webapp
import unittest
class GTPA425(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup("SIGAGTP","10092020","T1","M SP 04","88")
inst.oHelper.Program("GTPA425")
inst.oHelper.AddParameter("MV_PAPONTA", "M SP 04", "20200811/20200910", "20200811/... |
9822543 | import pytest
from ..model_base_test import ModelBaseTest
from tests.sampleresponse.direct_debit import payment_response
from xendit.models import DirectDebit
# fmt: off
class TestCreatePayment(ModelBaseTest):
@pytest.fixture
def default_direct_debit_payment_data(self):
tested_class = DirectDebit
... |
9822573 | from uuid import (
UUID,
)
from minos.aggregate import (
Aggregate,
EntitySet,
RootEntity,
)
class Stocks(RootEntity):
"""Stocks RootEntity class."""
ticker: str
updated: str
class StocksAggregate(Aggregate[Stocks]):
"""StocksAggregate class."""
@staticmethod
async def add... |
9822582 | from __future__ import print_function
__copyright__ = """
Copyright 2019 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
... |
9822600 | import tensorflow as tf # deep learning library. Tensors are just multi-dimensional arrays
mnist = tf.keras.datasets.mnist # mnist is a dataset of 28x28 images of handwritten digits and their labels
(x_train, y_train),(x_test, y_test) = mnist.load_data() # unpacks images to x_train/x_test and labels to y_train/y_te... |
9822659 | import sys
import os,pdb,time
#######################################################################################
## relative to config
config_file='standard.yaml'
#cluster=True
#cluster=False
#######################################################################################
ckpt_dir = '../ckpt'
main_dirs = ... |
9822687 | import pytest
from py21cmfast.inputs import DATA_PATH
@pytest.fixture(scope="module")
def datafiles():
return list(DATA_PATH.glob("*.dat"))
def test_exists(datafiles):
for fl in datafiles:
assert fl.exists()
assert (DATA_PATH / "x_int_tables").exists()
assert (DATA_PATH / "x_int_tables").i... |
9822719 | result = x[:, fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b, ::2]
da.to_hdf5(os.path.join('data', 'myfile.hdf5'), '/output', result) |
9822742 | class Perro:
nombre = ""
raza = ""
def __init__(self, n, r):
self.nombre = n
self.raza = r
def comer(self):
print("El perro esta comiendo.")
def dormir(self):
print("Zzzz....") |
9822768 | import unittest
from functools import wraps
from time import perf_counter
import platform
import numpy as np
from Orange.data import Table
# override method prefix for niceness
BENCH_METHOD_PREFIX = "bench"
unittest.TestLoader.testMethodPrefix = BENCH_METHOD_PREFIX
def _timeitlike_time_format(time_seconds, precisi... |
9822799 | from tinypy.runtime.testing import UnitTest
class Create:
def __init__(self, **args):
self.__dict__.update(args)
def create_with_a(a):
return Create(a=a)
create_with_a = staticmethod(create_with_a)
def create_with_b(b):
return Create(b=b)
create_with_b = staticmethod(creat... |
9822851 | import unittest
from unittest import TestCase
import numpy as np
class TestMetamodelClassification(TestCase):
def _generate_mock_data(self, n_samples, n_classes, n_features):
from sklearn.datasets import make_classification
return make_classification(n_samples=n_samples, n_features=n_features, n_... |
9822853 | import numpy as np
from .unit import Unit
class CharacterIndex(Unit):
"""
CharacterIndexUnit for DIIN model.
The input of :class:'CharacterIndexUnit' should be a list of word
character list extracted from a text. The output is the character
index representation of this text.
:class:`NgramLe... |
9822867 | from domain import domain
from ..TagData import TagData
class domain_hm(domain):
CONTACT_TYPES = (
'admin',
'tech',
)
def render_info(self, request, data):
command = self.render_command_with_fields(request, 'info', [
TagData('name', data.get('name'), {})
])
... |
9822883 | from __future__ import print_function
import stateutils
import viewerstate.utils as su
import math
from datetime import datetime
import json
from hutil.Qt import QtGui
from hutil.Qt.QtCore import Qt
from lightpanel.widgets import PointingLabel
hou = hou
class UndoClass():
def __init__(self):
print('init undo')
... |
9822895 | import gzip
import json
import requests
import string
import xml.etree.ElementTree as etree
# Converts the KANJIDIC dictionary in xml.gz format into JSON discarding unneeded data
# The data is downloaded by the script from the official KANJIDIC project website
# Outputs kanjidic.json with stroke, grade, freq, jlpt, me... |
9822916 | import sublime, sublime_plugin
import os, shlex, json, collections, traceback
from ....libs.global_vars import *
from ....libs import util
from ....libs import JavascriptEnhancementsExecuteOnTerminalCommand
from ....libs import Terminal
from ....libs import Hook
from ....libs import NPM
def express_ask_custom_path(pro... |
9822929 | import argparse
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise argparse.ArgumentTypeError("Boolean value expected.")
... |
9822955 | def lps(s):
result = ''
for c in range(len(s)):
palindrome = s[c]
r_offset = 0
if c < len(s) - 1 and s[c] == s[c+1]:
palindrome += s[c+1]
r_offset = 1
for offset in range(1, min(c, len(s) - 1 - r_offset - c) + 1):
if s[c-offset] == s[c+offset+r... |
9822990 | from io import StringIO
from contexts.plugins.reporting import cli
from contexts import action
from .. import tools
class VerboseReporterSharedContext:
def context(self):
self.stringio = StringIO()
self.reporter = cli.VerboseReporter(self.stringio)
self.outputs = []
class WhenPrintingVer... |
9823005 | import io
import numpy as np
import pytest
from imageio import imsave
from ebonite.ext.imageio.helpers import bytes_image_input, bytes_image_output
@pytest.fixture
def numpy_image():
return np.zeros((5, 5, 3))
@pytest.fixture
def bytes_image(numpy_image):
buffer = io.BytesIO()
imsave(buffer, numpy_ima... |
9823036 | import brainfuck_interpreter as brainfuck
import random
import copy
import numpy as np
from statistics import mean
import sys
import time
import matplotlib.pyplot as plt
ASCII_CHARS_COUNT = 256
AVAILABLE_OPS = [">", # Increment the pointer.
"<", # Decrement the pointer.
"+", # Increment the byte at the poi... |
9823061 | import typing as t
import attr
import pytest
import middle
def test_mixed_schema():
class TestModel(middle.Model):
__looks_reserved__ = {"type": str}
name = {"type": str}
surname = middle.field(type=str)
age = {"type": int}
hobby = middle.field(type=t.List[str])
inst... |
9823074 | import sublime, sublime_plugin
from os import path
gte_st3 = int(sublime.version()) >= 3000
if gte_st3:
from .config import *
else:
from config import *
class HiveInlinePathRemovalBaseCommand(sublime_plugin.TextCommand):
def run(self, edit, event=None):
conf = sublime.load_settings(CONFIG_BASE_NA... |
9823096 | import FWCore.ParameterSet.Config as cms
# Use this object to make changes when different configurations are active
ecalDetIdAssociator = cms.ESProducer("DetIdAssociatorESProducer",
ComponentName = cms.string('EcalDetIdAssociator'),
etaBinSize = cms.double(0.02),
nEta = cms.int32(300),
nPhi = cms.int3... |
9823107 | import argparse
from tfutils.utils import frozendict, format_devices
import os
import logging
import tensorflow as tf
import copy
import numpy as np
from tfutils.optimizer import ClipOptimizer, MinibatchOptimizer
import tfutils.utils as utils
from tfutils.utils import aggregate_outputs
import pdb
import inspect
from si... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.