id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9946562 | from setuptools import setup
from setuptools.extension import Extension
sources = ['module.m', 'Vandercook.m', ]
frameworks = ['AppKit', 'Foundation', 'Quartz', 'CoreText',]
flags = sum((['-framework', fmwk] for fmwk in frameworks), [])
cFoundry = Extension('cFoundry', sources=sources, extra_link_args=flags)
setup (n... |
9946569 | import curses
import curses.wrapper
from Installer import Installer
# Change this depending on your installer behaviour
filesdir = "root:/install-files"
# Will get set by "selectDest()"
installdir = "pedigree:/test"
def main(stdscr):
global filesdir, installdir
return 0
inst = Installer(stdscr, "Pedigree", f... |
9946606 | from collections import namedtuple
import os
import string
from typing import Dict, List, Optional, Set
import attr
import rdflib
from SPARQLWrapper import SPARQLWrapper, JSON
from SPARQLWrapper.SPARQLExceptions import EndPointInternalError
from diskcache import Cache
from gleipnir.config import PATH_WWO_PERSONOG... |
9946608 | from datetime import datetime
# NOTE REGARDING TIMESTAMPS:
# It is currently difficult to have the timestamps calculated by the
# database in a portable way, so we're doing it in the client. This
# also saves us from needing to postfetch on postgres. HOWEVER: it
# relies on the client's clock being set correct... |
9946611 | from mozillians.graphql_profiles.utils import parse_datetime_iso8601, retrieve_v2_profile
from mozillians.users.models import Vouch
DATETIME_ATTRS = ['created', 'last_modified']
def dino_park_resolver(attname, default_value, root, info, *args):
"""Custom resolver for all the attributes in a profile."""
pro... |
9946621 | import copy
import torch
import numpy as np
import torch.utils.data as D
import utils as U
class MultiSentWordDataset(D.Dataset):
def __init__(self, *paths):
self.data = [
list(U.FileReader(path).sents()) for path in paths
]
assert all(len(d) == len(self.data[0]) for d in se... |
9946669 | import re
from key_value_store import KeyValueStore
from tools.doc_inherit import doc_inherit
INT_ID = 'int_%s'
SET_ID = 'set_%s'
VEC_ID = 'vector_%s'
INT_ID_EX = re.compile(r'int_([\S]*)')
SET_ID_EX = re.compile(r'set_([\S]*)')
VEC_ID_EX = re.compile(r'vector_([\S]*)')
class DictionaryStore(KeyValueStore):
def... |
9946672 | from __future__ import print_function, absolute_import, unicode_literals
import heapq
# Local
from .base import PureOkapiMixin
class PriorityQueue:
def __init__(self):
self.elements = []
def empty(self):
return len(self.elements) == 0
def put(self, item, priority):
heapq.heappus... |
9946717 | import asyncio
import contextvars
import functools
from asyncio import AbstractEventLoop
from importlib import import_module
from typing import Any, Optional, Type, Callable, Awaitable, Union, List
import numpy as np
import requests
from pydantic import BaseSettings
from mlserver.codecs import StringCodec, NumpyCodec... |
9946741 | import pytest
from django.contrib.auth.models import User
from django.test import Client
from django.urls import reverse
@pytest.mark.parametrize("url_name", ["import_batch-ui-list", "import_batch-ui-create"])
def test_import_urls_requires_superuser(
valid_user: User,
admin_user: User,
client: Client,
... |
9946806 | import re
class SimulationConditions(object):
""" Parameters about the simulations. Provide these parameters to plot the
graph of the simulation and draw the animation of the simulation.
Attributes:
simulation_time(): Returns the simulation time.
sampling_period(): Return... |
9946830 | SETTINGS = {'random seed': 1,
'num class labels': 10,
'learning rate': 0.001,
'batch size': 128,
'num epochs': 10,
'cuda device': 0,
'num workers': 0,
'validation fraction': 0.1}
|
9946897 | def foo():
return 1 # breakpoint
def main():
import linecache
import time
code = 'foo()'
# Intermediate <string> stack frame will have no source.
eval(code)
co_filename = '<something>'
co = compile(code, co_filename, 'exec')
# Set up the source in linecache. Python doesn't hav... |
9946901 | from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
setup(
name='arcplus',
version='0.1',
description="a few things missing from Esri's arcpy",
url='https://github.com/maphew/arcplus',
autho... |
9946904 | from __future__ import print_function
import argparse
import sys,os
import numpy as np
from sklearn.metrics import average_precision_score
from sklearn import preprocessing
from sklearn.externals import joblib
from IPython import embed
lb=preprocessing.LabelBinarizer()
Actions=['BG','BaseballPitch','Basketba... |
9946926 | import argparse
import numpy as np
from squeezenet import SqueezeNet
import os
from keras.preprocessing import image
from keras.applications.imagenet_utils import preprocess_input
import time
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
SIZE = 227
def main():
parser = argp... |
9946932 | import torchvision.datasets as D
from PIL import Image
from typing import Tuple, Any
import numpy as np
class MNIST(D.MNIST):
"""`MNIST <http://yann.lecun.com/exdb/mnist/>`_ Dataset.
Args:
root (str): Root directory of dataset where ``MNIST/processed/training.pt``
and ``MNIST/processed/t... |
9946963 | from dartcms.apps.auth.utils import get_user_model
from django.utils.translation import ugettext_lazy as _
from .managers import SiteUserManager
User = get_user_model()
class SiteUser(User):
class Meta:
verbose_name = _('Site User')
verbose_name_plural = _('Site Users')
proxy = True
... |
9946975 | df['Helpful %'] = np.where(df['helpful_votes'] > 0,
df['helpful_votes'] / df['total_votes'], -1)
df['% Upvote'] = pd.cut(df['Helpful %'],
bins = [-1, 0, 0.2, 0.4, 0.6, 0.8, 1.0],
labels = ['Empty', '0-20%', '20-40%',
'40-60%', '60-80%', '80-100%']
, include_lowest =... |
9947020 | import numpy as np
import torch
import rlkit.torch.pytorch_util as ptu
def get_flattened_grads(parameter_groups):
"""Flattens a variables and their gradients.
"""
parameter_list = get_flat_params(parameter_groups)
grads = [param.grad for param in parameter_list]
# return torch.cat([grad.view([num_... |
9947035 | from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
import discord
from ditto.types import User
from ..game import Player
from .select import *
if TYPE_CHECKING:
from .game import GameUI
__all__ = (
"PlayerButton",
"PlayerUI",
)
class PlayerButton(SelectButton[Player[User],... |
9947038 | import numpy as np
from wisdem.commonse import eps
def steel_cutting_plasma_time(length, thickness):
# Length input as meters, thickness in mm
# time = length / (-0.180150943 + 41.03815215/(1e3*thickness+eps)) # minutes
# Better conditioned polynomial fit to the above correlation
pp = np.array([2.449... |
9947043 | import json
import os
import sys
from enum import IntEnum as Enum
import ZODB
import ZODB.FileStorage
import persistent
import transaction
import ArtsInfo
from utils import decodeValue
import Levenshtein
bundle_dir = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
class ArtifactType(Enum):
... |
9947059 | from django.core.management.base import BaseCommand
from application.models import MovieDirectory
class Command(BaseCommand):
help = "Remove a movie directory"
def add_arguments(self, parser):
parser.add_argument('path', type=str)
def handle(self, *args, **options):
for directory in Movi... |
9947100 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.first_year_gpa import first_year_gpa
def test_first_year_gpa():
"""Test module first_year_gpa.py by downloading
first_year_gpa.csv and testin... |
9947174 | from urllib.parse import parse_qs, urlparse
import pytest
import responses
from busy_beaver.apps.github_integration.oauth.oauth_flow import GitHubOAuthFlow
from busy_beaver.common.wrappers.github import BASE_URL as GITHUB_BASE_URL
pytest_plugins = ("tests._utilities.fixtures.slack",)
@pytest.mark.end2end
@response... |
9947217 | from io import StringIO
def to_string(obj):
stream = StringIO()
obj._serialize(stream)
s = stream.getvalue()
stream.close()
return s
def to_file(obj, filename):
"""
Serialize data to test file (files file)
obj: must have serialize method
filename: the name of t... |
9947225 | try:
import MySQLdb
from MySQLdb.cursors import (
Cursor,
DictCursor,
)
except ImportError:
raise ImportError(
'In order to use quma with MySQL you need to install mysqlclient'
)
from .. import (
conn,
exc,
)
class Connection(conn.Connection):
def __init__(self... |
9947226 | import sys
import gzip
import pandas as pd
import numpy as np
def getDP(sample_info):
try:
dp = float(sample_info.split(':')[2])
except:
dp = np.nan
return dp
def main():
region = 0
temp = {}
result = {}
region_size = {}
input = sys.argv[1]
output = sys.argv[2]
step = int(sys.argv[3])
... |
9947244 | class Queue:
"""
A queue using two stacks (head and tail), the head
stack keeps the elements in a queue order, it means
ready to dequeue or print the top element.
When necessary the last elements in the tail stack
are moved to the head stack. The normalize_head method
verify if its necessary... |
9947263 | from flask import Flask, request
app = Flask(__name__)
PORT = 7000
@app.route('/', methods=["GET"])
def home():
remote_user = request.headers.get('REMOTE_USER')
return "Hello {}, this is service2.".format(remote_user)
if __name__ == "__main__":
app.run(port=PORT, debug=True)
|
9947266 | def copy_untouched_quantities(old_state, new_state):
for key in old_state.keys():
if key not in new_state:
new_state[key] = old_state[key]
def add(state_1, state_2):
out_state = {}
if 'time' in state_1.keys():
out_state['time'] = state_1['time']
for key in state_1.keys():
... |
9947285 | import logging
import os
import subprocess
from typing import Dict, List, Tuple
from flask import Flask, g, request, redirect, send_from_directory
from flask import session as flask_session
from flask_compress import Compress
from flask_cors import CORS
from flask_httpauth import HTTPBasicAuth
from prometheus_client i... |
9947293 | from aws_cdk import (
core,
aws_lambda
)
lambda_source_dirPath = "./lambda-source"
python_source_file_name = "hellopython"
lambda_function_name = "lambda_handler"
class PythonLambdaSimpleStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(sco... |
9947313 | from MA import *
import tempfile
from genome_reconstruction import *
def insert_reads(db_conn, reference, parameter_set, dataset_name):
print("inserting calls...")
ground_truth_id = insert_calls(db_conn, dataset_name)
print("done")
print("creating fmd index...")
fm_index = FMIndex(reference)
p... |
9947321 | from threading import Semaphore
class FooBar:
def __init__(self, n):
self.n = n
self.foosema = Semaphore(1)
self.barsema = Semaphore(0)
def foo(self, printFoo):
for i in range(self.n):
self.foosema.acquire()
printFoo()
self.barsema.release()
... |
9947348 | from tree_sitter import Language, Parser
Language.build_library(
'build/my-languages.so',
[
'/root/test_tree-sitter/tree-sitter-c-sharp',
'/root/test_tree-sitter/tree-sitter-java',
'/root/test_tree-sitter/tree-sitter-python'
]
) |
9947354 | import os
import json
from azureml.core import Workspace, Experiment
from azureml.core.authentication import ServicePrincipalAuthentication
from azureml.pipeline.core import PipelineRun
from azureml.train.hyperdrive import HyperDriveRun
from azureml.exceptions import AuthenticationException, ProjectSystemException, Az... |
9947359 | import os
import sys
import setuptools
from setuptools.command.install import install
import deidentify
VERSION = deidentify.__version__
with open("README.md", "r") as fh:
readme = fh.read()
class VerifyVersionCommand(install):
"""Custom command to verify that the git tag matches the version of the python... |
9947396 | import PySimpleGUI as sg
from ..model.objectdata import ObjectData
from ..model.search import SearchableList
from ..view import newvariation
from . import get_string_unit, filter_listbox
from myconfigparser import Section
def open_window(data):
options = SearchableList()
for d in data:
deco = Section(... |
9947430 | import unittest
from problog.web import server, server_debug
class TestWeb(unittest.TestCase):
def test_web(self):
server.main(["--local", "--test"])
if __name__ == "__main__":
unittest.main()
|
9947482 | from xv_leak_tools.test_framework.test_case import TestCase
from xv_leak_tools.log import L
class TestPass(TestCase):
"""Dummy test case for testing library functionality. This test does nothing other than
deliberately pass."""
def test(self):
L.info("This test does nothing but pass")
L.de... |
9947486 | import logging
import pathlib
import shutil
import cookiecutter
from cookiecutter import generate
try:
# Python < 3.9
import importlib_resources as ilr
except ImportError:
import importlib.resources as ilr
from . import appdir_template
_log = logging.getLogger(__name__)
class Step:
@staticmethod... |
9947496 | from nose2.tools import such
with such.A("test scenario with errors") as it:
@it.has_setup
def set_value():
it.value = 1
@it.should("check that value == 1")
def test_passes(case):
case.assertEqual(it.value, 1)
@it.should("check that value == 2 and fail")
def test_fails(case):... |
9947534 | from rest_framework import mixins, viewsets
from axians_netbox_pdu.filters import PDUConfigFilter, PDUStatusFilter
from axians_netbox_pdu.models import PDUConfig, PDUStatus
from .serializers import PDUConfigSerializer, PDUStatusSerializer
class PDUConfigViewSet(
mixins.CreateModelMixin,
mixins.ListModelMixi... |
9947548 | import torch
import torch.utils.data
from torch import nn
class CF_VAE(nn.Module):
def __init__(self, d, encoded_size):
super(CF_VAE, self).__init__()
self.encoded_size = encoded_size
self.data_size = len(d.ohe_encoded_feature_names)
self.minx, self.maxx, self.encoded_categorica... |
9947559 | import socket
from tlp import *
class Injector:
def __init__(self, ip="127.0.0.1", port=2345):
self.ip = ip
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.sendto(bytes([0]), (self.ip, self.port))
def run(self):
dwords = []
... |
9947614 | import hydra
import wandb
import warnings
import random
import logging
import os
from pathlib import Path
import sys
import torch
from omegaconf import OmegaConf
from upcycle.scripting import startup
from upcycle.logging.analysis import flatten_config
from gpytorch.settings import max_cholesky_size
@hydra.main(con... |
9947619 | import os
import sys
from tempfile import mkdtemp
# os.environ["CURL_CA_BUNDLE"] = "/etc/ssl/certs/ca-certificates.crt"
import mercantile
import json
from shapely import geometry, ops
import s3fs
import boto3
from subprocess import Popen
import shlex
import click
import tqdm
sys.path.append("../../../model/rob... |
9947621 | import py
from ctypes import *
import sys
class TestKeepalive:
""" Tests whether various objects land in _objects
or not
"""
def test_array_of_pointers(self):
# tests array item assignements & pointer.contents = ...
A = POINTER(c_int) * 24
a = A()
l = c_long(2)
... |
9947647 | from glob import glob
from PIL import Image
import pickle as pkl
import os
import configargparse
import configparser
import torch
import numpy as np
import argparse
import sys
import matplotlib.pyplot as plt
import yaml
from munch import munchify
import json
import PIL
from parse import parse
import collections
import ... |
9947657 | import pytest
from typing import Dict, List
from relevanceai import Client
from tests.globals.constants import generate_dataset_id
@pytest.fixture(scope="function")
def pandas_dataset(
test_client: Client,
pandas_documents: List[Dict],
):
test_dataset_id = generate_dataset_id()
response = test_cli... |
9947679 | class BlatannException(Exception):
pass
class InvalidStateException(BlatannException):
pass
class InvalidOperationException(BlatannException):
pass
class TimeoutError(BlatannException):
pass
class DecodeError(BlatannException):
pass
|
9947733 | import os
import io
from PIL import Image
from torch.utils.data import Dataset
""" This file defines a template for task-specific dataset.
"""
def add_parser_arguments(parser):
""" Add the arguments required by all types of dataset here.
Please add task-specific dataset arguments into the function
of... |
9947760 | import os
import time
import traceback
import threading
from packet import ScapyPacket
from or_event import OrEvent
from utils import Utils
from logger import Logger
def isLinkUp(intf, dbg = False):
flags_path = "/sys/class/net/{}/operstate".format(intf)
if os.path.isfile(flags_path):
if dbg:
os... |
9947769 | from ..helpers import IFPTestCase
class TestHelpVerb(IFPTestCase):
def test_help_prints_help_msg(self):
self.game.turnMain("help")
self.assertIn("Type INSTRUCTIONS", self.app.print_stack.pop())
def test_instructions_prints_instructions(self):
self.game.turnMain("instructions")
... |
9947791 | import os
import json
import random
import torch
import argparse
import importlib
from .utils import eval_distinct, calculate_ppl
from .pycocoevalcap.bleu.bleu import Bleu
from .fairness_test import bias_evaluate
def score(refs, hypos):
'''
:param refs: instance_num x refer_num x str
:param hypos: instance... |
9947828 | from typing import Dict, Optional
from .base import GatewayBase, SIGNAL_MQTT_PUB
from .. import utils
from ..device import XDevice
from ..mini_mqtt import MQTTMessage
# noinspection PyMethodMayBeStatic,PyUnusedLocal
class MIoTGateway(GatewayBase):
def miot_init(self):
self.dispatcher_connect(SIGNAL_MQTT_... |
9947838 | import io
import logging
import os
import numpy as np
from speech_datasets.transform.interface import TransformInterface
from speech_datasets.utils import get_root
from speech_datasets.utils.readers import read_cmvn_stats
logger = logging.getLogger(__name__)
class CMVN(TransformInterface):
def __init__(self, c... |
9947841 | from collections import OrderedDict
from rest_framework.fields import SkipField
"""
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
... |
9947844 | from time import time
class FPS_Monitor( object ):
def __init__( self, delta = 2.0 ):
super( FPS_Monitor, self ).__init__()
self.time = time()
self.frame_count = 0
self.print_time = delta
def increment_frame( self ):
# update our FPS
self.frame_count += 1
... |
9947931 | import pathlib
import pytest
from publish import config as config_module
@pytest.fixture
def config():
path = pathlib.Path(__file__) / '..' / '..' / 'configs' / 'basic.toml'
return config_module.Config(path)
|
9947949 | import re
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
from .. utils import SAMPLE_SUBSTITUTIONS
class BytesTests(TranspileTestCase):
pass
class BuiltinBytesFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
function = "bytes"
small_ints = True
substitutions = SAMPLE_SUBS... |
9947959 | class Solution:
def maxDepth(self, s: str) -> int:
depth = maxDepth = 0
for char in s:
if char == '(':
depth += 1
maxDepth = max(maxDepth, depth)
elif char == ')':
depth -= 1
return maxDepth |
9947963 | import matplotlib.pyplot as plt
import matplotlib.style as style
from data.cifar10_dataset import Cifar10Dataset
from data.config.cifar10_config import set_cifar_configs
from data.config.isic_config import set_isic_configs
from data.config.retinopathy_config import set_retinopathy_configs
from data.isic_dataset import... |
9947967 | from typing import Dict, List
import emoji
from colorama import init
from colorama import Fore, Style
import time
import os, sys
import inspect
import warnings
import glob
import shutil
import toml
from tqdm import tqdm
from inversionson import InversionsonError, InversionsonWarning
from salvus.flow.api import get_site... |
9947977 | from multiprocessing import Pool
from struct import Struct
import heapq
from bisect import bisect_left
import numpy as np
import yaml, glob
import argparse
import random
import os
import time
import sys
import json
import base64
import logging
from tqdm import tqdm
sys.path.append(os.path.join(os.path.dirname(__file__... |
9948002 | import functools
import tensorflow as tf
from .doc_utils import add_name_arg_doc
from .type_utils import is_tensor_object
__all__ = [
'get_static_shape', 'get_batch_size', 'get_rank', 'get_shape',
'get_dimension_size', 'get_dimensions_size', 'resolve_negative_axis',
'concat_shapes', 'is_shape_equal',
]
... |
9948010 | from flask.ext.admin import Admin
from app.core.models import User, Post, Category, Blogroll
from app.core.admin.views import AdminUserView, AdminIndexView, AdminPostView, AdminCategoryView, AdminBlogrollView
def create_admin(app=None, db=None):
admin = Admin(app, 'BlogAdmin', index_view=AdminIndexView(), base_te... |
9948032 | from share.bin.util import command
from share.ingest.scheduler import IngestScheduler
from share.models import SourceUniqueIdentifier
from share.models.jobs import IngestJob
from share.tasks import ingest as ingest_task
from share.util.osf import osf_sources
@command('Create IngestJobs for the specified RawDatum(s)')... |
9948070 | import asyncio
import os
import signal
from asyncio import CancelledError
from collections import Counter
import pytest
from scrapy_autoextract.task_manager import TaskManager
from tests.utils import async_test
class _TasksBench:
def __init__(self):
self.lock = asyncio.Lock()
self.manager = TaskM... |
9948079 | from typing import List
import torch
import random
from torch.utils.data import Dataset
from src.data.typed_table import TypedColumnSequenceDataset
from src.geometry.skeleton import Skeleton
class BaseBatchedSequenceDataset(Dataset):
"""
Base class for batched sequence data. Defines the interface the batched ... |
9948090 | from __future__ import division
import numpy as np
np.seterr(invalid='raise')
import copy
from scipy.special import digamma
from HDP.basic.distributions import Multinomial
from HDP.util.general import cumsum, rcumsum
################# HDP dishes matrix
class _HDPMatrixBase(object):
def __init__(self,num_state... |
9948094 | import json
from pathlib import Path
import pytest
from libcflib.analyze_pkgs import (
file_path_to_import,
get_imports_and_files,
extract_importable_files,
)
STREAMZ_IMPORTS = {
"streamz",
"streamz.batch",
"streamz.collection",
"streamz.compatibility",
"streamz.core",
"streamz.da... |
9948106 | import os
import numpy as np
from compas.datastructures import Mesh
import logging
import compas_slicer.utilities as utils
from compas_slicer.slicers import InterpolationSlicer
from compas_slicer.post_processing import simplify_paths_rdp
from compas_slicer.pre_processing import InterpolationSlicingPreprocessor
from com... |
9948156 | from sys import argv
out = ''
with open(argv[1]) as file:
for line in file.readlines():
line = line.strip('\n').strip('\r')
out += line + '\tAF=1\tGT\t1/1\n'
with open(argv[2], 'w') as file:
file.write(out)
|
9948174 | from nksnd.utils import numerics
def set_log_alpha(d, graph):
for last_pos in range(2 + graph.x_length):
for node in graph.nodes_list[last_pos]:
prev_nodes = graph.nodes_list[node.start_pos]
node.log_alpha = node.weight
for prev_node in prev_nodes:
w = d.... |
9948181 | import os
import torch
import pytorch_lightning as pl
from torch.utils.data import DataLoader, Dataset
import numpy as np
import os
import glob
import hydra
class JointLimDataSet(Dataset):
def __init__(self, dataset_path, subject):
dataset_path = hydra.utils.to_absolute_path(dataset_path)
seqs =... |
9948201 | from datetime import datetime, timezone
from typing import TypeVar
from pydantic import UUID4, BaseModel, Field
def now_utc():
return datetime.now(timezone.utc)
class BaseAccessToken(BaseModel):
"""Base access token model."""
token: str
user_id: UUID4
created_at: datetime = Field(default_facto... |
9948220 | import torch
import torchvision
import torchvision.transforms as transforms
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Function, Variable
from torch.nn.parameter import Parameter
from torch.distributions import Bernoulli
... |
9948224 | import logging
import robot.running
from robot.output import librarylogger as log
from robot.libraries.BuiltIn import BuiltIn
class AssistantLibrary:
def start_assistant(self):
log.console('\nHello, how may i help you today?\n')
while True:
keyword = raw_input().strip()
... |
9948252 | import test
import unittest
from unittest.mock import Mock
from applications.editArticle.controllers import save_image
class Object(object): pass
class SaveCoverImageTest(unittest.TestCase, test.CustomAssertions):
"""Test all behavior related with te cover image.
"""
def setUp(self):
os = Mock()... |
9948253 | import sys
import pytest
import repobee_plug as plug
from _repobee.ext import studentsyml
def test_raises_PlugError_on_bad_syntax(tmp_path):
students_file = tmp_path / "students.yml"
students_file.write_text(
"""
first-team:
members: [first, second, third
)
""",
encoding=sys.getdefaulten... |
9948259 | from sqlalchemy import Column, exc
from clickhouse_sqlalchemy import types, Table
from tests.testcase import BaseTestCase
from tests.util import with_native_and_http_sessions
@with_native_and_http_sessions
class LimitTestCase(BaseTestCase):
table = Table(
't1', BaseTestCase.metadata(),
Column('x'... |
9948273 | from typing import Union
from pybraries.helpers import extract
from pybraries.make_request import make_request
def sub_api(action, manager="", package="", *args, **kwargs) -> Union[bool, str]:
url_end_list = [
"https://libraries.io/api/subscriptions"
] # start of list to build url
more_args = []... |
9948282 | import sys
sys.path.insert(0, '../')
import bayesnewton.kernels as kernels
import numpy as np
from bayesnewton.utils import transpose
from jax import vmap
import jax.numpy as jnp
from jax.scipy.linalg import cho_factor
np.random.seed(3)
def wiggly_time_series(x_):
noise_var = 0.15 # true observation noise
r... |
9948318 | import os
import pandas as pd
from sklearn.model_selection import StratifiedKFold
def extract_files(pos_file, neg_file, domain):
with open(pos_file, 'r', encoding='utf-8') as f:
pos = f.readlines()
with open(neg_file, 'r', encoding='utf-8') as f:
neg = f.readlines()
corpus_pos = []
fl... |
9948322 | from django.test import TestCase
from ..models import Category, Product
from ..queries import products_list, products_list_select_related
class ProductsTestMixin(object):
def setUp(self):
category = Category.objects.create(name="Test category")
for num in range(1, 10):
Product.object... |
9948355 | from starlette.requests import Request
from starlette.responses import JSONResponse
from asyncpg.exceptions import UniqueViolationError
from .dataaccess import featureda
from .dataaccess import releasesda
from . import permissions
from . import toggles
from . import auditing
from . import metrics
async def create_fe... |
9948388 | import dash_echarts
import dash_html_components as html
import dash_core_components as dcc
option = {
"tooltip": {"trigger": "axis", "axisPointer": {"type": "shadow"}},
"legend": {
"data": ["Direct", "Mail Ad", "Affiliate Ad", "Video Ad", "Search Engine"]
},
"grid": {"left": "3%", "right": "4%... |
9948391 | import os
import time
import pytest
from tests.models import EmployeeInfo
@pytest.mark.asyncio
async def test_query_without_caching(loaded_database_and_model_no_cache):
db, Employee = loaded_database_and_model_no_cache
sel = await Employee.select('*')
sel2 = await Employee.select('*')
assert len(sel... |
9948453 | import re
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
def dfs(i, j, parent):
letter = board[i][j]
node = parent[letter]
if '$' in node:
ret.append(node.pop('$'))
board[i][j] = ''
... |
9948494 | from .aws import AWS, LambdaFunction # noqa
from .config import AWSConfig # noqa
from .s3 import S3 # noqa
|
9948541 | doors = [False]*100
for i in range(0,100):
j = i
while j < 100:
doors[j] = not doors[j]
j += i + 1
for door in range(0,100):
if doors[door]:
print("Door "+ str(door+1) + " is open.")
|
9948559 | from typing import Iterable
import torch as t
def compute_centered_ranks(x: Iterable[float]) -> Iterable[float]:
"""
Compute centered ranks, e.g. [-81.0, 11.0, -0.5] --> [-0.5, 0.5, 0.0]
"""
x = t.tensor(x)
assert x.ndim == 1
ranks = t.zeros((len(x),), dtype=t.long)
ranks[x.argsort()] = t.... |
9948568 | from cook import core
@core.rule
def run(
command, outputs, inputs=None, message=None, env=None, timeout=None,
cwd=None
):
inputs = core.resolve(inputs or [])
outputs = core.build(outputs)
command[0] = core.which(command[0])
yield core.publish(
inputs=inputs + [command[0]],
ou... |
9948654 | import fileinput
from collections import defaultdict
from utils import parse_line
GOAL = 'shiny gold'
graph = defaultdict(set)
for i, line in enumerate(fileinput.input()):
line = line.strip()
color, rest = parse_line(r'(\w+ \w+) bags contain (.+)+', line)
rest = rest.replace('.', '').split(',')
for ... |
9948719 | import struct
from os import urandom
from util import transform
def read_random_bits(nbits: int) -> bytes:
"""
Reads 'nbits' random bits.
"""
nbytes, rbits = divmod(nbits, 8)
randomdata = urandom(nbytes)
if rbits > 0:
randomvalue = ord(urandom(1))
randomvalue >>=... |
9948746 | import copy
import string
import random
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
# function to make key => value dict lowercase
def multi_to_lower(old_dict, also_values=False):
new = {}
for key in old_dict:
new[key.lower()] = old_dict[key].lowe... |
9948793 | import unittest
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from ui import VisualTab
app = QApplication(sys.argv)
visualTab_widget = QWidget()
visualTab_widget_ui = VisualTab.Ui_visual_tab()
visualTab_widget_ui.setupUi(visualTab_widget)
class VisualTabTests(unittest.TestCase):
def test_defaults(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.