id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1626284 | import discord
import asyncio
import random
import steam
from steam.steamid import SteamId
from steam.steamprofile import SteamProfile
from steam.steamaccountuniverse import SteamAccountUniverse
from steam.steamaccounttype import SteamAccountType
from discord.ext import commands
from utils import checks
from mods.cog i... |
1626316 | import obspython as S
from itertools import cycle
class Example:
def __init__(self, source_name=None):
self.source_name = source_name
self.data = ""
def update_text(self):
source = S.obs_get_source_by_name(self.source_name)
if source is not None:
settin... |
1626363 | import logging
import unittest
import random
import copy
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence
from type_system import Type, PolymorphicType, PrimitiveType, Arrow, List, UnknownType, INT, BOOL
from program import Progra... |
1626385 | import importlib
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'api'
verbose_name = 'Api'
def ready(self):
importlib.import_module('api.signals')
|
1626400 | import requests, json
import pandas as pd
from dataiku.connector import Connector
import importio_utils
class ImportIOConnector(Connector):
def __init__(self, config):
"""Make the only API call, which downloads the data"""
Connector.__init__(self, config)
if self.config['api_url'].startswi... |
1626407 | from bisect import bisect
from biicode.common.utils.bii_logging import logger
import difflib
from biicode.common.exception import BiiException
def _lcs_unique(a, b):
# set index[line in a] = position of line in a unless
# a is a duplicate, in which case it's set to None
index = {}
for i in xrange(len(... |
1626426 | from setuptools import setup
from setuptools import find_packages
setup(
name="emojipastabot",
description="Generate emojipasta from text.",
version="1.0.0",
url="https://github.com/Kevinpgalligan/EmojipastaBot",
author="<NAME>",
author_email="<EMAIL>",
classifiers=[
"Programming La... |
1626433 | from aiochan import *
def cleanup():
print('Cleaned up')
async def boring(msg, quit):
c = Chan()
async def work():
i = 0
while True:
_, ch = await select((c, f'{msg} {i}'), quit)
if ch is quit:
cleanup()
await quit.put('See you!')
... |
1626434 | from PyObjCTools import NibClassBuilder, AppHelper
NibClassBuilder.extractClasses("MainMenu")
import MyView
AppHelper.runEventLoop()
|
1626436 | del_items(0x80132930)
SetType(0x80132930, "struct Creds CreditsTitle[6]")
del_items(0x80132AD8)
SetType(0x80132AD8, "struct Creds CreditsSubTitle[28]")
del_items(0x80132F74)
SetType(0x80132F74, "struct Creds CreditsText[35]")
del_items(0x8013308C)
SetType(0x8013308C, "int CreditsTable[224]")
del_items(0x801342BC)
SetTy... |
1626462 | import cartography.intel.aws.ec2.volumes
import tests.data.aws.ec2.volumes
TEST_ACCOUNT_ID = '000000000000'
TEST_REGION = 'eu-west-1'
TEST_UPDATE_TAG = 123456789
def test_load_volumes(neo4j_session):
data = tests.data.aws.ec2.volumes.DESCRIBE_VOLUMES
cartography.intel.aws.ec2.volumes.load_volumes(
ne... |
1626468 | import logging
from datetime import timedelta
from typing import Optional, Iterable, List
from homeassistant.components.climate import SUPPORT_TARGET_TEMPERATURE, SUPPORT_PRESET_MODE, HVAC_MODE_OFF, \
HVAC_MODE_HEAT
from homeassistant.components.climate.const import HVAC_MODE_AUTO, HVAC_MODE_COOL, CURRENT_HVAC_IDL... |
1626483 | from unittest import TestCase
from simplejson.compat import StringIO, long_type, b, binary_type, PY3
import simplejson as json
def as_text_type(s):
if PY3 and isinstance(s, binary_type):
return s.decode('ascii')
return s
class TestDump(TestCase):
def test_dump(self):
sio = StringIO()
... |
1626497 | import logging
import math
from copy import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.init import _calculate_fan_in_and_fan_out
def extract_top_level_dict(current_dict):
"""
Builds a graph dictionary from the passed depth_keys, value pair. Useful... |
1626502 | import pytest
def test_blurhash_decode(api):
fake_media_dict = {
'width': 320,
'height': 240,
'blurhash': '=~NdOWof1PbIPUXSvgbI$f'
}
decoded_image = api.decode_blurhash(fake_media_dict)
assert len(decoded_image) == 9 * 16
assert len(decoded_image[0]) == 16
decoded_i... |
1626505 | try:
import OpenGL.GL as gl
except:
from galry import log_warn
log_warn(("PyOpenGL is not available and Galry won't be"
" able to render plots."))
class _gl(object):
def mock(*args, **kwargs):
return None
def __getattr__(self, name):
return self.mock
g... |
1626638 | r"""
Local Frames
The class :class:`LocalFrame` implements local frames on vector bundles
(see :class:`~sage.manifolds.vector_bundle.TopologicalVectorBundle` or
:class:`~sage.manifolds.differentiable.vector_bundle.DifferentiableVectorBundle`).
For `k=0,1,\dots`, a *local frame* on a vector bundle `E \to M` of class `... |
1626722 | import sys, os, time, json, random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
sys.path.append(os.getcwd())
class Structure(object):
def __init__(self):
self.first_title = None
self.secord_title = None
self.font_path = "cover_generator/font"
with open("cover_genera... |
1626746 | import subprocess
from lib.resp import Resp
from lib import settings, utils
from subprocess import getoutput
from lib.interface.mac_gen import MacGen
class InterfaceBackend:
wlan = None
monitor_mode = "monitor"
managed_mode = "managed"
interfaces = [
settings.SCAN_INTERFACE,
settings.... |
1626766 | from collections import defaultdict
import data_io
def main():
print("Getting features for valid papers from the database")
data = data_io.get_features_db("ValidPaper")
author_paper_ids = [x[:2] for x in data]
features = [x[2:] for x in data]
print("Loading the classifier")
classifier = data_i... |
1626792 | from __future__ import division
import sys
import kenlm
from marmot.features.feature_extractor import FeatureExtractor
class LMFeatureExtractor(FeatureExtractor):
def __init__(self, lm_file):
self.model = kenlm.LanguageModel(lm_file)
def get_features(self, context_obj):
#sys.stderr.write("S... |
1626794 | from __future__ import unicode_literals
import codecs
import numpy
import os
import transaction
from base64 import b64decode
from hashlib import sha1
import itertools
from pyramid_addons.helpers import (http_created, http_gone, http_ok)
from pyramid_addons.validation import (EmailAddress, Enum, List, Or, String,
... |
1626851 | import os
from aioresponses import aioresponses
from aiounittest import AsyncTestCase, futurized
from asyncopenstackclient import AuthPassword
from unittest.mock import patch
class TestAuth(AsyncTestCase):
def setUp(self):
self.auth_args = ('http://url', 'm_user', 'm_pass', 'm_project',
... |
1626859 | import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import utils.distance as distance
import utils.inertia as inertia
from swarm import Swarm, Particle
import functions
|
1626863 | from zlib import decompress
def get_row(db, name):
query = "SELECT rowid, sz FROM sqlar WHERE name=:name"
return db.cursor().execute(query, {"name": name}).fetchone()
def get_blob(db, row):
return db.blobopen("main", "sqlar", "data", row["rowid"], False)
def get_data(db, row):
blob = get_blob(db, ... |
1626900 | from flask import url_for
from arrested import ArrestedAPI, Resource, Endpoint
def initialise_app_via_constructor(app):
"""Test instantiating ArrestedAPI obj passing flask app object directly
"""
api_v1 = ArrestedAPI(app)
assert api_v1.app == app
def defer_app_initialisation(app):
"""Test defe... |
1626909 | import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=False)
xs = mnist.test.images
ys = mnist.test.labels
np.save('orig_images.npy', xs)
np.save('orig_labels.npy', ys)
|
1627007 | import pyjd
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.DockPanel import DockPanel
from pyjamas.ui.HTML import HTML
from pyjamas.JSONService import JSONProxy
from pyjamas import DOM
from pyjamas import Factory
from pyjamas import History
from pyjamas import Window
from pyjamas import logging
log = lo... |
1627039 | from arepl_pickler import specialVars, pickle_user_vars, pickle_user_error
import arepl_python_evaluator as python_evaluator
import arepl_jsonpickle as jsonpickle
def test_special_floats():
x = float("infinity")
y = float("nan")
z = float("-infinity")
vars = jsonpickle.decode(pickle_user_vars(locals()... |
1627042 | import logging
from argparse import Namespace
from re import RegexFlag, fullmatch
from typing import Optional, Callable, Awaitable
from aiohttp.hdrs import METH_OPTIONS
from aiohttp.web import HTTPRedirection, HTTPNotFound, HTTPBadRequest, HTTPException, HTTPNoContent
from aiohttp.web_exceptions import HTTPServiceUnav... |
1627053 | import FWCore.ParameterSet.Config as cms
fftjetVertexAdder = cms.EDProducer(
"FFTJetVertexAdder",
#
# Label for the beam spot info
beamSpotLabel = cms.InputTag("offlineBeamSpot"),
#
# Label for an existing collection of primary vertices
existingVerticesLabel = cms.InputTag("offlinePrimaryVe... |
1627063 | import argparse
import logging
import ipdb
import os
import sys
import torch
import random
import importlib
import yaml
from box import Box
from pathlib import Path
import resource
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (2048, rlimit[1]))
import src
def main(ar... |
1627100 | import re
import numpy as np
from string import punctuation
# snowball stopwords from http://snowball.tartarus.org/algorithms/english/stop.txt
_STOPWORDS = {'a', 'about', 'above', 'after', 'again', 'against', 'all', 'am', 'an', 'and', 'any', 'are', "aren't", 'as',
'at', 'be', 'because', 'been', 'before',... |
1627116 | import rdtest
import renderdoc as rd
class VK_Buffer_Truncation(rdtest.Buffer_Truncation):
demos_test_name = 'VK_Buffer_Truncation'
internal = False |
1627144 | from abc import abstractmethod
from starfish.core.intensity_table.decoded_intensity_table import DecodedIntensityTable
from starfish.core.morphology.binary_mask import BinaryMaskCollection
from starfish.core.pipeline.algorithmbase import AlgorithmBase
class AssignTargetsAlgorithm(metaclass=AlgorithmBase):
"""
... |
1627260 | from typing import Dict, Optional
from io import BytesIO
from geventhttpclient import HTTPClient
from geventhttpclient.url import URL
from geventhttpclient.response import HTTPSocketPoolResponse
from thrift.transport.TTransport import TTransportBase
from line4py.config import LONG_POLLING_V4_PATH
class THttpClient(... |
1627309 | from sparknlp_jsl.base import FeaturesAssembler
"""
The FeaturesAssembler is used to collect features from different columns.
It can collect features from single value columns (anything which can be cast to a float, if casts fails then the value is set to 0),
array columns or SparkNLP annotations (if the annotation i... |
1627342 | from django.db import models
from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, PageChooserPanel
from wagtail.images.edit_handlers import ImageChooserPanel
from base.forms import TopicCollectionPageForm
from pa... |
1627349 | import csv
from logging import Logger
import os
import sys
from typing import List
import numpy as np
import torch
from tqdm import trange
import pickle
from torch.optim.lr_scheduler import ExponentialLR
from torch.optim import Adam, SGD
import wandb
from .evaluate import evaluate, evaluate_predictions
from .predict ... |
1627391 | from pubnub.models.consumer.v3.pn_resource import PNResource
class Channel(PNResource):
def __init__(self, resource_name=None, resource_pattern=None):
super(Channel, self).__init__(resource_name, resource_pattern)
@staticmethod
def id(channel_id):
channel = Channel(resource_name=channel_... |
1627444 | import sys
import time
import weaver.client as client
import simple_client
# creating graph
nodes = [None] * 5
coord_id = 0
c = client.Client(client._CLIENT_ID+1, coord_id)
sc = simple_client.simple_client(c)
tx_id = c.begin_tx()
center = c.create_node(tx_id)
nodes[0] = c.create_node(tx_id)
nodes[1] = c.create_node(... |
1627455 | import requests
def create_invitation(context, tenant, alias, invitation_type):
data = {"alias": alias, "invitation_type": invitation_type}
response = requests.post(
context.config.userdata.get("traction_host")
+ "/tenant/v1/contacts/create-invitation",
json=data,
headers=conte... |
1627462 | from pygsti.tools import pdftools
from ..util import BaseCase
class PDFToolsTester(BaseCase):
def test_pdf_tools(self):
p = {'a': 0., 'b': 1.0}
q = {'a': 0.5, 'b': 0.5}
self.assertAlmostEqual(pdftools.tvd(p, q), .5)
self.assertAlmostEqual(pdftools.classical_fidelity(p, q), .5)
... |
1627518 | import os
import glob
import shutil
import logging
import traceback
import sys
import re
import subprocess
import yaml
from pentagon.component import ComponentBase
from pentagon.helpers import render_template
from pentagon.defaults import AWSPentagonDefaults as PentagonDefaults
class Cluster(ComponentBase):
_pat... |
1627530 | from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
from CapsuleNet import CapsuleNet, CapsuleLoss
from tqdm import tqdm
def parse_args(... |
1627554 | from horch.models.modules import Norm, Conv2d
from horch.models.attention import SEModule
from horch.models.cifar.pyramidnet import Bottleneck as PyrUnit
from torch import nn as nn
from pytorchcv.models.shufflenetv2b import ShuffleUnit
def shuffle_block(in_channels, out_channels):
return ShuffleUnit(in_channels,... |
1627561 | import logging
from django.views.generic import TemplateView, FormView, View
from django.contrib import messages
from django.core.mail import EmailMessage
from django.conf import settings
import mailchimp
from braces.views import (
AjaxResponseMixin,
JSONResponseMixin,
LoginRequiredMixin,
)
from glucoses... |
1627589 | from seleniumwire.thirdparty.mitmproxy.addons import core
from seleniumwire.thirdparty.mitmproxy.addons import streambodies
from seleniumwire.thirdparty.mitmproxy.addons import upstream_auth
def default_addons():
return [
core.Core(),
streambodies.StreamBodies(),
upstream_auth.UpstreamAuth... |
1627635 | import abc
class CoverageFile(object):
"""
Templated class for Lighthouse-compatible code coverage file reader.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __init__(self, filepath=None):
self.filepath = filepath
self.modules = {}
self._parse()
#--------... |
1627636 | from docopt import docopt, DocoptExit
from chemaboxwriters.ontospecies import write_abox
import json
doc = """aboxwriter
Usage:
ospecies <fileOrDir> [--inp-file-type=<type>]
[--qc-log-ext=<ext>]
[--out-dir=<dir>]
[--out-base-name=<name>... |
1627649 | from __future__ import absolute_import, print_function
try:
# PY2
# noinspection PyUnresolvedReferences
from ConfigParser import ConfigParser
except ImportError:
# PY3
# noinspection PyUnresolvedReferences
from configparser import ConfigParser
from itertools import chain
from warnings import w... |
1627679 | def pareto_frontier(Xs, Ys, maxX = True, maxY = True):
myList = sorted([[Xs[i], Ys[i]] for i in range(len(Xs))], reverse=maxX)
p_front = [myList[0]]
for pair in myList[1:]:
if maxY:
if pair[1] >= p_front[-1][1]:
p_front.append(pair)
else:
if pair[... |
1627737 | import pytest
import mock
import gym_quadrotor
import sys
# try to load pyglet, but in case we can't for whatever reason, just mock it at the module level
try:
import pyglet.gl
except:
sys.modules["pyglet.gl"] = mock.Mock()
from gym_quadrotor.envs.rendering import *
@pytest.fixture()
def renderer():
ren... |
1627762 | from starry.compat import theano
from starry.compat import tt
import numpy as np
import starry
import matplotlib.pyplot as plt
import pytest
@pytest.fixture
def model():
class Model:
def __init__(self):
self.map = starry.Map(ydeg=1, reflected=True)
_b = tt.dvector("b")
... |
1627783 | from wpc import db, app, socketio
from wpc.flask_utils import url_for_other_page, url_change_args, nl2br, nl2br_py, get_or_create, is_safe_url
from wpc.models import MozillaStreamHack # NOQA
from wpc.models import YoutubeStream, WPCStream, Stream, Streamer, Subscriber, Idea, ChatMessage
from wpc.forms import Subscribe... |
1627793 | from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from rest_framework import permissions
from api.models import College
from api.serializers import CollegeSerializer
COLLEGE_URL ... |
1627817 | from collections import defaultdict
import copy
# 3p
import mock
# project
from tests.checks.common import AgentCheckTest
MOCK_DATA = """# pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,l... |
1627825 | from smtplib import SMTP as smtp
import json
def sendmail(sender_add, reciever_add, msg, password):
server = smtp('smtp.gmail.com:587')
server.starttls()
server.login(sender_add, password)
server.sendmail(sender_add, reciever_add, msg)
print("Mail sent succesfully....!")
group = {}
print('\t\t ..... |
1627856 | import os, sys, json
from wptserve.utils import isomorphic_decode, isomorphic_encode
import importlib
util = importlib.import_module("common.security-features.scope.util")
def main(request, response):
policyDeliveries = json.loads(request.GET.first(b"policyDeliveries", b"[]"))
maybe_additional_headers = {}
met... |
1627875 | import pytest
from diofant import (I, O, Rational, Symbol, atanh, conjugate, elliptic_e,
elliptic_f, elliptic_k, elliptic_pi, gamma, hyper,
meijerg, oo, pi, sin, sqrt, tan, zoo)
from diofant.abc import m, n, z
from diofant.core.function import ArgumentIndexError
from diofant.u... |
1627893 | from django.http import HttpResponse
from django.views.generic import View
from django_renderpdf.views import PDFView
class PromptDownloadView(PDFView):
template_name = "test_template.html"
prompt_download = True
download_name = "myfile.pdf"
class NoPromptDownloadView(PDFView):
template_name = "tes... |
1627917 | from .revoked_token import RevokedToken
from .copy_job import CopyJob
from .hashsum_job import HashsumJob
from .cloud_connection import CloudConnection
|
1627924 | from typing import List, Optional
from pydantic.dataclasses import dataclass
from rastervision.pipeline.config import (Config, register_config, Field,
validator, ConfigError)
from rastervision.core.data.raster_transformer import RasterTransformerConfig
from rastervision.core.u... |
1627947 | import os
import torch
import torchvision
import torch.nn as nn
from torchvision import transforms
from torchvision.utils import save_image
# Device Configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Hyper-parameters
latent_size = 64
hidden_size = 256
image_size = 784
num_epochs = 2... |
1627951 | import copy
import shutil
import tensorflow as tf
import tensorflow_hub as hub
from detext.layers import embedding_layer
from detext.utils.layer_utils import get_sorted_dict
from detext.utils.parsing_utils import InternalFtrType
from detext.utils.testing.data_setup import DataSetup
class TestEmbeddingLayer(tf.test.... |
1627974 | from types import *
def check_type(obj,atts=[],callables=[]):
got_atts=True
for att in atts:
if not hasattr(obj,att):
got_atts=False;break
got_callables=True
for call in callables:
if not hasattr(obj,call):
got_callables=False;break
the_attr=getattr(obj,call)
if not ca... |
1627979 | import django
import math
register = django.template.Library()
def calc_bar(value, *args):
"""Calculate percentage of value out of the maximum
of several values, for making a bar chart."""
top = max(args + (value,))
percent = value / top * 100
return percent
def calc_mid_bar(value1, value2, *arg... |
1628006 | from .. util import deprecated
if deprecated.allowed():
from . channel_order import ChannelOrder
|
1628015 | import os
import argparse
import sys
import subprocess
import multiprocessing
import pyexcel
import itertools
import nvgpu
DEFAULT_M3D_PATH = r'PATH_TO_MATTERPORT3D'
DEFAULT_DRONE_TRAJECTORIES = r'PATH_TO_TRAJECTORY_FOLDERS'
DEFAULT_BLENDER_PATH = r'PATH_TO_BLENDER_EXE'
DEFAULT_OUTPUT_PATH = r'PATH_TO_DUMP_RESULTS'
DE... |
1628033 | from __future__ import print_function
import argparse
import jinja2
import os
import io
import sys
import logging
import markdown2
from .utils import initialize_logger, readable_dir
from .templates import template_path
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
def get_args():
example_text = '''
... |
1628052 | from typing import List
from .comment_tokenizer import scan_for_comment
from .iterator import LineWrapIterator
from .number_tokenizer import scan_for_number
from .preprocessor_tokenizer import scan_for_preprocessor
from .quote_tokenizer import scan_for_quote
from .remaining_tokenizer import scan_for_remaining
from .to... |
1628071 | from __future__ import absolute_import
from __future__ import unicode_literals
from unittest import TestCase
from webfriend.scripting.execute import execute_script
class FormatProxyTest(TestCase):
def setUp(self):
self.maxDiff = 10000
def _eval(self, script):
return execute_script(None, scrip... |
1628110 | import json
import discord
from discord.ext import commands
from utils.converters import LanguageConverter
from utils.errors import NoAPIKey
from utils.functions import load_json
from utils.paginator import Paginator
class English(commands.Cog):
"""Commands for the english language"""
def __init__(self, bo... |
1628116 | class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
# dp[i] = cost[i] + min(dp[i-1], dp[i-2])
# result = min(dp[-1], dp[-2])
dp = [0 for _ in range(len(cost))]
dp[0] = cost[0]
dp[1] = cost[1]
for i in range(2, len(cost)):
dp[i] = cost[i] + min(dp[i-1], dp[i-2])
r... |
1628117 | import os.path
import os
from dotenv import load_dotenv
import sys
import platform
import urllib
import tarfile
import requests
from zipfile import ZipFile
from config import DOWNLOAD_PATH, VERSION_FILE
from .list import list_remote
""" Download Required kubectl / kustomize / helm / helmfile Versions """
def downloa... |
1628120 | from argparse import ArgumentParser
from multiprocessing import Pool
import os
from NISP.dataset import NISPDataset
from NISP.lightning_model import LightningModel
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.callbacks.early_stopping import EarlyStoppi... |
1628123 | from __future__ import unicode_literals
from django.db.models import fields
from django.utils.translation import ugettext_lazy as _
from ...models import FieldDefinition, FieldDefinitionManager
auto_now_help_text = _('Automatically set the field to now every time the '
'object is saved.')
auto... |
1628132 | import numpy as np
from sklearn.metrics import r2_score
from metaflow_helper.models import KerasRegressor
from metaflow_helper.constants import RunMode
def test_keras_model_regressor_handler_train():
n_examples = 10
n_repeat = 10
offset = 0
X = np.repeat(np.arange(n_examples).astype(float)/n_examples,... |
1628138 | import sympy
maxLimit = 10000
for n in range(maxLimit+1):
print "true" if sympy.isprime(n) else "false" |
1628150 | import numpy as np
from scipy.constants import g
from floodlight.utils.types import Numeric
from floodlight.core.xy import XY
from floodlight.core.property import PlayerProperty
from floodlight.models.base import BaseModel, requires_fit
from floodlight.models.kinematics import VelocityModel, AccelerationModel
class ... |
1628170 | class Node:
"""A binary tree node"""
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def morris_traversal(root):
"""Generator function for iterative inorder tree traversal"""
current = root
while cur... |
1628172 | from abc import ABCMeta
import numpy as np
import torch
import torch.nn as nn
from torch.nn.modules.batchnorm import _BatchNorm
from mmcv.cnn import normal_init, constant_init
from core.gdrn_selfocc_modeling.tools.layers.layer_utils import resize
from core.gdrn_selfocc_modeling.tools.layers.conv_module import ConvModu... |
1628186 | import random
import string
import pytest
from django.core.files import File
def randomword(length=5):
letters = string.ascii_lowercase
return "".join(random.choice(letters) for i in range(length))
@pytest.fixture()
def tempFile() -> File:
from django.core.files.uploadedfile import SimpleUploadedFile
... |
1628219 | from discord.ext import commands
from discord_components import Button
from discord_slash import SlashContext, cog_ext, ButtonStyle
import discord
import random
from External_functions import cembed, equalise
from stuff import req, re
class Polls(commands.Cog):
def __init__(self, bot):
self.bot = bot
... |
1628340 | import warnings
warnings.filterwarnings('ignore', category=UserWarning)
from numpy.testing import assert_equal, assert_almost_equal
import os
import sys
import numpy as np
import skvideo.io
import skvideo.datasets
import skvideo.measure
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import u... |
1628349 | from wharfee.__init__ import __version__
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
description='Wharfee: a shell for Docker',
author='<NAME>',
url='http://wharfee.com',
download_url='http://github.com/j-bennet/wharfee',
author_email='i[do... |
1628483 | import sys
import os
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
import pynab.ids
from pynab.db import db_session, MetaBlack
def local_postprocess():
with db_session() as db:
# noinspection PyComparisonWithNone,PyComparisonWithNone
db.query(MetaBlack).filter(... |
1628490 | import image_embeddings.downloader
import image_embeddings.inference
import image_embeddings.knn
import image_embeddings.cli
|
1628506 | import unittest
from pyfinder import Crawler
class TestCrawler(unittest.TestCase):
def setUp(self):
self.crawler = Crawler()
self.n = 10
def test_crawl(self):
self.crawler.run()
@unittest.skip("Skipping test_build")
def test_build_test(self):
images = self.crawler.bui... |
1628581 | import logging
import unittest
import requests
from configcatclient import DataGovernance
try:
from unittest import mock
except ImportError:
import mock
try:
from unittest.mock import Mock, ANY
except ImportError:
from mock import Mock, ANY
from configcatclient.configfetcher import ConfigFetcher
log... |
1628593 | from bs4 import BeautifulSoup
import requests
choice = {
'1': 'english',
'2': 'hindi',
'3': 'punjabi',
'4': 'bengali',
'5': 'gujarati'
}
ch = input('Enter your choice (1-5) : ')
res = requests.get('https://www.saavn.com/s/featured/' + choice[ch] + '/Weekly_Top_Songs')
soup = BeautifulSoup(res.te... |
1628680 | import re
import sys
from collections import namedtuple
import pytest
import mock_autogen.generator
import tests.sample.code.tested_module
import tests.sample.code.second_module
from tests.sample.code.comprehensions_and_loops import get_square_root, \
summarize_environ_values, trimmed_strings, \
get_square_ro... |
1628687 | from unittest import TestCase
import sys
sys.path.append("./PathPlanning/RRTDubins/")
sys.path.append("./PathPlanning/DubinsPath/")
try:
from PathPlanning.RRTDubins import rrt_dubins as m
# from RRTDubins import rrt_dubins as m
except:
raise
print(__file__)
class Test(TestCase):
def test1(self):
... |
1628718 | from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
from os.path import join
from aequilibrae.paths import NetworkSkimming, SkimResults
from ..common_tools.auxiliary_functions import *
from ..common_tools.global_parameters import *
from ..common_tools.worker_thread im... |
1628722 | import torch
from data.data_transforms import ifft2, fft2, complex_abs
image = torch.rand(10, 20, 30, 2)
lr_flip = torch.flip(image, dims=[-2])
ud_flip = torch.flip(image, dims=[-3])
all_flip = torch.flip(image, dims=[-3, -2])
kspace = fft2(image)
lr_kspace = fft2(lr_flip)
ud_kspace = fft2(ud_flip)
all_kspace = fft2(... |
1628725 | magic = (b"\x00\x00\x00\x00\x00\x00\x00\x00" +
b"\x00\x00\x00\x00\xc2\xea\x81\x60" +
b"\xb3\x14\x11\xcf\xbd\x92\x08\x00" +
b"\x09\xc7\x31\x8c\x18\x1f\x10\x11")
align_1_checker_value = b'3'
align_1_offset = 32
align_1_length = 1
align_1_value = 4
u64_byte_checker_value = b'3'
align_2_offset =... |
1628734 | from __future__ import (absolute_import, print_function, unicode_literals)
from jodel_api.protos import mcs_pb2
from jodel_api.protos import checkin_pb2
from jodel_api.gcmhack import AndroidAccount
from jodel_api.jodel_api import *
|
1628738 | import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
faminstances = UnwrapElement(I... |
1628743 | from PyPowerStore.utils import constants
from PyPowerStore.tests.unit_tests.base_test import TestBase
from PyPowerStore.utils.exception import PowerStoreException
import mock
class TestVolume(TestBase):
def test_get_volumes(self):
vol_list = self.provisioning.get_volumes()
self.assertListEqual(v... |
1628804 | from abc import abstractmethod
from typing import Any
class IDisplay:
@abstractmethod
def Markdown(self, data: str) -> None:
...
@abstractmethod
def display(self, value: Any) -> None:
...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.