id
stringlengths
3
8
content
stringlengths
100
981k
451045
from typing import List class Solution: def findMiddleIndex(self, nums: List[int]) -> int: s, far = sum(nums), 0 for i, v in enumerate(nums): if s - v == 2 * far: return i far += v return -1
451056
from globibot.lib.plugin import Plugin from globibot.lib.decorators import command from globibot.lib.helpers import parsing as p from globibot.lib.helpers.hooks import master_only import re URL_PATTERN = re.compile('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') class Reactions(Pl...
451081
import numpy as np from autoconf import conf from autofit import exc from autofit.messages.normal import NormalMessage, UniformNormalMessage from autofit.messages.transform import log_10_transform from autofit.messages.transform_wrapper import TransformedWrapperInstance from .abstract import epsilon, assert_within_lim...
451105
import pytest import smartsheet # Given Python's variable naming convention of snake_case, # and Smartsheet's API attribute naming convention of # lowerCamelCase, this set of tests is intended to make # sure all of that is handled correctly. @pytest.mark.usefixtures("smart_setup") class TestModelAttributes: def ...
451163
import os import webbrowser import shutil import json import requests import re import wx import time import tempfile from threading import Thread from .result_event import * from .config import * class PushThread(Thread): def __init__(self, wxObject): Thread.__init__(self) self.wxObject = wxObjec...
451176
import os import pytest from ._util import assert_simple_file_realize try: from fs_gcsfs import GCSFS except ImportError: GCSFS = None SCRIPT_DIRECTORY = os.path.abspath(os.path.dirname(__file__)) FILE_SOURCES_CONF = os.path.join(SCRIPT_DIRECTORY, "gcsfs_file_sources_conf.yml") skip_if_no_gcsfs_libs = pyt...
451207
import sys, os, os.path, glob import cPickle from scipy.io import loadmat import numpy from multiprocessing import Process, Queue import torch from torch.autograd import Variable N_CLASSES = 527 N_WORKERS = 6 GAS_FEATURE_DIR = '../../data/audioset' DCASE_FEATURE_DIR = '../../data/dcase' with open(os.path.join(GAS_FEA...
451256
import unittest import numpy as np import paramak class TestCuttingWedgeFS(unittest.TestCase): def test_shape_construction_and_volume(self): """Makes cutting cylinders from shapes and checks the volume of the cutter shape is larger than the shape it encompasses.""" hoop_shape = ...
451261
import os from icrawler.builtin import BaiduImageCrawler from icrawler.builtin import BingImageCrawler def check_path(path): if not os.path.exists(path): os.makedirs(path) return path def baidu_bing_crwal(key_words=['中国人'], max_nums=[1000], save_root=r'./'): assert len(key_words)==len(max_nums), ...
451327
import tqdm from io import BytesIO from functools import partial from multiprocessing.pool import ThreadPool from PIL import Image from torchero.utils.io import download_from_url def download_image(url): """ Download an image from an url Arguments: url (str): Url of the image Returns: T...
451362
import io class Brainfuck: @staticmethod def cleanup(code): return "".join(filter(lambda x: x in [".", "[", "]", "<", ">", "+", "-"], code)) @staticmethod def getlines(code): return [code[i : i + 50] for i in range(0, len(code), 50)] @staticmethod def buildbracemap(code): ...
451413
from flask import Blueprint from flask import jsonify from flask import request from yelp_beans.logic.user import get_user user_blueprint = Blueprint('user', __name__) @user_blueprint.route('/', methods=["GET"]) def user_api(): user = get_user(request.args.get('email')) if not user: resp = jsonify({...
451417
class Pickleable(object): """ Base class that implements getstate/setstate, since most of the classes are overriding getattr. """ def __getstate__(self): return self.__dict__ def __setstate__(self, data): self.__dict__.update(data)
451454
from collections import OrderedDict import io import logging import os import h5py import kaldiio import numpy as np import soundfile from espnet.transform.transformation import Transformation class LoadInputsAndTargets(object): """Create a mini-batch from a list of dicts >>> batch = [('utt1', ... ...
451456
import FWCore.ParameterSet.Config as cms from JetMETCorrections.Configuration.JetCorrectionServices_cff import * # L1 Correction Producers ak4CaloJetsL1 = cms.EDProducer( 'CaloJetCorrectionProducer', src = cms.InputTag('ak4CaloJets'), correctors = cms.vstring('L1Fastjet') ) ak4PFJetsL1 = cms.ED...
451530
from concurrent.futures import ThreadPoolExecutor from typing import NamedTuple, Callable, Union, List, Dict import numpy as np from keras import optimizers from kerl.common.agent import MultiAgent, EpisodeSample from kerl.common.multi_gym_env import MultiGymEnv from kerl.wm.networks import WorldModelVAE, WorldEnvMod...
451561
from __future__ import absolute_import import pytest import os from qark.decompiler.decompiler import Decompiler from qark.scanner.scanner import Scanner from qark.scanner.plugin import JavaASTPlugin, ManifestPlugin DECOMPILER_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "qark", "lib", "de...
451578
import win32clipboard, win32con def get_pattern(): text = str(eval(raw_input("Pattern:\n"))) win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(text) win32clipboard.CloseClipboard() def main(): while True: get_pattern() if __name__ == "__...
451593
import tensorflow as tf from tqdm import tqdm from PIL import Image from hailo_model_zoo.core.infer.infer_utils import log_accuracy, write_results, save_image from hailo_sdk_client import SdkFineTune def np_infer(runner, target, logger, eval_num_examples, print_num_examples, batch_size, data_feed_callb...
451604
from __future__ import unicode_literals from django.core.management.base import AppCommand from django.db import DEFAULT_DB_ALIAS, connections class Command(AppCommand): help = 'Prints the SQL statements for resetting sequences for the given app name(s).' output_transaction = True def add_arguments(sel...
451640
from misc import * import mido while True: msg_a = None msg_b = None print("=====================================") print_full("Waiting for first message... ") seen = list() try: with mido.open_input('monologue 1 KBD/KNOB 1') as inport: for msg in inport: ...
451649
import pytest import os from functools import lru_cache import logging as _logging from logging.handlers import RotatingFileHandler from test.tutils import random_str from calculate_anything import logging @lru_cache(maxsize=None) def get_file_handler(filepath): file_hdlr = RotatingFileHandler( filepath, ...
451655
import unittest import numpy as np try: from numcodecs.msgpacks import MsgPack except ImportError: # pragma: no cover raise unittest.SkipTest("msgpack not available") from numcodecs.tests.common import (check_config, check_repr, check_encode_decode_array, check_backwar...
451664
from __future__ import unicode_literals import frappe def execute(): """Executed by bench execute erpnext_biotrack.patches.delete_all_synced_stock_entries.execute """ frappe.flags.mute_emails = True # rows = frappe.db.sql() i = 0 for name in frappe.get_all("Stock Entry"): doc = frappe.ge...
451705
import json, pygame import thorpy.miscgui.theme as theme class MetaDataManager(object): def __init__(self, data=None): if data is None: data = {} self.data = data def write_data(self, fn): json.dump(self.data, open(fn,'w')) def read_data(self, fn): try: self...
451706
import torch.nn as nn import torch as th class MultiColumn(nn.Module): def __init__(self, num_classes, conv_column, column_units, clf_layers=None): """ - Example multi-column network - Useful when a video sample is too long and has to be split into multiple clip...
451713
from Tkinter import * import os class RecentFile: recent = None def __init__(self,app): self.recent = [] self.app = app #self.loadRecent() self.update_menu(self.app.Filemenu) def add(self,filename): self.app.logen.preferences.add_recent(filenam...
451718
from __future__ import print_function, absolute_import, division import KratosMultiphysics import KratosMultiphysics.ParticleMechanicsApplication as KratosParticle import KratosMultiphysics.KratosUnittest as KratosUnittest class TestParticleEraseProcess(KratosUnittest.TestCase): def _generate_particle_element_a...
451732
from symphony.bdk.core.auth.auth_session import AuthSession from symphony.bdk.core.config.model.bdk_retry_config import BdkRetryConfig from symphony.bdk.core.retry import retry from symphony.bdk.core.service.connection.model.connection_status import ConnectionStatus from symphony.bdk.gen.pod_api.connection_api import C...
451762
import logging import sys from .recorder import Recorder logger = logging.getLogger("offstream") logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler(sys.stdout)) __all__ = ["Recorder"]
451775
import bz2 import hashlib import os import re import stat import subprocess as subp import sys import tarfile import time import zipfile from glob import glob import urllib.request def remove_prefix(text): return re.sub(r'^[a-z]__', '', text) def read_and_split(ofn): return (l.decode('utf-8').strip().spli...
451800
sleep(1)#file : InMoov2.<NAME> import random keyboard = Runtime.createAndStart("keyboard", "Keyboard") keyboard.addListener("keyCommand", python.getName(), "input") leftPort = "COM3" rightPort = "COM7" i01 = Runtime.createAndStart("i01", "InMoov") cleverbot = Runtime.createAndStart("cleverbot","CleverBot") ...
451838
from datasets.base.video.dataset import VideoDataset, VideoDatasetSequence, VideoDatasetFrame from datasets.base.common.viewer.qt5_viewer import draw_object from miscellanies.viewer.qt5_viewer import Qt5Viewer from PyQt5.QtGui import QPixmap, QColor from miscellanies.simple_prefetcher import SimplePrefetcher import ran...
451844
import pyblish.api import openpype.api class ValidateVDBInputNode(pyblish.api.InstancePlugin): """Validate that the node connected to the output node is of type VDB. Regardless of the amount of VDBs create the output will need to have an equal amount of VDBs, points, primitives and vertices A VDB is...
451869
for _ in range(int(input())): n=input() if len(n)>10: print("{}{}{}".format(n[0],len(n)-2,n[-1])) else: print(n)
451892
from parser.config import Config from argparse import ArgumentParser from goodluck.goodluck.main import Luck import pdb argparser = ArgumentParser('train sentence generator') argparser.add_argument('--dozat', action='store_true') argparser.add_argument('--extra', action='store_true') argparser.add_argument('...
451893
import numpy as np from prml.nn.array.broadcast import broadcast_to from prml.nn.math.abs import abs from prml.nn.math.exp import exp from prml.nn.math.log import log from prml.nn.random.random import RandomVariable from prml.nn.tensor.constant import Constant from prml.nn.tensor.tensor import Tensor class Laplace(Ra...
451905
from collections import defaultdict import ipywidgets as ipw from jinja2 import Template from progressivis.core import JSONEncoderNp import progressivis.core.aio as aio from .control_panel import ControlPanel from .sensitive_html import SensitiveHTML from .utils import wait_for_change, wait_for_click, update_widget fro...
451925
from __future__ import print_function from setuptools import setup, find_packages setup( name='rc-cts-urlscanio', version='1.0.1', url='https://github.com/IBMResilient/resilient-community-apps', license='MIT', author='<NAME>', author_email='<EMAIL>', install_requires=[ 'rc-cts' ...
451968
import arrow import pytest import unittest from weasyl import define as d from weasyl import profile from weasyl.error import WeasylError from weasyl.test import db_utils @pytest.mark.usefixtures('db') class ProfileManageTestCase(unittest.TestCase): def setUp(self): self.mod = db_utils.create_user() ...
452006
from django.db import models from django.utils.translation import gettext_lazy as _ from account.models import User class Discounts(models.Model): """ Model for Product price discount """ STATUS = ( ('accepted', 'accepted'), ('pending', 'pending'), ('rejected', 'rejected'), ...
452012
import sys import xml.etree.ElementTree as ET from netconf.client import connect_ssh def usage(): print('usage: test.py host user password operation{route_dump, face_dump, face_add, route_add, punt_add, face_del, punt_del, route_del}') def test(host,user,password,operation): with connect_ssh(host, 830, user, pa...
452020
import redis import json with open('mock_data.json') as json_file: data=json.load(json_file) redis_client = redis.Redis(host='redis_db', port=6379) for i in data: redis_client.set("id":i['id'],"first_name":i['first_name'],"last_name":i['last_name'],"email":i['email'],"gender":i['gender'],"ip_address":i['ip_a...
452026
import FWCore.ParameterSet.Config as cms from RecoBTag.SecondaryVertex.pfInclusiveSecondaryVertexFinderTagInfos_cfi import * pfInclusiveSecondaryVertexFinderCA15TagInfos = pfInclusiveSecondaryVertexFinderTagInfos.clone( trackIPTagInfos = "pfImpactParameterCA15TagInfos", extSVDeltaRToJet = 1.5, trackSelec...
452030
import FWCore.ParameterSet.Config as cms import collections def customiseEarlyDeleteForSeeding(process, products): # Find the producers depends = collections.defaultdict(list) def _branchName(productType, moduleLabel, instanceLabel=""): return "%s_%s_%s_%s" % (productType, moduleLabel, instanceLa...
452031
import numpy as np from numpy.testing import assert_almost_equal import cubedsphere as cs def test_csgrid_gmap(): # read reference data ds_FV3 = cs.open_FV3data("./example_notebooks/sample_data/FV3diag_C48/", 'atmos_daily') # calculate grid online grid = cs.csgrid_GMAO(4...
452078
import pytest from torch.optim import SGD as _SGD from neuralpy.optimizer import SGD # Possible values that are invalid learning_rates = [-6, False, ""] momentums = [-6, False, ""] dampenings = ["asd", False, 3] weight_decays = [-0.36, "asd", "", False] nesteroves = [122, ""] @pytest.mark.parametrize( "learning_...
452084
import numpy as np from pandas import PeriodIndex import pandas._testing as tm class TestFactorize: def test_factorize(self): idx1 = PeriodIndex( ["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"], freq="M" ) exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.int...
452111
import copy import requests import os import time import threading import json import logging import multiprocessing from .autotune_task_manager import AutotuneTaskManager from bagua.bagua_define import ( TensorDtype, TensorDeclaration, BaguaCoreTelemetrySpan, BaguaHyperparameter, ) from flask import re...
452118
import itertools from hamcrest import * @when("we check for messages by the bot") def step_impl(context): context.bot.get_messages() @then("there are no messages") def step_impl(context): assert_that(context.bot.current_messages, empty()) @then('there is a message for {person} which includes the text "{t...
452138
from assistantforynab import settings import os import time import shutil import re from webdriver_manager.chrome import ChromeDriverManager from assistantforynab.utils import gui, utils def restore_defaults(): utils.log_info('Restoring default settings') for p in [settings.chromedriver_path, settings.setti...
452154
import hashlib import re from livestreamer.plugin import Plugin from livestreamer.plugin.api import http from livestreamer.stream import HDSStream # Got the secret from the swf with rev number location # (tv/wat/player/media/Media.as) TOKEN_SECRET = '<KEY>' _url_re = re.compile("http(s)?://(\w+\.)?wat.tv/") _video_i...
452161
import pygame pygame.init() pygame.joystick.init() joystick_count = pygame.joystick.get_count() if joystick_count == 0: print("No joysticks found.") exit(0) for i in range(joystick_count): print("%d - %s" % (i, pygame.joystick.Joystick(i).get_name())) try: joystick_id = int(input("Choose a joystick:...
452186
import unittest from HARK.datasets import load_SCF_wealth_weights from HARK.datasets.cpi.us.CPITools import cpi_deflator from HARK.datasets.SCF.WealthIncomeDist.SCFDistTools import income_wealth_dists_from_scf class test_load_SCF_wealth_weights(unittest.TestCase): def setUp(self): self.SCF_wealth, self.SC...
452191
import re import pytest from dagster.core.definitions import intermediate_storage, pipeline, solid from dagster.core.definitions.mode import ModeDefinition from dagster.core.execution.api import execute_pipeline, reexecute_pipeline from dagster.core.instance import DagsterInstance from dagster.core.storage.object_stor...
452197
import requests import subprocess, shlex import argparse import os import logging import urllib3 urllib3.disable_warnings() def main(): parser = argparse.ArgumentParser(description='Required args for recursive clone') parser.add_argument('--group_id', metavar='group_id', type=int, help...
452241
from django.core.exceptions import ImproperlyConfigured from django.urls import reverse from django_sorcery import forms from django_sorcery.views import edit from ..base import TestCase from ..testapp.models import Owner, db from ..testapp.views import OwnerCreateViewWithForm class TestCreateView(TestCase): def...
452255
from gym import ObservationWrapper class TransformObservation(ObservationWrapper): r"""Transform the observation via an arbitrary function. Example:: >>> import gym >>> env = gym.make('CartPole-v1') >>> env = TransformObservation(env, lambda obs: obs + 0.1*np.random.randn(*obs.shape...
452274
from bs4 import BeautifulSoup as bsoup import pandas as pd import numpy as np import humanfriendly # Read in email data file df = pd.read_csv('../bodytext.csv', header = 0) # Filter out sent mail emails = df.query('FromEmail != "[my email address]"').copy() def wordCount(row): if(row['Format'] == 'Html'): ...
452279
from __future__ import division, generators, print_function import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import macarico.util as util from macarico.util import Var, Varng import macarico def sample_from(l): r = sum((p for _, p in l)) * np.random.random() last_chance = ...
452285
import sys import os import time from robot.libraries.BuiltIn import BuiltIn from robot.output.logger import LOGGER class runKeywordAsync: def __init__(self): self._thread_pool = {} self._last_thread_handle = 1 #self._robot_log_level = BuiltIn().get_variable_value("${LOG_LEVEL}") def r...
452297
import asyncio import sys import os import time import importlib import logging import traceback import sqlite3 import sys from pathlib import Path from pprint import pprint from matrixroom import MatrixRoom from plugin import Plugin import nio DEFAULT_BOTNAME = "Matrix Bot" DEFAULT_PLUGINPATH = [ "./plugins" ] DEF...
452318
import codecs, csv def readCSV (fname, delimiter="\t"): #f = codecs.open(fname, 'r') #lines = f.readlines() #f.close() header = {} table = [] with codecs.open(fname, 'r') as csvfile: lines = csv.reader(csvfile, delimiter=delimiter, quotechar='"') ...
452329
from unittest.mock import MagicMock, patch import numpy as np import torch def _print_success_message(): print("Tests Passed") class AssertTest(object): def __init__(self, params): self.assert_param_message = "\n".join( [str(k) + ": " + str(v) + "" for k, v in params.items()] ) ...
452352
from puq import * def run(): x = UniformParameter('x', 'x', min=0, max=1) y = UniformParameter('y', 'y', min=0, max=1) host = InteractiveHost() prog = TestProgram('./dome_prog.py') uq = MonteCarlo([x,y], 500) return Sweep(uq, host, prog)
452354
class Minus: reserved = {} tokens = ('MINUS',) # Tokens t_MINUS = r'-' precedence = ( ('left', 'MINUS'), )
452382
from __future__ import print_function, division import os import sys import subprocess if __name__=="__main__": dir_path = sys.argv[1] dst_dir_path = sys.argv[2] for file_name in os.listdir(dir_path): if '.mp4' not in file_name: continue name, ext = os.path.splitext(file_name) dst_directory_p...
452385
from __future__ import absolute_import, division, unicode_literals import uuid import xmltodict from twisted.trial.unittest import SynchronousTestCase from twisted.internet.task import Clock from mimic.core import MimicCore from mimic.resource import MimicRoot from mimic.test.helpers import request_with_content from ...
452391
import torch import torch.nn as nn import torch.nn.functional as F from torchvision import models from ImitationLearning.backbone import EfficientNet from ImitationLearning.backbone import MemoryEfficientSwish from ImitationLearning.VisualAttention.network.Lambda import λLayer """ Convolutional Neuronal Networ...
452434
import os import sys import h5py import numpy as np import glob # Local imports rootpath = os.path.dirname(os.path.abspath(__file__)) + '/../' sys.path.append(rootpath) from DataFiles.Hdf5.hdf5lib import h5getstr # --------------------------------------------------------------------------- def PrintArraySize(v, vna...
452449
from realtime_py.connection import Socket def callback1(payload): print("Callback 1: ", payload) def callback2(payload): print("Callback 2: ", payload) if __name__ == "__main__": URL = "ws://localhost:4000/socket/websocket" s = Socket(URL) s.connect() channel_1 = s.set_channel("realtime:publ...
452450
from __future__ import unicode_literals from .utils import init_kernel def test_read(): for to_test in ["test\n", "test test", "testtestt"]: k = init_kernel(stdin=to_test) k.stack.push(0) # Push stream_num k.stack.push(10) # Push size k.stack.push(0) # Push location in memory t...
452468
import math import unittest from simulation.utils.geometry import Line, Point, Polygon, Pose, Transform from simulation.utils.road.config import Config from simulation.utils.road.sections import StaticObstacle from simulation.utils.road.sections.road_section import RoadSection class DummyRoadSection(RoadSection): ...
452514
import django_rq from fakeredis import FakeStrictRedis from rq import Queue from autoemails.job import Job connection = FakeStrictRedis() def dummy_job(): return 42 def dummy_fail_job(): return 42 / 0 class FakeRedisTestCaseMixin: """TestCase mixin that provides easy setup of FakeRedis connection to...
452524
import numpy as np class DataSet: """Class to represent some dataset: train, validation, test""" @property def num_examples(self): """Return qtty of examples in dataset""" raise NotImplementedError def next_batch(self, batch_size): """Return batch of required size of data, labels""" raise NotImplement...
452589
import caffe2onnx.src.c2oObject as Node def getGemmAttri(layer): dict = {"alpha": 1.0, "beta": 1.0, "transA": 0, "transB": 1} return dict def getGemmOutShape(input_shape,num_output): output_shape = [[input_shape[0][0], num_output]] return output_shape def creat...
452597
import os import matplotlib.pyplot as plt import matplotlib import numpy as np from microfilm import microplot, colorify image = 100*np.ones((3,3), dtype=np.uint8) image[0,0] = 200 image2 = 100*np.ones((3,3), dtype=np.uint8) image2[0,1] = 180 more_than_3d = np.zeros((5,3,3), dtype=np.uint8) more_than_3d[0,0,0] = 1 mo...
452598
import cisreg import numpy as np # the color rgb_codes={"EnhancerActive":"255,215,0", #gold, EnhancerActive "EnhancerInactive":"184,134,11", # dark golden rod, EnhancerInactive "PromoterActive":"255,0,0", # red, PromoterActive "PromoterInactive":"250,128,114", # salmon, Promote...
452610
import sys, java, unittest from geoscript.layer import GeoTIFF class GeoTIFF_Test: def setUp(self): self.tif = GeoTIFF('data/sfdem.tif') def testBounds(self): assert self.tif.bounds() is not None assert self.tif.bounds().getwest() == 589980.0 assert self.tif.bounds().south == 4913700.0 assert...
452637
import re import json from subprocess import call, Popen, PIPE def init_parser(parser): parser.add_argument('name', type=str, help='Cluster name.') parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.") parser.add_argument('--hail-log', '-l', r...
452683
import logging from pajbot.models.command import Command from pajbot.modules import BaseModule from pajbot.modules import ModuleSetting log = logging.getLogger(__name__) class PaidSubmodeModule(BaseModule): ID = __name__.split(".")[-1] NAME = "Paid Submode" DESCRIPTION = "Allows user to toggle subscrib...
452693
import numpy as np import scipy.spatial as spatial from source.base import file_utils def get_aabb(points: np.ndarray): aabb_min = points.min(axis=0) aabb_max = points.max(axis=0) return aabb_min, aabb_max def load_xyz(file_path): data = np.loadtxt(file_path).astype('float32') nan_lines = np.is...
452695
def displayBanner(): banner = open('./banner/banner.txt', 'r', encoding = 'utf8') print(banner.read()) def choice(): while True: choice = int(input(">")) if choice == 0: break elif choice == 1: exit() else: print("Retry")
452713
import os from testtools import TestCase from cloudify_cli import inputs from cloudify_cli.exceptions import CloudifyCliError class InputsToDictTest(TestCase): def test_valid_inline(self): resources = ['key1=value1;key2=value2'] result = inputs.inputs_to_dict(resources) self.assertDictEqu...
452778
from cereal import car from selfdrive.car import apply_toyota_steer_torque_limits from selfdrive.car.chrysler.chryslercan import create_lkas_hud, create_lkas_command, \ create_wheel_buttons from selfdrive.car.chrysler.values import CAR, CarControllerParams from opendbc.can...
452837
import logging from claripy.vsa import StridedInterval l = logging.getLogger("angr_tests") def check_si_fields(si, stride, lb, ub): if si.stride != stride: return False if si.lower_bound != lb: return False if si.upper_bound != ub: return False return True def test_smart_jo...
452869
from DRecPy.Recommender.Baseline.aggregation import mean from DRecPy.Recommender.Baseline.aggregation import weighted_mean import pytest @pytest.fixture def interactions(): return [5, 2, 3, 1] @pytest.fixture def interactions_zeroes(): return [0, 0, 0, 0] @pytest.fixture def similarities(): return [1,...
452889
def getNum(prompt = 'Positive real number, please: '): while 1: try: num = float(eval(input(prompt))) if num >= 0: return num except ValueError: print('Bad number') num = getNum(prompt = 'Give it! ') print(num)
452898
import argparse import time import os import random import collections import numpy as np import torch from model import DAE, VAE, AAE from vocab import Vocab from meter import AverageMeter from utils import set_seed, logging, load_sent from batchify import get_batches parser = argparse.ArgumentParser() # Path argume...
452917
from django.template.response import TemplateResponse def not_found(request, exception=None): """404 error handler which includes ``request`` in the context.""" return TemplateResponse( request, "status/404.html", {"request": request}, status=404 ) def server_error(request): """500 error han...
452920
from logging import getLogger import numpy as np import scipy.stats as stats from .controller import Controller from ..envs.cost import calc_cost logger = getLogger(__name__) class DDP(Controller): """ Differential Dynamic Programming Ref: <NAME>., <NAME>., & <NAME>. (2012). In 2012 IEEE/...
452937
from typing import Optional, List, Union from .generic import MeshTorchLayer, PermutationLayer from ..meshmodel import RectangularMeshModel, TriangularMeshModel, PermutingRectangularMeshModel, ButterflyMeshModel from ..helpers import rectangular_permutation, butterfly_layer_permutation from ..config import DEFAULT_BAS...
452969
import math import numpy as np import sys from collections import Counter import torch from torch.autograd import Variable import torch.nn as nn import editdistance import models import data import ops from cuda import CUDA def get_precisions_recalls_DEPRECIATED(inputs, preds, ground_truths): """ v1 of preci...
453000
from __future__ import unicode_literals import functools import re from .turner import TurnerBaseIE from ..compat import ( compat_urllib_parse_urlencode, compat_urlparse, ) from ..utils import ( OnDemandPagedList, remove_start, ) class NBAIE(TurnerBaseIE): _VALID_URL = r'https?://(?:watch\.|www\...
453004
import numpy as np import tensorflow as tf from distutils.version import LooseVersion if LooseVersion(tf.__version__) > LooseVersion("1.14"): import tensorflow.compat.v1 as tf from graphgallery import functional as gf from graphgallery.utils import tqdm from graphgallery.attack.targeted import TensorFlow...
453079
from . import BaseCMLTest from virl.api.plugin import _test_enable_plugins from click.testing import CliRunner import requests_mock import os class CMLGoodPluginTest(BaseCMLTest): def setUp(self): _test_enable_plugins() super().setUp() os.environ["CML_PLUGIN_PATH"] = os.path.realpath("./te...
453085
import numpy as np from numpy.testing import assert_array_almost_equal import pytest from scipy.spatial.transform import Rotation from tadataka.camera import CameraModel, CameraParameters from tadataka.projection import pi, inv_pi def test_pi(): P = np.array([ [0, 0, 0], [1, 4, 2], [-1, 3...
453132
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import re import sys def read_flo(filename): with open(filename, 'rb') as f: magic = np.fromfile(f, np.float32, count=1) if 202021.25 != magic: print('Magic number incorrect. Invalid .flo file') else: ...
453148
import numpy as np from rllab import spaces from rllab.core.serializable import Serializable from rllab.envs.proxy_env import ProxyEnv from rllab.spaces.box import Box from rllab.misc.overrides import overrides from rllab.envs.base import Step class NormalizedEnv(ProxyEnv, Serializable): def __init__( ...
453160
from mpi4py import MPI import mpiunittest as unittest import sys try: import array except ImportError: array = None class TestMemory(unittest.TestCase): def testNewEmpty(self): memory = MPI.memory mem = memory() self.assertEqual(mem.address, 0) self.assertEqual(mem.obj, No...