id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
445991 | import unittest
from winthingies.win32.const import EVENT_TRACE_FLAG_REGISTRY
from winthingies.trace import TraceProvider
from winthingies.trace import TraceSession
class TestProvider(unittest.TestCase):
def test_kernel_provider(self):
provider_kernel_trace = TraceProvider(
'Windows Kernel Tra... |
446022 | from random import randint
import codecs
import pickle
# First create a dictionary for each relation with the heads/tails
# Given a triple sample a negative triple by changing the head/tail from the corresponding triple dictionary
def load_binary_file(in_file, py_version=2):
if py_version == 2:
... |
446026 | import pandas as pd
import json
class ParsePsort:
def __init__(self, max_entries):
self.max_entries = max_entries
def parse_psortdb(self):
"""
To parse database psortdb gram negative without outer membrane file
and create JSON files conforming to datanator_pat... |
446050 | from typing import List, Dict, Set
from pathlib import PurePosixPath
from collections import deque
import re
from alipcs_py.alipcs import AliPCSApi, PcsFile
from alipcs_py.commands.list_files import list_files
from alipcs_py.commands.sifter import Sifter
from alipcs_py.commands.display import display_shared_links
from... |
446088 | from django.contrib import admin
from manabi.apps.books.models import Textbook
from manabi.apps.flashcards.models import (
Card,
CardHistory,
Deck,
DeckCollection,
Fact,
)
class CardAdmin(admin.ModelAdmin):
raw_id_fields = ('fact',)
list_display = (
'__unicode__', 'last_due_at', '... |
446101 | import logging
import os
import sys
from functools import wraps
from telegram.ext import CommandHandler
from telegram.ext.dispatcher import run_async
from config import config
logger = logging.getLogger(__name__)
def restricted(func):
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
user_id ... |
446124 | import click
import rvo.db as db
import rvo.views as views
@click.command(short_help="Show transactions",
help="""
Transactions are logged informations
about changes and access to the documents.
`log' is used to get those transactions listed.
... |
446150 | import os
from setuptools import setup
PACKAGE = "allure-robotframework"
classifiers = [
'Development Status :: 5 - Production/Stable',
'Framework :: Robot Framework',
'Framework :: Robot Framework :: Tool',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
... |
446156 | class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, to_add):
if self.value > to_add:
if self.left:
self.left.insert(to_add)
else:
self.left = BinarySear... |
446191 | from easydict import EasyDict as edict
from tensorflow.python.keras import Input
from tensorflow.python.keras import Model
from tensorflow.python.keras import layers
from gans.models import model
class LatentToImageConditionalGenerator(model.Model):
def __init__(
self,
model_parameters: ... |
446203 | import numpy as np
from scipy import ndimage as nd
import tensorflow as tf
from prdepth import sampler
import prdepth.utils as ut
import cv2
H, W = sampler.H, sampler.W
IH, IW = sampler.IH, sampler.IW
PSZ = sampler.PSZ
STRIDE = sampler.STRIDE
HNPS, WNPS = sampler.HNPS, sampler.WNPS
class S2DOptimizer:
''' Opti... |
446222 | from sepal.ee.image import band_intersection, evaluate, select_and_add_missing, when
def to_index(image, index_name):
return {
'ndvi': to_ndvi(image),
'ndmi': to_ndmi(image),
'ndwi': to_ndwi(image),
'mndwi': to_mndwi(image),
'evi': to_evi(image),
'evi2': to_evi2(ima... |
446248 | import requests
from . import FeedSource, _request_headers
class Biki(FeedSource):
def _fetch(self):
feed = {}
url = "https://openapi.biki.cc/open/api/get_ticker?symbol={quote}{base}"
for base in self.bases:
for quote in self.quotes:
if quote == base:
... |
446276 | from __future__ import division
import numpy as np
import logging
from scipy.ndimage import zoom
from .base import Attack
from .base import generator_decorator
from ..utils import softmax
class GenAttack(Attack):
"""The GenAttack introduced in [1]_.
This attack is performs a genetic search in order to find ... |
446318 | import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
from torch.nn.modules.container import ModuleList
from transformers import BertModel
class ArgModule(nn.Module):
def __init__(self, arg_layer, n_layers):
"""
Module for extracting arguments based on given encoder output... |
446343 | import intelhex
ih = intelhex.IntelHex()
for i in range(65536): ih[i] = i & 0x0FF
print(len(ih))
print(ih.get_memory_size())
|
446358 | import logging
import os
import sys
from nltk.corpus import stopwords as nltk_stopwords
from hunmisc.utils.huntool_wrapper import Hundisambig, Ocamorph, OcamorphAnalyzer, MorphAnalyzer # nopep8
from stemming.porter2 import stem as porter_stem
from utils import get_cfg
class Lemmatizer():
def __init__(self, cfg... |
446361 | import torch
import ci_sdr
def test_burn_single_source():
t1 = torch.tensor([1., 2, 4, 7, 1, 3, 7, 8, 0, 3, 4])
t2 = torch.clone(t1)
t2[:4] += 2
sdr = ci_sdr.pt.ci_sdr(t1, t2, filter_length=3)
assert sdr.shape == (), sdr.shape
torch.testing.assert_allclose(sdr, 13.592828750610352)
def test_... |
446371 | import sublime
import sublime_plugin
from ..lib import omnisharp
from ..lib import helpers
class OmniSharpNavigateTo(sublime_plugin.TextCommand):
data = None
def run(self, edit):
if self.data is None:
params = {}
params['ShowAccessModifiers'] = False
omnisharp.ge... |
446379 | from libzmx import FiniteSurface, Standard
from libzmx import (Property, Parameter, AuxParameter, ExtraParameter,
PickupFormat)
from libzmx import SemiDiameterParameter
class Toroidal(Standard):
surface_type = "TOROIDAL"
radius_of_rotation = Property(AuxParameter, 1)
num_poly_terms =... |
446381 | import sys
import time
import random
from twisted.internet import fdesc
from twisted.internet import reactor
from twisted.internet import defer, abstract
from scapy.config import conf
from scapy.all import RandShort, IP, IPerror, ICMP, ICMPerror, TCP, TCPerror, UDP, UDPerror
from ooni.errors import ProtocolNotRegiste... |
446383 | try:
from collections import OrderedDict
except ImportError:
from .OrderedDictFallback import OrderedDictFallback as OrderedDict
|
446393 | dest = [0x21, 0x58, 0x33, 0x57, 0x24, 0x2c, 0x66, 0x25,
0x45, 0x53, 0x34, 0x28, 0x08, 0x61, 0x11, 0x07,
0x14, 0x3d, 0x07, 0x62, 0x13, 0x72, 0x02, 0x4c]
flag = ""
random = 2019
for i in range(24):
random = (random * 23333 + 19260817) % 127
flag += chr(random ^ dest[i])
print(flag)
|
446422 | from django.urls import reverse
def _get_relative_path_to_watch(pk: int = 1) -> str:
url: str = reverse("stream:watch", kwargs={"movie_id": pk})
return url.replace(str(pk), "")
|
446436 | from typing import Dict, List, Tuple
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from classy.data.data_drivers import (
GenerationSample,
QASample,
SentencePairSample,
SequenceSample,
TokensSample,
)
from classy.evaluation.base import Evaluation
from classy.utils.co... |
446453 | from apps.blocklist.models import BlocklistApp, BlocklistPlugin
def run():
# only blocked plugins with all 3 are app based blocks, otherwise the
# min/max refer to the version of the plugin.
plugins = (BlocklistPlugin.objects.exclude(min='').exclude(min=None)
.exclude... |
446476 | n= int(input("Enter the number : "))
sum = 0
temp = n
while (n):
i = 1
fact = 1
rem = int(n % 10)
while(i <= rem):
fact = fact * i
i = i + 1
sum = sum + fact
n = int(n / 10)
if(sum == temp):
print(temp,end = "")
print(" is a strong number")
else:
print(temp,end = "")
print... |
446477 | import glob
from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError
from os.path import expanduser
class Config(object):
"""A ConfigParser wrapper to support defaults when calling instance
methods, and also tied to a single section"""
def __init__(self, section=None, values=None, extra_s... |
446528 | import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader, random_split
from torch.optim.lr_scheduler import LambdaLR
import pytorch_lightning as pl
import numpy as np
import math
from argparse import ArgumentParser
from gpt2 import GPT2
from utils import quantize
def _to_sequence(x):... |
446533 | from django import template
register = template.Library()
@register.inclusion_tag(
'transitions/templatetags/available_transitions.html', takes_context=True
)
def available_transitions(context, obj, field):
"""Render available transitions for instance."""
get_available_transitions = getattr(
obj,... |
446535 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
import os
import numpy as np
import json
import gdown
from PIL import Image
import cv2
from .models.fcn_net import _build_fcn
from .util.utils import make_color_seg_map
__PREFIX__ = os.path.dirname(os.path... |
446628 | import numpy as np
from keras.preprocessing import sequence
from keras.datasets import imdb
import torch
from torch.autograd import Variable
from torch.optim import Adam
import Model.Constants as Constants
from Model.Modules import Encoder, Generator, Discriminator
from utils import check_cuda
max_features = 10000
ma... |
446654 | import asyncio
from aiohttp import web
from aiohttp_request import ThreadContext, middleware_factory, grequest, get_request
def thread():
assert grequest['sense'] == 42
async def task():
# grequest is `lazy` version of request
assert grequest['sense'] == 42
# works for threads as well with ThreadC... |
446668 | from setuptools import find_packages
from setuptools import setup
import os
from glob import glob
package_name = 'simple_launch'
setup(
name=package_name,
version='1.0.0',
packages=find_packages('src', exclude=['test']),
package_dir={'': 'src'},
data_files=[
(os.path.join('share', package_name... |
446699 | class GRPCConfiguration:
def __init__(self, client_side: bool, server_string=None, user_agent=None,
message_encoding=None, message_accept_encoding=None,
max_message_length=33554432):
self._client_side = client_side
if client_side and server_string is not None:
... |
446712 | import requests
from typing import Dict, Any, List, Union, Tuple, Any, Optional
from mist.action_run import execute_from_text
from mist.lang.config import config
import asyncio, json
from zipfile import ZipFile
from io import BytesIO
import os
# Disable insecure warnings
requests.packages.urllib3.disable_warnings() #... |
446729 | import math
from builtins import object
import numpy as np
import numba as nb
@nb.vectorize
def _pow(x, y):
return math.pow(x, y)
@nb.vectorize
def _log10(x):
return math.log10(x)
class ParameterTransformation(object):
def __init__(self, is_positive=False):
self._is_positive = is_positive
... |
446749 | class PlayFabBaseObject():
pass
class PlayFabRequestCommon(PlayFabBaseObject):
"""
This is a base-class for all Api-request objects.
It is currently unfinished, but we will add result-specific properties,
and add template where-conditions to make some code easier to follow
"""
pass
class P... |
446762 | import numpy as np
import pytest
from numpy.testing import assert_almost_equal, assert_raises
from ...tools import power, rot_ksamp
from .. import MANOVA
class TestManova:
@pytest.mark.parametrize(
"n, obs_stat, obs_pvalue",
[(1000, 0.005062841807278008, 1.0), (100, 8.24e-5, 0.9762956529114515)],... |
446788 | from setuptools import setup, find_packages
import os
long_description = open('README.rst').read()
VERSION = '0.0.4'
package_data = {"github_bot_close_inactive_issues": ["logging.conf"]}
setup(name='github-bot-close-inactive-issues',
version=VERSION,
description='Bot for automatically closing inactive i... |
446804 | import os
import json
val= json.load(open('quora_prepro_test.json', 'r'))
out=[]
outermost = {}
for i in range(0,len(val)):
# imgid = str(val[i]['ques_id'])[:-1]
# qcapid = val[i]['ques_cap_id']
# quesid = val[i]['question_index']
# ques = val[i]['question']
# imgpath = val[i]['image_filename']
# img_id = va... |
446811 | import requests
import json
import hashlib
import time
from Crypto.Cipher import AES
from src.plugins import PluginManager
from lib.conf.config import settings
from concurrent.futures import ThreadPoolExecutor
class Base(object):
pool = ThreadPoolExecutor(10)
def api_encrypt(self):
"""
api接口验... |
446865 | from visions.types import (
Boolean,
Categorical,
Complex,
DateTime,
Float,
Generic,
Integer,
Object,
String,
TimeDelta,
)
from visions.typesets.typeset import VisionsTypeset
class StandardSet(VisionsTypeset):
"""The standard visions typesets
Includes support for the f... |
446900 | from .kmatch import K
class KmatchTestMixin(object):
"""
A mixin for test classes to perform kmatch validation on dictionaries
"""
def assertKmatches(self, pattern, value, suppress_key_errors=False):
"""
Assert that the value matches the kmatch pattern.
:type pattern: list
... |
446905 | from loguru import logger
from datetime import datetime
from pymysql import Connection
from pymysql.cursors import Cursor
def newHoldemRecord(db: Connection, userID: int, money: int, tableID: int, tableUUID: str) -> bool:
if db is None:
return False
now: datetime = datetime.utcnow()
currentTime: ... |
446910 | from os import makedirs
from os.path import exists
from traceback import print_exc
from gi.repository.GLib import get_user_config_dir, get_user_cache_dir, \
log_default_handler, LogLevelFlags
from gi.repository.Gtk import Orientation
try:
from configparser import ConfigParser, NoSectionError, NoOptionErro... |
446929 | import pickle
import random
import numpy as np
from scipy.stats import rankdata
import torch
import torch.autograd as autograd
import torch.utils.data as data
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class AnswerSelection(nn.Module):
def __init__(self, conf):
super(... |
446932 | from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
class ModuleGroup(models.Model):
class Meta:
verbose_name_plural = _('Module Groups')
verbose_name = _('Module Group')
ordering = ['sort']
... |
446945 | from . import term
from . import log as _log
"""
Import the log object into your project to use fastlog
This can be done simply by using:
>>> from fastlog import log
or
>>> from fastlog import *
"""
log = _log.FastLogger() |
446953 | import logging
from amitools.vamos.cfgcore import ConfigDict
from amitools.vamos.log import *
def do_log():
log_main.debug("debug")
log_main.info("info")
log_main.warning("warn")
log_main.error("error")
log_mem.debug("debug")
log_mem.info("info")
log_mem.warning("warn")
log_mem.error(... |
446962 | import uvicore
from app1.models.post import Post
from app1.models.comment import Comment
from app1.models.tag import Tag
from app1.models.hashtag import Hashtag
from app1.models.image import Image
from uvicore.support.dumper import dump, dd
from uvicore import log
@uvicore.seeder()
async def seed():
log.item('Seed... |
447082 | import click
import pytest
@pytest.mark.xfail(raises=AttributeError,
reason="App Engine doesn't provide a tty")
def test_progressbar_strip_regression(runner, monkeypatch):
label = ' padded line'
@click.command()
def cli():
with click.progressbar(tuple(range(10)), label=label... |
447107 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ota', '0008_auto_20190108_1808'),
]
operations = [
migrations.CreateModel(
name='DeviceLogRequest',
fields=[
('id', models.AutoField(auto_created=Tru... |
447148 | from abc import ABC, abstractmethod
class MMWrapper(ABC):
"""
A super class for all molecular mechanics wrappers
Note
----
Since MMWrapper is a super class and has abstract methods
the user cannot actually instantiate a MMWrapper object, but only its child objects
"""
kjmol_to_au = 0.... |
447208 | import os
import dill
from django.core.files.base import ContentFile
from django.db import models
from estimators import get_storage, get_upload_path, hashing
class PrimaryMixin(models.Model):
create_date = models.DateTimeField(
auto_now_add=True, blank=False, null=False)
class Meta:
abstr... |
447211 | import sys
import datetime
import csv
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils import timezone
from radio.models import *
class Command(BaseCommand):
help = 'Helper for new TalkGroup Access'
def add_arguments(self, parser):
p... |
447216 | from __future__ import absolute_import, division, unicode_literals
from flask_restful.reqparse import RequestParser
from sqlalchemy import or_
from sqlalchemy.orm import joinedload
from uuid import UUID
from changes.api.base import APIView, error
from changes.models.build import Build
from changes.models.job import... |
447325 | from eudplib import *
t = [Forward() for _ in range(115)]
def onPluginStart():
global reph_epd
reph_epd = f_epdread_epd(EPD(0x6D5CD8))
s = EUDArray([EPD(x) + 86 for x in t])
i = EUDVariable()
if EUDWhile()(i <= 114):
k = EUDVariable()
EUDWhile()(k <= 63 * 8)
EUDBreakIf([i... |
447335 | import unittest
import torch
import torch.nn as nn
import torch.nn.utils.prune as prune
import torchvision
import simplify
from simplify.layers import ConvB, ConvExpand
from utils import set_seed
class ConvBTest(unittest.TestCase):
def setUp(self):
set_seed(3)
def test_conv_b(self):
con... |
447339 | import os
import logging
import numpy as np
from xml.etree import ElementTree as ET
# setup logger
parent_dir, filename = os.path.split(__file__)
base_dir = os.path.basename(parent_dir)
logger = logging.getLogger(os.path.join(base_dir, filename))
class Parser(object):
def __init__(self, base_dir, xml_file):
... |
447356 | from __future__ import absolute_import, division
import os
from binascii import hexlify
import sqlalchemy
from sqlalchemy.engine import RowProxy
from sqlalchemy.event import listens_for
from sqlalchemy.exc import StatementError
from sqlalchemy.schema import CreateTable
from twisted.trial import unittest
from alchim... |
447359 | from hyperadmin.mediatypes.passthrough import Passthrough
class ClientMixin(object):
"""
Contains logic for connecting to an endpoint on the API
"""
resource = None
url_name = None
client_site = None
def get_api_endpoint(self):
for endpoint in self.resource.get_view_endpoints(... |
447379 | import traceback
import sys
class ViewErrorLoggingMiddleware:
def process_view(self, request, view_func, view_args, view_kwargs):
self.view_name = view_func.__name__
def process_exception(self, request, exception):
print '=' * 60
print '[ERROR] exception in view "%s"' % self.view_na... |
447390 | import numpy as np
import utils
from HopfieldNetwork import HopfieldNetwork
def process_shape(initial_shape: np.ndarray, net: HopfieldNetwork):
noised_shapes = []
for i in range(5, 105, 5):
noise_level = i / 100
noised_shapes.append(utils.noise_shape(initial_shape, noise_level))
for i ... |
447506 | from interactor.database.models.scene_spec import make_spec
from interactor.database.base import Base
from sqlalchemy import Column, Integer, String, Text, Boolean
from delfick_project.norms import sb
class Scene(Base):
uuid = Column(String(64), nullable=True, index=True)
matcher = Column(Text(), nullable=Fa... |
447530 | import tensorflow as tf
from tfsnippet.utils import add_name_arg_doc, is_tensor_object
__all__ = ['smart_cond']
@add_name_arg_doc
def smart_cond(cond, true_fn, false_fn, name=None):
"""
Execute `true_fn` or `false_fn` according to `cond`.
Args:
cond (bool or tf.Tensor): A bool constant or a ten... |
447532 | import numpy as np
import cv2
# Recognize the code from a barcode location
class BarcodeRecognizer(object):
def __init__(self, useDebugMode=False):
self.useDebugMode = useDebugMode
def reconize(self, image):
if image is None:
return False, None
gray = cv2.cvtColor(image, ... |
447552 | from hive_metastore_client import HiveMetastoreClient
HIVE_HOST = "<ADD_HIVE_HOST_HERE>"
HIVE_PORT = 9083
# You must create a list with the columns' names to drop
columns = ["quantity"]
with HiveMetastoreClient(HIVE_HOST, HIVE_PORT) as hive_client:
# Dropping columns from table
hive_client.drop_columns_from_... |
447577 | import os
import time
import tensorflow as tf
import qaData
from qaLSTMNet import QaLSTMNet
def restore():
try:
print("正在加载模型,大约需要一分钟...")
saver.restore(sess, trainedModel)
except Exception as e:
print(e)
print("加载模型失败,重新开始训练")
train()
def train():
print("重新训练,请... |
447585 | import argparse
import pickle
import numpy as np
import torch
from model import train
if __name__ == '__main__':
# Arguments
parser = argparse.ArgumentParser()
parser.add_argument('--graph_file_path', type=str)
parser.add_argument('--random-walk-length', type=int, default=2)
parser.add_argument(... |
447596 | import urllib2
#from google.appengine.api import oauth
print "==================Create System and device==================================="
print "[CreateSystem]"
print urllib2.urlopen('http://localhost:8888/createsystem?id=a&holder=b&devices=c&fbps=d&gateways=e&wuclasses=f').read()
print "[CreateDevice]"
print ur... |
447675 | from ckan.common import _
"""
A template file for comment notification emails.
"""
subject = _("New comment in dataset '{dataset}'")
message = _("""\
User {user} ({email}) has left a comment in dataset ({dataset}):
--
Subject:
{comment_subject}
Message:
{comment}
--
{link}
Best regards
Avoindata.fi support
... |
447681 | from pylimit.pyratelimit import PyRateLimit
from pylimit.pyratelimit_exception import PyRateLimitException
from pylimit.redis_helper import RedisHelper
|
447693 | import pybullet as p
import time
p.connect(p.GUI)
t = time.time() + 0.1
logId = p.startStateLogging(p.STATE_LOGGING_PROFILE_TIMINGS, "haha")
while (time.time() < t):
p.submitProfileTiming("pythontest")
p.stopStateLogging(logId)
|
447706 | from rest_framework import routers
from .api import TruckViewSet
router = routers.DefaultRouter()
router.register('api/truck', TruckViewSet, 'truck')
urlpatterns = router.urls
|
447801 | import os
import sys
from subprocess import call
import argparse
import time
from time import sleep
from threading import Thread, Event
import ssl
import urllib.request
import dbus
from flask import Flask, render_template, jsonify, request
from flask_socketio import SocketIO, emit
debug = False
# Create a default SSL... |
447802 | import os
import time
import pytest
from geopandas import GeoDataFrame
from sentinelhub import BBox, Geometry
from eogrow.core.area import UtmZoneAreaManager
from eogrow.core.config import interpret_config_from_path
from eogrow.utils.vector import count_points
pytestmark = pytest.mark.fast
@pytest.fixture(scope="... |
447828 | import json
from django.http import JsonResponse
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import (
csrf_protect,
ensure_csrf_cookie,
)
from django.views.generic import View
from django_graph_api.graphql.request... |
447856 | STACK_COUNT = 6
INITIAL_STACK_SIZE = 6
MAX_STACK_SIZE = 15
STACK_RANGE = range(STACK_COUNT)
class GameState:
def __init__(self):
self.actions_taken = 0
# List of lists of tuples
# Finished stacks become None - won state contains 4 Nones and 2 empty lists
self.stacks = []
... |
447858 | import numpy as np
def check_grad(f, X, e, args=()):
"""
This function checks the gradients of f by comparing them to
finite difference approximations. The partial derivatives
returned by f and the finite difference approximations are
printed for comparison.
Parameters
----------
f : f... |
447873 | import sys
import os
PADDING_LEN = 0x100 + 32
def unrle(val):
out = []
for i in range(len(val)//2):
a, b = val[i*2], val[i*2+1]
if a == 0:
a = 256
out.append(bytes([b]) * a)
return b''.join(out)
def pad():
return b'AB' * (PADDING_LEN//4)
def main():
rv = pa... |
447889 | import asyncio
import hashlib
from yarl import URL
from feedsearch_crawler.crawler.lib import to_bytes
class DuplicateFilter:
"""
Filters duplicate URLs.
"""
def __init__(self):
# Dictionary whose keys are the hashed fingerprints of the URLs
self.fingerprints = dict()
# Lock... |
447938 | from keras.preprocessing import image as image_utils
from imagenet_utils import decode_predictions
from imagenet_utils import preprocess_input
from vgg16 import VGG16
import argparse
import cv2
import numpy as np
import os
import random
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--folder", required=True)
ar... |
447962 | import numpy as np
from gym import error, spaces
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.base_env import ActionTuple
from mlagents_envs.side_channel.environment_parameters_channel import (EnvironmentParametersChannel,)
from mlagents_envs.side_channel.engine_configuration_channel impor... |
447975 | from dbnd_luigi.luigi_tracking import dbnd_luigi_run
if __name__ == "__main__":
dbnd_luigi_run()
|
447992 | import rdkit.Chem.AllChem as rdkit
def test_get_num_atoms(case_data):
"""
Test :meth:`.Molecule.get_num_atoms`.
Parameters
----------
case_data : :class:`.CaseData`
A test case. Holds the molecule to test and its correct SMILES.
Returns
-------
None : :class:`NoneType`
"... |
448024 | from django.contrib.auth.models import Permission
from django.urls import reverse_lazy
from django.utils.text import slugify
from model_bakery import baker
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from sponsors.models import Sponsor
from sponsors.models.enums import... |
448067 | import os
import time
import torch
import numpy as np
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from tensorboardX import SummaryWriter
from utils import *
from options import get_args
from dataloader import nyudv2_... |
448124 | def isAnagram(string1, string2):
"""Checks if two strings are an anagram
An anagram is a word or phrase formed by rearranging the letters
of a different word or phrase.
This implementation ignores spaces and case.
@param string1 The first word or phrase
@param string2 The second word or phras... |
448165 | import json
import logging
import src.server.cea_608_encoder.caption_string_utility as utils
import src.server.cea_608_encoder.scene_utility as scene_utils
import src.server.config as config
# At a future time this could live in it's own config file
# Leaving it here temporarily
supported_caption_formats = [
'CEA... |
448197 | from unittest import TestCase
from app import app
from i18n.i18n import I18n
class MockApp(object):
def add_template_filter(self, fn):
pass
class IntegrationTestBase(TestCase):
def setUp(self):
I18n(app)
app.testing = True
self.app = app.test_client()
def _assertStatusC... |
448223 | import itertools
import os
import platform
import signal
import stat
import sys
import subprocess
import time
from .options import get_parser, parse_args, validate
SKIP_DIRS = [
'.bzr', '.cache', '.git', '.hg', '.pytest_cache', '.svn',
'__pycache__', 'build', 'dist', 'node_modules',
]
SKIP_EXT = ['.pyc', '.p... |
448258 | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('',
url(r'static/', include('core.registration.static.urls')),
)
|
448277 | from __future__ import print_function
import os
import numpy as np
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import time
import datetime
from constant import *
def currentTime():
return datetime.datetime.now().isoformat()
def get_mask(re_sel):
rm=torch... |
448298 | import collections
import unittest
try:
import unittest.mock as mock
except ImportError:
import mock
import torch
import torch.utils.data as data
from nonechucks import *
import nonechucks
class SafeDatasetTest(unittest.TestCase):
"""Unit tests for `SafeDataset`."""
SafeDatasetPair = collections.n... |
448345 | import numpy as np
from pytools import generate_nonnegative_integer_tuples_summing_to_at_most \
as gnitstam
# prepare plot and eval nodes on triangle
dims = 2
node_n = 40
node_tuples = list(gnitstam(node_n, dims))
plot_nodes = np.array(node_tuples, dtype=np.float64) / node_n
eval_nodes = 2*(plot_nodes - 0.5).T... |
448360 | from .knn_classifier import knn_classifier_log_cpm
from .knn_classifier import knn_classifier_scran
from .logistic_regression import logistic_regression_log_cpm
from .logistic_regression import logistic_regression_scran
from .mlp import mlp_log_cpm
from .mlp import mlp_scran
|
448380 | import copy
import math
import random
from typing import *
import torch
from torch import Tensor
from torch import nn
from torch.nn import functional as F
from transformers import modeling_bart as bart
from transformers.modeling_utils import BeamHypotheses, calc_banned_ngram_tokens, calc_banned_bad_words_ids, \
to... |
448396 | import comet_ml, json
import numpy as np
import torch
from torch import optim
from misc import clear_gradients
from lib import create_agent
from util.env_util import create_env
from util.plot_util import load_checkpoint
from lib.distributions import kl_divergence
from local_vars import PROJECT_NAME, WORKSPACE, LOADING_... |
448458 | import json
import re
import requests
from azure.cli.core.commands import CliCommandType
from .cli_utils import az_cli
def load_command_table(self, _):
custom = CliCommandType(operations_tmpl="{}#{{}}".format(__name__))
with self.command_group("vm auto-shutdown", custom_command_type=custom) as g:
g.c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.