id
stringlengths
3
8
content
stringlengths
100
981k
69867
import logging import os import sys import pandas as pd import torch class Batch_evaluate: ''' A class to evaluate a function by several batches to save memory. Sometimes out=func(x) requires a large memory to compute, this class devide x into several batches and combine the outputs. ''' def __i...
69869
import torch import torch.nn.functional as F def compas_robustness_loss(x, aggregates, concepts, relevances): """Computes Robustness Loss for the Compas data Formulated by Alvarez-Melis & Jaakkola (2018) [https://papers.nips.cc/paper/8003-towards-robust-interpretability-with-self-explaining-neural-ne...
69878
import pandas as pd import bayesianpy from bayesianpy.network import Builder as builder import logging import os import numpy as np import scipy.stats as ss import matplotlib.pyplot as plt import seaborn as sns def main(): logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) logger.se...
69882
from core.models import ProviderType from api.v2.serializers.details import ProviderTypeSerializer from api.v2.views.base import AuthModelViewSet class ProviderTypeViewSet(AuthModelViewSet): """ API endpoint that allows instance actions to be viewed or edited. """ queryset = ProviderType.objects.all()...
69883
import dash_bootstrap_components as dbc from dash import html from .util import make_subheading form = html.Div( [ make_subheading("Form", "form"), dbc.Form( [ html.Div( [ dbc.Label("Username"), dbc.Inp...
69909
import pytest from django.contrib.auth import get_user_model from rest_framework.reverse import reverse from boards.models import Column, Board, Task User = get_user_model() @pytest.fixture def board(create_user): user = create_user() uni_board = Board.objects.create(name="University", owner=user) uni_b...
69933
import io from twisted.internet import reactor from ygo.card import Card from ygo.duel_reader import DuelReader from ygo.parsers.duel_parser import DuelParser from ygo.utils import process_duel def msg_select_unselect_card(self, data): data = io.BytesIO(data[1:]) player = self.read_u8(data) finishabl...
69969
import numpy as np import pytest def test_camera_display_create(): from ctapipe.visualization.bokeh import CameraDisplay CameraDisplay() def test_camera_geom(example_event, example_subarray): from ctapipe.visualization.bokeh import CameraDisplay t = list(example_event.r0.tel.keys())[0] geom = ...
70018
import os from pathlib import Path from typing import Iterable from .ext import Date from .ext import make_weekday_calendar, parse_calendar, make_const_calendar from .weekday import parse_weekdays #------------------------------------------------------------------------------- def load_calendar_file(path, ...
70021
import pybullet as p def render(height, width, view_matrix, projection_matrix, shadow=1, light_direction=[1, 1, 1], renderer=p.ER_BULLET_HARDWARE_OPENGL): # ER_BULLET_HARDWARE_OPENGL img_tuple = p.getCameraImage(width, height, ...
70022
import datetime import threading from django.utils.html import escape as html_escape from mongoengine import EmbeddedDocument try: from mongoengine.base import ValidationError except ImportError: from mongoengine.errors import ValidationError from mongoengine.base.datastructures import BaseList from mongoengi...
70027
from typing import List, Union, Dict from unittest import TestCase from unittest.mock import ANY, patch, Mock from parameterized import parameterized from samcli.lib.cookiecutter.question import Question, QuestionKind, Choice, Confirm, Info, QuestionFactory class TestQuestion(TestCase): _ANY_TEXT = "any text" ...
70043
import copy import logging import dask import numpy as np import xarray as xr from numcodecs.compat import ensure_ndarray from xarray.backends.zarr import ( DIMENSION_KEY, encode_zarr_attr_value, encode_zarr_variable, extract_zarr_variable_encoding, ) from zarr.meta import encode_fill_value from zarr.s...
70052
def hvplot_with_buffer(gdf, buffer_size, *args, **kwargs): """ Convenience function for plotting a GeoPandas point GeoDataFrame using point markers plus buffer polygons Parameters ---------- gdf : geopandas.GeoDataFrame point GeoDataFrame to plot buffer_size : numeric size o...
70078
import argparse import cv2 import numpy as np import torch.nn.functional as F from torchvision.transforms.functional import normalize from facexlib.matting import init_matting_model from facexlib.utils import img2tensor def main(args): modnet = init_matting_model() # read image img = cv2.imread(args.img...
70104
from pydub import AudioSegment class Frame(): def __init__(self, start=0, end=0, audio=AudioSegment.empty()): self.start = start self.end = end self.audio = audio def __eq__(self, frame): return self.start == frame.start and self.end == frame.end def __len__(self): ...
70116
from __future__ import absolute_import import numpy as np import chainer import tqdm import glob import warnings from abc import ABCMeta, abstractmethod from collections import OrderedDict from ..data import load_image # NOQA class BaseDataset(chainer.dataset.DatasetMixin, metaclass=ABCMeta): """ Base class of ...
70142
import os from appdirs import AppDirs from cihai.config import Configurator, expand_config #: XDG App directory locations dirs = AppDirs("cihai", "cihai team") # appname # app author def test_configurator(tmpdir): c = Configurator() isinstance(c.dirs, AppDirs) assert c def test_expand_config_xdg_v...
70179
import tinyflow as tf from tinyflow.datasets import get_cifar10 import numpy as np num_epoch = 10 num_batch = 600 batch_size = 100 def conv_factory(x, filter_size, in_filters, out_filters): x = tf.nn.conv2d(x, num_filter=out_filters, ksize=[1, filter_size, filter_size, 1], padding='SAME') x = t...
70200
from typing import Dict, List from aiohttp import web from .path import full_url def default_server(request: web.Request) -> Dict[str, str]: app = request.app url = full_url(request) url = url.with_path(app["cli"].base_path) return dict(url=str(url), description="Api server") def server_urls(reque...
70355
import turbodbc.data_types from turbodbc import STRING, BINARY, NUMBER, DATETIME, ROWID ALL_TYPE_CODES = [turbodbc.data_types._BOOLEAN_CODE, turbodbc.data_types._INTEGER_CODE, turbodbc.data_types._FLOATING_POINT_CODE, turbodbc.data_types._STRING_CODE, ...
70357
import torch import torch.optim as optim import sys import os import argparse import tokenization from torch.optim import lr_scheduler from loss import registry as loss_f from loader import registry as loader from model import registry as Producer from evaluate import overall #hyper-parameters parser = argparse.Argum...
70358
import os, sys os.environ['CUDA_VISIBLE_DEVICES'] = '0' import tensorflow as tf import cv2 import numpy as np sys.path.insert(1, os.path.join(sys.path[0], '/mywork/tensorflow-tuts/sd19reader')) from batches2patches_tensorflow import GetFuncToPatches, GetFuncOverlapAdd from myutils import describe from vizutils import ...
70373
from django.views.decorators.http import require_http_methods from graphene_django.views import GraphQLView @require_http_methods(['POST']) def graphql_view(request): from graph_wrap.tastypie import schema schema = schema() view = GraphQLView.as_view(schema=schema) return view(request)
70416
from .model_action import ModelAction """ If the seed model has displacement ventilation object, this measure will delete or keep the related objects If the seed model has no displacement ventilation object but the decision value is 1 (On) This measure will insert room air model objects for zones under the control o...
70450
from rest_framework.mixins import ( CreateModelMixin, DestroyModelMixin, ListModelMixin ) from rest_framework.viewsets import GenericViewSet from pydis_site.apps.api.models.bot.offensive_message import OffensiveMessage from pydis_site.apps.api.serializers import OffensiveMessageSerializer class Offensive...
70462
from hamcrest import * from utils import * @pytest.mark.serial @pytest.mark.manual_batch_review def test_approve_pending_batch_change_success(shared_zone_test_context): """ Test approving a batch change succeeds for a support user """ client = shared_zone_test_context.ok_vinyldns_client approver =...
70463
import info class subinfo( info.infoclass ): def setTargets( self ): for ver in ["2.4.6"]: self.targets[ ver ] = f"https://ftp.gnu.org/gnu/libtool/libtool-{ver}.tar.xz" self.targetInstSrc[ ver ] = f"libtool-{ver}" self.targetDigests["2.4.6"] = (['7c87a8c2c8c0fc9cd5019e402b...
70501
from germanium.decorators import login from germanium.test_cases.rest import RESTTestCase from germanium.tools import assert_in from germanium.tools.http import assert_http_unauthorized, assert_http_forbidden, assert_http_not_found from .test_case import HelperTestCase, AsSuperuserTestCase __all__ =( 'HttpExcept...
70528
import cPickle __all__ = ['memoize'] # This would usually be defined elsewhere class decoratorargs(object): def __new__(typ, *attr_args, **attr_kwargs): def decorator(orig_func): self = object.__new__(typ) self.__init__(orig_func, *attr_args, **attr_kwargs) return self return decorator class memoi...
70556
import heapq class Solution: """ @param k: an integer @param W: an integer @param Profits: an array @param Capital: an array @return: final maximized capital """ def findMaximizedCapital(self, k, W, Profits, Capital): # Write your code here cappq = [(cap, i) for i, cap in...
70583
import os import logging import numpy as np import pandas as pd logger = logging.getLogger(__name__) from supervised.utils.config import LOG_LEVEL from supervised.utils.common import learner_name_to_fold_repeat from supervised.utils.metric import Metric logger.setLevel(LOG_LEVEL) import matplotlib.pyplot as plt impo...
70622
import datetime as dt import json from typing import List, Optional from uuid import UUID from fastapi.encoders import jsonable_encoder from injector import singleton, inject from common.cache import fail_silently, hash_cache_key from common.injection import Cache from database.utils import map_to from post.models im...
70662
from typing import Type import warnings from base64 import b64encode from html import escape import json import pandas as pd import numpy as np from rdkit import Chem from rdkit.Chem import Draw from .utils import (env, requires, tooltip_formatter, mol_to_reco...
70717
from unittest.mock import patch from urllib.parse import urlencode import pytest from pyinaturalist.constants import API_V1_BASE_URL from pyinaturalist.v1 import get_taxa, get_taxa_autocomplete, get_taxa_by_id, get_taxa_map_layers from test.conftest import load_sample_data CLASS_AND_HIGHER = ['class', 'superclass', ...
70735
class LDAP_record: """ consume LDAP record and provide methods for accessing interesting data """ def __init__(self, unid): self.error = False ldap_dict = {} # # request complete user record from LDAP cmd = "/Users/" + unid try: raw_data = sub...
70745
import datetime import logging import json import hashlib import hmac import base64 import aiohttp import asyncio from collections import deque class AzureSentinelConnectorAsync: def __init__(self, session: aiohttp.ClientSession, log_analytics_uri, workspace_id, shared_key, log_type, queue_size=1000, queue_size_b...
70763
import sys import yaml class Config: def __init__(self, cfg=None): self.cfg = {} if cfg is not None: self.update(cfg) def __getattribute__(self, name): cfg = object.__getattribute__(self, 'cfg') if name not in cfg: return object.__getattribute__(self, n...
70820
import os import copy import json import logging import torch from torch.utils.data import TensorDataset logger = logging.getLogger(__name__) class InputExample(object): """ A single training/test example for simple sequence classification. Args: guid: Unique id for the example. text_a...
70844
import numpy as np import scipy.sparse as ssp import torch from beta_rec.models.torch_engine import ModelEngine from beta_rec.utils.common_util import timeit def top_k(values, k, exclude=[]): """Return the indices of the k items with the highest value in the list of values. Exclude the ids from the list "ex...
70849
class RetrievalError(Exception): pass class SetterError(Exception): pass class ControlError(SetterError): pass class AuthentificationError(Exception): pass class TemporaryAuthentificationError(AuthentificationError): pass class APICompatibilityError(Exception): pass class APIError(Ex...
70857
from __future__ import print_function, absolute_import, division from future.builtins import * from future import standard_library standard_library.install_aliases() # Copyright 2017 Autodesk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with ...
70877
from rknn.api import RKNN class RKNN_model_container(): def __init__(self, model_path, target=None, device_id=None) -> None: rknn = RKNN() # Direct Load RKNN Model rknn.load_rknn(model_path) print('--> Init runtime environment') if target==None: ret = rknn.ini...
70891
import geopandas as gpd import requests from vt2geojson.tools import vt_bytes_to_geojson MAPBOX_ACCESS_TOKEN = "<KEY>" x = 150 y = 194 z = 9 url = f"https://api.mapbox.com/v4/mapbox.mapbox-streets-v6/{z}/{x}/{y}.vector.pbf?access_token={MAPBOX_ACCESS_TOKEN}" r = requests.get(url) assert r.status_code == 200, r.cont...
70892
from tensorflow.python.ops import init_ops from tensorflow.python.util import nest import tensorflow as tf def stack_bidirectional_dynamic_rnn(cells_fw, cells_bw, inputs, initial_states_fw=None, initial_states_bw=None, dtype=None, sequence_length=None, parallel_iterations=None, sco...
70909
import urllib.parse from datetime import datetime from unittest.mock import patch from django.contrib.auth.models import User from django.contrib.messages import get_messages from django.test import TestCase from django.utils import timezone from dfirtrack_main.models import ( System, Systemstatus, Task, ...
70995
from __future__ import absolute_import # Copyright (c) 2010-2019 openpyxl import pytest from openpyxl.xml.functions import fromstring, tostring from openpyxl.tests.helper import compare_xml @pytest.fixture def PictureOptions(): from ..picture import PictureOptions return PictureOptions class TestPictureOpt...
71029
from nalp.corpus import TextCorpus from nalp.encoders import IntegerEncoder from nalp.models import SeqGAN # When generating artificial text, make sure # to use the same data, classes and parameters # as the pre-trained network # Creating a character TextCorpus from file corpus = TextCorpus(from_file='data/text/chapt...
71046
import fnmatch import os import datetime import sys from subprocess import Popen, PIPE import zipfile import skimage.io import scipy.io.wavfile import jsonlines import torch from setka.pipes.Pipe import Pipe def get_process_output(command): if not isinstance(command, (list, tuple)): command = command.sp...
71067
from django import forms from tally_ho.libs.permissions import groups from tally_ho.apps.tally.models.tally import Tally from tally_ho.apps.tally.models.user_profile import UserProfile from tally_ho.libs.utils.form import lower_case_form_data disable_copy_input = { 'onCopy': 'return false;', 'onDrag': 'retur...
71104
from __future__ import print_function import sys import os from glob import glob import shutil try: import setuptools except ImportError: sys.stderr.write( "Please install setuptools before running this script. Exiting.") sys.exit(1) from setuptools import setup, find_packages # --------------------...
71113
import json, re, select, random, traceback, urllib, datetime, base64 import asyncio, aiohttp # The core codes for YouTube support are basically from taizan-hokuto/pytchat headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"...
71120
import math; import decimal; import sys def trunc(f): if f == 0: return '0.0'; d = decimal.Decimal(f) if type(d)(int(d)) == d: return str(d) + '.0'; slen = len('%.*f' % (20, d)) return str(d)[:slen] # min, max: values; lower, upper: domain def interpolate(minV, maxV, lower, upper, varname): fact =...
71128
import pytest from redis.exceptions import RedisError from rq.exceptions import NoSuchJobError from busy_beaver.models import Task, PostGitHubSummaryTask, PostTweetTask MODULE_TO_TEST = "busy_beaver.models.task" ########### # Base Task ########### def test_create_task(session): # Arrange task = Task( ...
71152
import glob from setuptools import setup setup( name='edxcut', version='0.4', author='<NAME> and <NAME>', author_email='<EMAIL>', packages=['edxcut'], scripts=[], url='http://pypi.python.org/pypi/edxcut/', license='LICENSE.txt', description='edX course unit tester', long_descrip...
71202
import random from ananas import PineappleBot, ConfigurationError, hourly, reply def make_gram(word_array): return " ".join(word_array) class NGramTextModel(): def __init__(self, n, lines): self.n = n self.gram_dictionary = dict() self.build_from_lines(lines) def build_from_lines(...
71245
from social_auth.backends import PIPELINE from social_auth.utils import setting def save_status_to_session(request, auth, pipeline_index, *args, **kwargs): """Saves current social-auth status to session.""" next_entry = setting('SOCIAL_AUTH_PIPELINE_RESUME_ENTRY') if next_entry and next_entry in PIPELINE...
71269
from __future__ import print_function import torch import torch.optim as optim from data.data_loader import CreateDataLoader import tqdm import cv2 import yaml from schedulers import WarmRestart, LinearDecay import numpy as np from models.networks import get_nets from models.losses import get_loss from models.models i...
71284
from __future__ import absolute_import import sys import copy import operator from functools import reduce from sqlbuilder.smartsql.compiler import compile from sqlbuilder.smartsql.constants import CONTEXT, PLACEHOLDER, MAX_PRECEDENCE from sqlbuilder.smartsql.exceptions import MaxLengthError from sqlbuilder.smartsql.py...
71294
import torch import torch import numpy as np import torch from torch.autograd import Variable import os import argparse from datetime import datetime import torch.nn.functional as F def joint_loss(pred, mask): weit = 1 + 5*torch.abs(F.avg_pool2d(mask, kernel_size=31, stride=1, padding=15) - mask) wbce = F.bi...
71413
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal from torch.distributions.transforms import TanhTransform from rl_sandbox.constants import OBS_RMS, VALUE_RMS, CPU from rl_sandbox.model_architectures.utils import RunningMeanStd class ActorCritic(nn.Module): ...
71414
import os train_src="../dynet_nmt/data/train.de-en.de.wmixerprep" train_tgt="../dynet_nmt/data/train.de-en.en.wmixerprep" dev_src="../dynet_nmt/data/valid.de-en.de" dev_tgt="../dynet_nmt/data/valid.de-en.en" test_src="../dynet_nmt/data/test.de-en.de" test_tgt="../dynet_nmt/data/test.de-en.en" for temp in [0.5]: j...
71485
import os import typing from datetime import datetime from importlib import import_module from typing import Dict, Callable, Optional, List, Tuple from twitchbot.database import CustomCommand from twitchbot.message import Message from .config import cfg from .enums import CommandContext from .util import get_py_files,...
71489
import torch import torch.nn as nn import torch.nn.functional as F import logging from typing import Iterator import time import json from seq2seq.helpers import sequence_accuracy from seq2seq.ReaSCAN_dataset import ReaSCANDataset import pdb device = torch.device("cuda" if torch.cuda.is_available() else "cpu") logger ...
71559
import os import numpy import numpy as np import torch from dg_util.python_utils import misc_util from torch import nn numpy.set_printoptions(precision=4) torch.set_printoptions(precision=4, sci_mode=False) def batch_norm_layer(channels): return nn.BatchNorm2d(channels) def nonlinearity(): return nn.ReLU(...
71569
import npc import pytest def test_creates_character(campaign): result = npc.commands.create_character.werewolf('wer<NAME>', 'cahalith') character = campaign.get_character('werewolf mann.nwod') assert result.success assert character.exists() assert campaign.get_absolute(result.openable[0]) == str(ch...
71571
from odoo import fields, models class IrModel(models.Model): _inherit = 'ir.model' rest_api = fields.Boolean('REST API', default=True, help="Allow this model to be fetched through REST API")
71593
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("auditlog", "0005_logentry_additional_data_verbose_name"), ] operations = [ migrations.AlterField( model_name="logentry", name="object_pk", field=models.C...
71624
import os import torch from typing import List, Tuple from torch import nn from transformers import BertConfig, BertModel, BertPreTrainedModel, BertTokenizerFast, AutoTokenizer from repconc.models.repconc import RepCONC class TCTEncoder(BertPreTrainedModel): def __init__(self, config: BertConfig): BertPr...
71645
import time from compactor.process import Process from compactor.context import Context import logging logging.basicConfig() log = logging.getLogger(__name__) log.setLevel(logging.INFO) class WebProcess(Process): @Process.install('ping') def ping(self, from_pid, body): log.info("Received ping") def r...
71748
from __future__ import absolute_import # flake8: noqa # import apis into api package from hubspot.cms.performance.api.public_performance_api import PublicPerformanceApi
71749
from roscraco.helper import validator from roscraco.exception import RouterSettingsError class WirelessSettings(object): """Represents all available Wireless settings for a router.""" SECURITY_TYPE_NONE = 'none' SECURITY_TYPE_WEP64 = 'wep64' SECURITY_TYPE_WEP128 = 'wep128' SECURITY_TYPE_WPA = 'wp...
71768
try: from unittest import mock except ImportError: import mock from rest_email_auth import serializers @mock.patch( "rest_email_auth.serializers.models.EmailAddress.send_confirmation", autospec=True, ) def test_create(mock_send_confirmation, user_factory): """ Test creating a new email addres...
71802
from __future__ import print_function import codecs import logging import os import sys from optparse import OptionParser from pypugjs.utils import process def convert_file(): support_compilers_list = [ 'django', 'jinja', 'underscore', 'mako', 'tornado', ...
71809
from hachoir_parser.game.zsnes import ZSNESFile from hachoir_parser.game.spider_man_video import SpiderManVideoFile from hachoir_parser.game.laf import LafFile from hachoir_parser.game.blp import BLP1File, BLP2File from hachoir_parser.game.uasset import UAssetFile
71812
import csv import numpy as np import matplotlib.pyplot as plt import matplotlib from math import ceil from constants import ENV_NAMES import seaborn # sets some style parameters automatically COLORS = [(57, 106, 177), (218, 124, 48)] def switch_to_outer_plot(fig): ax0 = fig.add_subplot(111, frame_on=False) a...
71813
import torch from torch import nn, Tensor from torch.nn import functional as F class BasicBlock(nn.Module): expansion = 1 def __init__(self, c1, c2, s=1, downsample= None, no_relu=False) -> None: super().__init__() self.conv1 = nn.Conv2d(c1, c2, 3, s, 1, bias=False) self.bn1 = nn.Batch...
71846
from datetime import datetime from datetime import timezone from uuid import UUID from bson import ObjectId UUID_1_EPOCH = datetime(1582, 10, 15, tzinfo=timezone.utc) UUID_TICKS = 10000000 UUID_VARIANT_1 = 0b1000000000000000 def is_uuid(candidate): """Determine if this is a uuid""" try: UUID(candid...
71897
from matplotlib.offsetbox import AnchoredOffsetbox, AuxTransformBox, VPacker,\ TextArea, AnchoredText, DrawingArea, AnnotationBbox from mpl_toolkits.axes_grid1.anchored_artists import \ AnchoredDrawingArea, AnchoredAuxTransformBox, \ AnchoredEllipse, AnchoredSizeBar
72068
import os import shutil import subprocess import sys import re import glob from colors import prGreen,prCyan,prRed TRACES_DIR = './.fpchecker/traces' TRACES_FILES = TRACES_DIR+'/'+'trace' STRACE = 'strace' SUPPORTED_COMPILERS = set([ 'nvcc', 'c++', 'cc', 'gcc', 'g++', 'xlc', 'xlC', 'xlc++', 'xlc...
72070
from .cifar import Cifar10DataProvider, Cifar100DataProvider, \ Cifar10AugmentedDataProvider, Cifar100AugmentedDataProvider from .svhn import SVHNDataProvider def get_data_provider_by_name(name, train_params): """Return required data provider class""" if name == 'C10': return Cifar10DataProvider(*...
72100
class Socks5Error(Exception): pass class NoVersionAllowed(Socks5Error): pass class NoCommandAllowed(Socks5Error): pass class NoATYPAllowed(Socks5Error): pass class AuthenticationError(Socks5Error): pass class NoAuthenticationAllowed(AuthenticationError): pass
72115
import os import sys import cv2 import numpy as np from imageio import imread import json import argparse import visualization.visualizer.shader from PyQt5 import QtWidgets, QtGui, QtOpenGL from PyQt5.QtWidgets import * from PyQt5.QtGui import QIcon import PyQt5.QtCore as QtCore import glm from OpenGL.GL import * fro...
72127
import unittest try: import torch_butterfly BUTTERFLY = True except ImportError: BUTTERFLY = False class TestCase(unittest.TestCase): def test(self, butterfly=False): pass @unittest.skipIf(not BUTTERFLY, "torch_butterfly not found") def test_butterfly(self, **kwargs): self...
72138
import logging class LogHelper(): handler = None @staticmethod def setup(): FORMAT = '[%(levelname)s] %(asctime)s - %(name)s - %(message)s' LogHelper.handler = logging.StreamHandler() LogHelper.handler.setLevel(logging.DEBUG) LogHelper.handler.setFormatter(logging.Formatter(F...
72160
import logging import platform from unittest.mock import Mock from sanic import __version__ from sanic.application.logo import BASE_LOGO from sanic.application.motd import MOTDTTY def test_logo_base(app, run_startup): logs = run_startup(app) assert logs[0][1] == logging.DEBUG assert logs[0][2] == BASE_...
72167
import json import sqlite3 from scrapekit.logs import log_path conn = sqlite3.connect(':memory:') def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d def log_parse(scraper): path = log_path(scraper) with open(path, 'r') as...
72177
import os from flask import g, request, jsonify, make_response from flask_sqlalchemy import SQLAlchemy from .app import app from .conf import CONFIG from .utils import get_allowed_service from DeviceManager.Logger import Log app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = ...
72192
import numpy as np class Renderer: def __init__(self, height, width, config): self.height = height self.width = width self.content = None self.zbuffer = None self.m = None self.f = 1.0 self.resize(height, width) self.colors = config.colors s...
72201
import pathlib def iter_examples(): example_dir = pathlib.Path(__file__).parent.absolute() for fp in example_dir.iterdir(): if fp.name.startswith("_") or fp.suffix != ".py": continue yield fp
72214
from typing import Sequence, Dict from anoncreds.protocol.globals import LARGE_VPRIME, LARGE_MVECT, LARGE_E_START, \ LARGE_ETILDE, \ LARGE_VTILDE, LARGE_UTILDE, LARGE_RTILDE, LARGE_ALPHATILDE, ITERATIONS, \ DELTA from anoncreds.protocol.primary.primary_proof_common import calcTge, calcTeq from anoncreds.pr...
72223
import token as TOKEN __all__ = ("EXCEPT", "INDENT", "LINE_LENGTH", "TOKEN") LINE_LENGTH = 100 # line length to use while formatting code TOKEN.COLONEQUAL = 0xFF # for versions that have assignment expressions implemented SPACE = " " INDENT_LENGTH = 4 # length of indentation to use INDENT = SPACE * INDENT_LENGT...
72266
import os, sys #import GaussianRunPack from GaussianRunPack import GaussianDFTRun #test_sdf = GaussianRunPack.GaussianDFTRun('B3LYP', '3-21G*',12, 'OPT energy deen nmr uv homolumo',infilename,0) #test_sdf = GaussianRunPack.GaussianDFTRun('B3LYP', '3-21G*',1, 'OPT energy deen nmr uv homolumo',infilename,0) #outd...
72279
import pytest from ruptures.datasets import pw_constant from ruptures.show import display from ruptures.show.display import MatplotlibMissingError @pytest.fixture(scope="module") def signal_bkps(): signal, bkps = pw_constant() return signal, bkps def test_display_with_options(signal_bkps): try: ...
72323
from flask_restful import Resource from flask_restful.reqparse import RequestParser from pajbot.managers.db import DBManager from pajbot.models.playsound import Playsound from pajbot.models.sock import SocketClientManager from pajbot.modules import PlaysoundModule from pajbot.web.utils import requires_level from pajbo...
72331
from torch import nn from .PGFA_backbone import PGFABackbone from .PGFA_pool import PGFAPool from .PGFA_pose_guided_mask_block import PGFAPoseGuidedMaskBlock from .PGFA_reduction import PGFAReduction from .PGFA_classifier import PGFAClassifier class PGFA(nn.Module): def __init__(self, cfg): super(PGFA, se...
72342
from amaranth_boards.zturn_lite_z010 import * from amaranth_boards.zturn_lite_z010 import __all__ import warnings warnings.warn("instead of nmigen_boards.zturn_lite_z010, use amaranth_boards.zturn_lite_z010", DeprecationWarning, stacklevel=2)
72395
import numpy as np from scipy.spatial import distance from Quaternions import Quaternions import Animation import AnimationStructure def constrain(positions, constraints): """ Constrain animation positions given a number of VerletParticles constrains Parameters ---------- ...
72417
import numpy as np import torch from torch.utils.data import Dataset import numpy as np from ad3 import factor_graph as fg try: import cPickle as pickle except: import pickle from tqdm import tqdm import time from .random_pgm_data import RandomPGMData, worker_init_fn len = 100000 class RandomPGMHop(Dataset):...
72426
input = """ num(2). node(a). p(N) :- num(N), #count{Y:node(Y)} = N1, <=(N,N1). """ output = """ {node(a), num(2)} """