id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
455663 | from math import sin, cos
import pytest
import numpy as np
from .._esn_online import ESNOnline
from reservoirpy.datasets import lorenz
@pytest.fixture(scope="session")
def matrices():
Win = np.array([[1, -1],
[-1, 1],
[1, -1],
[-1, -1]])
W = np.arr... |
455687 | from skimage.transform import resize
heatmap_1_r = resize(heatmap_1, (50,80), mode='reflect',
preserve_range=True, anti_aliasing=True)
heatmap_2_r = resize(heatmap_2, (50,80), mode='reflect',
preserve_range=True, anti_aliasing=True)
heatmap_3_r = resize(heatmap_3, (50,80), mod... |
455698 | import logging
import boto3
from botocore.exceptions import ClientError
def download_file(dest_bucket_name, dest_file_key):
"""Fetch an file to an Amazon S3 bucket
The src_data argument must be of type bytes or a string that references
a file specification.
:param dest_bucket_name: string... |
455699 | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../"))
import tensorflow as tf
import magenta.models.melody_rnn.melody_rnn_create_dataset as md
import scripts.target as tgt
def main(unused_argv):
tf.logging.set_verbosity(md.FLAGS.log)
config = md.melody_rnn_config_flags.confi... |
455711 | from rest_framework.authentication import SessionAuthentication
class CsrfExemptSessionAuthentication(SessionAuthentication):
def enforce_csrf(self, request):
return
|
455725 | import json
import os
import pickle
import ulmo
import param
import pandas as pd
import geopandas as gpd
from shapely.geometry import box, Point
from quest import util
reserved_catalog_entry_fields = [
'name',
'service',
'service_id',
'publisher_id',
'display_name',
'description',
'reser... |
455756 | import game_config
from game_config import Position
import copy
class Snake(object):
def __init__(self) -> None:
self.window_size = Position(game_config.game_sizes["width"], game_config.game_sizes["height"])
self.direction = game_config.D_Down
self.body = []
self.last_body = []
... |
455773 | from io import BytesIO
from typing import List
from lor_deckcodes.utils import next_varint, decode_base32
from lor_deckcodes.constants import faction_mapping, CURRENT_FORMAT_VERSION, SUPPORTED_VERSIONS
def _decode_card_block(n: int, data_stream: BytesIO) -> List[str]:
card_block_list = []
n_card_copies = ne... |
455804 | import os, subprocess, sys, getopt
from subprocess import run
def find_cppcheck():
drive_letters = ['C', 'D']
for drive_letter in drive_letters:
cppcheck_path = drive_letter + r":\Program Files\Cppcheck\cppcheck.exe"
if os.path.isfile(cppcheck_path):
return cppcheck_path
print('Failed to find cp... |
455835 | r"""Assorted function for use when computing metrics and evals."""
import collections
import os
import numpy as np
import scipy
from scipy import signal
from scipy.ndimage.filters import convolve
import tensorflow.compat.v1 as tf
def _FSpecialGauss(size, sigma):
"""Function to mimic the 'fspecial' gaussian MATLAB ... |
455875 | from sys import platform
import sys
try:
import caffe
except ImportError:
print("This sample can only be run if Python Caffe if available on your system")
print("Currently OpenPose does not compile Python Caffe. This may be supported in the future")
sys.exit(-1)
import os
os.environ["GLOG_minloglev... |
455907 | from InstruccionesPL.TablaSimbolosPL.InstruccionPL import InstruccionPL
from InstruccionesPL.IndicesPL import IndicePL1, IndicePL7, IndicePL8, IndicePL9, IndicePLUnique, IndicePLUsing, IndicePLUsingNull
from InstruccionesPL.Expresiones import PrimitivoPL
class AlterIndice(InstruccionPL):
def __init__(self, nombre... |
455913 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as D
from base import BaseModel
EPSILON = 1e-30
class GraphVAE(BaseModel):
def __init__(self, input_dim, n_nodes, node_dim):
super(GraphVAE, self).__init__()
# store parameters
self.input_dim = in... |
456017 | from dse.cqlengine import columns
from dse.cqlengine.models import Model
from dse.cqlengine.query import LWTException
from datetime import datetime
import hashlib
import validate_email
from .user_management_events_kafka import UserManagementPublisher
class UserModel(Model):
"""Model class that maps to the user tab... |
456032 | import numpy as np
from keras import backend as K
import os
import sys
def patch_path(path):
return os.path.join(os.path.dirname(__file__), path)
def main():
K.set_image_dim_ordering('tf')
sys.path.append(patch_path('..'))
from keras_video_classifier.library.recurrent_networks import VGG16Bidirecti... |
456047 | from concurrent.futures import ThreadPoolExecutor
from pprint import pprint
from datetime import datetime
import time
from itertools import repeat
import logging
import yaml
from netmiko import ConnectHandler, NetMikoAuthenticationException
logging.getLogger("paramiko").setLevel(logging.WARNING)
logging.basicConfig... |
456065 | from __future__ import print_function, absolute_import
from collections import OrderedDict
import numpy as np
import tables
from six import iteritems
from ._result import H5NastranResult
from ._bdf import H5NastranBDF
class H5Nastran(H5NastranBDF, H5NastranResult):
def __init__(self, h5filename, mode='r', nast... |
456073 | effects = {
# instruction name -> [bytes, newva, contraints, effects]
'rdtsc': ('0f31', None, (),
('edx = TSC_HIGH',
'eax = TSC_LOW')),
'div16': ('66f7f2', None, (),
('eax = (((((edx & 0x0000ffff) << 16) | (eax & 0x0000ffff)) / (edx & 0x0000ffff)) | (eax & 0xffff00... |
456075 | import os
import unittest
from os.path import expanduser
from util.Docker import Docker
class GoServices(unittest.TestCase):
def test_go(self):
script_dir = os.path.dirname(os.path.realpath(__file__))
code_dir = script_dir + "/.."
home = expanduser("~")
goPath = os.environ['GOPATH... |
456088 | import numpy as np
from axelerate.networks.yolo.backend.utils.box import BoundBox
from axelerate.networks.yolo.backend.utils.box import BoundBox, nms_boxes, boxes_to_array
class YoloDecoder(object):
def __init__(self,
anchors = [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.... |
456159 | import functools
import torch
class TensorList(list):
"""Container mainly used for lists of torch tensors. Extends lists with pytorch functionality."""
def __init__(self, list_of_tensors = None):
if list_of_tensors is None:
list_of_tensors = list()
super(TensorList, self).__init__... |
456181 | import pytest
from ddtrace.internal.sma import SimpleMovingAverage
from ddtrace.internal.writer import DEFAULT_SMA_WINDOW
def test_min_size():
sma = SimpleMovingAverage(DEFAULT_SMA_WINDOW)
assert DEFAULT_SMA_WINDOW == sma.size
assert DEFAULT_SMA_WINDOW == len(sma.counts)
assert DEFAULT_SMA_WINDOW ==... |
456184 | import sys
import unittest
from linkml_runtime.dumpers import rdf_dumper, json_dumper
from linkml_runtime.loaders import yaml_loader
from pyshex.evaluate import evaluate
from linkml.generators.jsonldcontextgen import ContextGenerator
from linkml.generators.shexgen import ShExGenerator
from tests.test_generators.envir... |
456187 | from __future__ import print_function, unicode_literals
import platform
import sys
info = {
'impl': platform.python_implementation(),
'version': platform.python_version(),
'revision': platform.python_revision(),
'maxunicode': sys.maxunicode,
'maxsize': sys.maxsize
}
search_modules = ['charade', ... |
456194 | class ImageBackgroundSettings(BackgroundSettings,IDisposable):
""" Represents the rendering image background settings. """
def Dispose(self):
""" Dispose(self: BackgroundSettings,A_0: bool) """
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: BackgroundSettings,disposin... |
456195 | import json
import spacy
from collections import defaultdict
nlp = spacy.load('en_core_web_sm')
def load_json(filename):
"Wrapper function to load JSON data."
with open(filename) as f:
data = json.load(f)
return data
def save_json(data, filename):
"Wrapper function to save the data as JSON.... |
456204 | import argparse
import json
import pytest
from typing import Dict, List, Tuple, Union
NestedDict = Union[Dict[str, float], "NestedDict"]
def flatten_nested_dict(nested_dict: NestedDict) -> Dict[Tuple[str, ...], float]:
def _recursively_flatten(
target: Dict[Tuple[str, ...], float], d: NestedDict, prefix:... |
456216 | import argparse
import torch
from utils.cli import boolean_argument
def get_args(rest_args):
parser = argparse.ArgumentParser()
parser.add_argument("--env-name", default="PointRobotSparse-v0")
parser.add_argument("--seed", type=int, default=73)
parser.add_argument("--max-rollouts-per-task", default=2)... |
456218 | from builtins import str
from django.contrib import messages
from django.urls import reverse
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from pykeg.web.decorators import staff_member_required
from pykeg.util import kbjson
from . i... |
456243 | import sys
from ._C import mecab_cost_train, mecab_dict_gen, mecab_dict_index, mecab_main, mecab_system_eval, mecab_test_gen
def run_mecab_main(argv=sys.argv):
mecab_main(argv)
def run_mecab_dict_index(argv=sys.argv):
mecab_dict_index(argv)
def run_mecab_dict_gen(argv=sys.argv):
mecab_dict_gen(argv)
... |
456351 | from PyFlow.UI.Canvas.UINodeBase import UINodeBase
from PyFlow.Packages.PyFlowOpenCv.UI.UIOpenCvBaseNode import UIOpenCvBaseNode
from PyFlow.Packages.PyFlowOpenCv.UI.UICv_TransformNode import UICv_TransformNode
def createUINode(raw_instance):
if raw_instance.__class__.__name__ == "cv_Transform":
return UICv_Transf... |
456357 | from datetime import date
from decimal import Decimal
from django.db.models.fields.files import ImageFieldFile, FileField
class BaseSerializer(object):
def serialize(self, value):
return value
class DateSerializer(BaseSerializer):
def serialize(self, value):
return str(value)
class Decimal... |
456370 | import multiprocessing
import os
import pickle
import tempfile
import time
import unittest
import uuid
from hypothesis import given
from hypothesis.strategies import text
try:
import pymongo
except ImportError:
pymongo = None
from chocolate import SQLiteConnection, MongoDBConnection, DataFrameConnection, Spa... |
456373 | class CandidateDescriptor(object):
"""
Descriptor that defines an candidate the solver wants to be checked.
It is used to lable/identify the candidates and their results in the case of batch processing.
"""
def __init__(self, **definingValues):
"""
@param definingValues Class assume... |
456470 | from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
def sysMsg(channel_name, msg_type, not_level, content={}):
"""
Notify system message to channel
"""
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
channel_name,
{
... |
456489 | from numba import njit, boolean, int64, float64
from numba.experimental import jitclass
import numpy as np
from .utils import isin
@jitclass([
('value', float64[:]),
('sign', float64[:]),
('size', int64)
])
class signed:
def __init__(self, value, sign=None):
""" If sign is None, init from val... |
456496 | from creme import stream
from . import base
class ChickWeights(base.FileDataset):
"""Chick weights along time.
The stream contains 578 items and 3 features. The goal is to predict the weight of each chick
along time, according to the diet the chick is on. The data is ordered by time and then by
chic... |
456551 | from zope.interface import implements
from twisted.plugin import IPlugin
from twisted.application.service import IServiceMaker
from twisted.application import internet
from oauth_proxy import oauth_proxy
class OAuthProxyServiceMaker(object):
implements(IServiceMaker, IPlugin)
tapname = "oauth_proxy"
desc... |
456617 | import tensorflow as tf
import copy
from icecaps.estimators.estimator_chain import EstimatorChain
from icecaps.estimators.seq2seq_encoder_estimator import Seq2SeqEncoderEstimator
from icecaps.estimators.seq2seq_decoder_estimator import Seq2SeqDecoderEstimator
class Seq2SeqEstimator(EstimatorChain):
def __init__... |
456661 | import ConfigParser
import string
_ConfigDefault = {
"database.dbms": "mysql",
"database.name": "",
"database.user": "root",
"database.password": "",
"database.host": "127.0.0.1"
}
def LoadConfig(file, config={}):
"""
returns a diction... |
456683 | from paddleflow.pipeline import Pipeline
from paddleflow.pipeline import ContainerStep
from paddleflow.pipeline import Parameter
from paddleflow.pipeline import Artifact
from paddleflow.pipeline import CacheOptions
from paddleflow.pipeline import PF_USER_NAME
def job_info():
return {
"PF_JOB_TYPE": "vcjob"... |
456714 | import configs_and_settings
import csv
import os
# C:\Users\Xavier\LSTMforSHM\data\time_series_datasets\csv_data_test_file.csv
# csv_file_path = r"C:\Users\Xavier\LSTMforSHM\data\time_series_datasets\csv_data_test_file.csv"
csv_file_path = r"C:\Users\Xavier\LSTMforSHM\data\csv_data\csv_data_test_file123.csv"
def re... |
456738 | import fileinput
from itertools import count
def slice_to_str(slice):
return ''.join(str(n) for n in slice)
INPUT = int(fileinput.input()[0])
input_str = str(INPUT)
input_len = len(input_str)
recipes = [3, 7]
recipes_len = 2
elf_1 = 0
elf_2 = 1
part_1 = None
part_2 = None
while part_1 is None or part_2 is No... |
456770 | import bpy
import os
import math
import json
from copy import deepcopy
from . import DataBase
from . import Versions
from . import Util
bUsePrincipledMat = True
isHighHeel = False
bRotationLimit = False
bLimitOnTwist = True
bUseCustomBone = False
bUseDrivers = False
#remove shape key from all wearable things, not just... |
456790 | import math
import time
import os
import PyQt5.QtWidgets as QtWidgets
import PyQt5.QtCore as Qt
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
from vtkUtils import *
from config import *
class MainWindow(QtWidgets.QMainWindow, QtWidgets.QApplication):
def __init__(self, app):
se... |
456819 | from PIL import Image
import argparse
import os
import mimetypes
from utils.transforms import get_no_aug_transform
import torch
from models.generator import Generator
import numpy as np
import torchvision.transforms.functional as TF
import torch.nn.functional as F
from torchvision import transforms
import cv2
from torc... |
456846 | import math
from mks.models import Member
from persons.models import Person, PersonAlias
# from: http://www.cs.princeton.edu/introcs/21function/ErrorFunction.java.html
# Implements the Gauss error function.
# erf(z) = 2 / sqrt(pi) * integral(exp(-t*t), t = 0..z)
#
# fractional error in math formula less than 1.2 * 1... |
456887 | import elasticsearch
import argparse
import re
def parse_rule_line(rule_line):
"""
Parse each rule line and return a dict representation of a rule
:param rule_line:
:return: rule dict
"""
rule_dict = {}
rule_info = re.search("\((.*)\)", rule_line).group(1)
msg_sections = rule_info.spli... |
456918 | import cympy
import pandas
class Substation(object):
""""""
def __init__(self, model_filename):
""""""
# Open the model
self.model_filename = model_filename
cympy.study.Open(self.model_filename)
def baseload_allocation(self, feeder_loads):
"""Allocate lo... |
456925 | from abc import ABC, abstractmethod
from pathlib import Path
from typing import List
from novelsave.core.entities.novel import Novel
class BasePackager(ABC):
@property
@abstractmethod
def priority(self):
"""Determines the order in which the packager must be called. Lowest first"""
@abstract... |
456935 | import os
import utils
import config
import traceback
import argparse
import logging.config
from luna import LunaExcepion
logging.config.fileConfig("logging.conf")
logger = logging.getLogger()
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-... |
456947 | import logging
from telegram import Update
from telegram.ext import CommandHandler, Updater, CallbackContext
logger = logging.getLogger(__name__)
def add_core(upd: Updater, core_handlers_group: int):
logger.info("register smile-mode handlers")
dp = upd.dispatcher
dp.add_handler(CommandHandler("start", s... |
456974 | import warnings
from types import FrameType
from typing import Optional, Dict, Any, cast
__all__ = ["make_step"]
import inspect
from baikal.steps import Step
def make_step(
base_class: type, attr_dict: Dict[str, Any] = None, class_name: Optional[str] = None
) -> type:
"""Creates a step subclass from the gi... |
457016 | import webview
import pytest
from .util import run_test
def test_bg_color():
window = webview.create_window('Background color test', 'https://www.example.org', background_color='#0000FF')
run_test(webview, window)
def test_invalid_bg_color():
with pytest.raises(ValueError):
webview.create_window... |
457042 | import hoki.age_utils as au
import hoki.load as load
import pkg_resources
import numpy as np
import pandas as pd
import pytest
from hoki.utils.exceptions import HokiFatalError, HokiUserWarning, HokiFormatError
# Loading Data
data_path = pkg_resources.resource_filename('hoki', 'data')
hr_file = data_path + '/hrs-sin-i... |
457092 | import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Wordpress Profile Builder Plugin Cross-Site Scripting''',
"description": '''The Profile Builder User Profile & User Registration Forms WordPress plugin is vulnerable to cross-site scripting due to insu... |
457099 | from blesuite.connection_manager import BLEConnectionManager
from blesuite.event_handler import ATTEventHook
from blesuite.entities.gatt_device import BLEDevice
from blesuite.entities.permissions import Permissions
import blesuite.utils.att_utils as att_utils
from scapy.layers.bluetooth import ATT_Read_Request, ATT_Rea... |
457104 | import numpy as np
import matplotlib.pyplot as plt
import afterglowpy as grb
Z = {'jetType': grb.jet.TopHat, # Top-Hat jet
'specType': 0, # Basic Synchrotron Emission Spectrum
'thetaObs': 0.05, # Viewing angle in radians
'E0': 1.0e53, # Isotropic-equivalent ene... |
457113 | import FWCore.ParameterSet.Config as cms
# Set the HLT paths
import HLTrigger.HLTfilters.hltHighLevel_cfi
ALCARECOSiStripCalMinBiasAAGHLT = HLTrigger.HLTfilters.hltHighLevel_cfi.hltHighLevel.clone(
andOr = True, ## choose logical OR between Triggerbits
## HLTPaths = [
## #Minimum Bias
## "HLT_MinBias*"... |
457128 | from setuptools import setup, find_packages
setup(
name='mkdocs-pdf-export-plugin',
version='0.5.10',
description='An MkDocs plugin to export content pages as PDF files',
long_description='The pdf-export plugin will export all markdown pages in your MkDocs repository as PDF files'
... |
457143 | import random
from six import string_types
import frappe
import jwt
from frappe import _
from frappe.auth import LoginManager
from frappe.utils import cint, get_url, get_datetime
from frappe.utils.password import check_password, passlibctx, update_password
from renovation_core.utils import update_http_response
from ... |
457161 | import idc
import ida_enum
from bip.py3compat.py3compat import *
from .bipelt import BipRefElt
class BipEnum(object):
"""
Class for representing and manipulating an enum in IDA.
Class method :meth:`~BipEnum.get` and :meth:`~BipEnum.create` allows
to easily create and recuperate a :class:... |
457248 | import sys
import subprocess
import re
from tabulate import tabulate
import textwrap
import warnings
import datetime as dt
import numpy as np
from scipy.interpolate import interp1d
from ._exceptions import InterfaceError, AdapterUnaccessibleError
from .utils import db2dbm, RealTimePlot, spin, rssi_to_colour_str
from .... |
457257 | import pytest
pytestmark = [
pytest.mark.django_db,
pytest.mark.freeze_time('2032-12-01 16:20'),
]
@pytest.fixture(autouse=True)
def material(course, mixer):
return mixer.blend('notion.Material', course=course, is_home_page=True, page_id='deadbeef')
@pytest.fixture
def another_material(course, mixer, f... |
457282 | import alarm
import board
import time
import digitalio
import neopixel
## WAKING PINS - uncomment appropriate pin per microcontroller
wake_pin = board.X1 # STM32F4 Pyboard
# wake_pin = board.GP0 # RP2040 Pico
# wake_pin = board.A4 # NRF52840 Feather
# wake_pin = board.IO5 ... |
457284 | import sys
import os
import dk
import gc
from .mainframe import MainFrame
class App(dk.App):
''' 응용 프로그램 인스턴스 (dk.App)'''
def onInit(self):
self.resourceDir = os.path.abspath(os.path.join( os.path.dirname(__file__), 'resources' ))
print('resourceDir: ', self.resourceDir)
displayBound... |
457290 | from utils.basic_utils import load_json, save_json
def combine(video_name_split_path, video_duration_path, save_path):
video_name_split = load_json(video_name_split_path)
video_duration_dict = load_json(video_duration_path)
combined_dict = {}
for split_name, split_video_names in video_name_split.item... |
457359 | from navycut.utils.server import create_asgi_app
from os import environ
# Asynchronus server gateway interface
# use uvicorn asgi server to run this app
#define your default settings file here:
environ.setdefault("NAVYCUT_SETTINGS_MODULE", "check1.settings")
application = create_asgi_app() |
457388 | import os
from argparse import ArgumentParser
import random
def read_ner(path):
data = [[]]
with open(path, encoding='ISO-8859-1') as f:
for line in f:
line = line.strip()
# New sentence
if len(line) == 0:
if len(data[-1]) > 0:
d... |
457391 | import json
from os.path import expanduser
class RenderEnvironment():
def __init__(self):
self.queueName = None
self.largeDiskQueueName = None
self.jobDefinition = None
self.sourceBucket = None
self.resultsBucket = None
def validate(self):
if self.queueName is ... |
457409 | import pytest
from cx_const import Number, StepperDir
from cx_core.stepper import MinMax, Stepper, StepperOutput
class FakeStepper(Stepper):
def __init__(self) -> None:
super().__init__(MinMax(0, 1), 1)
def step(self, value: Number, direction: str) -> StepperOutput:
return StepperOutput(next_... |
457411 | import os
import json
import copy
import subprocess
from dotenv import load_dotenv, find_dotenv
import yaml
import logging
import argparse
import requests
# grafana api host
grafana_api_host = "https://monitor.harmony.one/api/"
# set shard count
shard_count = 4
# min storage space for alerting
min_storage_space = 5
# ... |
457435 | import warnings
from collections import OrderedDict, defaultdict
from typing import (
Any,
Callable,
Collection,
DefaultDict,
Dict,
Iterable,
List,
Optional,
Sequence,
Set,
Tuple,
cast,
)
import torch
from torch import nn
import pystiche
from ..misc import build_deprec... |
457455 | from deficrawler.lending import Lending
def test_liquidation_aave_2_eth():
aave = Lending(protocol="Aave", chain="Ethereum", version=2)
liquidations = aave.get_data_from_date_range(
'21/04/2021 05:20:01', '22/04/2021 06:22:01', "liquidation")
assert(liquidations[0]['tx_id'] != "")
assert(liqui... |
457460 | from utils import registry
DATASETS = registry.Registry('dataset')
def build_dataset_from_cfg(cfg, default_args = None):
"""
Build a dataset, defined by `dataset_name`.
Args:
cfg (eDICT):
Returns:
Dataset: a constructed dataset specified by dataset_name.
"""
return DATASETS.... |
457543 | import tuned.logs
log = tuned.logs.get()
__all__ = ["Monitor"]
class Monitor(object):
"""
Base class for all monitors.
Monitors provide data about the running system to Plugin objects, which use the data
to tune system parameters.
Following methods require reimplementation:
- _init_available_devices(cls)
... |
457579 | import warnings
from typing import Dict, Type
from ..core.builder import DatasetBuilder
from ...serializers.event import EventDataSerializer, StatsBombSerializer
# 3749133 / 38412
class Statsbomb(DatasetBuilder):
def get_dataset_urls(self, **kwargs) -> Dict[str, str]:
warnings.warn(
"\n\nYou ... |
457587 | import numpy as np
import numpy.random as rnd
from libtlda.rba import RobustBiasAwareClassifier
def test_init():
"""Test for object type."""
clf = RobustBiasAwareClassifier()
assert type(clf) == RobustBiasAwareClassifier
assert not clf.is_trained
def test_fit():
"""Test for fitting the model."""... |
457589 | myvar = {1:10,2:20}
class myclass():
def __init__(self):
myvar[1]=100
print myvar
self.printvar()
def printvar(self):
print myvar
k = myclass()
|
457625 | import logging
from django_elasticsearch_dsl.registries import registry
from django.apps import apps
from froide.celery import app as celery_app
logger = logging.getLogger(__name__)
def get_instance(model_name, pk):
model = apps.get_model(model_name)
try:
return model._default_manager.get(pk=pk)
... |
457626 | import os, urllib, sys, getopt
class Renamer:
input_encoding = ""
output_encoding = ""
path = ""
is_url = False
def __init__(self, input, output, path, is_url):
self.input_encoding = input
self.output_encoding = output
self.path = path
self.is_url = is_url
def... |
457736 | from behave import given, when, then
from hamcrest import *
empty_database = ''
one_user_registered = 'alice <PASSWORD>'
URL = 'http://localhost:8080/demo/library.html'
DEFAULT_USERNAME = 'alice'
DEFAULT_PASSWORD = '<PASSWORD>'
@given('I am not registered')
def step_impl(context):
pass
@when('I register with a... |
457810 | from __future__ import print_function
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import h5py
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Input, Dense, Dropout
from tensorflow.keras.models import Model, model_fro... |
457837 | from typing import Iterable, Callable, TypeVar
from .config import CacheType
from .foreach_recipe import ForeachRecipe
from .recipe import Recipe
R = TypeVar("R") # The return type of the bound function
def recipe(ingredients: Iterable[Recipe] = (), transient: bool = False, cache: CacheType = CacheType.Auto) -> \
... |
457848 | import supriya.realtime
def test_01(server):
control_bus = supriya.realtime.Bus.control()
control_bus.allocate()
assert control_bus.is_allocated
result = control_bus.get()
assert result == 0.0
assert control_bus.value == result
control_bus.set(0.5)
result = control_bus.get()
as... |
457891 | from __future__ import absolute_import, division, print_function
# svn co https://cbflib.svn.sourceforge.net/svnroot/cbflib/trunk/CBFlib_bleeding_edge sourceforge_cbflib
class info_counters(object):
def __init__(O):
O.mkdir = 0
O.copied = 0
O.updated = 0
O.already_up_to_date = 0
def report(O):
... |
457895 | from __future__ import absolute_import
from past.builtins import basestring
import re
from ckan.common import _
import ckan.lib.navl.dictization_functions as df
from ckanext.fluent.validators import fluent_text
from ckan.common import config
import ckan.plugins.toolkit as toolkit
import ckan.logic.validators as validat... |
457919 | import json
import pytest
from graphene.test import Client
from main.schema import schema
@pytest.mark.django_db
def test_municipalities_exists():
client = Client(schema)
result = client.execute('''
query {
municipalities {
edges {
node {
id
name
bfsNumber
}
}
}
... |
457955 | import logging
import re
import secrets
import django
from django.contrib.auth import authenticate
from django.core.mail import send_mail
from django.http import HttpResponse
from django.shortcuts import render, redirect
from app.views import validate_user_email
from .models import CustomUser
def get_logger():
... |
457957 | from __future__ import division, print_function
import numpy as np
import plyades.util as util
def precession(date):
''' Vallado 2nd Edition p.215
'''
# Julian centuries since the epoch
t = (date - 2451545)/36525
zeta = util.dms2rad(0, 0, 2306.2181*t + 0.30188*t**2 + 0.017998*t**3)
theta = util... |
457987 | from ..factory import Type
class callStateReady(Type):
protocol = None # type: "callProtocol"
connections = None # type: "vector<callConnection>"
config = None # type: "string"
encryption_key = None # type: "bytes"
emojis = None # type: "vector<string>"
allow_p2p = None # type: "Bool"
|
458025 | from __future__ import absolute_import
import time
from flexmock import flexmock
import pony.tasks
from tests.test_base import BaseTest
class SendMessageTest(BaseTest):
def test_execute(self):
task = pony.tasks.SendMessage('_to', '_text', [1, 2, 3])
(flexmock(self.bot.slack_client.server)
... |
458092 | import info
class subinfo(info.infoclass):
def setTargets( self ):
self.svnTargets[ "master"] = f"https://github.com/hunspell/hunspell.git"
for ver in ["1.6.2"]:
self.targets[ver] = f"https://github.com/hunspell/hunspell/archive/v1.6.2.tar.gz"
self.archiveNames[ver] = f"hun... |
458107 | import pickle
import torch
import math
import time
def to_cuda(x):
use_gpu = torch.cuda.is_available()
if use_gpu:
x = x.cuda()
return x
def time_since(since):
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
def save_checkpoint... |
458114 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .fusion import AsymBiChaFuseReduce, BiLocalChaFuseReduce, BiGlobalChaFuseReduce
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride, downsample):
super(ResidualBlock, self).__init__()
self.bod... |
458233 | import discord
from discord.ext import commands
class Help(commands.Cog):
"""Displays the message you are currently viewing!"""
def __init__(self,bot):
self.bot = bot
@commands.command()
@commands.has_permissions(add_reactions=True,embed_links=True)
async def help(self,ctx,*cog):
"... |
458251 | import rclpy
from rclpy.node import Node
from rclpy.exceptions import ParameterNotDeclaredException
from rcl_interfaces.msg import ParameterType
class MyPythonNode(Node):
def __init__(self):
super().__init__("dummy_node")
self.get_logger().info("This node just says 'Hello'")
timer_period ... |
458284 | from numpy import inf, nan
from sklearn.gaussian_process import GaussianProcessClassifier as Op
from lale.docstrings import set_docstrings
from lale.operators import make_operator
class _GaussianProcessClassifierImpl:
def __init__(self, **hyperparams):
self._hyperparams = hyperparams
self._wrappe... |
458286 | import cv2
import numpy as np
def draw_rectangle(event, x, y, flags, params):
global x_init, y_init, drawing
def update_pts():
params["top_left_pt"] = (min(x_init, x), min(y_init, y))
params["bottom_right_pt"] = (max(x_init, x), max(y_init, y))
img[y_init:y, x_init:x] = 255 - img[y_... |
458298 | import rdkit.Chem as Chem
import rdkit.Chem.AllChem as AllChem
from rdkit.Chem.rdchem import ChiralType, BondType, BondDir
from rdchiral.chiral import template_atom_could_have_been_tetra
from rdchiral.utils import vprint
class rdchiralReaction():
'''
Class to store everything that should be pre-computed for a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.