id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11512893 | from django.core.management import call_command
from django_comments.models import Comment
from . import CommentTestCase
from testapp.models import Article
class CommentManagerTests(CommentTestCase):
def testDoesNotRemoveWhenNoStaleComments(self):
self.createSomeComments()
initial_count = Comme... |
11512902 | from django.apps import AppConfig
class YogaTrainPredConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'yoga_train_pred'
|
11512921 | import numpy as np
def topN_accuracy(y_true: np.array,
y_pred_onehot: np.array,
N: int):
""" Top N accuracy """
assert len(y_true.shape) == 1
assert len(y_pred_onehot.shape) == 2
assert y_true.shape[0] == y_pred_onehot.shape[0]
assert y_pred_onehot.shape[1] >= N... |
11512971 | from typing import List
from ..base_tracker import GenericPrivateTracker
class KinozalTracker(GenericPrivateTracker):
"""This class implements .torrent files downloads for http://kinozal.tv/ tracker."""
alias: str = 'kinozal.tv'
login_url: str = 'https://%(domain)s/takelogin.php'
auth_cookie_name: s... |
11512977 | import sys
import os
from gi.repository import Gtk, Gdk
from misc.log import with_logging
from cave.libcave.registered_elements import get_registered_elements, get_registered_elements_implementing
from cave.libcave.tags.registered_tags import get_tagtype_names, get_required_functions_of_tag
from cave.libcave.util imp... |
11512996 | import requests
from .config import PYTHON_VERSION
def quote_url(url):
'''encodes URLs.'''
if PYTHON_VERSION == 2:
url = encode_str(url)
return requests.utils.quote(url, safe=';/?:@&=+$,#')
def unquote_url(url):
'''decodes URLs.'''
if PYTHON_VERSION == 2:
url = encode... |
11512998 | import numpy as np
import pytest
import theanets
import util as u
REG_LAYERS = [
(u.CNN.NUM_WIDTH, u.CNN.NUM_HEIGHT, u.NUM_INPUTS),
dict(size=u.NUM_HID1, form='conv2', filter_size=u.CNN.FILTER_SIZE),
dict(size=u.NUM_HID2, form='conv2', filter_size=u.CNN.FILTER_SIZE),
'flat',
u.NUM_OUTPUTS]
CLF_LA... |
11513019 | import numpy as np
import os
import sys
import tensorflow as tf
import cv2
import imutils
import time
from imutils.video import FPS
from sklearn.metrics import pairwise
import copy
import pathlib
from collections import defaultdict
colors = np.random.uniform(0, 255, size=(100, 3))
font = cv2.FONT_HERSHEY_SIMPLEX
#... |
11513034 | from abc import ABC, abstractmethod
import json
import logging
import requests
from .exc import TransferError
LOG = logging.getLogger("wetransfer")
LOG.addHandler(logging.NullHandler())
LOG.setLevel(logging.INFO)
def http_response(func):
def wrapper_http_response(*args, **kwargs):
"""
The wrapper... |
11513157 | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from .core.config import get_db_connection_url
import time
import os
engine = None
SessionLocal = None
Base = None
retries = 5
while retries > 0:
try:
engine = create_engi... |
11513163 | import requests
from files.workers.api import *
f = open("files/cache/cosmetics.json",'w+')
f.truncate(0)
data = requests.get("https://fortnite-api.com/v2/cosmetics/br").json()
for cos in data['data']:
if str(cos['id']).startswith("CID"):
f.write('''
"AthenaCharacter:'''+cos["id"]+'''": {
"templateId":... |
11513165 | import appdaemon.plugins.hass.hassapi as hass
import json
import datetime
import asyncio
import aiohttp
""" App to manage docker containers.
The app extracts data from the docker API and creates sensors
and services in HA and Appdaemon to monitor and manage
docker containers.
"""
class Docke... |
11513232 | import numpy as np
from .components import BlochMZI, SMMZI
from .config import NP_FLOAT
from typing import Callable, Tuple
from .numpy import MeshNumpyLayer, RMNumpy
from .meshmodel import MeshModel
from .helpers import inverse_permutation
def clements_decomposition(u: np.ndarray, pbar_handle: Callable = None, smmzi:... |
11513274 | import numpy as np
import random
from utils import save_obj, load_obj
import torch
from torch.utils import data
import cv2
import os
from ReDWebNet import resNet_data_preprocess
def draw(img, target, fname):
img_temp = img.copy()
color_close = (255, 0, 0) # close is blue
color_far = (0, 255, 0) # far is green... |
11513278 | import os
import vigra
import argparse
from regression_test_utils import init, run_mc, run_lmc, regression_test
from multicut_src import ExperimentSettings
from multicut_src import MetaSet
#from multicut_src import load_dataset
def regression_test_isbi(cache_folder, data_folder):
# if the cache does not exist, c... |
11513287 | from ..registry import DETECTORS
from .single_stage import SingleStageDetector
import time
import pdb
import torch
from torch import nn
import spconv
import logging
from .. import builder
import pickle
import os
import numpy as np
def mkdir(path):
try:
os.makedirs(path)
except:
pass
@DETECTO... |
11513324 | import pandas as pd
import numpy as np
df = pd.DataFrame({'col1': [2, 3, 1, 3, 3, 4],
'col2': [30, 10, 10, 40, 40, 20]},
index=['A', 'B', 'C', 'D', 'E', 'F'])
print(df)
# col1 col2
# A 2 30
# B 3 10
# C 1 10
# D 3 40
# E 3 40
# F 4 20
... |
11513325 | import pytest
from pymtl import *
from tests.context import lizard
from lizard.util.test_utils import run_test_vector_sim
from lizard.util.rtl.registerfile import RegisterFile
from tests.config import test_verilog
from lizard.util.fl.registerfile import RegisterFileFL
from lizard.model.wrapper import wrap_to_cl
from li... |
11513357 | from scoring_engine.engine.engine import Engine
from scoring_engine.models.service import Service
from scoring_engine.models.environment import Environment
from scoring_engine.models.property import Property
from scoring_engine.models.account import Account
from tests.scoring_engine.unit_test import UnitTest
class C... |
11513360 | import unittest
import mock
from Game import Game
from Grid import Grid
from FileManager import FileManager
class TestGame(unittest.TestCase):
def setUp(self):
"""
setUp class
"""
# Instantiate
self.game = Game()
self.grid = Grid()
self.file_manager = FileM... |
11513364 | class A:
def __init__(self,name):
self.name=name
def display(self):
print(self.name)
class b(A):
def __init__(self,name,age):
super().__init__(name)
self.age=age
def display(self):
print(self.name)
print(self.age)
bb = b('raj',33)
bb.display()
|
11513369 | import cv2
from models import server
from utils import utils
from configs import configs
# Reading example image
img = cv2.imread('{}'.format(configs.TEST_DATA_FP['img']))
# Reading example points cloud
pclds = utils.load_velo_scan('{}'.format(configs.TEST_DATA_FP['pclds']))
test_input = {'img': img, 'pclds': pclds}... |
11513381 | import logging
import os
import random
import sys
from transformers import (
AutoConfig,
AutoTokenizer,
AdapterConfig
)
from model.utils import get_model, TaskType
from tasks.glue.dataset import GlueDataset
from training.trainer_base import BaseTrainer
from transformers import Trainer, AdapterTrainer, Ear... |
11513435 | import re
def custom_format(template_string, **kwargs):
"""
The python format uses {...} to indicate the variable that needs to be replaced.
custom_format uses &lformat ... &rformat to indicate the variable, which means {} can be used in the template_string
as a normal character.
"""
template_... |
11513533 | import ckanext.hdx_pages.model as pages_model
import ckanext.hdx_pages.helpers.dictize as dictize
import ckan.logic as logic
NotFound = logic.NotFound
def page_delete(context, data_dict):
'''
Delete a meta information entry
:param id: the id or name of the page
:type id: str
:return: deleted dict... |
11513572 | import fidimag.common.helper as helper
from fidimag.common.fileio import DataSaver, DataReader
import numpy as np
class SimBase(object):
"""
A class with common methods and definitions for both micromagnetic and
atomistic simulations
"""
def __init__(self, mesh, name):
self.name = nam... |
11513641 | import sys
AWS = """
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
s3_force_path_style = true
"""
AZURE = """
skip_credentials_validation = true
skip_provider_registration = true
"""
PROVIDER_FILE = sys.argv[1] if len(sys.argv) > 1 el... |
11513645 | class ITTKException(Exception):
"""
Vanilla base exception, for readability only. More specific ITTK-related exceptions should subclass this.
"""
pass
class AsymmetricMatrixException(ITTKException):
pass
|
11513652 | import json
from django.db import models
from django.db.models.constraints import UniqueConstraint
from django.urls import reverse
from django.utils import timezone
from django.utils.functional import cached_property
from uuslug import slugify
from dictionary.models.managers.messaging import ConversationManager, Mes... |
11513686 | import scriptures
from address.models import AddressField
from django.db import models
from django.utils.functional import cached_property
from website.models import UUIDModel
import mammoth
from rake_nltk import Rake
from taggit.managers import TaggableManager
import docx
import sumy
from djrichtextfield.models impor... |
11513729 | import tensorflow as tf
def build_graph(images, labels, loss_function, inference_function, learning_rate, global_step):
optimizer_net = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=0.95)
tf.summary.scalar('learning_rate', learning_rate)
with tf.variable_scope(tf.get_variable_scope()) as scope... |
11513730 | from distutils.core import setup
import py2exe, sys, os
#This to change the script to an exe edit the variables inside the duckhunt-configurable.py file then run this script
sys.argv.append('py2exe')
setup(
name = 'duckhunt',
description = 'duckhunt-',
options = {'py2exe': {'bundle_files': 1, 'compressed... |
11513731 | from django.test import TestCase
from filemanager.core import Filemanager
class FilemanagerTest(TestCase):
def setUp(self):
self.fm = Filemanager()
def test_basic_path(self):
self.assertEqual(self.fm.path, '')
self.assertEqual(self.fm.abspath, 'uploads')
def test_different_path(... |
11513741 | import os
file = open("1.txt", "w")
file.write("mmd\rmmd\rdnt")
file.close()
f = open("1.txt", "r")
lines = f.readlines()
f.close()
print(lines) |
11513780 | import numpy as np
import torch
class UnNormalizer(object):
def __init__(self, mean=None, std=None):
if mean == None:
self.mean = [0.485, 0.456, 0.406]
else:
self.mean = mean
if std == None:
self.std = [0.229, 0.224, 0.225]
else:
self... |
11513795 | from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views import ... |
11513808 | import os
import cells.utility as utility
from PySide2.QtCore import QSize
from PySide2.QtGui import QColor, QFont, QFontDatabase
from PySide2.QtWidgets import QScrollBar
class Fonts:
def initDb():
monoRegular = os.path.join(utility.viewResourcesDir(), "fonts",
"FiraCod... |
11513837 | import d6tstack.combine_csv
#import d6tstack.convert_xls
import d6tstack.sniffer
#import d6tstack.sync
import d6tstack.utils
|
11513865 | import sys
sys.path.append('../')
from s7scan import ask_yes_no, get_ip_list, validate_ip, validate_mac, get_user_args, validate_user_args
def test_ask_yes_no():
print("Testing ask_yes_no()")
result = ask_yes_no()
print("Result was {}".format(result))
def test_get_ip_list(ip_list):
print("Testing get_i... |
11513919 | from __future__ import absolute_import
from __future__ import print_function
from boto import sqs
import json
import signal
import sys
import traceback
from workers import sqs_tasks
def process_messages(queue, handler, num_messages=10, wait_time_seconds=20):
messages = queue.get_messages(num_messages=num_message... |
11513956 | import torch
from torch import nn
from src.backbone.layers.conv_block import InvertedResidualBlock, conv1x1, conv3x3, ConvBNReLU, mobilenet_v2_init
from src.backbone.utils import load_from_zoo
class MobileNetV2(nn.Module):
"""This implementation follow torchvision works"""
def __init__(self, block=InvertedRe... |
11513985 | from .preprocessing import pivot_data
from .preprocessing import sample_dataset
from .dataframewriter import DataFrameWriter
|
11513997 | import glob
import inspect
import json
import os
from unittest.mock import patch
import pytest
from ioccheck.iocs import Hash
from ioccheck.services import MalwareBazaar
test_inputs = []
for input_file in glob.glob("./test/data/malwarebazaar_bulk_responses/*.json"):
with open(input_file, "r") as f:
pri... |
11514040 | from .stats_influx import StatsInflux
from pymongo import MongoClient, database, collection
from urllib.parse import quote_plus
class Reporter:
def __init__(self, server_id, exchange_id):
#self.session_uuid = session_uuid
self.server_id = server_id
self.exchange_id = exchange_id
... |
11514084 | from app import app
import os
host = os.environ.get('IP', '0.0.0.0')
port = int(os.environ.get('PORT', 9090))
app.run(host=host,port=port,debug=True,threaded=True)
|
11514090 | from config.config import Config
from util.sql import SnekDB
if __name__ == '__main__':
# get config data
data = Config()
snekdb = SnekDB(data.database_user, data.network, data.delegate)
snekdb.setup()
|
11514116 | from sqlalchemy import (
Column, Integer, String, update, delete
)
from sqlalchemy.future import select
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.ext.asyncio import (
create_async_engine, AsyncSession
)
url_do_banco = 'sqlite+aiosqlite:///db.db'
engine = create_async_engine(url... |
11514137 | import tensorflow as tf
import numpy as np
from keras.models import load_model
import pandas as pd
import json
def init_tf():
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
return sess
def invoke(config):
init_tf()
model = load_model(str(co... |
11514155 | import PyPDF2
pdf = open('test.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf)
pdf_page = read_pdf.getPage(1)
pdf_content = pdf_page.extractText()
print(pdf_content)
pdf.close()
|
11514166 | import argparse
import os
import shutil
import time
import sys
import gc
import platform
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
cwd = os.g... |
11514183 | from . import BasicType
class ResponseParameters(BasicType):
fields = {
'migrate_to_chat_id': str,
'retry_after': int
}
def __init__(self, obj=None):
super(ResponseParameters, self).__init__(obj)
|
11514200 | import bokeh.plotting as plotting
import bokeh.models
from bokeh.resources import CDN
from bokeh.embed import autoload_static
class BokehHelper:
def __init__(self, div_id, js_path):
self.div_id = div_id
self.js_path = js_path
def create_fig(self, *args, **kwargs):
raise RuntimeError("P... |
11514206 | from django.http import Http404
from django.shortcuts import render
from .models import SubmissionResult
class LoggedInMixin:
"""
A mixin requiring a user to be logged in.
If the user is not authenticated, show the 404 page.
"""
def dispatch(self, request, *args, **kwargs):
if not reque... |
11514215 | import time
from .. import widgets, logs, runs, tests, files
from . import registry
import pandas as pd
import threading
from contextlib import contextmanager
import _thread
from logging import getLogger
log = getLogger(__name__)
def adaptive_rule(df):
timespan = (df.index[-1] - df.index[0]).total_seconds()
i... |
11514218 | from .. import Verb
class Adapter(object):
def __init__(self):
pass
def get_value(self, ctx : Verb) -> str:
return "" |
11514258 | import logging
import sys
from logbook import StreamHandler
from logbook.compat import redirect_logging
def setup_logging():
logging.getLogger("pdfminer").setLevel(logging.WARNING)
logging.getLogger("ocrmypdf").setLevel(logging.WARNING)
redirect_logging()
format_string = "{record.level_name}: {recor... |
11514264 | import logging,ptypes
from ptypes import pstruct,parray,ptype,dyn,pstr,pint,pbinary
from ..headers import *
from . import symbols,relocations,linenumbers
class IMAGE_DATA_DIRECTORY(pstruct.type):
def _object_(self):
# called by 'Address'
res = self['Size'].int()
return dyn.block(res)
... |
11514325 | from dataclasses import dataclass
from typing import Optional
from running_modes.configurations.transfer_learning.link_invent_learning_rate_configuration import \
LinkInventLearningRateConfiguration
@dataclass
class LinkInventTransferLearningConfiguration:
empty_model: str
learning_rate: LinkInventLearni... |
11514349 | import sys
import logging
from ntfs.BinaryParser import Block
from ntfs.BinaryParser import OverrunBufferException
from ntfs.mft.MFT import InvalidRecordException
from ntfs.mft.MFT import MREF
from ntfs.mft.MFT import MSEQNO
from ntfs.mft.MFT import MFTRecord
from ntfs.mft.MFT import ATTR_TYPE
from ntfs.mft.MFT import... |
11514353 | import scipy.io
import os
import matplotlib.pylab as plt
import utils
import numpy as np
import itertools
import boltons.iterutils
import keras_image_preprocessing
class Dataset(object):
"""
Base class for a dataset helper. Implements functionality while subclasses will focus on loading
the data into the ... |
11514375 | from miscellanies.simple_api_gateway import ServerLauncher, Client, CallbackFactory
from data.tracking.sampler._sampling_algos.sequence_picking.run_through._server import ApiGatewayRunThroughSamplerServerHandler
class RunThroughSequencePickingOrchestrationServer:
def __init__(self, datasets, socket_address, seed:... |
11514378 | import os
from elastalert.alerts import Alerter, BasicMatchString
from notifications_python_client.notifications import NotificationsAPIClient
class GovNotifyAlerter(Alerter):
required_options = set(['log_file_path', 'email'])
def __init__(self, rule):
Alerter.__init__(self, rule)
self.templ... |
11514397 | import random
from collections import deque
from abc import abstractmethod
class MemoryTemplate:
"""
Memory abstract class
"""
_counter = 0
def __init__(self, seed):
if seed is not None:
random.seed(seed)
@property
def counter(self):
return self._counter
... |
11514404 | from binascii import unhexlify
from lbry.testcase import AsyncioTestCase
from lbry.wallet.constants import CENT, NULL_HASH32
from lbry.wallet.bip32 import PrivateKey, KeyPath
from lbry.wallet.mnemonic import Mnemonic
from lbry.wallet import Ledger, Database, Headers, Transaction, Input, Output
from lbry.schema.claim i... |
11514431 | import errno
import glob
import os
import time
from checks import AgentCheck
class FileCheck(AgentCheck):
MAX_FILES_TO_STAT = 1024
STATUS_ABSENT = 'absent'
STATUS_PRESENT = 'present'
def __init__(self, name, init_config, agentConfig, instances=None):
AgentCheck.__init__(self, name, init_conf... |
11514446 | import abc
"""Localised ensemble filters for inference in spatially extended state-space models."""
from typing import Tuple, Dict, Callable, Any, Optional, Sequence
from functools import partial
import numpy as np
import numpy.linalg as nla
from numpy.random import Generator
from scipy.special import logsumexp
from ... |
11514460 | from django.conf.urls import patterns, include, url
urlpatterns = patterns(
'',
url(r'^csw$','OpenDataCatalog.catalog.views.csw'),
)
|
11514493 | from magma import *
from magma.bitutils import lutinit
__all__ = ['RAM16x1S', 'RAM16',
'RAM16x2S', 'RAM16x2',
'RAM16x1D', 'RAM16D']
__all__ += ['RAM16DxN', 'DefineRAM16DxN']
RAM16x1S = DeclareCircuit('RAM16X1S',
"A0", In(Bit),
"A1", In(Bit),
"A2", In(Bit),... |
11514518 | from tools.precommit_converter.converter.convert_engine import ConvertEngine
from tools.precommit_converter.extractor.extractor import Extractor
from tools.precommit_converter.printer.printer import Printer
class Convert:
NAME = "convert"
HELP_MSG = "Convert hex string data to human readable"
@classmetho... |
11514524 | import pytest
import lazy_dataset
import inspect
subclasses = lazy_dataset.Dataset.__subclasses__()
@pytest.mark.parametrize(
'method,dataset_cls', [
(method, cls)
for method in [
'__iter__',
'copy',
'__len__',
'__getitem__',
'keys',
... |
11514525 | from . import filters
from jinja2 import Environment, PackageLoader, select_autoescape
environment = Environment(
loader=PackageLoader('lib'),
autoescape=select_autoescape()
)
environment.filters['noneNull'] = filters.noneNull
|
11514547 | from httpx_cache.cache.base import BaseCache
from httpx_cache.cache.file import FileCache
from httpx_cache.cache.memory import DictCache
|
11514551 | from ..feats import Feats
def test_smoke():
train_dataset = [
{
'words' : ['Once', 'upon', 'a', 'time', 'in', 'Boston'],
'labels': ['O', 'O', 'O', 'O', 'O', 'S-LOC'],
},
{
'words' : ['Mr.', 'Boss', 'opened', 'a', 'meeting'],
'label... |
11514575 | from rest_framework import fields
from rest_framework.serializers import Serializer
class AnonymousCartSerializer(Serializer):
pass
class CartSerializer(Serializer):
pass
class DiscountSerializer(Serializer):
product = ProductSerializer(many=True)
collection = CollectionSerializer(many=True)
... |
11514576 | import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
inds = torch.LongTensor([0, -1, -2, -3, 1, 0, 3, -2, 2, -3, 0, 1, 3, 2, -1, 0]).view(4, 4)
def hamilton_product(q1, q2):
q_size = q1.size()
# q1 = q1.view(-1, 4)
# q2 = q2.view(-1, 4)
q1_q2_prods = []
for i in range(4):... |
11514649 | from nipype.interfaces import afni as afni
import os
import glob
import click
from .batch_manager import BatchManager, Job
from .config_json_parser import ClpipeConfigParser
import logging
import sys
from .error_handler import exception_handler
from nipype import MapNode, Node, Workflow
import nipype.utils
import panda... |
11514651 | from __future__ import absolute_import
import unittest
import numpy as np
from tests.sample_data import SampleData
from pyti import vertical_horizontal_filter
class TestVerticalHorizontalFilter(unittest.TestCase):
def setUp(self):
"""Create data to use for testing."""
self.data = SampleData().get... |
11514711 | from onir import metrics as _metrics
class JudgedMetrics(_metrics.BaseMetrics):
QRELS_FORMAT = 'dict'
RUN_FORMAT = 'dict'
def supports(self, metric):
metric = _metrics.Metric.parse(metric)
if metric is None:
return False
return metric.name in ('judged',) and len(metric... |
11514720 | from ..factory import Method
class deleteSupergroup(Method):
supergroup_id = None # type: "int32"
|
11514721 | import collections
import signal
import traceback
from twisted.internet import task
# These values are seconds
CANCEL_INTERVAL = 0.1
MAX_DELAY = 0.5
class HangWatcher(object):
"""
Object which watches a L{twisted} reactor to determine whether the
reactor is hung
@ivar cancel_interval: how often to ... |
11514753 | import pathlib
from setuptools import setup
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
name="ssgetpy",
version="1.0-pre2",
description="A Python interface to the SuiteSparse Matrix Collection",
author="<NAME>",
author_email="<EMAIL>",
url="http://ww... |
11514797 | import sys, os, lucene, threading, time
import math
from multiprocessing import Pool
import shutil
from datetime import datetime
from org.apache.lucene import analysis, document, index, queryparser, search, store, util
from java.nio.file import Paths
from org.apache.lucene.analysis.miscellaneous import LimitTokenCoun... |
11514821 | import sys
sys.path.append("../../")
from appJar import gui
def press(btn):
if btn == "SEARCH":
app.searchGoogleMap("m1", app.getEntry("e1"))
elif btn == "ZOOM":
app.zoomGoogleMap("m1", int(app.getEntry("e1")))
elif btn == "TERRAIN":
app.setGoogleMapTerrain("m1", app.getEntry("e1... |
11514832 | import pytest
from hippy.objects.strobject import W_ConstStringObject
from hippy.objects.intobject import W_IntObject
from testing.test_interpreter import BaseTestInterpreter, hippy_fail
class TestReflectionClass(BaseTestInterpreter):
def test_constants(self):
output = self.run("""
echo Refl... |
11514839 | import os
from contextlib import contextmanager
from mach.exceptions import MachError
_ignore_var_not_found = False
class EmptyVar(str):
pass
IGNORED_EMPTY_VAR = EmptyVar("")
class VariableNotFound(MachError):
def __init__(self, var_name: str, pool_name="variables"):
super().__init__(f"Variable ... |
11514875 | import numpy as np
from scipy import stats
from sranodec.util import marge_series, series_filter
class Silency(object):
def __init__(self, amp_window_size, series_window_size, score_window_size):
self.amp_window_size = amp_window_size
self.series_window_size = series_window_size
self.scor... |
11514877 | from os import path
from setuptools import setup
readme_fn = path.join(path.dirname(__file__), "README.rst")
with open(readme_fn) as fp:
readme_text = fp.read()
cli_tools = ["spritemapper = spritecss.main:main"]
setup(name="spritemapper", version="1.0.0",
url="http://yostudios.github.com/Spritemapper/",
... |
11514953 | from atsd_client import connect, connect_url
from atsd_client.services import EntitiesService, SeriesService
from atsd_client.models import SeriesDeleteQuery
'''
Delete series for all metrics for the specified entity with names starting with the specified prefix.
'''
# Connect to ATSD server
# connection = connect('/... |
11514999 | from baremetal import *
from math import pi, sin, cos
import sys
from half_band_filter import half_band_filter
from cordic import rectangular_to_polar
from scale import scale
def upconverter(clk, i, q, stb):
phase, _ = counter(clk, 0, 3, 1, en=stb)
i, q = i.subtype.select(phase, i, -q, -i, q), q.subtype.sele... |
11515010 | import os
import click
from sotabenchapi import consts
from sotabenchapi.config import Config
from sotabenchapi.client import Client
@click.group()
@click.option(
"--config",
"config_path",
type=click.Path(exists=True),
envvar="SOTABENCH_CONFIG",
help="Path to the alternative configuration file.... |
11515036 | from __future__ import division, print_function
from __future__ import absolute_import
from moha.system.basis.gaussian_orbital import *
from moha.system.basis.slater_determinant import *
|
11515050 | from marshmallow import Schema, fields, validate
from werkzeug.exceptions import Forbidden
from opendc.models.model import Model
from opendc.exts import db
class ProjectAuthorizations(Schema):
"""
Schema representing a project authorization.
"""
userId = fields.String(required=True)
level = field... |
11515113 | import netCDF4 as nc
if __name__ == '__main__':
f = nc.Dataset(input())
print(f)
print(f.variables.keys())
print("---- Shapes ----")
for key in f.variables.keys():
print(f.variables[key].long_name)
print(f.variables[key].shape)
|
11515166 | import json
from textwrap import fill
from typing import Sequence, cast
from looker_sdk import models
from henry.modules import exceptions, fetcher, spinner
class Pulse(fetcher.Fetcher):
"""Runs a number of checks against a given Looker instance to determine
overall health.
"""
@classmethod
def... |
11515173 | import dash_html_components as html
from dash import Dash
from dash.dependencies import Input, Output
from dash_extensions.websockets import SocketPool, run_server
from dash_extensions import WebSocket
# Create example app.
app = Dash(prevent_initial_callbacks=True)
socket_pool = SocketPool(app)
app.layout = html.Div... |
11515229 | from .aiogithub import GitHub
__all__ = ('GitHub',)
try:
from aiogithub.version import version as __version__
except ImportError:
from setuptools_scm import get_version
__version__ = get_version(root='..', relative_to=__file__)
|
11515235 | import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
test_dir = os.path.join(current_dir, '..')
project_dir = os.path.join(test_dir, '..', '..')
sys.path.insert(0, project_dir)
|
11515270 | import torch
from torch.autograd.function import InplaceFunction
class Zoneout(InplaceFunction):
r"""During training an RNN, randomly swaps some of the elements of the
input tensor with its values from a prevous time-step with probability *p*
using samples from a bernoulli distribution. The elements to ... |
11515284 | from __future__ import absolute_import
from __future__ import print_function
import os
import veriloggen
import types_axi_read_lite
def test(request):
veriloggen.reset()
simtype = request.config.getoption('--sim')
rslt = types_axi_read_lite.run(filename=None, simtype=simtype,
... |
11515301 | import boto3
from celery import Celery
import config
app = Celery('tasks', broker='redis://localhost//', backend = 'redis://localhost/')
app.conf.task_routes = {'s3_logs.tasks.*': {'queue': 'logs'}}
import s3_logs.tasks
import s3_events.tasks
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.