id
stringlengths
3
8
content
stringlengths
100
981k
406598
import os import errno import random import socket def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def get_random_free_port(interface = '0.0.0.0'): wh...
406607
from collections import defaultdict from urllib.parse import urlparse from datetime import datetime, timedelta import pymysql import html2text import subprocess import yaml h = html2text.HTML2Text() full_html_str = '' num_for_each_category = 10 with open('config.yml', 'r') as config_file: config = yaml.load(conf...
406612
apps_details = [ { "app": "Learning xc functional from experimental data", "repo": "https://github.com/mfkasim1/xcnn", # leave blank if no repo available # leave blank if no paper available, strongly suggested to link to open-access paper "paper": "https://arxiv.org/abs/2102.04229",...
406623
import os from google.cloud import storage as google_storage from label_studio_sdk import Client BUCKET_NAME = 'my-bucket' # specify your bucket name here GOOGLE_APPLICATION_CREDENTIALS = 'my-service-account-credentials.json' # specify your GCS credentials os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = GOOGLE_APPLI...
406635
import pytest from simple_zpl2 import ZPLDocument def test_field_block(): zdoc = ZPLDocument() zdoc.add_field_block() assert(zdoc.zpl_bytes == b'^XA\n^FB0,1,0,L,0\n^XZ') zdoc = ZPLDocument() zdoc.add_field_block(1000) assert (zdoc.zpl_bytes == b'^XA\n^FB1000,1,0,L,0\n^XZ') zdoc = ZPLDocu...
406666
from django.utils.functional import cached_property from waldur_core.structure.tests import fixtures as structure_fixtures from . import factories class PayPalFixture(structure_fixtures.CustomerFixture): @cached_property def payment(self): return factories.PaypalPaymentFactory(customer=self.customer...
406680
import os import sys import time import json import copy import shlex import shutil import random import signal import hashlib import platform import subprocess from pyeoskit import config from pyeoskit import wallet from pyeoskit import utils from pyeoskit import eosapi from pyeoskit import log logger = log.get_logg...
406722
import picamera camera = picamera.PiCamera() for filename in camera.record_sequence('%d.h264' % i for i in range(1, 11)): camera.wait_recording(2)
406738
import glob import bs4 import concurrent.futures import os import re import json import hashlib import gzip def _name(arr): index, names = arr for name in names: try: soup = bs4.BeautifulSoup( gzip.decompress(open(name, 'rb').read()) ) reviews = soup.find_all('div', {'data-hook':'review'}) ...
406793
from contextlib import contextmanager from PIL import Image from .quantize import mmcq @contextmanager def get_palette(filename, color_count=10): with Image.open(filename) as image: colors = [] rgb = image.convert('RGB') for x in range(0, rgb.width, 5): for y in range(0, rgb.h...
406794
import json import decimal class DecimalEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, decimal.Decimal): return { "_type": "decimal", "value": str(obj) } return super(DecimalEncoder, self).default(obj) class DecimalDecod...
406830
from thinc.api import chain, Relu, reduce_max, Softmax, add, concatenate bad_model = chain(Relu(10), reduce_max(), Softmax()) bad_model2 = add(Relu(10), reduce_max(), Softmax()) bad_model_only_plugin = chain( Relu(10), Relu(10), Relu(10), Relu(10), reduce_max(), Softmax() ) bad_model_only_plugin2 = add( Rel...
406855
import numpy as np from pandas import DataFrame from typing import Optional, Tuple from numbers import Number from pycsou.core.solver import GenericIterativeAlgorithm from pycsou.core.map import DifferentiableMap from pycsou.core.linop import LinearOperator from pycsou.core.functional import ProximableFunctional from ...
406887
import json from test.factories import AttendanceFactory, OrganizationFactory from test.harness import IntegrationTest from app import db, Attendance class TestAttendance(IntegrationTest): def test_attendance(self): cfsf = OrganizationFactory(name=u"Code for San Francisco") url = u"https://www.c...
406960
from django.contrib import admin from . import models class VenueAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} class VenueAPIConfigurationAdmin(admin.ModelAdmin): list_display = ("id", "venue") list_select_related = ("venue",) class VenueTapManagerAdmin(admin.ModelAdmin): lis...
406966
import binaryninja from .XTENSAArch import XTENSA XTENSA.register() # built-in view EM_XTENSA = 94 binaryninja.BinaryViewType['ELF'].register_arch(EM_XTENSA, binaryninja.enums.Endianness.LittleEndian, binaryninja.Architecture['XTENSA'])
407004
import math import operator import random from queue import PriorityQueue import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from log import timeit SOS_token = 2 EOS_token = 3 MAX_LENGTH = 50 class Encoder(nn.Module): def __init__(self, input_size, embed_size,...
407025
from setuptools import setup, find_packages from torch.utils import cpp_extension with open("README.md") as f: long_description = f.read() setup( name="dconv_native", version="0.1.10", author="<NAME>", author_email="<EMAIL>", description="Cuda implementation of (modulated) deformable convolut...
407033
import paddlex as pdx import time import glob image_names = glob.glob('steel/JPEGImages/*.jpg') model = pdx.load_model('output/hrnet/best_model') start_time = 0 for i, image_name in enumerate(image_names): if i == 100: # 前面100张不计时,用于warm up start_time = time.time() if i > 299: break result...
407079
import torch import torch.nn as nn class Flatten(nn.Module): """Flattens input by reshaping it into a one-dimensional tensor.""" def forward(self, input): return input.view(input.size(0), -1) class UnFlatten(nn.Module): """Unflattens a tensor converting it to a desired shape.""" def forwar...
407089
from __future__ import absolute_import from app.logic import resultsets from sympy import sympify, I, sqrt def test_predicates(): assert not resultsets.is_approximatable_constant(sqrt(2)) assert not resultsets.is_approximatable_constant(sympify('2')) assert resultsets.is_complex(2 * I + 3) assert not ...
407103
import numpy as np def vdiff(x,dim): """VDIFF Length-preserving first central difference. DX=VDIFF(X,DIM) differentiates X along dimension DIM using the first central difference; DX is the same size as X. !!! Only works for 1-D and 2-D arrays _________________________________________________________...
407107
from django.urls import path from . import views app_name = 'app_author' urlpatterns = [ path('<slug:slug>/edit', views.author_edit_view, name='author_edit'), path('<slug:slug>', views.author_single_view, name='author_single'), ]
407123
import typing as t from marshmallow import Schema as Schema from marshmallow.fields import Integer from marshmallow.fields import URL # schema for the detail object of validation error response validation_error_detail_schema: t.Dict[str, t.Any] = { "type": "object", "properties": { "<location>": { ...
407138
from __future__ import unicode_literals from django.apps import apps from django.utils.translation import ugettext_lazy as _ from navigation import Link from .permissions import permission_events_view def get_kwargs_factory(variable_name): def get_kwargs(context): ContentType = apps.get_model( ...
407142
import sys # variables username=sys.argv[1] password=<PASSWORD>[2] adminUrl=sys.argv[3] applicationName=sys.argv[4] serverName=sys.argv[5] # connect to the server connect(username, password, adminUrl) # move to the managed server serverConfig() cd('Servers\server1') ls() # Deploy application undeploy(applicationNa...
407202
from ase.io import read from flosic_os import calculate_flosic, flosic,xyz_to_nuclei_fod,ase2pyscf,get_multiplicity from pyscf import dft,gto # This example shows how FLO-SIC calculations can be done in the one-shot mode. # The necessary input is a .xyz file with the molecular geometry and the FOD positions. # The ea...
407298
from time import sleep from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class FacebookLogin: def __init__(self, driver): self.dri...
407311
from mock import AsyncMock import pytest from webex_assistant_sdk.dialogue.manager import MissingHandler, SimpleDialogueManager from webex_assistant_sdk.dialogue.rules import SimpleDialogueStateRule from webex_assistant_sdk.models.mindmeld import DialogueState pytestmark = pytest.mark.asyncio async def test_rule_ma...
407331
import pytest from django.db import transaction from node.blockchain.models.account_state import AccountState from node.core.database import ensure_in_transaction from node.core.exceptions import DatabaseTransactionError @pytest.mark.django_db @pytest.mark.parametrize('iteration', map(str, range(3))) # we need mult...
407344
import unittest import munch import basecrm from basecrm.test.testutils import BaseTestCase class TagsServiceTests(BaseTestCase): def test_service_property_exists(self): self.assertTrue(hasattr(self.client, 'tags')) def test_method_list_exists(self): self.assertTrue(hasattr(self.client.tags,...
407346
from typing import Any, Callable, List, Protocol, TypeVar, runtime_checkable _F = TypeVar("_F", bound=Callable[..., Any]) def language_id(id: str) -> Callable[[_F], _F]: def decorator(func: _F) -> _F: setattr(func, "__language_id__", id) return func return decorator @runtime_checkable clas...
407349
import unittest import asyncio import aiohttp import tech import json class TestTechMethods(unittest.TestCase): def setUp(self): self._loop = asyncio.get_event_loop() self._session = aiohttp.ClientSession(loop = self._loop) self._tech = tech.Tech(self._session) self._loop.run_until_...
407412
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import difflib import gc import os import re import sys import hashlib import heapq import lz4.frame import math import operator import tempfile import threading import x...
407445
import asyncio from distutils.version import LooseVersion import uuid import bluesky from bluesky.run_engine import RunEngine, TransitionError from bluesky.plans import scan from bluesky.preprocessors import SupplementalData import event_model import ophyd.sim import pymongo import pytest # Make module-scoped versio...
407453
from .architectures import build_model from .losses import build_loss __all__ = ['build_model', 'build_loss']
407468
from LSP.plugin.core.logging import debug from LSP.plugin.core.protocol import Request from LSP.plugin.core.registry import windows from LSP.plugin.core.types import ClientStates from LSP.plugin.core.typing import Any, Generator from LSP.plugin.documents import DocumentSyncListener from os.path import join from setup i...
407486
from __future__ import annotations from .. import query_utils from . import contract_creation_blocks_statements async_query_contract_creation_block = query_utils.with_connection( contract_creation_blocks_statements.async_select_contract_creation_block, 'contract_creation_blocks', ) async_query_contract_cre...
407489
from datetime import datetime def add_watermark(ax): ax.text( 0.97, 0.9, f"Generated {datetime.now()}", transform=ax.transAxes, fontsize=12, color="gray", alpha=0.5, ha="right", va="center", )
407490
from django.core.exceptions import ValidationError import jsonschema from jsonschema.exceptions import SchemaError def validate_json_schema(value): """Wrap jsonschema validation with serializers.ValidationError""" try: jsonschema.Draft4Validator.check_schema(value) except SchemaError as e: ...
407496
import os import setuptools with open("version.txt") as f: VERSION = f.read().strip() with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() atari = ["gym[atari,accept-rom-license]~=0.21", "opencv-python~=4.0"] gym_minigrid = ["gym-minigrid~=1.0"] petting_zoo = ["pettingzoo[sisl,a...
407504
from wagtail.images.formats import Format, register_image_format register_image_format( Format( 'bleed', 'Bleed into left/right margins', 'richtext-image image-bleed', 'width-1170' ) )
407517
import csv from StringIO import StringIO def csv_res2_dict_lst(res): """Convert CSV string with a header into list of dictionaries""" return list(csv.DictReader(StringIO(res), delimiter=",")) def expected_repnames(repos_cfg): """Generate expected repository names '{account_name}/{repo_name}'""" temp...
407550
import json import unittest from tests import setup_django_settings from mengenali.views import download from django.test.client import RequestFactory class EndToEndTest(unittest.TestCase): test_performance = False def setUp(self): self.factory = RequestFactory() setup_django_settings() ...
407561
def test(): from kale.utils import pod_utils as _kale_pod_utils _kale_pod_utils.snapshot_pipeline_step( "T", "test", "/path/to/nb")
407662
entries = [ { "env-title": "atari-alien", "env-variant": "No-op start", "score": 1536.05, }, { "env-title": "atari-amidar", "env-variant": "No-op start", "score": 497.62, }, { "env-title": "atari-assault", "env-variant": "No-op start", ...
407665
import numpy as np import cudarray as ca from ..wrap import blas from ..linalg import matmul_shape class Dot(object): def __init__(self, a, b, out=None): self.batch_size = a.shape[0] self.a = a self.b = b if a.dtype != b.dtype: raise ValueError('dtype mismatch') ...
407673
from __future__ import absolute_import, print_function, unicode_literals import struct from wolframclient.utils import six from wolframclient.utils.datastructures import Settings if six.JYTHON: pass if six.PY2: def _bytes(value): return chr(value) else: def _bytes(value): return byte...
407676
import re import argparse import os.path from argparse import RawTextHelpFormatter if __name__ == "__main__": parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter) parser.add_argument('--mapping_file', type=str, default="Resnet50_kcp_ws.m", help="<name of your mapping file with layer specs>") ...
407724
from pytest import fixture @fixture(autouse=True) def ensure_no_local_config(no_local_config): pass
407727
def psd(data, fs, df_exp): """ psd of data """ from math import ceil, log from numpy import fft, linspace a = ceil(log(data.shape[0])/log(2)) b = ceil(log(fs/df_exp+2)/log(2)) nfft = 2**int(max(a,b)) Y0 = fft.fft(data, nfft, 0) Y = Y0[:nfft/2,:]/data.shape[0] Pxx = abs(Y) #Pangle = angle...
407730
import tensorflow as tf from trainer.trainer import Trainer from utils.multi_gpu_wrapper import MultiGpuWrapper as mgw FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_bool('enbl_multi_gpu', False, 'Enable training with multiple gpus') tf.app.flags.DEFINE_string('data_path', './data/tfrecord', 'path to data tfrecords')...
407771
import aiohttp_jinja2 from aiohttp import web from aiohttp_security import remember, forget, authorized_userid from aiohttpdemo_blog import db from aiohttpdemo_blog.forms import validate_login_form def redirect(router, route_name): location = router[route_name].url_for() return web.HTTPFound(location) @aio...
407802
import cv2 MODEL_PATH = '/home/ubuntu/models/' models = ( cv2.CascadeClassifier(MODEL_PATH + 'haarcascade_frontalface_default.xml'), cv2.CascadeClassifier(MODEL_PATH + 'haarcascade_profileface.xml'), )
407833
import pytest from indy import did from plenum.common.exceptions import RequestRejectedException from plenum.common.constants import TRUSTEE_STRING from plenum.test.pool_transactions.helper import sdk_add_new_nym from plenum.test.helper import sdk_get_and_check_replies, sdk_sign_and_submit_op def test_new_DID_cannot...
407836
import os import sys import numpy as np import matplotlib.image as mpimg from ..core.data import Data from ..util import tryremove class SintelData(Data): SINTEL_URL = 'http://files.is.tue.mpg.de/sintel/MPI-Sintel-complete.zip' dirs = ['sintel'] def __init__(self, data_dir, stat_log_dir=None, ...
407848
import pandas as pd import os, glob import seaborn as sns import matplotlib.pyplot as plt from datetime import datetime import matplotlib import numpy as np from configparser import ConfigParser, MissingSectionHeaderError, NoOptionError, NoSectionError from simba.drop_bp_cords import * from simba.rw_dfs import...
407854
from unittest import TestCase from unittest.mock import MagicMock from signalflow_algorithms.algorithms.graph import Graph, Branch, Node class TestGraph(TestCase): def test_graph_copy(self): # Create graph graph = Graph() node_1 = Node(graph) node_2 = Node(graph) node_3 =...
407881
import numpy as np import pytest from scipy.sparse.linalg import lsqr import krylov from .helpers import assert_consistent from .linear_problems import ( complex_shape, complex_unsymmetric, hermitian_indefinite, hpd, real_shape, real_unsymmetric, spd_dense, spd_sparse, symmetric_in...
407935
from spark.config.domain import DomainType class ConfigNormalizer: def __init__(self, config_set): self._config_set = config_set self._param_list = config_set.get_params() self._normalized_config = self.__init_normalized_config() def __init_normalized_config(self): normalized_...
407953
from __future__ import absolute_import, division, print_function import json from base64 import b64decode from flask import Blueprint, current_app, jsonify, request import appr.api.impl.registry from appr.api.app import getvalues, repo_name from appr.exception import ( ApprException, ChannelNotFound, InvalidPara...
407983
from datetime import datetime, timedelta from typing import List, Optional import numpy as np def datetime_range( granularity: timedelta, # np.timedelta64(1, 'D') or python timedelta start_time: datetime, end_time: Optional[datetime] = None, num_points: Optional[int] = None, ) -> List[datetime]: ...
407985
from __future__ import division import torch from torch import nn import numpy as np def compute_errors_test(gt, pred): gt = gt.numpy() pred = pred.numpy() thresh = np.maximum((gt / pred), (pred / gt)) a1 = (thresh < 1.25 ).mean() a2 = (thresh < 1.25 ** 2).mean() a3 = (thresh < 1.25 ** 3).mea...
407986
import argparse import os EMPTY_RESPONSE = 'EMPTY_RESPONSE' def print_dialogs(dialogs, history_size, sparse=True, print_next_post=False, delimeter='\\n'): if sparse: step = history_size + 1 else: step = 1 if print_next_post: window_sz = history_size + 1 else: window_sz...
408017
import sys, os import socket from distutils import sysconfig from Package import Package petsc_text = r''' #include <stdlib.h> #include <stdio.h> #include <mpi.h> #include <petsc.h> int main(int argc, char* argv[]) { PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL); printf("MPI version %d.%d\n", MPI_VERSION...
408033
import importlib import pkgutil from contextlib import ( suppress, ) from functools import ( lru_cache, ) from types import ( ModuleType, ) from typing import ( Callable, Union, ) from .exceptions import ( MinosImportException, ) @lru_cache() def import_module(module_name: str) -> Union[type,...
408048
from . import views from rest_framework.routers import SimpleRouter router = SimpleRouter() router.register("posts", views.PostViewSet, "posts") urlpatterns = router.urls
408120
from copy import deepcopy from dataclasses import dataclass, field from random import shuffle from typing import Optional import logging from paiargparse import pai_dataclass, pai_meta from tfaip import TrainerPipelineParams, TrainerPipelineParamsBase, PipelineMode from calamari_ocr.ocr.dataset.datareader.base import...
408130
import openmdao.api as om from openaerostruct.common.reynolds_comp import ReynoldsComp from openaerostruct.common.atmos_comp import AtmosComp class AtmosGroup(om.Group): def setup(self): self.add_subsystem( "atmos", AtmosComp(), promotes_inputs=["altitude", "M...
408143
import numpy as np from extra_keras_metrics import F1Score from sklearn.metrics import f1_score as baseline from .utils import compare_metrics def f1score_score(y_true, y_pred): return baseline(y_true, np.round(y_pred).astype(int)) def test_precision(): compare_metrics(F1Score(), f1score_score)
408162
import bisect import numpy as np class ReadCoverage: def __init__(self, in_paf): self.paf = in_paf self.glob_mean = None self.glob_std = None self.coverage_map = dict() self.ctg_lens = dict() self._make_coverage_map() self._get_glob_mean() @staticmeth...
408195
from binascii import hexlify, unhexlify from dataclasses import dataclass import random import uuid from flask import ( Flask, Blueprint, request, render_template, ) from Crypto.Random import ( get_random_bytes ) from crypto.crypto import ( get_rsa_key, get_public_key, sign_message, ...
408213
import warnings from django.shortcuts import render, redirect from django.views.generic import View from django.contrib.auth import get_user_model from dashboard.views.utils import Util, page_manage class Register(View): @page_manage def get(self, request): context = Util.get_context(request) ...
408252
str=input("Enter string:") str_list=list(str) rev_list=[] rev_str="" length=len(str_list) for i in range(-1,-(length+1),-1): rev_list.append(str_list[i]) rev=rev_str.join(rev_list) print(rev) print("Character in even index:") for i in range(0,len(str),2): print(str[i])
408254
import sys from enum import Enum class flag(Enum): UNVISITED = -1 VISITED = -2 AL = [] dfs_num = [] ts = [] def toposort(u): global AL global dfs_num global ts dfs_num[u] = flag.VISITED.value for v, w in AL[u]: if dfs_num[v] == flag.UNVISITED.value: toposort(v) ts.append(u) def main(): ...
408284
from __future__ import division from __future__ import print_function from past.utils import old_div def f(x): """Runge's function.""" return old_div(1,(1 + x**2)) # Plot f import matplotlib.pyplot as plt import numpy as np xcoor = np.linspace(-3, 3, 101) ycoor = f(xcoor) plt.plot(xcoor, ycoor) plt.savefig('f_...
408296
from all_models.models.A0001_user import * from all_models.models.A0002_config import * from all_models.models.A0003_attribute import * from all_models.models.A0004_globals import * from all_models.models.A0005_interface import * from all_models.models.A0006_testcase import * from all_models.models.A0007_task import * ...
408341
from django.db import models # Create your models here. from sqlorders.models import DbConfig from users.models import UserAccounts class DbQuerySchemas(models.Model): """ 存储远程查询数据库的库名 """ id = models.AutoField(primary_key=True, verbose_name=u'主键ID') cid = models.ForeignKey(DbConfig, blank=True, ...
408385
from slot_attention.slot_attention import SlotAttention from slot_attention.slot_attention_experimental import SlotAttentionExperimental
408392
from venv import EnvBuilder from .deps_handler import DepsHandle import shutil import os from subprocess import call import logging from simple_term_menu import TerminalMenu extra_options = ["manually specify", "ignore dependency"] class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m...
408450
import parser import player import random opcodes = { # Opcodes are keys, number of ticks are values. 'harvest': 5, 'plant': 4, 'peek': 4, 'poke': 3, 'goto': 1, 'ifequal': 2, 'ifless': 2, 'ifmore': 2, 'add': 3, 'sub': 3, 'mult': 5, 'div': 8, 'mod': 7, 'random': 6...
408473
import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import climate, sensor, time from esphome.components.remote_base import CONF_TRANSMITTER_ID from esphome.const import CONF_ID, CONF_TIME_ID, CONF_MAC_ADDRESS, \ ESP_PLATFORM_ESP32, \ UNIT_PERCENT, ICON_PERCENT ESP_PLATF...
408475
from __future__ import division import h5py import pickle from gwpy.table import EventTable import numpy as np from scipy import integrate, interpolate import random import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import lal import lalsimulation from pylal import antenna, cosmography import ar...
408487
import numpy as np from . import logger from duckietown_utils.expand_variables import expand_environment import os __all__ = [ 'd8n_read_images_interval', 'd8n_read_all_images', 'd8n_get_all_images_topic', ] def d8n_read_images_interval(filename, t0, t1): """ Reads all the RGB data from the ba...
408497
import numpy as np import torch import torch.jit as jit import torch.nn as nn import torch.nn.functional as F from habitat_baselines.rl.models.rnn_state_encoder import RNNStateEncoder def _unflatten_helper(x, t: int, n: int): sz = list(x.size()) new_sz = [t, n] + sz[1:] return x.view(new_sz) class RCMS...
408508
from __future__ import division import numpy as np import nibabel as nib import copy import time import configparser from skimage.transform import resize from scipy.ndimage import measurements import tensorflow as tf from glob import glob import re import SimpleITK as sitk import random from keras_preprocessing.image i...
408516
b = False e = "Hello world" while b: print(b) d = True while d: print(d and False) print(d and True) print("hello")
408560
from pydantic import validator, BaseModel from app.models.schema.base import PityModel class DatabaseForm(BaseModel): id: int = None name: str host: str port: int = None username: str password: str database: str sql_type: int env: int @validator("name", "host", "port", "usern...
408601
import cv2 import numpy as np import torch import torch.nn.functional as F from data import CenterAffine def gather_feature(fmap, index, mask=None, use_transform=False): if use_transform: # change a (N, C, H, W) tenor to (N, HxW, C) shape batch, channel = fmap.shape[:2] fmap = fmap.view(b...
408631
import tensorflow as tf import numpy as np import tqdm __all__ = ('pad_ragged_2d', 'shuffle_ragged_2d', 'inputs_to_labels', 'get_pos_encoding', 'get_quant_time', 'softmax_with_temp', 'generate_midis') def pad_ragged_2d(ragged_tensor, pad_idx): # ragged_tensor -> RAGGED(batch_siz...
408646
import pyqrcode import png from pyqrcode import QRCode # Text which is to be converted to QR code print("Enter text to convert") s=input(": ") # Name of QR code png file print("Enter image name to save") n=input(": ") # Adding extension as .pnf d=n+".png" # Creating QR code url=pyqrcode.create(s) # Saving QR code as a...
408714
class Room: def __init__(self): pass def intro_text(self): raise NotImplementedError() def adjacent_moves(self): pass def available_actions(self): pass class StartingRoom(Room): def __init__(self, ): super().__init__() def intro_text(self): r...
408715
import asyncio import aiodocker from async_timeout import timeout from fastapi import FastAPI from simcore_service_director_v2.models.schemas.constants import ( DYNAMIC_SIDECAR_SERVICE_PREFIX, ) from simcore_service_director_v2.modules.dynamic_sidecar.scheduler import ( DynamicSidecarsScheduler, ) SERVICE_WAS...
408717
from yoyo import step step( "CREATE TABLE IF NOT EXISTS evolve_log (pokemon text, iv real, cp real, dated datetime DEFAULT CURRENT_TIMESTAMP)" )
408752
from rest_framework import serializers from mayan.apps.rest_api.relations import MultiKwargHyperlinkedIdentityField from ..models.document_type_models import DocumentType, DocumentTypeFilename class DocumentTypeQuickLabelSerializer(serializers.ModelSerializer): document_type_url = serializers.HyperlinkedIdentit...
408769
import logging import ibmsecurity.utilities.tools logger = logging.getLogger(__name__) def get(isdsAppliance, check_mode=False, force=False): """ Get all snmp objects """ return isdsAppliance.invoke_get("Get all alert objects", "/system_alerts") def enable(isdsAp...
408800
import FWCore.ParameterSet.Config as cms RawDataConverter = cms.EDAnalyzer( "RawDataConverter", # list of digi producers DigiProducersList = cms.VPSet( cms.PSet( DigiLabel = cms.string( 'ZeroSuppressed' ), DigiProducer = cms.string( 'laserAlignmentT0Producer' ), #simSiStrip...
408834
from build.pymod import test_runtime_error try: test_runtime_error() except RuntimeError as e: print(e) print('successfully caught error')
408841
import functools import tensorflow as tf import math import sys def doublewrap(function): """ A decorator decorator, allowing to use the decorator to be used without parentheses if not arguments are provided. All arguments must be optional. """ @functools.wraps(function) def decorator(*args, **k...
408909
from importlib import import_module from ..config import * import fython.traceback as tbk from .lexem import Lexem class Unit: def __init__(s, t, module=None): s.lex_type = t.type s.value = t.value s.lineno = t.lineno s.url_value = t.value s.is_interpolation_safe = 1 s.lexem = [Lexem(type=t.type, line...