id
stringlengths
3
8
content
stringlengths
100
981k
4866092
from __future__ import division, absolute_import from __future__ import print_function, unicode_literals import nose.tools as nt import numpy as np import theano import theano.tensor as T import treeano import treeano.nodes as tn import canopy def test_piecewise_linear_schedule(): s = canopy.schedules.Piecewise...
4866114
import math import torch import torch.nn as nn from transformers import BertConfig, BertModel def get_attn_mask(seq_lens, device=torch.device("cpu")): batchsize, maxlen = len(seq_lens), max(seq_lens) seq_range = torch.arange(0, maxlen, dtype=torch.int64).unsqueeze(0) seq_range_lens = seq_range.new_tensor...
4866130
import typing import re from metal.serial import MacroHook, Engine from metal.serial.preprocessor import MacroExpansion from metal.unit import Reporter level_t = ["cancel", "info", "enter", "exit", "assert", "expect"] type_t = ["plain", "critical", "critical_section", "loop", "ranged", "message", "call", "log", "chec...
4866180
from elote import EloCompetitor good = EloCompetitor(initial_rating=500) better = EloCompetitor(initial_rating=450) best = EloCompetitor(initial_rating=400) print('Starting ratings:') print('%7.2f, %7.2f, %7.2f' % (good.rating, better.rating, best.rating, )) print('\nAfter matches') for _ in range(20): better.b...
4866193
import os def get_tempdir() -> str: """Get the directory where temporary files are stored.""" return next((os.environ[var] for var in ( 'XDG_RUNTIME_DIR', 'TMPDIR', 'TMP', 'TEMP' ) if var in os.environ), '/tmp') class PidLock: """PID lock handler class.""" def __init__(self, name: str): ...
4866207
from flexmeasures import Sensor def make_sensor_data_request_for_gas_sensor( num_values: int = 6, duration: str = "PT1H", unit: str = "m³" ) -> dict: """Creates request to post sensor data for a gas sensor. This particular gas sensor measures units of m³/h with a 10-minute resolution. """ sensor =...
4866222
from tracardi.domain.storage_result import StorageResult from tracardi.service.storage.factory import storage_manager import typing async def get_by_id(consent_id): return await storage_manager("consent-type").load(consent_id) async def add_consent(id: str, name: str, description: str, revokable: bool, default_...
4866263
from celery import task from django.conf import settings from django.core import mail import smtplib @task def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email =...
4866281
from collections import OrderedDict def convert_pytorch_checkpoint_to_paddle(pytorch_checkpoint_path, paddle_dump_path): import paddle import paddle.nn.functional as F import torch dont_transpose = [ ".ln1.weight", ".ln2.weight", "ln_f.weight", "time_ww", "time...
4866294
import pandas as pd import xarray as xr import numpy as np import cartopy.feature as cfeature import cartopy.crs as ccrs import cartopy.io.shapereader as shapereader import matplotlib.pyplot as plt import matplotlib.cm as cm from salem import GoogleVisibleMap, Map import math import os class Cfplot(object): "...
4866315
from unittest import TestCase from mathparse import mathparse class PositiveIntegerTestCase(TestCase): def test_addition(self): result = mathparse.parse('4 + 4') self.assertEqual(result, 8) def test_addition_words(self): result = mathparse.parse('four plus four', language='ENG') ...
4866373
from salttesting import TestSuite, TestLoader import os tests = TestSuite() loader = TestLoader() # add some useful tests from the main suite extra = ('integration.modules.sysmod', ) tests.addTest(loader.loadTestsFromNames(extra)) # this should resolve to the salt-contrib directory # need to check if we are compiled...
4866392
from django.http import (HttpResponse, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseGone, HttpResponseNotAllowed, HttpResponsePermanentRedirect, HttpResponseRedirect, HttpResponseServerError) from django.http.response import HttpRe...
4866407
import sys import csv csv.field_size_limit(sys.maxsize) from pymystem3 import Mystem import time import cProfile from collections import defaultdict class CsvHandler: INPUTFILE = 'wiki_noxml_full.txt' OUTPUTFILE = 'my_frequency_list.csv' def __init__(self): self.file_name = self.INPUTFILE ...
4866420
import asyncio import os import struct import logging import random import cmd import argparse from urllib.parse import urlparse from collections import defaultdict from ipaddress import ip_address from datetime import datetime, timedelta from version import __version__ class ServerError(Exception): pass class Ud...
4866444
import mock import types import uuid import charmhelpers.contrib.network.ovs as ovs import tests.utils as test_utils # NOTE(fnordahl): some functions drectly under the ``contrib.network.ovs`` # module have their unit tests in the ``test_ovs.py`` module in the # ``tests.contrib.network`` package. class TestOVS(tes...
4866465
import math import numpy as np import random import string import copy import cv2 def printMethods(obj): for x in dir(obj): print( x, ':', type(eval("obj."+x)) ) def randomname(n): randlst = [random.choice(string.ascii_letters + string.digits) for i in range(n)] return ''.join(randlst) def str2floats(x): retur...
4866520
from rest_framework import status from mayan.apps.documents.tests.mixins.document_mixins import DocumentTestMixin from mayan.apps.rest_api.tests.base import BaseAPITestCase from ..permissions import ( permission_document_file_content_view, permission_document_type_parsing_setup ) from .mixins import ( Do...
4866526
import multiprocessing import unittest import subprocess import time import signal import sys import os import wexpect from tests import PexpectTestCase @unittest.skipIf(wexpect.spawn_class_name == 'legacy_wexpect', "legacy unsupported") class Exp_TimeoutTestCase(PexpectTestCase.PexpectTestCase): def test_matches...
4866530
from protocols.byteutils import ByteUtils from protocols.protocolutils import ProtocolUtils class MotorProtocol(): def __init__(self, number, group_id): self.connection_number = number self._group_id = group_id def _set_pause(self, hexlist, pause, pause_location): ### set pause ...
4866596
from mpi4py import MPI import jax import jax.numpy as jnp comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() def test_scan(): from mpi4jax import scan arr = jnp.ones((3, 2)) * rank res, _ = scan(arr, op=MPI.SUM) assert jnp.array_equal(res, jnp.ones((3, 2)) * sum(range(rank + 1))) ...
4866626
import unittest import cpmpy as cp from cpmpy.expressions import * from cpmpy.solvers.pysat import CPM_pysat from cpmpy.transformations.to_cnf import to_cnf class TestCardinality(unittest.TestCase): def setUp(self): self.bv_before = boolvar(shape=7) self.bvs = boolvar(shape=3) def test_pysat_...
4866635
import argparse from typing import Dict from singer import Catalog, get_logger, Schema from singer.utils import check_config, load_json LOGGER = get_logger('transform_field') def parse_args(required_config_keys): """ Parse standard command-line args. Parses the command-line arguments mentioned in the ...
4866659
import contextlib import importlib import os import psutil import sys import threading import time from concurrent.futures import ThreadPoolExecutor, as_completed, thread class ProviderRunner(object): """Runner executes provider jobs on threads.""" class SpinningCursorThread(threading.Thread): def __...
4866667
import re from pathlib import Path MODE_BETWEEN_COMMENTS = 0 MODE_COMMENT_START = 1 MODE_PARAMS_START = 2 for path in Path('.').rglob('*.js'): out_lines = [] cur_mode = MODE_BETWEEN_COMMENTS with open(path, 'r', encoding='utf-8') as f: for line in f: if line.strip() == '/**' and c...
4866675
import os.path import pytest from audiomate.annotations import Label, LabelList from audiomate.annotations import relabeling class TestLabelListUtilities: def test_relabel_maps_a_onto_b(self): label_list = LabelList(labels=[ Label('a', 3.2, 4.5) ]) actual = relabeling.relab...
4866680
from argparse import Namespace import dataclasses import pytest from espnet2.utils.build_dataclass import build_dataclass @dataclasses.dataclass class A: a: str b: str def test_build_dataclass(): args = Namespace(a="foo", b="bar") a = build_dataclass(A, args) assert a.a == args.a assert a....
4866689
from .listings_listing_view import listings_listing_view from .listings_api_view import listings_api_view
4866754
from orm import models, tools, configuration, menu, data from orm.client import init, init_compile from javascript import JSON, Object, Error, asynchronous, function if not configuration.server_url: configuration.server_url = '' import sys import orm sys.modules['orm'] = orm import modules configuration.modules = mo...
4866800
BOOST_VERSION = "1.70.0" def new_boost_library(name, deps = []): boost_library(name, deps) boost_build_rule(name) def boost_library(name, deps = []): native.cc_library( name = name, srcs = select({ "osx": [ "libboost_{}.a".format(name), ...
4866851
from . import Models from .Helpers.saver import Saver from .Helpers.trainer import trainer from .Helpers.tester import tester from .World.environment import Environment
4866916
from aiohttp import web PLAIN_TYPE = "text/plain" JSON_TYPE = "application/json" def error(message="Error", status=519): return web.Response(text=message, status=status, content_type=PLAIN_TYPE) def not_implemented(): return web.Response(text="Not implemented...
4866940
from __future__ import print_function import torch from torch.autograd.variable import Variable from multi_categorical_gans.utils.cuda import to_cuda_if_available def calculate_gradient_penalty(discriminator, penalty, real_data, fake_data): real_data = real_data.data fake_data = fake_data.data alpha =...
4866941
import numpy as np import os from scipy import stats from sklearn.model_selection import LeaveOneOut from sklearn.metrics.pairwise import cosine_distances import torch from pytorch_metric_learning.distances import CosineSimilarity import matplotlib.pyplot as plt from multiprocessing import Pool from scipy import stats ...
4866980
from elasticsearch import Elasticsearch import json import os SETTINGS_FILE = os.path.join(os.path.dirname(__file__), 'index_settings.json') with open(SETTINGS_FILE) as json_file: settings = json.load(json_file) def get_host(): return os.environ['ELASTIC_SERVERS'] if 'ELASTIC_SERVERS' in os.environ else 'loc...
4867088
from tornado.ioloop import IOLoop from tornado.gen import coroutine from asyncaws import SQS sqs = SQS('aws-key-id', 'sqs-key-secret', 'eu-west-1') ioloop = IOLoop.current() @coroutine def main(): queue_url = yield sqs.create_queue("test-queue") message_id = yield sqs.send_message(queue_url, "Hello, World!") ...
4867111
import concurrent_log_handler import logging.config import sys import os class StreamToLogger(object): """ Fake file-like stream object that redirects writes to a logger instance. """ def __init__(self, logger, log_level=logging.DEBUG): self.logger = logger self.log_level = log_lev...
4867118
import tiktok from tiktok.structures import Topic, Music # define file handler and specify folder video_file_handler = tiktok.handlers.VideoFileHandler(folder='./videos') music_file_handler = tiktok.handlers.MusicFileHandler(folder='./musics') # define db handler db_handler = tiktok.handlers.DBHandler(conn_uri='localh...
4867122
from setuptools import find_packages, setup # Derive install requires from base.in first order requirements with open("requirements/base.in") as f: base_requirements = f.read().strip() base_requirements = base_requirements.replace("==", ">=").split() # Convert to non-pinned for setup.py with open("requirements/e...
4867142
import math import numpy as np def rotate(pt, v1, v2, theta): m = np.zeros((4, 4)) a = v1[0] b = v1[1] c = v1[2] p = ((v2 - v1) / np.linalg.norm(v2 - v1)).reshape(-1) u = p[0] v = p[1] w = p[2] uu = u * u uv = u * v uw = u * w vv = v * v vw = v * w ww = w * w ...
4867146
from telegram.bot import Bot class TelegramNotifier: def __init__(self, token): self.bot = Bot(token) def notify(self, chat_id, message): self.bot.send_message(chat_id, message)
4867159
import gzip import json from airflow.hooks.S3_hook import S3Hook from airflow.contrib.operators.s3_delete_objects_operator import S3DeleteObjectsOperator def read_s3_json_files(bucket, file_list): s3 = S3Hook('aws_us_east_1') for file in sorted(file_list): obj = s3.get_key(file, bucket) f...
4867184
import numpy as np import cv2 import torch from assets.matchers.base import BaseMatcher from experiments.service.utils import desc_similarity class KnnMatcher(BaseMatcher): def __init__(self, matcher_cfg): super().__init__(matcher_cfg) self.d_threshold = matcher_cfg.matcher_params.feat_distance_th...
4867196
import sys from stringbuffer import StringBuffer import llvmcpy.llvm as llvm def isSystemCall(name): """returns a tuple consisting of the boolean and the cleaned up name. """ if name and ord(name[0]) == 1: return (True, name[1:]) else: return (False, name) #I think there ia a LLVM C-...
4867208
from .FunctionSpace import FunctionSpace from .JacobiPolynomials import JacobiPolynomials, DiffJacobiPolynomials from .OneDimensional import Line from .TwoDimensional import Tri from .ThreeDimensional import Tet from .TwoDimensional import QuadLagrangeGaussLobatto as Quad, QuadLagrange as QuadES from .ThreeDimensional ...
4867228
from django.urls import path from django.views.generic import RedirectView from .views import download_video urlpatterns = [ path('', download_video), path('<string>', RedirectView.as_view(url='/')) # Exceptions handling ]
4867230
from ltk.logger import logger from watchdog.events import FileSystemEventHandler class WatchHandler(FileSystemEventHandler): def __init__(self): FileSystemEventHandler.__init__(self) def process(self, event): logger.info(event.event_type) def on_modified(self, event): self.process...
4867283
import torch, time, h5py import numpy as np import utils def gradTest(params): zeroCount = 0 nonCount = 0 for no, param in enumerate(params): if param.grad is None: nonCount += 1 elif torch.abs(param.grad).sum() == 0: zeroCount += 1 return zeroCount, nonCount ...
4867284
import sys from nltk.translate.bleu_score import corpus_bleu import argparse from nltk.tokenize import word_tokenize import string def read_anno(anno_path): js_list=[] with open(anno_path, "r", encoding='utf-8') as reader: i = -1 for line in reader: i += 1 if i % 4 == 0:...
4867333
import csv import gzip class QRel(): def __init__(self, qid, docid, keywords): self.qid=qid self.docid=docid self.keywords = keywords def eval_rr(self, doc_ranking): """ Evaluate the provided doc ranking using reciprical rank (1/rank of the expected doc) ...
4867442
import os, platform, subprocess, dotbot, sys class Brew(dotbot.Plugin): _brewDirective = "brew" _caskDirective = "cask" _tapDirective = "tap" _brewFileDirective = "brewfile" def can_handle(self, directive): return directive in (self._tapDirective, self._brewDirective, self._caskDirective, ...
4867451
from .bprmf import BPRMF from .factorization_machine import FactorizationMachine from .matrix_factorization import MatrixFactorization from .online_sketch import OnlineSketch from .user_knn import UserKNN __all__ = ['BPRMF', 'FactorizationMachine', 'MatrixFactorization', 'OnlineSketch', 'UserKNN']
4867460
def solve(board): R = [0x1ff] * 9 C = [0x1ff] * 9 B = [0x1ff] * 9 solution = [[0] * 9 for _ in xrange(9)] for r in xrange(9): for c in xrange(9): v = solution[r][c] = board[r][c] if v == 0: continue R[r] &= ~(1 << (v - 1)) C[c] &= ~(1 << (v - 1)) b = r // 3 * 3 + c // 3 B[b] &= ~(1 << (v - ...
4867530
import os, tqdm, random, pickle import torch import torchvision from torch.autograd import Variable from torchvision.transforms import CenterCrop, ToTensor, Compose, Lambda, Resize, Grayscale, Pad from torchvision.datasets import coco from torchvision import utils from torch.nn.functional import binary_cross_entropy...
4867548
import appdaemon.plugins.hass.hassapi as hass import json SPOTIFY_SENSOR_ENTITY_ID = 'sensor.spotify_cover' MAIN_LIGHT_ENTITY = 'group.living_room_main_light' AMBIENT_LIGHT = 'group.living_room_ambient_light' SPOTIFY_SOURCE = '[AV] Samsung Soundbar K650' class SpotifyLight(hass.Hass): def initialize(self): self...
4867576
from collections import defaultdict import sys PYTHON2 = getattr(sys.version_info, "major", 0) == 2 PYTHON3 = getattr(sys.version_info, "major", 0) == 3 class Function(object): def __init__(self): self.calls = defaultdict(list) self.work = [] self.mocks = [] def handle_call(self, code...
4867584
import datetime as dt from calendar import isleap def days_per_month(year): return [31, 29 if isleap(year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def monthly_days(date_from, date_until): month = date_from.replace(day=1) while True: next_month = month + dt.timedelta( days=da...
4867591
import os, os.path from datetime import datetime import math import gtk from . import BuilderAware, idle, refresh_gui, ShortcutActivator from ..util import join_to_file_dir def median(values): values = sorted(values) a = int((len(values) + 1) / 2) b = a - len(values) % 2 return ( values[a-1] + value...
4867662
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter import onmt from onmt.modules import SRU from .modules.SRU_units import AttSRU from .modules.Attention import getAttention from .modules.Normalization import LayerNorm from torch.nn.utils.rnn import pad_packed_...
4867675
class DynamicArray: ... def append(self, item): newElements = [0] * (self.size + 1) for i in range(0, self.size): newElements[i] = self.elements[i] self.elements = newElements newElements[self.size] = item self.size += 1
4867721
import csv import json from argparse import ArgumentParser from collections import defaultdict import pytorch_lightning as pl import torch from pytorch_lightning import LightningModule from torch.utils.data import DataLoader from tqdm.auto import tqdm from transformers import ( AutoTokenizer, LongformerForMask...
4867745
class threeSumClosest: def threeSumClosestFn(self, nums: List[int], target: int) -> int: #just a random high value best_sum = 100000 sum = 0 nums.sort() for i in range(0,len(nums)-2): if nums[i] == nums[i-1] and i>0: continue ...
4867770
import stk import pytest from ..case_data import GenericCaseData @pytest.fixture def alkene(get_atom_ids): a, b, c, d, e, f = get_atom_ids(6) return _alkene( carbon1=stk.C(a), atom1=stk.C(b), atom2=stk.C(c), carbon2=stk.C(d), atom3=stk.C(e), atom4=stk.C(f), ...
4867784
from unittest import TestCase from HP_Utility import Utility class TestUtility(TestCase): def test_is_root(self): self.assertTrue(True) # pass # TODO: How to test root access for script? # self.assertTrue(Utility().is_root(), "Script is not root enabled for the machine!") def...
4867967
from django.core.urlresolvers import reverse from .base import BaseTestCase from filebrowser.conf import fb_settings from filebrowser.functions import get_version_path import os class ViewsTest(BaseTestCase): """ Test views """ def test_browse(self): response = self.client.get(reverse('fb_br...
4867981
from resotolib.baseplugin import BaseCollectorPlugin from resotolib.args import ArgumentParser from resotolib.baseresources import BaseResource from typing import ClassVar from dataclasses import dataclass @dataclass(eq=False) class SomeTestResource(BaseResource): kind: ClassVar[str] = "some_test_resource" d...
4868017
from .dataset import COCOEntities, FlickrEntities from .field import COCOControlSequenceField from .field import COCOControlSetField, COCOControlSetField_Verb, COCODetSetField, COCODetSetField_Verb from .field import ImageDetectionsField, FlickrDetectionField from .field import FlickrControlSetField, FlickrDetSetField,...
4868024
import torch import torch.nn as nn import torch.nn.functional as F from operations import * from torch.autograd import Variable from genotypes import PRIMITIVES from genotypes import Genotype from attention_resnet import * class Network(nn.Module): def __init__(self, num_classes): super(Network,...
4868044
from typing import List, Tuple import numpy as np from app.pipelines import Pipeline class AudioToAudioPipeline(Pipeline): def __init__(self, model_id: str): # IMPLEMENT_THIS # Preload all the elements you are going to need at inference. # For instance your model, processors, tokenizer th...
4868090
from demosys.resources.programs import programs # noqa from demosys.resources.textures import textures # noqa from demosys.resources.tracks import tracks # noqa from demosys.resources.scenes import scenes # noqa from demosys.resources.data import data # noqa
4868103
import torch import torch.nn as nn from options.model_options import MFBFusionOption from .base_model import BaseModel from options import GlobalOption class MFBFusion(BaseModel): def __init__(self, mfb_fusion_option: MFBFusionOption): super(MFBFusion, self).__init__() self.out_dim = mfb_fusion_o...
4868132
from a10sdk.common.A10BaseClass import A10BaseClass class DeviceContext(A10BaseClass): """Class Description:: The target device the following router commands to configure for. Class device-context supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` clas...
4868275
import unittest from unittest.mock import patch import logging import requests from gremlinapi.metrics import GremlinAPIMetrics from .util import mock_json, mock_data, mock_metrics class TestMetrics(unittest.TestCase): @patch("requests.get") def test_get_attack_metrics_with_decorator(self, mock_get) -> None:...
4868287
import os import torch import glob from pipeline import CustomDataset from network import Generator from option import TestOption from utils.Manger import save_image import datetime if __name__ == '__main__': start_time = datetime.datetime.now() opt = TestOption().parse() USE_CUDA = True if torch.cuda.is...
4868312
from django.conf import settings from django.contrib import admin from django.urls import include, path, re_path from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions from apps.core.views import WelcomePageView schema_view = get_schema_view( openapi.Info( ...
4868378
import pytest from liualgotrader.common import assets @pytest.mark.devtest def test_round_asset() -> bool: f = 0.999349343434 print(f, assets.round_asset("BTCUSD", f)) return True
4868412
import ibis.expr.operations as ops import ibis.expr.rules as rlz import ibis.expr.types as ir class TypedCaseBuilder: __slots__ = () def type(self): return rlz.highest_precedence_dtype(self.results) def else_(self, result_expr): """ Specify Returns ------- ...
4868429
import re from nltk.corpus import stopwords from krovetzstemmer import Stemmer class Tokenizer: def __init__(self, vocab_path, unk="<UNK>", pad="<PAD>"): self.vocab_path = vocab_path self.unk = unk self.pad = pad self.word2idx = self.load_vocab(vocab_path) self.sws = {} ...
4868463
import unittest from coba.exceptions import CobaException from coba.pipes import LibSvmReader, ArffReader, CsvReader from coba.pipes import Flatten, Encode, JsonEncode, Structure, Drop, Take, Identity, Shuffle from coba.encodings import NumericEncoder, OneHotEncoder, StringEncoder from coba.contexts import NullLogger,...
4868484
import logging import threading import util.primitives.funcs as funcs from gettext import ngettext log = logging.getLogger('common.ach_mixin') class AchievementMixin(object): MILESTONE_MESSAGES = { 'twit_post':('has sent %(number)d tweets using Digsby!', 'twitter'), ...
4868542
import sys import serial from time import sleep path = '/dev/ttyUSB0' baud = 115200 # OPTION A # To disable /RESET after hangup # # import termios # with open(path) as f: # attrs = termios.tcgetattr(f) # attrs[2] = attrs[2] & ~termios.HUPCL # termios.tcsetattr(f, termios.TCSAFLUSH, attrs) # OPTION B # To d...
4868567
from compas_cem.optimization.constraints import FloatConstraint from compas_cem.optimization.constraints import VectorConstraint __all__ = ["TrailEdgeForceConstraint", "ReactionForceConstraint"] class TrailEdgeForceConstraint(FloatConstraint): """ Make a trail edge reach a target force value. ...
4868568
import pytest import salt.modules.postgres as postgres # 'md5' + md5('password' + 'username') md5_pw = "md55a231fcdb710d73268c4f44283487ba2" scram_pw = ( "SCRAM-SHA-256$4096:wLr5nqC+3F+r7FdQPnB+nA==$" "0hn08ZdX8kirGaL4TM0j13digH9Wl365OOzCtAuF2pE=:" "LzAh/MGUdjYkdbDzcOKpfGwa3WwPUsyGcY+TEnSpcto=" ) def id...
4868609
from django.shortcuts import render, HttpResponse from django.views import View from model_model import models from dbms import forms from back.views.AuthAccount import AuthAccount, GetUserInfo from django.utils.decorators import method_decorator from django.conf import settings from scripts import functions from scrip...
4868636
import yaml import json import joblib import argparse import os import os.path as osp import time from collections import defaultdict import numpy as np from gym.envs.mujoco.ant import AntEnv from rlkit.envs.wrappers import ScaledEnv from rlkit.torch.sac.policies import MakeDeterministic from rlkit.samplers.in_place...
4868656
import factory from parkings.models import Operator from .faker import fake from .user import UserFactory class OperatorFactory(factory.django.DjangoModelFactory): class Meta: model = Operator name = factory.LazyFunction(fake.company) user = factory.SubFactory(UserFactory)
4868706
from setuptools import find_packages, setup setup( name='detr_tensorflow', packages=find_packages(include=['detr_tensorflow']), version='0.1.0', description='DETR Object Detection architecture in Tensorflow', author='<NAME>', )
4868735
import os import datetime import git from .hammer_test import HammerTest class HammerLimitedTest(HammerTest): def setUp(self): super().setUp() self.start_date = datetime.datetime(2018, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc) self.hammer.add_repository(os.path.join(self.current_direc...
4868781
from director import imageview from director import consoleapp import director.vtkAll as vtk import director.vtkNumpy as vnp # create a vtkImageData object s = vtk.vtkRTAnalyticSource() s.SetWholeExtent(-100, 100, -100, 100, 0, 0) s.Update() image = s.GetOutput() # get image data as a numpy array w,h,_ = image.GetDi...
4868790
import sling import os # Location of GeoNames dump. gn_dump_date = "2018-10-21" gn_base_path = "data/c/geonames" gn_path = gn_base_path + "/" + gn_dump_date output_dir = "data/e/dataset/geonames.sling" output_file = output_dir + "/geonames.sling" if not os.path.exists(output_dir): os.makedirs(output_dir) # Read knowl...
4868795
from flask import abort from marshmallow import fields from flexmeasures.data.models.generic_assets import GenericAsset class AssetIdField(fields.Integer): """ Field that represents a generic asset ID. It de-serializes from the asset id to an asset instance. """ def _deserialize(self, asset_id: int,...
4868800
from selenium.webdriver.common.by import By from . import scene from . import base class Graph(scene.Scene): class SVG(scene.Scene.SVG): nodes = base.make_elements(By.CSS_SELECTOR, "g.node") markers = base.make_elements(By.CSS_SELECTOR, "g.marker") edges = base.make_elements(By.CSS_SELECTO...
4868814
from src.DH.Physics import DHPhysics, DHPhysicsParams from src.ModelStats import ModelStats class DHMultiPhysics(DHPhysics): def __init__(self, params: DHPhysicsParams, stats: ModelStats): super().__init__(params, stats) def get_movement_budget_used(self): return sum(self.state.initial_moveme...
4868840
from transformers import AutoConfig, AutoModelForQuestionAnswering from paragen.models import register_model from paragen.models.abstract_encoder_decoder_model import AbstractEncoderDecoderModel from paragen.modules.layers.classifier import HuggingfaceClassifier @register_model class HuggingfaceExtractiveQuestionAns...
4868885
from .copy import copy from .corr import corr from .min import min from .max import max from .use_only import use_only from .rename import rename from .max_diff import max_diff from .time_intervals import time_intervals from .resample import resample from .slice_time import slice_time from .info_metadata impo...
4868886
import peewee as pw import bot_app.settings as settings db = pw.SqliteDatabase(settings.DB_NAME) # TODO merge those in models and conversation with conversation.. class Conversation(pw.Model): # id = pw.IntegerField() PEEWEE automatically adds this fb_auth = pw.CharField(null=True) class Meta: d...
4868894
from ows_refactored.ows_legend_cfg import legend_idx_0_1_5ticks # PQ mask common pq_mask_fmask_land = [ { "band": "oa_fmask", "values": [0, 2, 3], "invert": True, }, { "band": "land", "invert": True, "values": [1], } ] pq_mask_fmask_only = [ { ...
4868898
import math __author__ = 'kimvais' def to_bytes(x): # Converts an integer of arbitrary length to network-endian bytes l = math.ceil(x.bit_length() / 8) return x.to_bytes(l, 'big')
4868910
from django.conf.urls import include, url from django.contrib import admin from . import routers urlpatterns = [ url(r'^', include('todo.urls')), url(r'^api/', include(routers.SharedAPIRootRouter.router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespa...
4868920
from typing import Dict, Hashable, Optional import pytest from antidote.core.container import (Container, DependencyValue, RawContainer, RawProvider, Scope) from antidote.core.exceptions import DuplicateDependencyError from antidote.core.utils import DependencyDebug from antidote....