id
stringlengths
3
8
content
stringlengths
100
981k
1616468
import os import cv2 import xml.etree.ElementTree as ET import numpy as np # This function is used to load data # Path to image file, and xml_file are given as input, and it returns image, bounding_box, class as output def read_sample(image_path, label_path): image_path = image_path.strip("\n") label_path = l...
1616481
import bg_helper as bh import fs_helper as fh import input_helper as ih import settings_helper as sh from redis import StrictRedis, ConnectionError from time import sleep __doc__ = """Create an instance of `redis_helper.Collection` and use it import redis_helper as rh model = rh.Collection(...) """ logger = fh.get...
1616486
from django.db import models class Person(models.Model): COUNTRIES = ('Germany', 'France', 'Italy') first_name = models.CharField('First name', max_length=64) last_name = models.CharField('Last name', max_length=64, blank=True) country = models.CharField( 'Country', max_length=32, choices=zi...
1616588
import numpy as np from . import _fastmath_ext __all__ = ['polar_dec'] def polar_dec(matrices): """ Batched polar decomposition of an array of stacked matrices, e.g. given matrices [M1, M2, ..., Mn], decomposes each matrix into rotation and skew-symmetric matrices. >>> matrices = np.random.rand...
1616595
import json import typing from flask import Response as FlaskResponse from cauldron import environ from cauldron.cli import server Responses = typing.NamedTuple('TestResponses', [ ('flask', FlaskResponse), ('response', 'environ.Response') ]) def create_test_app(): """...""" return server.server_ru...
1616630
import copy import numpy as np import torch class Memory: def __init__(self, memory_size, nb_total_classes, rehearsal, fixed=True): self.memory_size = memory_size self.nb_total_classes = nb_total_classes self.rehearsal = rehearsal self.fixed = fixed self.x = self.y = self...
1616637
import os from dagster.core.storage.pipeline_run import PipelineRunStatus from dagster.core.test_utils import poll_for_finished_run from dagster.utils.merger import merge_dicts from dagster.utils.yaml_utils import merge_yamls from dagster_test.test_project import ( ReOriginatedExternalPipelineForTest, find_loc...
1616641
import subprocess from django.conf import settings from django.core.files.temp import NamedTemporaryFile class PenthouseCommand(object): command = '{phantomjs} {penthouse} {htmlurl} {csspath}' encoding = 'utf8' def __init__(self, phantomjs=None, penthouse=None): self.phantomjs = phantomjs or set...
1616652
from unittest.mock import MagicMock from mpf.platforms.interfaces.driver_platform_interface import PulseSettings from mpf.core.platform import SwitchSettings, DriverSettings from mpf.tests.MpfTestCase import MpfTestCase class TestKickback(MpfTestCase): def get_config_file(self): return 'config.yaml' ...
1616668
import sphinx_rtd_theme def get_version(): import pandas_plink return pandas_plink.__version__ extensions = [ "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx.ext.doctest", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.viewcode", "sphinx_autodoc_typehints",...
1616669
import os from typing import Dict from google.cloud import datastore from testcontainers.core.container import DockerContainer from testcontainers.core.waiting_utils import wait_for_logs from tests.integration.feature_repos.universal.online_store_creator import ( OnlineStoreCreator, ) class DatastoreOnlineStore...
1616716
from math import log, exp, sqrt, tanh, sin, cos, tan, atan2, ceil, pi import numpy as np from OpenGL.GL import * from PyEngine3D.Common import logger from PyEngine3D.App import CoreManager from PyEngine3D.OpenGLContext import CreateTexture, Texture2D, Texture2DArray, Texture3D, FrameBuffer from PyEngine3D.Render impo...
1616764
import sys import numpy as np import math import librosa import soundfile as sf import json from librosa.core.spectrum import power_to_db import scipy file_path = sys.argv[1] data, samplerate = sf.read(file_path) #data = np.clip(data*3, -1, 1) with open("MfccConfig.json", "r") as f: config = json.load(f) frame_s...
1616767
import logging from django.db import connection from django.core.management.base import BaseCommand from usaspending_api.etl.management.helpers.recent_periods import retrieve_recent_periods logger = logging.getLogger("script") UPDATE_AWARDS_SQL = """ WITH recent_covid_awards AS ( SELECT DISTINCT ON ...
1616783
from unittest.mock import MagicMock, patch import pytest from PySide2.QtGui import QClipboard from PySide2.QtTest import QTest from node_launcher.gui.menu.menu import Menu @pytest.fixture def menu() -> Menu: system_tray = MagicMock() node_set = MagicMock() node_set.tor_node.network = 'tor' node_set....
1616823
import os import sys import subprocess import platform import helpers from io import open def run(): test_name = 'optest' config = 'Release' libExt = helpers.static_lib_extensions() dc = helpers.detect_compiler() extra_args = list() helpers.setup_args(extra_args, config=config) if (helper...
1616830
import unittest import torch from laia.decoders import CTCNBestDecoder class CTCNBestDecoderTest(unittest.TestCase): def test(self): x = torch.tensor( [ [[1.0, 3.0, -1.0, 0.0]], [[-1.0, 2.0, -2.0, 3.0]], [[1.0, 5.0, 9.0, 2.0]], ...
1616854
import KratosMultiphysics as KM import KratosMultiphysics.KratosUnittest as KratosUnittest class TestPoint(KratosUnittest.TestCase): def test_point_constructor_with_kratos_array(self): coords = [1.0, -2.5, 3.3] arr = KM.Array3(coords) point = KM.Point(arr) self.assertAlmostEqual(p...
1616931
from itertools import islice from typing import Iterable, TypeVar import numpy as np from six import string_types # alphabets: from kipoiseq import Variant DNA = ["A", "C", "G", "T"] RNA = ["A", "C", "G", "U"] AMINO_ACIDS = ["A", "R", "N", "D", "B", "C", "E", "Q", "Z", "G", "H", "I", "L", "K", "M", "F...
1616941
import random import os import pickle import librosa as lb import numpy as np import musdb import yaml # ignore warning about unsafe loaders in pyYAML 5.1 (used in musdb) # https://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation yaml.warnings({'YAMLLoadWarning': False}) def musdb_pre_processing(pat...
1616972
from burp import IBurpExtender from burp import IHttpListener from burp import IProxyListener import re import sys import os urls_in_scope=['testblah.com','qa.ooboob.com'] #Adding directory to the path where Python searches for modules module_folder = os.path.dirname('/home/arvind/Documents/Me/My_Projects/Git/WebAppse...
1616979
SPARQL_ENDPOINTS = { 'ontocompchem': 'http://theworldavatar.com/blazegraph/namespace/ontocompchem/sparql', 'ontospecies': 'http://theworldavatar.com/blazegraph/namespace/ontospecies/sparql', 'ontopesscan': 'http://theworldavatar.com/blazegraph/namespace/ontopesscan/sparql' }
1616987
import torch import numpy as np import pandas as pd import os class MNIST: def __init__(self, DATASET_DIR='./dataset/MNIST/'): self.DATASET_DIR = DATASET_DIR def fit_normalizer(self, x): self.min = np.min(x) self.max = np.max(x) def transform_normalizer(self, x): return (x - self.min)/(self.max - self.min...
1617027
from re import T import re import bpy import os import math import bmesh from . import Global from . import DtbShapeKeys from . import Versions from . import DataBase from . import Util class ToRigify: notEnglish = False amtr_objs = [] METARIG = None RIG = None chest_upper_tail = [] neck_lower...
1617050
import boto3 import pytest from botocore.exceptions import ClientError import xoto3.dynamodb.write_versioned as wv from xoto3.dynamodb.write_versioned import delete from xoto3.dynamodb.write_versioned.ddb_api import ( built_transaction_to_transact_write_items_args, is_cancelled_and_retryable, known_key_sch...
1617089
import networkx as nx import numpy as np import pandas as pd from tqdm import tqdm from feature_engineering.tools import lit_eval_nan_proof # this script computes some features by considering the bidirectional graph of citations: jaccard, adar, # preferential_attachment, resource_allocation_index and common_neighbor...
1617109
import json import logging import pathlib import typing import yaml import znjson log = logging.getLogger(__name__) def read_file(file: pathlib.Path) -> dict: """Read a json/yaml file without the znjson.Decoder Parameters ---------- file: pathlib.Path The file to read Returns -----...
1617202
import os import pathlib from os.path import dirname from os.path import join from astride.detect import Streak from astride.utils.logger import Logger def test(file_path = '/Users/Owner/Desktop/Fits Files/Fits'): logger = Logger().getLogger() logger.info('Start.') module_path = dirname(__file__) ...
1617215
from elote.competitors.elo import EloCompetitor from elote.competitors.glicko import GlickoCompetitor from elote.competitors.ecf import ECFCompetitor from elote.competitors.dwz import DWZCompetitor from elote.competitors.ensemble import BlendedCompetitor from elote.arenas.lambda_arena import LambdaArena __all__ = [ ...
1617216
from django.contrib import admin from .models import Mirror class MirrorAdmin(admin.ModelAdmin): list_display = ['name', 'ip', 'hostname', 'content_url', 'enabled',] list_editable = ['ip', 'hostname', 'content_url', 'enabled',] admin.site.register(Mirror, MirrorAdmin)
1617249
import unittest import warnings from pathlib import Path import pronto class TestOboJsonExamples(unittest.TestCase): def setUp(self): warnings.simplefilter("error") def tearDown(self): warnings.simplefilter(warnings.defaultaction) @staticmethod def get_path(name): folder = ...
1617299
class ZaloAppInfo: def __init__(self, app_id, secret_key): self.app_id = app_id self.secret_key = secret_key self.callback_url = None
1617312
from typing import Callable from telegram import InlineKeyboardMarkup, InlineKeyboardButton def paginate(total: int, offset: int, items_per_page: int, callback_data_generator: Callable[[int], str]) -> InlineKeyboardMarkup: """ make `InlineKeyboardMarkup` with "back" / "forward" buttons if approp...
1617321
from collections import defaultdict from dataclasses import dataclass, fields from itertools import chain, filterfalse from typing import ( Any, Callable, Collection, Iterable, Iterator, Mapping, Optional, Set, Tuple, TypeVar, ) flatten = chain.from_iterable _T1 = TypeVar("_T1...
1617324
from django.db import models class Resource(models.Model): """Model representing a Resource that contains the resource's name, description and an external link to the resource. All the fields are required.""" name = models.CharField(max_length=50) link = models.URLField(max_length=200) description...
1617326
from humpday.objectives.classic import CLASSIC_OBJECTIVES import logging import numpy as np import math import warnings try: from hebo.design_space.design_space import DesignSpace from hebo.optimizers.hebo import HEBO using_hebo = True except ImportError: using_hebo = False if using_hebo: loggin...
1617330
def exchange_sort(numbers: list[int]) -> list[int]: """ Uses exchange sort to sort a list of numbers. Source: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort >>> exchange_sort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> exchange_sort([-1, -2, -3]) [-3, -2, -1] >>> exchange_sort([1...
1617335
import pickle import numpy as np from tqdm.auto import tqdm import moses from moses import CharVocab class NGram: def __init__(self, max_context_len=10, verbose=False): self.max_context_len = max_context_len self._dict = dict() self.vocab = None self.default_probs = None se...
1617336
from django.core.exceptions import ValidationError from django.db.models import Q from django.forms import widgets from django.forms.fields import BooleanField, ChoiceField, MultipleChoiceField from django.utils.safestring import mark_safe from django.utils.text import format_lazy from django.utils.translation import n...
1617391
class GeneralPogoException(Exception): """Throw an exception that moves up to the start, and reboots"""
1617423
from __future__ import absolute_import from . import data from . import data_augmentation from . import data_normalization from . import iterator from . import standardizer from . import tta from . import preprocessor
1617494
import tensorflow as tf import pickle from models.nets.CPM import CPM class CPM_Model(CPM): def __init__(self, input_size, heatmap_size, stages, joints, img_type='RGB', is_training=True): self.stages = stages self.stage_heatmap = [] self.stage_loss = [0 for _ in range(stages)] self...
1617507
import os from itertools import product from typing import Dict, List, Optional, Tuple, Union import torch from torch import Tensor from torch.nn.functional import log_softmax from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence from transformers import PreTrainedTokenizer from diagnnose.activations.se...
1617553
import chex import jax import jax.numpy as jnp from typing import Callable, Optional, Tuple from .moment import MomentTransform, MomentTransformClass from chex import Array, dataclass import tensorflow_probability.substrates.jax as tfp dist = tfp.distributions class UnscentedTransform(MomentTransformClass): def ...
1617559
from ..utils import attack, change_parameter XSS_STRING = u'<script>alert("XSS_STRING");</script>' def attack_post(client, log, form): # A helper function for modifing values of the parameter list. def modify_parameter(target_name, value): parameters = dict(form.get_parameters()) parameters[t...
1617587
import matplotlib.pyplot as plt import numpy as np import torch import cv2 def draw_figure(fig): fig.canvas.draw() fig.canvas.flush_events() plt.pause(0.001) def show_tensor(a: torch.Tensor, fig_num = None, title = None, range=(None, None), ax=None): """Display a 2D tensor. args: ...
1617603
import json from django.http import HttpResponse from gerapy.server.core.encoder import JSONEncoder class JsonResponse(HttpResponse): """ An HTTP response class that consumes data to be serialized to JSON. :param data: Data to be dumped into json. By default only ``dict`` objects are allowed to b...
1617648
from django.utils.translation import ugettext_lazy as _ EQUAL = 0 LESS_THAN = 1 LESS_THAN_EQUAL = 2 GREATER_THAN = 3 GREATER_THAN_EQUAL = 4 CONTAIN = 5 IS = 10 IS_NOT = 11 IS_VALID = 12 IS_NOT_VALID = 13 NUMBER_OPERATORS = ( (EQUAL, _(u"Equal to")), (LESS_THAN, _(u"Less than")), (LESS_THAN_EQUAL, _(u"Les...
1617684
import pickle # Save model #import matplotlib.pyplot as plt import re # regular expression library from random import random, choice # for random strategy from operator import itemgetter import numpy as np from scipy.sparse import csgraph from scipy.spatial import distance from sklearn.cluster import KMeans from s...
1617693
from .coordattention import CoordAttention, H_Sigmoid, H_Swish from .involution import Involution from .identity import Identity from .droppath import DropPath, droppath
1617718
import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import ConfigSpace from autoPyTorch.components.networks.base_net import BaseImageNet from autoPyTorch.utils.config_space_hyperparameter import add_hyperparameter, get_hyperparameter from autoPyTorch.comp...
1617756
from __future__ import absolute_import from torch import nn from torch.nn import functional as F from torch.nn import init import torchvision import torch import random from .gem import GeneralizedMeanPoolingP __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] class Wavebl...
1617768
from verifai.simulators.webots.webots_task import webots_task from verifai.simulators.webots.client_webots import ClientWebots from math import sin from math import cos import numpy as np from math import atan2 from collections import namedtuple import os from dotmap import DotMap import pickle from shapely.geometry im...
1617777
from enum import Enum class LogType(Enum): Info = 0 Success = 1 Fail = 2 Error = 3 Subtle = 4 Process = 5
1617791
from numpy import loadtxt, ndarray, min, max from sklearn.metrics import adjusted_mutual_info_score, adjusted_rand_score, fowlkes_mallows_score from SNNDPC import SNNDPC if __name__ == '__main__': # Parameter # -------------------------------------------------------------------------------- # pathData = "../data/...
1617818
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap # Lots of different places that widgets could come from... try: from ipywidgets import interact, FloatSlider, IntSlider except ImportError: import warnings # ignore ShimWarning raised by IPython, see GH...
1617845
import argparse import os import torch import yaml import numpy as np import torch.nn.functional as F import config_folder as cf from data_loaders.Chairs import Chairs from data_loaders.kitti import KITTI from data_loaders.sintel import Sintel from model import MaskFlownet, MaskFlownet_S, Upsample, EpeLossWithMask fro...
1617919
import os,argparse,time import numpy as np from omegaconf import OmegaConf import torch import torch.backends.cudnn as cudnn import torch.utils.data import utils import wandb tstart=time.time() # Arguments parser = argparse.ArgumentParser(description='RRR') parser.add_argument('--config', type=str, default='./conf...
1617968
import weakref from yggdrasil.metaschema import MetaschemaTypeError from yggdrasil.metaschema.properties.MetaschemaProperty import ( MetaschemaProperty) from yggdrasil.metaschema.properties.JSONArrayMetaschemaProperties import ( ItemsMetaschemaProperty) class ArgsMetaschemaProperty(MetaschemaProperty): r"...
1618004
from requests import get from sqlalchemy import ForeignKey, Integer from eNMS.database import db from eNMS.forms import ServiceForm from eNMS.fields import HiddenField from eNMS.models.automation import Service from eNMS.variables import vs class SwissArmyKnifeService(Service): __tablename__ = "swiss_army_knife...
1618010
from datetime import timedelta from django.test import TestCase from ..models import GameSession from ..resources import GamesPlayedResource from .factories import GameSessionFactory class ExportTests(TestCase): def test_export_correctly(self): GameSessionFactory.create(game__name='Overwatch', duration...
1618069
import sqlite3 import os MAX_DEPTH_CHAIN = 10 P_INSTANCE_OF = 31 P_SUBCLASS = 279 MAX_ITEMS_CACHE = 100000 conn = None entity_cache = {} chain_cache = {} DB_DEFAULT_PATH = os.path.abspath(__file__ + '/../../data_spacy_entity_linker/wikidb_filtered.db') wikidata_instance = None def get_wikidata_instance(): gl...
1618092
from uiautomator import Device device = Device() resource_id_dict = { 'salary': 'com.hpbr.bosszhipin:id/tv_position_salary', 'company': 'com.hpbr.bosszhipin:id/tv_company_name', 'address': 'com.hpbr.bosszhipin:id/tv_location', 'experence': 'com.hpbr.bosszhipin:id/tv_work_exp', 'degree': 'com.hpbr.b...
1618097
from diagrams import Diagram from diagrams.onprem.client import Users from diagrams.onprem.container import Docker from diagrams.programming.framework import Spring graph_attr = { "fontsize": "20", "bgcolor": "white" # transparent } with Diagram("", direction="LR", graph_attr=graph_attr, outformat="png", filenam...
1618130
from aiogram.types import ChatMemberUpdated from aiogram.dispatcher.filters import BaseFilter """ Note: Currently these filters don't check for group ownership transfer Consider this a #TODO """ class AdminAdded(BaseFilter): async def __call__(self, event: ChatMemberUpdated) -> bool: return event.new_ch...
1618172
from pathlib import Path import pandas as pd from autofe.get_feature import get_baseline_total_data, train_and_evaluate from xgboost import XGBRegressor if __name__ == '__main__': ROOTDIR = Path('./') PROCESSED_DATA_DIR = ROOTDIR / 'data/processed_data/house/' train_datafile = PROCESSED_DATA_DIR / 'train...
1618188
from ..common.optim import SGD as optimizer from ..common.coco_schedule import lr_multiplier_1x as lr_multiplier from ..common.data.coco import dataloader from ..common.models.mask_rcnn_fpn import model from ..common.train import train model.backbone.bottom_up.freeze_at = 2 train.init_checkpoint = "detectron2://ImageN...
1618202
from django.contrib.auth.models import AnonymousUser class FakeSuperuserMiddleware(object): def process_request(self, request): request.user = AnonymousUser() request.user.is_superuser = True
1618260
from AdminPage import AdminPage # Set this to False if you want to allow everyone to access secure pages # with no login required. This should instead come from a config file. requireLogin = True if not requireLogin: class AdminSecurity(AdminPage): def writeHTML(self): session = self.sessio...
1618277
from garcon import log class MockLogClient(log.GarconLogger): """Mock of an object for which we want to add a Garcon logger """ domain = 'test_domain' # Valid execution context execution_context = { 'execution.domain': 'dev', 'execution.run_id': '123abc=', 'execution.workflow_id': 'test-work...
1618305
from instapi.client_api.base import BaseClient from ..conftest import random_string def test_redirect_to_base(mocker): mocker.patch("instagram_private_api.client.Client.__init__", return_value=None) mock = mocker.patch("instagram_private_api.client.Client._call_api", return_value=None) client = BaseClie...
1618322
import base64 from datetime import timedelta from django.conf import settings from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.hashers import make_password from django.utils import timezone from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import Ob...
1618343
class Plugin(object): def onNew(self, view): pass def onClone(self, view): pass def onLoad(self, view): pass def onClose(self, view): pass def onPreSave(self, view): pass def onPostSave(self, view): pass def onModified(self, view):...
1618352
import logging from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from helium.common.views.views import HeliumAPIView from helium.planner.models import Course, CourseSchedule from helium.planner.schemas import CourseScheduleDetailSchema from helium.planner.serializers....
1618361
from __future__ import absolute_import, print_function, unicode_literals try: from unittest.mock import patch, MagicMock except ImportError: from mock import MagicMock, patch from rest_framework_latex import renderers from tests.testrenderers.tests.test_latex import RendererTestCase class CallbackTestCase(R...
1618381
import os import asyncio import hashlib import pathlib import synapse.tests.utils as s_t_utils import synapse.tools.pullfile as s_pullfile class TestPullFile(s_t_utils.SynTest): async def test_pullfile(self): async with self.getTestAxon() as axon: axonurl = axon.getLocalUrl() t...
1618382
from torch import nn import os from src.encoder import encoder_dict from src.neuralblox import models, training, training_fusion from src.neuralblox import generation, generation_fusion from src import data from src.common import decide_total_volume_range, update_reso def get_model(cfg, device=None, dataset=None, **kw...
1618416
from bson.objectid import ObjectId from pymongo.results import UpdateResult from project.infrastructure.drivers.mongo.adapter import MongoAdapter class MongoDataLayer(MongoAdapter): def __init__(self, collection: str) -> None: """ Generic access data layer to MongoDB """ super().__...
1618447
import requests from typing import List from .util import PlacementPreference from .storyprovider import StoryProvider from .story import Story class WeatherStoryProvider(StoryProvider): def __init__(self, woe: str = "2358820", F: bool = True): self.woe = woe self.F = F def CtoF(self, temp: ...
1618470
import sqlite3 from hacksport.problem import files_from_directory, PHPApp, ProtectedFile class Problem(PHPApp): files = files_from_directory("webroot/") + [ProtectedFile("users.db")] php_root = "webroot/" num_workers = 5 def setup(self): conn = sqlite3.connect("users.db") c = conn.cu...
1618531
from pyinstagram.entities import Account, Comment, Location, Media, Story, Tag import pytest from random import randint, choice from string import ascii_uppercase, ascii_lowercase, digits def setup_function(): Account.clear_cache() Comment.clear_cache() Location.clear_cache() Media.clear_cache() S...
1618598
from seamless.highlevel import Context import traceback ctx = Context() ctx.code = "head -$lines testdata > RESULT" ctx.code.celltype = "text" ctx.tf = lambda lines, testdata: None ctx.tf.language = "bash" ctx.tf.docker_image = "ubuntu" ctx.tf.testdata = "a \nb \nc \nd \ne \nf \n" ctx.tf.testdata.celltype = "text" ctx...
1618613
import ssl import logging from vibora.tests import TestSuite from vibora import client class TestSSLErrors(TestSuite): def setUp(self): # Python always warns about SSL errors but since where are forcing them to occur # there is no reason to fill the testing console with these messages. lo...
1618626
import wandb from transformers import is_torch_tpu_available from transformers.integrations import WandbCallback import os from transformers.utils import logging logger = logging.get_logger(__name__) class MyWandbCallback(WandbCallback): """ A :class:`~transformers.TrainerCallback` that sends the logs to `We...
1618684
import nltk import numpy as np import pyjsonrpc from features import Feature from stst.data import dict_utils from stst.libs.kernel import vector_kernel as vk class Embedding(object): def __init__(self): self.http_client = pyjsonrpc.HttpClient( url="http://localhost:8084", ) def ...
1618718
import itertools import re import urllib from django.views.generic import TemplateView from django.http import Http404 from django.template import Template, Context from billy.models import db, Metadata def templatename(name): return 'billy/web/public/%s.html' % name def mongo_fields(*fields): fields = di...
1618751
import os import torch from torch.utils import data import numpy as np from data.pose_graph_tools import Graph from data.sample_data import random_sample, sequential_sample def build_sub_graph(runs, data_dir): """ Build a pose graph from the stored data files. We build the pose graph using the tools prov...
1618758
import coloredlogs from dynaconf.utils.boxing import DynaBox import logging import sys def setup(config: DynaBox, name: str): fmt = "%(asctime)s %(levelname)-8s [%(name)s] %(message)s" colored_formatter = coloredlogs.ColoredFormatter(fmt) plain_formatter = logging.Formatter(fmt) logger = logging.getLo...
1618766
import os, torch, random, cv2, math, glob import numpy as np from torch.utils import data from torchvision import transforms as T from PIL import Image from torch.nn import functional as F from collections import defaultdict import random import copy from torch.utils.data.sampler import Sampler class IdentityCameraS...
1618810
import unittest import numpy from templevel import TempLevel from pymclevel.box import BoundingBox __author__ = 'Rio' class TestJavaLevel(unittest.TestCase): def setUp(self): self.creativelevel = TempLevel("Dojo_64_64_128.dat") self.indevlevel = TempLevel("hell.mclevel") def testCopy(self): ...
1618827
from torch.optim import Adam, SGD, AdamW import torch from torch.optim.lr_scheduler import OneCycleLR import numpy as np import os import time from torch.utils.data import DataLoader from dataset.vocab import Vocab from dataset.add_noise import SynthesizeData from params import * from models.seq2seq import Seq2Seq from...
1618866
from board_tests.test_support.doubles.fake_help_repository import FakeHelpRepository from board_tests.test_support.doubles.fake_new_face_repository import FakeNewFaceRepository from board_tests.test_support.doubles.fake_team_repository import FakeTeamRepository from board_tests.test_support.doubles.gui_spy import GuiSp...
1618869
from django.contrib.auth.models import User from django.test import TestCase from dfirtrack_config.forms import SystemImporterFileCsvConfigForm from dfirtrack_main.models import ( Analysisstatus, Case, Company, Dnsname, Domain, Location, Os, Reason, Recommendation, Serviceprovid...
1618873
import unittest import numpy as np import scipy.sparse as sp from multimodal.lib.array_utils import normalize_features from multimodal.evaluation import (evaluate_label_reco, evaluate_NN_label, chose_examples) class TestLabelEvaluation(unittest.T...
1618875
import os def fixdir(d): for e in os.listdir(d): p = os.path.join(d,e) if e.endswith('.wmf') or e.endswith('.WMF'): with open(p, 'rb') as f: b = f.read() with open(p, 'wb') as f: f.write(b[0xC:]) else: fixdir(p) fixdir('upic')
1618938
import time from hmac import compare_digest import jwt from quart import Blueprint, abort, current_app, request, jsonify from werkzeug.exceptions import HTTPException home = Blueprint("home", __name__) _SECRETS = {"worker1": "f0fdeb1f1584fd5431c4250b2e859457"} def _400(desc): exc = HTTPException() exc.cod...
1618941
import pickle import lmdb import os import glob from PIL import Image from pathlib import Path from tqdm import tqdm import numpy as np from scipy import ndimage def to_lmdb(root_path, lmdb_path): image_paths = [x.split(".")[0] for x in os.listdir(os.path.join(root_path, "color"))] print('#images: ', len(ima...
1618978
import importlib import re import pkg_resources from pkg_resources import VersionConflict from omniduct._version import __optional_dependencies__ from omniduct.utils.debug import logger def check_dependencies(protocols, message=None): if protocols is None: return dependencies = [] for protocol i...
1618979
try: from browser import timer except: class ajax: pass from . import futures class HTTPException(Exception): """ A class representing a HTTPRequest error """ def __init__(self, request): super(HTTPException, self).__init__() self.req = request class HTTPRequest(f...
1618984
import socket addr=input("Enter IP address: ") try: socket.inet_aton(addr) print ("IP address is valid") except socket.error: print ("IP address is NOT valid")