id
stringlengths
3
8
content
stringlengths
100
981k
64919
from Fusion.settings.common import * DEBUG = True SECRET_KEY = '=<KEY> ALLOWED_HOSTS = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fusionlab', 'HOST': '172.27.16.216', 'USER': 'fusion_admin', 'PASSWORD': '<PASSWORD>', } ...
64939
import torch from typing import Sequence from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset) import utils from utils import CQAExample, SMExample, NLIExample from utils import truncate_seq_pair, detok_batch class T5Input: def __init__(self, encoder_inputs, encoder_masks, d...
64943
from aw_nas.weights_manager.wrapper import BaseHead from .classifiers import BiFPNClassifier __all__ = ["BiFPNHead"] class BiFPNHead(BaseHead): NAME = "bifpn_head" def __init__( self, device, num_classes, feature_channels, bifpn_out_channels, activation="swis...
64954
from typing import Dict import numpy as np def buffer_from_example(example: Dict[str, np.ndarray], leading_dims) -> Dict[str, np.ndarray]: buf = {} for key, value in example.items(): buf[key] = np.zeros(leading_dims + value.shape, dtype=value.dtype) return buf def get_l...
64981
from copy import deepcopy from dataclasses import dataclass, asdict from logging import getLogger, WARNING import anyconfig import click import sys from pathlib import Path from typing import List, Tuple from .command import CwsMultiCommands from .error import CwsClientError from ..config import DEFAULT_PROJECT_DIR, ...
64987
import gym.wrappers from nn.mlp import MLP import pickle def test_cartpole(nn, file): global observation nn.load(file) for _ in range(500): env.render() action = nn.forward(observation) observation, reward, done, info = env.step(round(action.item())) if done: b...
65014
import torch import random from tqdm import trange from layers import Subgraph, Discriminator from utils import GraphDatasetGenerator import itertools import json from tqdm import tqdm import numpy as np import os class Subgraph_Learning(object): def __init__(self, args): super(Subgraph_Learning, self)._...
65015
import numpy as np from pyray.shapes.twod.paraboloid import * from pyray.shapes.twod.functional import * from pyray.rotation import * from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib as mpl...
65025
import logging import plotly.graph_objects as go from bots import imps, load_candle from openbb_terminal.common.technical_analysis import volume_model from openbb_terminal.decorators import log_start_end # pylint: disable=R0913 logger = logging.getLogger(__name__) @log_start_end(log=logger) def adosc_command( ...
65047
load("//tools:defaults.bzl", "protractor_web_test_suite") """ Macro that can be used to define a e2e test in `modules/benchmarks`. Targets created through this macro differentiate from a "benchmark_test" as they will run on CI and do not run with `@angular/benchpress`. """ def e2e_test(name, server, **kwargs): ...
65076
from typing import Dict, Optional, Text, List import apache_beam as beam import tensorflow_model_analysis as tfma from tensorflow_model_analysis import config from tensorflow_model_analysis import constants from tensorflow_model_analysis import model_util from tensorflow_model_analysis import types from tensorflow_mod...
65107
from data.python_templates.items import item_templates from data.python_templates.material import material_templates from items.item import Item class ItemFactory(object): """ At first this will only instantiate templates but eventually it should be able to pump out variations of a template ex: Adjusted t...
65130
import torch import torch.nn as nn import torch.nn.functional as F from .cond_bn import ConditionalBatchNorm1d # adopted Generator ResBlock from https://arxiv.org/abs/1909.11646 class GBlock(nn.Module): def __init__(self, in_channels, out_channels, condition_dim): super().__init__() self.cond_bn ...
65142
import torch import unittest import numpy as np from torch.autograd import Variable from losses.svm import SmoothTop1SVM, SmoothTopkSVM, MaxTop1SVM, MaxTopkSVM from losses.functional import Topk_Smooth_SVM from tests.utils import assert_all_close, V from tests.py_ref import svm_topk_smooth_py_1, svm_topk_smooth_py_2,\...
65146
import os import sys import platform from distutils.version import LooseVersion def is_active(): return True def get_name(): return "Android" def can_build(): return ("ANDROID_NDK_ROOT" in os.environ) def get_platform(platform): return int(platform.split("-")[1]) def get_opts(): from SCons...
65152
from setuptools import setup, find_packages from setuptools.command.install import install import os import setuptools import sys # should match codalab/common.py#CODALAB_VERSION CODALAB_VERSION = "1.1.4" class Install(install): _WARNING_TEMPLATE = ( '\n\n\033[1m\033[93mWarning! CodaLab was installed a...
65171
import time import torch from torch.utils.data import DataLoader, RandomSampler from torch.utils.data.distributed import DistributedSampler from tqdm import tqdm from datasets.dataset_FTR import * from src.models.FTR_model import * from .inpainting_metrics import get_inpainting_metrics from .utils import Progbar, cre...
65185
from optparse import make_option from django.core.management.base import AppCommand from django.core.management.sql import sql_custom from django.db import connections, DEFAULT_DB_ALIAS class Command(AppCommand): help = "Prints the custom table modifying SQL statements for the given app name(s)." option_list...
65187
from itertools import zip_longest from typing import List, Union from bytepatches.ops import Opcode, sync_ops, LOAD_FAST, STORE_FAST, JumpOp, LOAD_NAME, STORE_NAME from bytepatches.parser import Parser from bytepatches.utils import patch_function, make_bytecode class OpNotFound(Exception): pass def change_ops(...
65257
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.pension import pension def test_pension(): """Test module pension.py by downloading pension.csv and testing shape of extracted data has 19...
65287
from django.conf.urls import include, url from rest_framework import routers from api import views from django.urls import path route = routers.DefaultRouter() route.register(r'user', views.UserViewSet) route.register(r'store', views.StoreViewSet) route.register(r'itemCategory', views.ItemCategoryViewSet) route.regis...
65303
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, symbol existing testing, # or compilation error formatting ignored_keywords = [ 'src.c', 'CheckSymbolExists.c', 'test_compil...
65314
import asyncio from couchbase.asynchronous import AsyncSearchResult from couchbase.asynchronous import AsyncAnalyticsResult from .fixtures import asynct, AioTestCase from couchbase.exceptions import CouchbaseException, SearchException, NotSupportedException from unittest import SkipTest import couchbase.search as SEAR...
65331
from typing import Dict import torch from torchtyping import TensorType from typing import Dict, Optional from tqdm import tqdm from typeguard import typechecked """ # PCA rationale: # check for the constraints , if small, do nothing # if needed, project the result onto the constraints using the proje...
65356
from typing import Type from fpipe.exceptions import FileDataException from fpipe.file import File from fpipe.meta.abstract import FileData, T def meta_prioritized(t: Type[FileData[T]], *sources: File) -> T: error = FileDataException(t) for s in sources: try: return s[t] except Fi...
65451
import json import lzma from glob import glob from pprint import pprint import pandas as pd import smart_open import typer from tqdm import tqdm ORDERED_VAR = ["table", "name", "description", "type"] TEXTTT_VAR = ["table", "name"] app = typer.Typer() @app.command() def sniff(path: str, tar: bool = True, examples: ...
65455
SECRET_KEY = "abc" FILEUPLOAD_ALLOWED_EXTENSIONS = ["png"] # FILEUPLOAD_PREFIX = "/cool/upload" # FILEUPLOAD_LOCALSTORAGE_IMG_FOLDER = "images/boring/" FILEUPLOAD_RANDOM_FILE_APPENDIX = True FILEUPLOAD_CONVERT_TO_SNAKE_CASE = True
65457
import random import numpy as np import cv2 from utils.transforms.transforms import CustomTransform class RandomFlip(CustomTransform): def __init__(self, prob_x=0, prob_y=0): """ Arguments: ---------- prob_x: range [0, 1], probability to use horizontal flip, setting to 0 means dis...
65467
from head.metrics import * from head.metrics_parallel import * HEAD_DICT = { "Softmax": Softmax, "ArcFace": ArcFace, "Combined": Combined, "CosFace": CosFace, "SphereFace": SphereFace, "Am_softmax": Am_softmax, "CurricularFace": CurricularFace, "ArcNegFace": ArcNegFace, "SVX": SVXSo...
65469
from text import symbols class Hparams: def __init__(self): ################################ # Experiment Parameters # ################################ self.epochs = 500 self.iters_per_checkpoint = 1000 self.iters_per_validation = 1000 self.seed = 123...
65507
import spartan from spartan import core, expr, util, blob_ctx import numpy as np from .qr import qr def svd(A, k=None): """ Stochastic SVD. Parameters ---------- A : spartan matrix Array to compute the SVD on, of shape (M, N) k : int, optional Number of singular values and vectors to compute....
65528
from datetime import datetime, timedelta from urllib import parse from ably.http.paginatedresult import PaginatedResult from ably.types.mixins import EncodeDataMixin def _ms_since_epoch(dt): epoch = datetime.utcfromtimestamp(0) delta = dt - epoch return int(delta.total_seconds() * 1000) def _dt_from_ms...
65534
from collections import namedtuple import tensorflow as tf import numpy as np from rl.agents.a2c.agent import A2CAgent TestArgType = namedtuple('ArgType', ['name']) arg_type = TestArgType('arg') A = np.array class A2CAgentTest(tf.test.TestCase): def test_compute_policy_log_probs(self): from rl.agents.a2c.a...
65548
from oso import Oso from .auth import register_models class SQLAlchemyOso(Oso): """The central object to manage application policy state, e.g. the policy data, and verify requests when using Oso with SQLAlchemy. Supports SQLAlchemy-specific functionality, including data filtering. Accepts a SQLAlch...
65551
import logging from helium.common.managers.basemanager import BaseManager, BaseQuerySet __author__ = "<NAME>" __copyright__ = "Copyright 2019, Helium Edu" __version__ = "1.4.38" logger = logging.getLogger(__name__) class EventQuerySet(BaseQuerySet): def exists_for_user(self, id, user_id): return self.f...
65609
import pytest from unittest.mock import patch import tests.fixtures.journal as FakeJournalExporter from systemdlogger.elasticsearch import ElasticsearchLogger @pytest.mark.parametrize(('config_path'), [ 'tests/fixtures/config_es.json' ]) class TestRunner: def setup_method(self, method): """ setup any...
65616
from .base import TrainingCallback, ValueTrainingCallback class LearningRateScheduler(TrainingCallback): """ The learning rate scheduler may be used with a PyTorch learning rate scheduler. The callback is automatically triggered after the end of every iteration or epoch. """ def __init__(self, sch...
65629
from __future__ import absolute_import, division, unicode_literals from genshi.core import QName from genshi.core import START, END, XML_NAMESPACE, DOCTYPE, TEXT from genshi.core import START_NS, END_NS, START_CDATA, END_CDATA, PI, COMMENT from . import base from ..constants import voidElements, name...
65631
from __future__ import absolute_import from django.conf import settings from api.mon.backends import zabbix from api.mon.backends import dummy __all__ = ('get_monitoring', 'del_monitoring', 'MonitoringBackend', 'MonitoringServer') BACKEND_ALIASES = { 'dummy': dummy, 'zabbix': zabbix, } DEFAULT_BACKEND = 'z...
65647
from copy import deepcopy import six from lxml import etree from regparser import plugins from regparser.tree.xml_parser.preprocessors import replace_html_entities class XMLWrapper(object): """Wrapper around XML which provides a consistent interface shared by both Notices and Annual editions of XML""" d...
65668
from __future__ import absolute_import from __future__ import division from __future__ import print_function print 'hello world'
65673
import sys import base_func as base import twint from similar_hashtags import similar_hashtags from top_mentions_hashtags import top_mentions_hashtags as mentions def basic(username,search): base.get_user_bio(username,search) base.get_user_tweets(username,search,True) def get_keyword(key,limit=100): base...
65745
from flask import Flask, flash, request, redirect, url_for, render_template from werkzeug.utils import secure_filename import os from keras.models import load_model from keras.applications.inception_resnet_v2 import InceptionResNetV2 import tensorflow as tf from skimage.io import imsave from skimage.transform import re...
65764
import math from ffmpeg import probe def get_bitrate(video_path): bitrate = probe(video_path)['format']['bit_rate'] return f'{math.trunc(int(bitrate) / 1000)} kbit/s' def get_framerate_fraction(video_path): r_frame_rate = [stream for stream in probe(video_path)['streams'] if stream['...
65828
import tensorflow as tf import math from tensorflow.contrib.rnn import BasicLSTMCell, RNNCell, DropoutWrapper, MultiRNNCell from rnn import stack_bidirectional_dynamic_rnn, CellInitializer, GRUCell, DropoutGRUCell import utils, beam_search def auto_reuse(fun): """ Wrapper that automatically handles the `reuse'...
65838
import math, time, os, argparse, logging, json from wand.image import Image parser = argparse.ArgumentParser( prog='tile_cutter', description='Cuts large images into tiles.') parser.add_argument('--tile-size', metavar='SIZE', type=int, default=512, help='Tile size (width and height)') parse...
65845
import logging import os import numpy as np import xml.etree.ElementTree as ET from PIL import Image from paths import DATASETS_ROOT log = logging.getLogger() VOC_CATS = ['__background__', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'hors...
65846
import numpy as np from skmultiflow.drift_detection import ADWIN def demo(): """ _test_adwin In this demo, an ADWIN object evaluates a sequence of numbers corresponding to 2 distributions. The ADWIN object indicates the indices where change is detected. The first half of the data is a sequence ...
65874
from RnaseqDiffExpressionReport import ProjectTracker from RnaseqDiffExpressionReport import linkToEnsembl, linkToUCSC class TopDifferentiallyExpressedGenes(ProjectTracker): '''output differentially expressed genes.''' limit = 10 pattern = '(.*)_gene_diff' sort = '' def __call__(self, track, sli...
65892
from pkgcheck.checks import dropped_keywords from snakeoil.cli import arghparse from .. import misc class TestDroppedKeywords(misc.ReportTestCase): check_kls = dropped_keywords.DroppedKeywordsCheck def mk_pkg(self, ver, keywords='', eclasses=(), **kwargs): return misc.FakePkg( f"dev-uti...
65919
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDHarvester import DQMEDHarvester from DQM.SiPixelPhase1Common.HistogramManager_cfi import * import DQM.SiPixelPhase1Common.TriggerEventFlag_cfi as trigger SiPixelPhase1TrackEfficiencyValid = DefaultHistoTrack.clone( name = "valid", title = "Valid H...
65926
import json import sys import traceback import yaml import urllib3 from requests.exceptions import ConnectionError, SSLError from .client import CLI from awxkit.utils import to_str from awxkit.exceptions import Unauthorized, Common from awxkit.cli.utils import cprint # you'll only see these warnings if you've expli...
65933
import sys import math import random from collections import namedtuple import time from pyrf.util import (compute_usable_bins, adjust_usable_fstart_fstop, trim_to_usable_fstart_fstop, find_saturation) import numpy as np from twisted.internet import defer from pyrf.numpy_util import compute_fft import struct MAXI...
65954
TEMPLATE = """import numpy as np import unittest from {name}.algorithm.research_algorithm import {name_upper}Estimator class Test{name_upper}Estimator(unittest.TestCase): def test_predict(self): multiplier = 2 input_data = np.random.random([1, 2]) expected_result = input_data * multiplie...
65969
import socket from flask import Flask, Response from PIL import Image, ImageDraw import threading from collections import deque import struct import io HOST = '0.0.0.0' PORT = 54321 image_bytes_length = 640*480*3 bbox_bytes_length = 5*8 # The socket client sends one bounding box and score. data_bytes_length = image_...
66009
import os import csv import threading from .classes import Node, Link, Network, Column, ColumnVec, VDFPeriod, \ AgentType, DemandPeriod, Demand, Assignment, UI from .colgen import update_links_using_columns from .consts import SMALL_DIVISOR __all__ = [ 'read_network', 'load_columns', ...
66013
from PIL import Image from tflite_runtime.interpreter import Interpreter from tflite_runtime.interpreter import load_delegate from video import create_capture import numpy as np import cv2 as cv import io import picamera import simpleaudio as sa # tf model upload def load_label...
66034
import re def parseDeviceId(id): match = re.search('(#|\\\\)vid_([a-f0-9]{4})&pid_([a-f0-9]{4})(&|#|\\\\)', id, re.IGNORECASE) return [int(match.group(i), 16) if match else None for i in [2, 3]]
66043
import cv2 import numpy as np # Capture the input frame def get_frame(cap, scaling_factor=0.5): ret, frame = cap.read() # Resize the frame frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA) return frame if __name__=='__main__'...
66047
from . import core, mixin class Datum(mixin.Parameters, mixin.NetCDFVariable, core.Datum): """A datum component of a CF data model coordinate reference. A datum is a complete or partial definition of the zeroes of the dimension and auxiliary coordinate constructs which define a coordinate system. ...
66116
from models.rnn_mlp import RNN_MLP from models.social_attention import SocialAttention from models.cnn_mlp import CNN_MLP from models.spatial_attention import SpatialAttention from models.s2s_spatial_attention import S2sSpatialAtt from models.s2s_social_attention import S2sSocialAtt import time import json import...
66137
import unittest import numpy as np from sklearn import exceptions # from sklearn.datasets import load_boston as load from skcosmo.datasets import load_csd_1000r as load from skcosmo.feature_selection import CUR class TestCUR(unittest.TestCase): def setUp(self): self.X, _ = load(return_X_y=True) def...
66204
def deny(blacklist): """ Decorates a handler to filter out a blacklist of commands. The decorated handler will not be called if message.command is in the blacklist: @deny(['A', 'B']) def handle_everything_except_a_and_b(client, message): pass Single-item blacklists may...
66225
import os from shutil import copytree, copy2 from glob import glob import torchvision import torch from tensorboardX import SummaryWriter from sklearn import metrics def copy_source_code(path): if not os.path.isdir(path): os.makedirs(path) denylist = ["./__pycache__/"] folders = glo...
66242
from collections import ( defaultdict, ) from contextlib import ( asynccontextmanager, ) from datetime import ( datetime, ) from typing import ( Iterable, ) import psutil from core.db_entities import ( DBTable, DstDatabase, ) from core.enums import ( TransferringStagesEnum, ) from core.help...
66255
from a10sdk.common.A10BaseClass import A10BaseClass class DiskUsage(A10BaseClass): """This class does not support CRUD Operations please use parent. :param disk_usage: {"type": "string", "format": "string"} :param time: {"type": "number", "format": "number"} :param DeviceProxy: The device proxy ...
66259
import hashlib import typing from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list from .formats.join import JoinTable from .join_common import Structure, context_column, foreign_column, local_column from .join_key import KeyResolver from .sql import SqlQuery, SqlTableExpr, table_fields, update_excluded...
66266
from django.db import models from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.core.validators import FileExtensionValidator from .xmltools import analyze_file, include_sync_button import uuid def default_color(): return '#076AA...
66287
from idc import * from idaapi import * import idautils YARA_OPERAND_SIZE = 8 YARA_RELOCATION_NULL_MAGIC = 0xfffaBADA YARA_RELOCATION_END_MAGIC = 0xffffFFFF UNDEFINED_MAGIC = 0xFFFABADAFABADAFF def read_qw(self, insn, eaoffset): qw = get_qword(insn.ea+eaoffset) eaoffset += 8 return SIGNEXT(qw...
66306
HERO = {'B': 'Batman', 'J': 'Joker', 'R': 'Robin'} OUTPUT = '{}: {}'.format class BatmanQuotes(object): @staticmethod def get_quote(quotes, hero): for i, a in enumerate(hero): if i == 0: hero = HERO[a] elif a.isdigit(): quotes = quotes[int(a)] ...
66322
import unittest import numpy as np from .softlearning_env_test import AdapterTestClass from softlearning.environments.adapters.robosuite_adapter import ( RobosuiteAdapter) class TestRobosuiteAdapter(unittest.TestCase, AdapterTestClass): # TODO(hartikainen): This is a terrible way of testing the envs. # ...
66395
import sys import os # check SBMolGen_PATH setting if os.getenv('SBMolGen_PATH') == None: print("THe SBMolGen_PATH has not defined, please set it before use it!") exit(0) else: SBMolGen_PATH=os.getenv('SBMolGen_PATH') sys.path.append(SBMolGen_PATH+'/utils') from subprocess import Popen, PIPE from math i...
66401
import sys import numpy as np from matplotlib import pyplot from matplotlib.animation import FuncAnimation import matplotlib as mpl sys.path.append('..') from submission import SubmissionBase def displayData(X, example_width=None, figsize=(10, 10)): """ Displays 2D data in a nice grid. Parameters --...
66460
C = "C" CPP = "Cpp" CSHARP = "CSharp" GO = "Go" JAVA = "Java" JAVASCRIPT = "JavaScript" OBJC = "ObjC" PYTHON = "Python" # synonym for PYTHON3 PYTHON2 = "Python2" PYTHON3 = "Python3" RUST = "Rust" SWIFT = "Swift" def supported(): """Returns the supported languages. Returns: the list of supported languag...
66469
from fjord.base.plugin_utils import load_providers from fjord.redirector import _REDIRECTORS class RedirectorTestMixin(object): """Mixin that loads Redirectors specified with ``redirectors`` attribute""" redirectors = [] def setUp(self): _REDIRECTORS[:] = load_providers(self.redirectors) ...
66481
import ui, console import os import math def save_action(sender): with open('image_file.png', 'wb') as fp: fp.write(img.to_png()) console.hud_alert('image saved in the file image_file.png') def showimage_action(sender): img.show() def create_image(): img = None with ui.ImageContext(5...
66566
import os import time from getpass import getpass from netmiko import ConnectHandler def read_device(net_connect, sleep=1): """Sleep and read channel.""" time.sleep(sleep) output = net_connect.read_channel() print(output) return output if __name__ == "__main__": # Code so automated tests wi...
66568
import logging import requests from tenacity import before_log, retry, stop_after_attempt class MarketDataClient(object): logger = logging.getLogger(__name__) base_url = 'http://market-data:8000' def _make_request(self, url): response = requests.get( f"{self.base_url}/{url}", header...
66572
from os import listdir from os import path import io import json save_apsnypress = io.open('../hunalign_batch_apsnypress.txt','w+', encoding="utf-8") with open('../data_out.json', 'r') as f: data_j = json.load(f) for item in data_j: if len(item["possible match"]) != 0: for possible_item in item["possib...
66576
from unittest import SkipTest from holoviews.core import NdOverlay from holoviews.core.util import pd from holoviews.element import Segments from .test_plot import TestBokehPlot, bokeh_renderer try: from bokeh.models import FactorRange except: pass class TestSegmentPlot(TestBokehPlot): def test_segmen...
66584
from dataclasses import dataclass @dataclass class Division: id: int = None name: str = None link: str = None
66591
from django.core.management.base import BaseCommand, CommandError from django.urls import reverse from django.core.mail import send_mail from django.template.loader import get_template, render_to_string from django.conf import settings from django.contrib.sites.models import Site from accounts.models import Account, E...
66612
import json import os import time import numpy as np from metalearn import Metafeatures from tests.config import CORRECTNESS_SEED, METAFEATURES_DIR, METADATA_PATH from .dataset import read_dataset def get_dataset_metafeatures_path(dataset_filename): dataset_name = dataset_filename.rsplit(".", 1)[0] return o...
66656
import rlp from rlp.sedes import CountableList, text # big_endian_int from kademlia.utils import digest from utils import get_sender import json import logging from exceptions import InvalidTransaction import Globals logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) tx_fields = ('sender_pk',...
66705
import asyncio import sys import unittest import nest_asyncio def exception_handler(loop, context): print('Exception:', context) class NestTest(unittest.TestCase): def setUp(self): self.loop = asyncio.new_event_loop() nest_asyncio.apply(self.loop) asyncio.set_event_loop(self.loop) ...
66721
import json import functools from django.conf import settings from django.test import Client, TestCase __all__ = ['JsonTestClient', 'JsonTestMixin', 'JsonTestCase'] class JsonTestClient(Client): def _json_request(self, method, url, data=None, *args, **kwargs): method_func = getattr(super(JsonTestClient,...
66729
import py from rpython.rlib.signature import signature, finishsigs, FieldSpec, ClassSpec from rpython.rlib import types from rpython.annotator import model from rpython.rtyper.llannotation import SomePtr from rpython.annotator.signature import SignatureError from rpython.translator.translator import TranslationContext,...
66732
import copy from functools import wraps, reduce import socket import os from operator import mul import sys from statistics import mean import time import numpy as np from rdkit.Chem import AllChem, RWMol from rdkit import Chem from rdkit.Chem.rdChemReactions import ChemicalReaction from kgcn.data_util import dense_t...
66779
import torch import torchvision import torchvision.transforms as transforms import numpy as np import torch.nn as nn import torch.nn.functional as F class conv2d_circular(nn.Conv2d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, n...
66823
import io from os.path import dirname, abspath, join from nanohttp import settings, configure from restfulpy.messaging.providers import SMTPProvider from restfulpy.mockup import mockup_smtp_server HERE = abspath(dirname(__file__)) def test_smtp_provider(): configure(force=True) settings.merge(f''' ...
66836
import re import smtplib import dns.resolver # Address used for SMTP MAIL FROM command fromAddress = '<EMAIL>' # Simple Regex for syntax checking regex = '^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$' # Email address to verify inputAddress = input('Please enter the emailAddress to verify:')...
66849
import re from cybox.objects.address_object import Address from cybox.objects.uri_object import URI from .text import StixTextTransform class StixBroIntelTransform(StixTextTransform): """Generate observable details for the Bro Intelligence Framework. This class can be used to generate a list of indicators ...
66977
class Solution: # @param {integer} x # @return {integer} def reverse(self, x): neg = False if x<0: neg =True x = -x print x reversed_int = int(''.join(reversed(str(x)))) if reversed_int>(1<<31): reversed_int = 0 if neg: ...
66983
import cgen as c from sympy import Symbol from devito.cgen_utils import ccode from devito.ir.iet import (Expression, Iteration, List, UnboundedIndex, ntags, FindAdjacentIterations, FindNodes, IsPerfectIteration, NestedTransformer, Transformer, compose_nodes, ...
66985
from .monitor_bad_pixel_bokeh import BadPixelMonitor from .monitor_bias_bokeh import BiasMonitor from .monitor_dark_bokeh import DarkMonitor from .monitor_filesystem_bokeh import MonitorFilesystem from .monitor_mast_bokeh import MastMonitor from .monitor_readnoise_bokeh import ReadnoiseMonitor
66995
import pytest from configargparse import Namespace from pydpiper.core.arguments import CompoundParser, AnnotatedParser, application_parser, parse #, lsq6_parser, lsq12_parser from pydpiper.pipelines.MBM import mbm_parser # TODO should these test files be named test_*? # should these be fixtures or not? @pytest.fixt...
67045
import json import warnings from enum import Enum from typing import Any, List, Tuple, Union import numpy as np import torch from mmhuman3d.core.cameras.cameras import PerspectiveCameras from mmhuman3d.core.conventions.cameras.convert_convention import ( convert_camera_matrix, convert_K_3x3_to_4x4, conver...
67056
from .data import ( TxtTokLmdb, DetectFeatLmdb, ImageLmdbGroup, ConcatDatasetWithLens, ) from .loader import PrefetchLoader, MetaLoader from .vqa import ( VqaEvalDataset, vqa_collate, vqa_eval_collate, UNITER_VqaDataset, ) from .ve import ( VeEvalDataset, ve_collate, ve_eval_...
67067
from pwn import * # Create item print('1') FUNC = 0x701e40 #FUNC = 0x41414141 + 0x18 vtable_ptr = FUNC-0x18 print(p64(vtable_ptr) * 8) # name - pointer to fake vtable print('bob') # description print('1.23') # price # Add item to basket print('4') print('1') # second item, added above print('28823037615171174...
67086
from .detector3d_template import Detector3DTemplate class PartA2Net(Detector3DTemplate): def __init__(self, model_cfg, num_class, dataset): super().__init__(model_cfg=model_cfg, num_class=num_class, dataset=dataset) self.module_list = self.build_networks() def forward(self, batch_dict): ...