id
stringlengths
3
8
content
stringlengths
100
981k
142309
from enum import Enum from os import (getcwd, path as osp) import sys import click import cv2 from .conf import (get_config, print_config) from .detect.opencv import HaarCascadeDetector from .meme.basic import Meme from .meme.thug import ThugMeme MEME_RESULT_DIR = getcwd() CONTEXT = dict(help_option_names=['-h', '-...
142335
import sys log_file_path = sys.argv[1] with open(log_file_path) as f: lines = f.readlines() for line in lines: # Ignore errors from CPU instruction set or symbol existing testing keywords = ['src.c', 'CheckSymbolExists.c'] if all([keyword not in line for keyword in keywords]): print(line)
142342
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7 # Importing the Kratos Library import KratosMultiphysics from KratosMultiphysics.json_utilities import read_external_json, write_external_json # Importing the base class from KratosMul...
142377
import os import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from getdist import plots mpl.use("Agg") roots = ["mcmc"] params = ["beta", "alpha100", "alpha143", "alpha217", "alpha353"] g = plots.get_subplot_plotter( chain_dir=os.path.join(os.getcwd(), "chains"), analysis_settings={...
142416
import os from subprocess import run, PIPE try: version = os.environ['ELASTIC_VERSION'] except KeyError: version = run('./bin/elastic-version', stdout=PIPE).stdout.decode().strip()
142426
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, validators from wtforms.validators import DataRequired class LoginForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) ...
142466
import _plotly_utils.basevalidators class SurfaceaxisValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="surfaceaxis", parent_name="scatter3d", **kwargs): super(SurfaceaxisValidator, self).__init__( plotly_name=plotly_name, parent_name=paren...
142490
import spacy_streamlit import typer def main(models: str, default_text: str): models = [name.strip() for name in models.split(",")] spacy_streamlit.visualize(models, default_text, visualizers=["ner"]) if __name__ == "__main__": try: typer.run(main) except SystemExit: pass
142492
from sqlobject import * from sqlobject.tests.dbtest import * ######################################## ## Expiring, syncing ######################################## class SyncTest(SQLObject): name = StringCol(length=50, alternateID=True, dbName='name_col') def test_expire(): setupClass(SyncTest) SyncTest(...
142505
from .protoconf import ( Protoconf, ProtoconfSync, ProtoconfMutation, ProtoconfMutationSync, )
142533
from __future__ import division, absolute_import, print_function import numpy as np """ A sript to generate van der Waals surface of molecules. """ # Van der Waals radii (in angstrom) are taken from GAMESS. vdw_r = {'H': 1.20, 'HE': 1.20, 'LI': 1.37, 'BE': 1.45, 'B': 1.45, 'C': 1.50, 'N': 1.50, 'O...
142598
import unittest from bibliopixel.util import offset_range class OffsetRangeTest(unittest.TestCase): def test_empty(self): dmx = offset_range.DMXChannel.make() self.assertEqual(dmx.index(0), None) self.assertEqual(dmx.index(1), 0) self.assertEqual(dmx.index(2), 1) self.asse...
142601
from . import app from flask_sqlalchemy import SQLAlchemy import datetime import os # SQLAlchemy setup basedir = os.path.abspath(os.path.dirname(__file__)) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+os.path.join(basedir, '../data.sqlite') app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True db = SQLAlchemy(a...
142628
def main(name="User", name2="<NAME>"): print(f"Hello, {name}! I am {name2}!") if __name__=="__main__": main()
142683
from django.test import TestCase from django.conf import settings import json from newt.tests import MyTestClient, newt_base_url, login class AuthTests(TestCase): fixtures = ["test_fixture.json"] def setUp(self): self.client = MyTestClient() def test_login(self): # Should not be logged i...
142686
from __future__ import absolute_import import mock import os.path import responses import pytest import re import time from flask import current_app from uuid import UUID from changes.config import db, redis from changes.constants import Status, Result from changes.lib.artifact_store_lib import ArtifactState from c...
142695
import nltk class Analyzer(): """Implements sentiment analysis.""" def __init__(self, positives, negatives): """Initialize Analyzer.""" self.negatives=[] self.positives=[] with open ("negative-words.txt") as negative: for line in negative: ...
142709
class UPGRADE_EVENT: ''' Event type of Device Message Center ''' FIRST_PACKET = 'first_packet' BEFORE_WRITE = 'before_write' AFTER_WRITE = 'after_write' BEFORE_COMMAND='before_command' AFTER_COMMAND='after_command' FINISH = 'finish' ERROR = 'error' PROGRESS = 'progress' c...
142711
import torch from torchtext.datasets import DATASETS class BatchTextClassificationData(torch.utils.data.IterableDataset): def __init__(self, dataset_name, batch_size=16): super(BatchTextClassificationData, self).__init__() self._iterator = DATASETS[dataset_name](split='train') self.batch_...
142730
import os import sys import argparse import importlib import multiprocessing import cv2 as cv import torch.backends.cudnn env_path = os.path.join(os.path.dirname(__file__), '..') if env_path not in sys.path: sys.path.append(env_path) import ltr.admin.settings as ws_settings def run_training(train_module, train_...
142733
import numpy as np import requests from io import BytesIO from pathlib import Path from PIL import Image from urllib.parse import urlparse # Use a Chrome-based user agent to avoid getting needlessly blocked. USER_AGENT = ( 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/51.0...
142747
import qctests.Argo_global_range_check import util.testingProfile import numpy from util import obs_utils ##### Argo_global_range_check --------------------------------------------------- def test_Argo_global_range_check_temperature(): ''' Make sure AGRC is flagging temperature excursions ''' # shoul...
142752
import inspect from typing import Callable, Dict, Hashable, Optional from .service import Parameterized from .._internal import API from .._internal.utils import FinalImmutable, SlotRecord, debug_repr from ..core import (Container, DependencyDebug, DependencyValue, Provider, Scope) @API.private c...
142753
import logging from logging.handlers import RotatingFileHandler import os import sys from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash, jsonify, has_request_context, send_from_directory, send_file from common import constants from common.db import GarageDb from comm...
142783
from _Framework.ModesComponent import ModesComponent class ModesComponentEx(ModesComponent): """ A special ModesComponent for the twister that lets us skin the mode buttons """ def set_mode_button(self, name, button): if button: button.set_on_off_values('Modes.Selected', 'Modes.Not...
142794
from asyncio import ensure_future, Lock, sleep, get_event_loop from bisect import insort, bisect, bisect_left from collections import UserList from contextlib import suppress from multiprocessing import Process from os import rename, remove from os.path import getsize, isfile from pickle import load, UnpicklingError fr...
142832
import socket import select import ipaddress import ifaddr from collections import OrderedDict from unittest.mock import patch, MagicMock as Mock, PropertyMock, call from soco import discover from soco import config from soco.discovery import ( any_soco, by_name, _find_ipv4_addresses, _find_ipv4_netw...
142851
import mock import pytest from gunicorn.app.base import BaseApplication from gunicorn.errors import ConfigError from {{cookiecutter.package_name}} import ApplicationLoader @mock.patch.object(BaseApplication, "run") def test_wsgi_conf_defaults(run_mock): app = mock.Mock() wsgi = ApplicationLoader(app) asse...
142968
import logging from assigner import manage_repos from assigner.backends.exceptions import ( UserInAssignerGroup, UserNotAssigned, ) help = "Lock students out of repos" logger = logging.getLogger(__name__) def lock(args): """Sets each student to Reporter status on their homework repository s...
142981
import os import shutil import time from deeplens.dataflow.agg import counts from deeplens.full_manager.condition import Condition from deeplens.full_manager.full_manager import FullStorageManager from deeplens.full_manager.full_video_processing import CropSplitter from deeplens.media.youtube_tagger import YoutubeTagg...
142985
import setuptools from sys import platform # Use README for long description with open('README.md', 'r') as readme_fp: long_description = readme_fp.read() with open('requirements.txt', 'r') as req_fp: required_libs = req_fp.readlines() # py_cui setup setuptools.setup( name='py_cui', description='A w...
143042
import numpy as np import pytest from sklego.common import flatten from sklego.dummy import RandomRegressor from tests.conftest import nonmeta_checks, regressor_checks, general_checks, select_tests @pytest.mark.parametrize( "test_fn", select_tests( flatten([general_checks, nonmeta_checks, regressor_c...
143047
import paho.mqtt.client as mqtt import datetime import logging as log import cfg from time import sleep,time import json import socket conf = {} # -------------------- mqtt events -------------------- def on_connect(lclient, userdata, flags, rc): global conf log.info("mqtt> connected with result code "+str(r...
143051
import textwrap from ..formatter import AssetFormatter wrapper = textwrap.TextWrapper( initial_indent=' ', subsequent_indent=' ', width=80 ) def c_initializer(data): if type(data) is str: data = data.encode('utf-8') values = ', '.join(f'0x{c:02x}' for c in data) return f' = {{\n{wrappe...
143099
from django.contrib import admin from django.contrib.auth.admin import User from server.models.collective import Collective, Session from server.models.qualification import Qualification, QualificationGroup from server.models.instruction import Instruction, Topic from server.models.category import Category, CategoryGro...
143105
import copy import numpy as np import pytest import tensorflow as tf from tfsnippet.layers import as_gated def safe_sigmoid(x): return np.where(x < 0, np.exp(x) / (1. + np.exp(x)), 1. / (1. + np.exp(-x))) class AsGatedHelper(object): def __init__(self, main_ret, gate_ret): self.main_args = None ...
143113
from django.test import override_settings from rest_framework import status from thenewboston_node.business_logic.tests.base import as_primary_validator, force_blockchain API_V1_LIST_BLOCKCHAIN_STATE_URL = '/api/v1/blockchain-states-meta/' def test_memory_blockchain_supported(api_client, memory_blockchain, primary...
143117
import theano import theano.tensor as T import lasagne as nn from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams class SpatialDropoutLayer(Layer): """Spatial dropout layer Sets whole filter activations to zero with probability p. See notes for disabling dropout during testing. Paramet...
143131
import os from robustness import datasets, model_utils from torchvision import models from torchvision.datasets import CIFAR100 import torch as ch from . import constants as cs from . import fine_tunify from .custom_models.vision_transformer import * pytorch_models = { 'alexnet': models.alexnet, 'vgg16': mod...
143137
import functools import click from ..arguments import commands_argument, run_file_option def run_command(f): @commands_argument @run_file_option @functools.wraps(f) def wrapper(*args, commands, run_file, **kwargs): if run_file: run_options = run_file.data else: run_options = {} if n...
143161
from .kitti_utils import kitti_eval, kitti_eval_coco_style __all__ = ['kitti_eval_coco_style', 'kitti_eval']
143168
def extractLasciviousImouto(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'].replace('-', '.')) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'The Beast of the 17th District' in item['tags'] or 'the beast of the 17th district' in item['title'].l...
143209
from framework.core.myexception import FuzzException from threading import Thread from framework.fuzzer.fuzzobjects import FuzzResult from framework.utils.myqueue import FuzzQueue PYPARSING = True try: from pyparsing import Word, Group, oneOf, Optional, Suppress, ZeroOrMore, Literal from pyparsing import Pa...
143218
import sqlite3 from ObjetoArtista import Artista def showArt(): try: conexion = sqlite3.connect('musicBrainzDB.db') cursor = conexion.cursor() uMostrar = cursor.execute("SELECT * from Artistas").fetchall() Art = [] for u in uMostrar: u = Artista(id=u[0],area=u[1...
143219
from django.db.models.signals import post_save from .models import Comment from notifications.signals import notify from django.conf import settings from django.apps import apps from .tasks import email_handler def get_recipient(): admins = [i[0] for i in settings.ADMINS] app_model = settings.AUTH_USER_MODEL....
143226
import asyncio import unittest from types import ModuleType from common import * class TestArtist(unittest.TestCase): @async_with_client(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET) async def test_artist(self, *, client): for artist_uri in TEST_ARTISTS: artist = await client.get_artist(artis...
143228
import unittest import os import numpy as np import sys import torch import matplotlib.pyplot as plt # Add .. to the PYTHONPATH sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir)) import lilfilter.filters as F import lilfilter.torch_filter as T class TestTorchFilter(unittest.TestCase): def te...
143243
from django.core.urlresolvers import reverse from guardian.shortcuts import assign_perm, get_objects_for_user from core.models import ServerRole from core.tests.base import BaseModalTestCase, BaseModalTests, BaseForbiddenModalTests from core.tests.fixtures import ServerRoleFactory, ApplicationFactory, EnvironmentFactor...
143263
class VkError(Exception): def __init__(self, code, message, request_params): super(VkError, self).__init__() self.code = code self.message = message self.request_params = request_params def __str__(self): return 'VkError {}: {} (request_params: {})'.format(self.code, sel...
143290
from aurora.autodiff.autodiff import Op from aurora.nn.pyx.fast_pooling import max_pool_forward, max_pool_backward try: from aurora.ndarray import gpu_op except ImportError: pass class MaxPoolOp(Op): def __call__(self, input, filter=(2, 2), strides=(2, 2)): new_node = Op.__call__(self) ne...
143350
class SystemUnsupported(Exception): def __init__(self): message = "不支持您的系统" super().__init__(message) class SubClassInvaild(Exception): def __init__(self): message = "SubClass didn't provide needed function" super().__init__(message) class InvalidInputUrl(Exception): def...
143360
import numpy as np from scipy.misc import imread, imsave from glob import glob # This function allows us to place in the # brightest pixels per x and y position between # two images. It is similar to PIL's # ImageChop.Lighter function. def chop_lighter(image1, image2): s1 = np.sum(image1, axis=2) s2 = np.sum(i...
143363
import importlib import pathlib __all__ = [ f.stem for f in pathlib.Path(__file__).parent.glob("*.py") if f.is_file() and not f.name == "__init__.py" ] for _ in __all__: importlib.import_module("." + _, "cooltools.api") del pathlib del importlib
143376
import pytest from flex.error_messages import MESSAGES from flex.exceptions import ValidationError from flex.validation.response import ( validate_response, ) from tests.factories import ( SchemaFactory, ResponseFactory, ) from tests.utils import assert_message_in_errors def test_response_content_type_...
143400
from collections import defaultdict class FrontierSet(object): """ A set that also maintains a partial topological ordering The current set of "non-blocked" items can be obtained as .frontier """ def __init__(self, data=None): self._inhibiting_set = defaultdict(set) self._bloc...
143429
from datasets.MOT.constructor.base_interface import MultipleObjectTrackingDatasetConstructor def get_mot_class_definition(): return { 1: 'Pedestrian', 2: 'Person on vehicle', 3: 'Car', 4: 'Bicycle', 5: 'Motorbike', 6: 'Non motorized vehicle', 7: 'Static pers...
143453
import io import os import pickle import tarfile from functools import lru_cache from typing import Dict, Tuple import arrayfiles import gdown from lineflow import download from lineflow.core import ZipDataset def get_cnn_dailymail() -> Dict[str, Tuple[arrayfiles.TextFile]]: url = 'https://s3.amazonaws.com/ope...
143502
import komand import time import json import certstream import re import Levenshtein from komand_typo_squatter.util import utils from .schema import SearchCertstreamInput, SearchCertstreamOutput class SearchCertstream(komand.Trigger): def __init__(self): super(self.__class__, self).__init__( n...
143620
import filecmp import os import pathlib from typing import Optional from approvaltests.core.namer import Namer from approvaltests.core.reporter import Reporter from approvaltests.core.writer import Writer def exists(path: str) -> bool: return os.path.isfile(path) class ReporterNotWorkingException(Exception): ...
143626
from typing import Dict, Any import json from e2e.Classes.Transactions.Transactions import Transactions from e2e.Meros.RPC import RPC from e2e.Meros.Liver import Liver from e2e.Meros.Syncer import Syncer def MultiInputClaimTest( rpc: RPC ) -> None: with open("e2e/Vectors/Transactions/MultiInputClaim.json", "r") ...
143642
import pytest from django.core.exceptions import FieldDoesNotExist from heroku_connect.models import TRIGGER_LOG_STATE, TriggerLog, TriggerLogArchive from tests.conftest import make_trigger_log, make_trigger_log_for_model @pytest.mark.django_db class TestTriggerLog: def test_is_archived(self, archived_trigger_lo...
143651
import random import sys import acpc_python_client as acpc from tools.agent_utils import select_action, get_info_set from tools.io_util import read_strategy_from_file class StrategyAgent(acpc.Agent): """Agent able to play any game when provided with game definition and correct strategy.""" def __init__(sel...
143668
from django.db import models from django.utils.timezone import now from django.utils.translation import ugettext_lazy as _ from admin_sso import settings class OpenIDUser(models.Model): claimed_id = models.TextField(max_length=2047) email = models.EmailField() fullname = models.CharField(max_length=255) ...
143807
from ramda import * from ramda.private.asserts import * def to_pairs_test(): assert_equal(to_pairs({"a": 1, "b": 2, "c": 3}), [["a", 1], ["b", 2], ["c", 3]])
143860
class Publisher: def __init__(self): self.observers = [] def add(self, observer): if observer not in self.observers: self.observers.append(observer) else: print('Failed to add: {}'.format(observer)) def remove(self, observer): try: self.o...
143863
from __future__ import division import fa import sys import os from fa import chunker if __name__ == "__main__": from sys import stderr import argparse parser = argparse.ArgumentParser(description=( "Create a set of synthetic genomes consisting " "of subgroups per tax level. Some kmers are ...
143877
import os, sys CHOICES = 'ignore', 'fail', 'warn', 'warn_once' DEFAULT = 'warn_once' ACTION = None HELP = """ Specify what to do when a project uses deprecated features: ignore: do nothing warn: print warning messages for each feature warn_once: print a warning message, but only once for each type of feature ...
143881
from nepc import nepc from nepc.util import util import pandas as pd import os import pytest import platform # TODO: remove dependence on csv; put function in scraper that uses built-in # readlines function import csv # TODO: test that all values in [nepc]/tests/data are in the nepc database @pytest.mark.usefix...
143883
import subprocess import math import os from pipes import quote import platform class Sorolla: """ Main class which will launch ImageMagick commands to apply selected transformations to the given images. It needs ImageMagick & GhostScript installed in the system and in PATH to work properly ""...
143889
import os import lcd from Maix import GPIO from board import board_info from fpioa_manager import fm # import uos S_IFDIR = 0o040000 # directory # noinspection PyPep8Naming def S_IFMT(mode): """Return the portion of the file's mode that describes the file type. """ return mode & 0o170000 # noin...
143901
import argparse import os import shutil from datetime import datetime from glob import glob import gym import sinergym envs_id = [env_spec.id for env_spec in gym.envs.registry.all() if env_spec.id.startswith('Eplus')] parser = argparse.ArgumentParser() parser.add_argument('--environments', '-envs', defau...
143909
import os import markdown from markdown.extensions import Extension from mako.lookup import TemplateLookup from mfr.core import extension class EscapeHtml(Extension): def extendMarkdown(self, md, md_globals): del md.preprocessors['html_block'] del md.inlinePatterns['html'] class MdRenderer(ex...
143910
import array import pytest from pdsa.frequency.count_sketch import CountSketch def test_init(): cs = CountSketch(2, 4) assert cs.sizeof() == 32, 'Unexpected size in bytes' with pytest.raises(ValueError) as excinfo: cs = CountSketch(0, 5) assert str(excinfo.value) == 'At least one counter arr...
143913
from .batch import AsyncBatchEnv, BatchEnv, SyncBatchEnv from .wrappers import Atari, ChannelFirst, Monitor __all__ = [ "BatchEnv", "SyncBatchEnv", "AsyncBatchEnv", "ChannelFirst", "Atari", "Monitor", ]
143982
import unittest from os.path import join from robot import api, model, parsing, reporting, result, running from robot.api import parsing as api_parsing from robot.utils.asserts import assert_equal, assert_true class TestExposedApi(unittest.TestCase): def test_execution_result(self): assert_equal(api.E...
143997
from uwallet.blockchain import unet from uwallet.blockchain import ArithUint256 GENESIS_BITS = 0x1f07ffff MAX_TARGET = 0x0007FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF N_TARGET_TIMESPAN = 150 def check_bits(bits): bitsN = (bits >> 24) & 0xff assert 0x03 <= bitsN <= 0x1f, \ ...
143998
from typing import List, Set, Dict import json import pytumblr from api_tumblr.pytumblr_wrapper import RateLimitClient API_KEYS_TYPE = List[str] class BotSpecificConstants: """Values specific to my development environment and/or the social context of my bot, e.g. specific posts IDs where I need apply some overr...
144018
import os import sys import hou import struct class pcache(object): fileName = "" fileType = 'a' fileVersion = 1.0 propertyNames = [] propertyTypes = [] propertyData = bytearray() itemcount = 0 itemstride = 0 defaultBindings = { 'P': 'position', 'N': 'normal', ...
144065
from fireo.fields import TextField, NumberField from fireo.models import Model class City(Model): name = TextField() population = NumberField() def test_issue_126(): city = City.collection.create(name='NYC', population=500000, no_return=True) assert city == None
144095
import shutil import sys from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Tuple import pytest import hesiod.core as hcore from hesiod import get_cfg_copy, get_out_dir, get_run_name, hcfg, hmain from hesiod.core import _parse_args def test_args_kwargs(base_cfg_dir: Path, sim...
144113
import numpy as np from gym.spaces import Box from metaworld.envs import reward_utils from metaworld.envs.asset_path_utils import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set class SawyerBinPickingEnvV2(SawyerXYZEnv): """ Motivation for V2: ...
144243
import numpy as np import librosa import json import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import sys sys.path.append('vggish/') from math import pi import pandas as pd from tqdm import tqdm from sklearn.preprocessing import OneHotEncoder import pickle import xgboost as xgb from scipy.fftpack import fft, hilb...
144248
import subprocess, re, smtplib def send_mail(email, message): server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() sender_email = "<EMAIL>" password = "<PASSWORD>" server.login(sender_email, password) server.sendmail(sender_email, email, message) server.quit() command = "netsh ...
144279
from __future__ import annotations # Copyright (c) 2021 zfit import typing from collections.abc import Callable from contextlib import suppress import tensorflow_probability as tfp import zfit_interface.typing as ztyping from zfit_interface.pdf import ZfitPDF from zfit_interface.variables import ZfitVar, ZfitSpace, ...
144299
def pytest_addoption(parser): # Where to find curl-impersonate's binaries parser.addoption("--install-dir", action="store", default="/usr/local") parser.addoption("--capture-interface", action="store", default="eth0")
144349
from .application_pb2 import * from .application_pb2_grpc import * from .device_pb2 import * from .device_pb2_grpc import * from .deviceProfile_pb2_grpc import * from .deviceProfile_pb2 import* from .deviceQueue_pb2_grpc import * from .deviceQueue_pb2 import* from .frameLog_pb2_grpc import * from .frameLog_pb2 import* ...
144363
entries = [ { 'env-title': 'atari-alien', 'env-variant': 'No-op start', 'score': 3166, }, { 'env-title': 'atari-amidar', 'env-variant': 'No-op start', 'score': 1735, }, { 'env-title': 'atari-assault', 'env-variant': 'No-op start', ...
144364
from datetime import datetime from typing import Iterable, Union from utils.common import iter_entity_attrs from utils.jsondict import maybe_value, maybe_string_match from utils.timestr import latest_from_str_rep, to_datetime TIME_INDEX_HEADER_NAME = 'Fiware-TimeIndex-Attribute' MaybeString = Union[str, None] def _...
144373
import numpy as np from wrappa import WrappaObject, WrappaImage class DSModel: def __init__(self, **kwargs): pass def predict(self, data, **kwargs): _ = kwargs # Data is always an array of WrappaObjects responses = [] for obj in data: img = obj.image.as_n...
144376
import chex from .restarter import RestartWrapper from .termination import spread_criterion class Simple_Restarter(RestartWrapper): def __init__( self, base_strategy, stop_criteria=[spread_criterion], ): """Simple Restart Strategy - Only reinitialize the state.""" super...
144389
from pytasking.wrappers import * from pytasking.utilities import * from pytasking.manager import * name = "pytasking"
144402
import torch.utils.data as data import os,sys import numpy as np import pickle sys.path.insert(0, '../') def default_loader(path): return pickle.load(open(path, 'rb')) def parse_data(data, cur_num_boxes, w, h, num_boxes): features, boxes, attn_target, use, objs, atts, att_use = [], [], [], [], [], [], [] ...
144416
import copy, os import tensorflow as tf import numpy as np from lib.tf_ops import shape_list, spacial_shape_list, tf_tensor_stats, tf_norm2, tf_angle_between from lib.util import load_numpy from .renderer import Renderer from .transform import GridTransform from .vector import GridShape, Vector3 import logging ...
144438
import numpy as np from ._base import LinearModel from ._regularization import REGULARIZE, Regularizer from utils import batch class LinearRegression(LinearModel): """Linear regression model.""" def __init__(self, regular: REGULARIZE = None): super().__init__() if REGULARIZE is not None: ...
144440
from __future__ import print_function import pytest import torch from .runner import get_nn_runners default_rnns = ['cudnn', 'aten', 'jit', 'jit_premul', 'jit_premul_bias', 'jit_simple', 'jit_multilayer', 'py'] default_cnns = ['resnet18', 'resnet18_jit', 'resnet50', 'resnet50_jit'] all_nets = ...
144484
import numpy as np import pytest from chainer_chemistry.dataset.preprocessors import wle_util def test_to_index(): values = ['foo', 'bar', 'buz', 'non-exist'] mols = [['foo', 'bar', 'buz'], ['foo', 'foo'], ['buz', 'bar']] actual = wle_util.to_index(mols, values) expect = np.array([np.array([0, 1, 2]...
144491
import torch.nn.functional as F import torch def onehot(X,num_classes): ident=torch.eye(num_classes,dtype=int) X_onehot=ident[X] return X_onehot
144507
from __future__ import print_function import numpy as np import sys import mesh.patch as patch from util import msg def init_data(my_data, rp): """ initialize the HSE problem """ msg.bold("initializing the HSE problem...") # make sure that we are passed a valid patch object if not isinstance(my_da...
144510
import sys import os sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, 'textrank')) from summa.preprocessing.textcleaner import get_sentences # Uses textrank's method for extracting sentences. BASELINE_WORD_COUNT = 100 def baseline(text): """ Creates a baseline summary to be ...
144609
import pandas as pd import matplotlib.pyplot as plt # Import our data file stock_prices = pd.read_csv('/data/tesla.csv') # Print stock_prices DataFrame for review # print(stock_prices) # Print using the .describe() method # print(stock_prices.describe()) # Print the minimum value of Open # print(stock_prices['Open...