text stringlengths 3.07k 22.1k |
|---|
from telnetlib import EL
from eth_account import Account
#from brownie import JToken
from scripts.helpful_scripts import get_account, connect_to_ETH_provider
from brownie import interface, config, network, chain, accounts
import sys
from web3 import Web3
from pprint import pprint
import time
def swap(amount_avax, ... |
"""
Assets Script.
"""
from __future__ import annotations
import json
import os
import math
from typing import Dict, List, Set, Tuple
ColorEntry = Tuple[float, str, Tuple[int, int, int]]
class DuplicateNameError(Exception):
"""Custom error for duplicate asset name"""
pass
# Constants
COLOR_DIFFERENCE_THRE... |
import tensorflow as tf
from tensorflow.keras.models import Model
from compression_tools.decompose.decompose_schemes import decompose_conv2d_layer
from compression_tools.decompose.rank_estimation import estimate_rank
from tools.visualization.decompose_visualization_tool import plot_rank_percentage
from tools.progress.b... |
import torch as t
import torch.nn as nn
import math
from collections import OrderedDict
__all__ = ['shufflenet2']
#### The model below is defined by myself
def channel_shuffle(x, groups=2):
bat_size, channels, w, h = x.shape
group_c = channels // groups
x = x.view(bat_size, groups, group_c, w, h)
x = t.transpos... |
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import _name_estimators
class ColumnTransformerNoStack(ColumnTransformer):
"""Applies transformers to columns of an array, and does not stack them.
This estimator allows different columns or column subsets of the input to
be transformed ... |
"""
Title: Image classification with ConvMixer
Author: [<NAME>](https://twitter.com/RisingSayak)
Date created: 2021/10/12
Last modified: 2021/10/12
Description: An all-convolutional network applied to patches of images.
"""
"""
## Introduction
Vision Transformers (ViT; [Dosovitskiy et al.](https://arxiv.org/abs/1612.0... |
import random
# This is the amount of digits that are accounted for in the random number generation and user input collection processes. This value can be modified to increase/decrease diversity in value selection.
digitCount = 3
def getRandomNumber():
'''
This function generates a random number (the s... |
import sys
import os
import math
import fnmatch
from timeit import default_timer as timer
from multiprocessing import Process, Queue
import numpy
from scipy.spatial import KDTree
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as Figure... |
## EXAMPLE FILE FOR THE OXFORD QIS WORKSHOP FROM 22 FEB 2020
## THIS IS WRITTEN TO WORK WITH PYTKET v0.4.1 AND WILL NOT BE UPDATED IN FUTURE
from pytket.circuit import Circuit, PauliExpBox, Pauli
from pytket.predicates import CompilationUnit
from pytket.passes import DecomposeBoxes, PauliSimp, SequencePass
from pytket... |
import svgwrite
from svgwrite.shapes import Line, Circle, Polygon, Rect
from svgwrite.path import Path
import numpy as np
import numpy.random as random
from svgpathtools import parse_path
stroke_width = 25
class primitive():
def __init__(self):
pass
def svgcode(self):
pass
... |
import pytest
from django.urls import reverse
from core.client import _build_absolute_uri
@pytest.fixture
def data_list_no_licence_required():
return [
{
"count": 1,
"total_pages": 1,
"results": [
{
"id": "66297b19-8753-4f37-8b6d-83... |
from spacy.lang.en import STOP_WORDS
import pickle
import spacy
import numpy as np
import pandas as pd
# Load up spacy model and import stop words
nlp = spacy.load('en_core_web_sm')
for word in STOP_WORDS:
lexeme = nlp.vocab[word]
lexeme.is_stop = True
def save_pickle(data, filename):
"""Saves the data i... |
import argparse
import os
import time
from io import BytesIO
import numpy as np
import pandas as pd
import torch
from PIL import Image
from torchvision.transforms import functional
from models import get_model, get_iou_types
from models.mimic.split_rcnn import split_rcnn_model
from myutils.common import yaml_util
fro... |
import pickle
import os
import re
from inspect import signature
from os.path import dirname, abspath, join
from collections import OrderedDict
from io import StringIO
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktLanguageVars
decorated_features = OrderedDict()
#The current python file must be in the sa... |
from os import path as osp
import pytest
from smartsim import Experiment
from smartsim._core.generation import Generator
from smartsim.database import Orchestrator
from smartsim.settings import RunSettings
rs = RunSettings("python", exe_args="sleep.py")
"""
Test the generation of files and input data for an experi... |
"""
LCLS-specific epicsArch.txt plugin.
"""
from __future__ import annotations
import argparse
import json
import logging
import pathlib
import typing
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Type
import apischema
import lark
from .. import transformer
from ..common import A... |
import shutil
import traceback
from abc import ABC, abstractmethod
from pathlib import Path, PurePath
from tempfile import TemporaryDirectory
from typing import List, IO, Optional
from zipfile import ZipFile
import yaml
from opera.error import ParseError, OperaError
from opera.utils import determine_archive_format
... |
import time
import joblib
import numpy as np
from sklearn.base import clone
from .base import Explainer
from .parsers import util
class DShap(Explainer):
"""
Explainer that approx. data Shapley values using
the TMC-Shapley algorithm.
Local-Influence Semantics
- Inf.(x_i, x_t) = Avg. L(y_i, ... |
import time
from common.scene import Scene
from common.tool import load_resource
from azurelane.assist import calculate_move_map
###自己添加
def siren_heavy_blue(prefix):
return Scene("检测蓝色塞壬重巡",identify_image=load_resource("map_siren_heavy_blue.png", prefix)) #判断塞壬蓝色重巡
def siren_heavy_purple(prefix):
... |
'''A wrapper for fixed column text files
This module copies a fixed column TXT file into a dictionary to manipulate,
and enrich. It can also be exported into a TXT file with a different
structure than the original file.
'''
import logging
from pathlib import Path
import sys
import tempfile
import beetools
import di... |
import argparse
import sys
# import numpy as np
# from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
import sympy
from sympy import *
import sys
sys.path.append(r'C:\Users\elira\Google Drive\butools2\Py... |
import os
import argparse
from glob import glob
from functools import partial
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import cv2
from PIL import Image
import wandb
import jax
import jax.numpy as jnp
import flax
import torch
import torchvision.transforms as transforms
import tensorf... |
import os
import tqdm
import argparse
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
from torch.utils import data
import torchvision.transforms as T
import datetime
from plane_estimation.log import Logger
from plane_estimation.misc import AverageMeter, get_nyu_coordinate_map
from plane_es... |
"""Functions for exactly computing the optimal Lagrange multipliers"""
from enum import Enum
import torch
import warnings
try:
from time import perf_counter
except ImportError:
from time import time as perf_counter
from src.derivatives import jacobian
class Timing_Events(Enum):
"""A set of Sub-Batch ev... |
"""Metadata mutation."""
from collections import namedtuple
from typing import Optional
import common_helpers
RESERVED_WORDS = [
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
... |
# -*- coding: utf-8 -*-
import base64
import chardet
import functools
import hashlib
import json
import os
import platform
import random
import requests
import rsa
import shutil
import subprocess
import sys
import threading
import time
import toml
from multiprocessing import freeze_support, Manager, Pool, Process
from... |
from typing import Optional
from typing import Union
import numpy as np
from scipy.sparse.coo import coo_matrix
from ._typing_utils import Float
from ._typing_utils import Matrix
from ._utils import coo_matrix_builder
def build_frame_cost_matrix(
dist_matrix: coo_matrix_builder,
*,
track_start_cost: Opt... |
# This work is based on original code developed and copyrighted by TNO 2020.
# Subsequent contributions are licensed to you by the developers of such code and are
# made available to the Project under one or several contributor license agreements.
#
# This work is licensed to you under the Apache License, Version 2... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Copyright 2017 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
from __future__ import annotations
import base64
import binascii
import copy
import hashlib
import json
import secrets
import string
import struct
from functools import reduce
from operator import concat
from typing import Any, Union
from urllib.parse import parse_qsl, urlencode as urlencode_
class FullDict(dict):
... |
"""Selector eventloop for Unix with signal handling."""
import errno
import fcntl
import os
import signal
import socket
import stat
import subprocess
import sys
from asyncio import base_subprocess
from asyncio import constants
from asyncio import events
from . import selector_events
from asyncio import tasks
from as... |
from django.db import models
from django.utils.timezone import now
import datetime
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from esmond.util import datetime_to_unixtime, remove_metachars, max_datetime, atencode
class DeviceTag(models.Model):
"""... |
#!/usr/bin/env python3
import os
import subprocess
import re
import shutil
import sys
import urllib.request
import zipfile
###############################
### Setup of CG simulations ###
###############################
def get_py_paths(protocol_path):
"""
Establish python3 and dssp paths used as input for CG... |
import json
import logging
import os
import pytest
from openff.evaluator.attributes import UNDEFINED
from openff.evaluator.datasets import PhysicalPropertyDataSet
from openff.evaluator.properties import Density
from openff.toolkit.typing.engines.smirnoff import ForceField as OFFForceField
from nonbonded.library.facto... |
# -*- coding: utf-8 -*-
import logging
import pdfkit
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# from django.template import RequestContext
# from django.db import models
from django.db.models import Q
from django import forms
from django.forms import ModelForm
from e... |
"""
Use Blender to render a scene to one or more image files.
"""
# Copyright (c) 2021 <NAME>. All rights reserved.
import math
import pickle
import os
import json
import sys
from typing import Optional
import bpy
import bpy.types as btypes
# TODO: there is probably a better way to find the script directory at ru... |
import persistent
import BTrees.IOBTree
from dateutil import parser
import datetime
from stf.common.out import *
# Create one of these classes for each new model constructor you want to implement
class Model_Constructor(object):
"""
The First Model constructor. Each of this objects is unique. We are going to... |
#Code for training the BARZ network
import torch
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn as nn
import ResNetBARZ
import time
import os
#Train the BARZ network from scratch
def TrainBARZNetwork(percentBiasPixel... |
# -*- coding: utf-8 -*-
"""
mtslice
~~~~~~~
mtslice module contains all the actions w.r.t. the mean temperature slices.
"""
import numpy as np
import matplotlib.pyplot as plt
import xspline
import limetr
import utils
import copy
# utils
# ------------------------------------------------------------------... |
import time
import cv2
import datetime
import imutils
import json
import os
import numpy as np
import tensorflow as tf
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.25)
config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options)
sess = tf.Sessi... |
#MVC control层
#登陆注册相关业务,
# #python3自带hashlib 模块,直接导入
from py import dbutils
from py import utils
import json
#注册
def register(username_front, passwd_front):
#前台传参数
# json数据
data = {}
# 要返回的数据
code = 500 # 返回给调用者的值,默认是500 Number类型的
msg = '注册失败'
count = 0
regiser_sql_return_json_data =... |
'''
Venn diagram plotting routines.
Test module (meant to be used via py.test).
Copyright 2012, <NAME>.
http://kt.era.ee/
Licensed under MIT license.
'''
from numpy import array, pi, sqrt, arcsin
from matplotlib_venn._venn3 import *
from matplotlib_venn._math import *
def test_circle_intersection():
f = lambda x... |
import tensorflow as tf
import numpy as np
import tensorflow as tf
import numpy as np
import os
def xavier_init(size):
in_dim = size[0]
xavier_stddev = 1. / tf.sqrt(in_dim / 2.)
return tf.random_normal(shape=size, stddev=xavier_stddev)
class New_Start_Invariant_Mnist( object ):
def __init__(... |
'''
Question 2.2 Skeleton Code
Here you should implement and evaluate the Conditional Gaussian classifier.
'''
import data
import numpy as np
# Import pyplot - plt.imshow is useful!
import matplotlib.pyplot as plt
from datetime import datetime
def compute_mean_mles(train_data, train_labels):
'''
... |
# Copyright 2017 Pilosa Corp.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2... |
import sys
import os
import random
import re
sys.path += os.path.abspath(os.path.join(os.path.split(__file__)[0], "../../pylib")),
from simplerpcgen.lang_cpp import emit_rpc_source_cpp
from simplerpcgen.lang_python import emit_rpc_source_python
def error(msg, ctx):
from yapps import runtime
err = runtime.Synta... |
#!/usr/bin/env python
"""
.. module:: belt
:synopsis: The belt function.
.. moduleauthor:: <NAME>
"""
import math
import numbers
import numpy
import opensdraw.lcad_language.curveFunctions as curveFunctions
import opensdraw.lcad_language.geometry as geometry
import opensdraw.lcad_language.interpreter as interp
imp... |
import argparse
import copy
import datetime
import hashlib
import json
import os
import re
import uuid
DEBUG=True
def parse_filename_s3(the_file_name):
if DEBUG:
print(the_file_name)
p = re.compile('(S3_|S3B|S3A)_([A-Z|0-9|_]{11})_([A-Z|0-9|_]{15})_([A-Z|0-9|_]{15})_([A-Z|0-9|_]{15}).*')
ama = p.m... |
import re
import json
import logging
from abc import ABC, abstractmethod
from enum import auto, Enum
from wallabag.config import Options, Sections
import requests
from packaging import version
MINIMUM_API_VERSION = "2.1.1"
class ApiException(Exception):
error_text = None
error_description = None
def... |
# Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import logging
from typing import Iterable, Union
import discord
from discord.ext import commands, tasks
from discord.errors import HTTPException
from bot import constants
from bot.cogs.utils.checks import check_if_it_is_tortoise_guild
from bot.cogs.utils.embed_handler import success, warning, failure, authored, welc... |
"""
Generate integrated gradients for clean images and their adversarial twins and construct a dataset
"""
import argparse
import logging
import os
import sys
import time
import numpy as np
import shap
import torch
import torch.nn.functional as F
import torchvision.models as models
from scipy.special import softmax
f... |
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
class L2Norm(nn.Module):
def __init__(self,n_channels, scale):
super(L2Norm,self).__init__()
self.n_channels = n_channels
self.gamma = scale or None
self.eps = 1e-10
se... |
# code adapted from https://github.com/huggingface/notebooks/blob/master/examples/translation.ipynb
# # need special branch of sacrebleu for thai bleu
# !pip uninstall -q sacrebleu
# !pip install -q git+https://github.com/cstorm125/sacrebleu.git@add_thai_tokenizer
# # written with transformers 4.6.0
# export WANDB_PR... |
from enum import unique
from os import name
from flask import Flask, request, jsonify
from flask import json
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
import math
from flask_sqlalchemy.model import camel_to_snake_case
from marshmallow.fields import Method
from sqlalche... |
import datetime
import logging
import os
import shutil
import sqlite3
import tempfile
import pytest
from c4.backends.sharedSQLite import (DBManager,
SharedSqliteDBBackend)
from c4.system.backend import BackendInfo
log = logging.getLogger(__name__)
@pytest.fixture(scope="functi... |
#
# Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/
# Written by <NAME> <<EMAIL>>,
# <NAME> <<EMAIL>>
#
import argparse
from itertools import chain
import math
import time
import torch
import numpy as np
import matplotlib.pyplot as plt
from imageio import imwrite
from fast_transformers.builders imp... |
import math
import random
villages_to_fake = ["407|498", "415|498", "401|492", "410|490", "403|486", "402|491", "402|489", "409|473", "410|475",
"402|479", "405|490", "408|498", "411|499", "413|489", "401|495", "404|494", "402|485", "401|486",
"403|498", "404|499", "405|499", "4... |
import torch
from torch import nn, Tensor
from .layers import DropPath
class MLP(nn.Module):
def __init__(self, dim, hidden_dim, out_dim=None) -> None:
super().__init__()
out_dim = out_dim or dim
self.fc1 = nn.Linear(dim, hidden_dim)
self.act = nn.GELU()
self.fc2 = nn.Linea... |
import csv
import math
import os
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as rnd
from numpy.core.function_base import linspace
from tqdm import tqdm
titleHeaders = ['Simulate', 'Validate', 'ATE']
xAxisLabels = ['Frequency', 'Voltage', 'Time', 'Decibels (dB)'... |
# -*- coding: utf-8 -*-
import math
import os
import random
import time
import src.hyperka.et_funcs.utils as ut
from src.hyperka.ea_funcs.train_funcs import find_neighbours_multi
from src.hyperka.et_apps.util import generate_adjacent_graph
# 根据相应参数初始化模型
def get_model(folder, kge_model, args):
print("data folder:... |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
"""
"""
import math
import numpy as np
from addict import Dict
from constants import *
def getNParticles(params):
# get total particles
nparticles = 0
for species in params.species:
nparticles += species.quantity
return nparticles
def getPositions(distribution, quantity, ndimensions, innerB... |
"""
Utils for evaluation.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
# Error metrics
def compute_accel(joints):
"""
Computes acceleration of 3D joints.
Args:
joints (Nx25x3).
Returns:
... |
from __future__ import division
from __future__ import unicode_literals
import time
import numpy as np
import torch
import torch.nn as nn
import collections
from deepchem.utils.save import log
from deepchem.metrics import to_one_hot
from deepchem.metrics import from_one_hot
from deepchem.models.torchgraph... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import json
import os
import re
import logging
import shutil
from base64 import urlsafe_b64encode
import pytest
from .._env import E2E_FIXTURE_NAME, TESTING_PLUGIN, e2e_active, get_env_vars, E2E_PARENT_PYTHON, \... |
import copy
from logging import getLogger
from collections import deque
import os
import gym
import numpy as np
import cv2
from pfrl.wrappers import ContinuingTimeLimit, RandomizeAction, Monitor
from pfrl.wrappers.atari_wrappers import ScaledFloatFrame, LazyFrames
cv2.ocl.setUseOpenCL(False)
logger = getLogger(__nam... |
import os
from torch.utils.data import TensorDataset, DataLoader, Dataset, Sampler
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from tqdm import tqdm
import scanpy as sc
class Setting:
"""Para... |
import os
import sys
import imp
import numpy as np
import warnings
warnings.filterwarnings("ignore")
# Test for Torch
def torch(test_models, model_path, img_path):
results_o, results_d, op_sets = dict(), dict(), dict()
from PIL import Image
import torch
import torchvision.models as models
from tor... |
# --------------------------------------------------------
# Multi-Epitope-Ligand Cartography (MELC) phase-contrast image based segmentation pipeline
#
#
# Written by <NAME>
# --------------------------------------------------------.
import copy
import numpy as np
def get_diff(x):
""" Returns the edge represetnat... |
class BaseItem:
def __init_(self, name, item_id, page_url):
self.name = name
self.id = item_id
self.page_url = page_url
class ItemDrop:
def __init__(self, enabled, level, max_level, leagues, areas, text):
self.enabled = enabled
self.level = level
self.max_level ... |
import argparse
import os
import json
import shutil
import random
from itertools import islice
import sys
import torch
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
from ignite.contrib.handlers import ProgressBar
from ignite.engine import Engine, Events
from ignite.handl... |
# Copyright 2021 <NAME> and the PyHopper team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
import sys
import pygame as pg
import re
from enum import Enum
import copy
import numpy as np
class color(Enum):
RED = (255,0,0)
GREEN = (0,255,0)
BLUE =(0,0,255)
BLACK =(0,0,0)
WHITE =(255,255,255)
GRAY =(150,150,150)
def fill_gradient(surface, color, gradient, rect=None, vertical=True, forwa... |
from logging import getLogger
from pathlib import Path
import epimargin.plots as plt
import geopandas as gpd
import matplotlib as mpl
import numpy as np
import pandas as pd
import shapely
from epimargin.estimators import analytical_MPVS, linear_projection
from epimargin.etl.commons import download_data
from epimargin.... |
"""
portrait_divergence.py
---------------------
Adapted from "An information-theoretic, all-scales approach to comparing
networks" by <NAME> and <NAME>, 2018 arXiv:1804.03665 and [this
repository](https://github.com/bagrow/portrait-divergence)
author: <NAME>
email: brennanjamesklein at gmail dot com
submitted as par... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 7/20/20 12:31 PM
# @Author : anonymous
# @File : Mutation_diff.py
import random
import re
from math import pi
gate_set_cirq = ["cirq.H","cirq.X","cirq.Y","cirq.Z","cirq.rx","cirq.CNOT","cirq.SWAP"]
gate_set_qiskit = ["prog.h","prog.x","prog.y","prog.z","... |
# [setup]
import math
import os
import magnum as mn
import numpy as np
import habitat_sim
from habitat_sim.utils import viz_utils as vut
dir_path = os.path.dirname(os.path.realpath(__file__))
data_path = os.path.join(dir_path, "../../data")
output_path = os.path.join(dir_path, "VHACD_tutorial_output/")
if not os.pa... |
# -*- coding: utf-8 -*-
import time
from utils import letterbox_image,exp,minAreaLine,draw_lines,minAreaRectBox,draw_boxes,line_to_line,sqrt,rotate_bound,timer,is_in
from line_split import line_split
import numpy as np
import cv2
from PIL import Image
from skimage import measure
import json
# crnn
from crnn.crnn_torch... |
from starry import kepler, Map
from pylab import *#; ion()
from pandas import DataFrame
from lmfit import report_errors
from scipy import optimize as op
from time import time
import numpy as np
import exomast_api # pip install git+https://github.com/exowanderer/exoMAST_API
import spiderman as sp
import corner
import s... |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright © 2018, GoodData Corporation. All rights reserved.
import ipaddress
import itertools
import logging
from .exceptions import InvalidConfiguration
from .utils import Base, StrEnum
logger = logging.getLogger(__name__)
class Direction(StrEnum):
Ingress = 'ingress... |
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
""" Classes for uniform and attribute variables.
These classes are mainly containers, the only gl functionality is
the uploading of gl data to the GPU.
"""
from __future__ ... |
import logging
import homeassistant.util.dt as dt_util
from homeassistant.core import (
HomeAssistant,
callback,
)
from homeassistant.helpers.event import (
async_track_state_change,
async_track_point_in_time,
)
from homeassistant.helpers.dispatcher import (
async_dispatcher_conne... |
# Based on the 'util/collect_env.py' script from PyTorch.
# <https://github.com/pytorch/pytorch>
#
# From PyTorch:
#
# Copyright (c) 2016- Facebook, Inc (<NAME>)
# Copyright (c) 2014- Facebook, Inc (<NAME>)
# Copyright (c) 2011-2014 Idiap Research Institute (<NAME>)
# Copyright (c) 2012-20... |
# coding:utf-8
import os
import gym
import random
import numpy as np
import tensorflow as tf
from collections import deque
from skimage.color import rgb2gray
from skimage.transform import resize
from keras.models import Sequential
from keras.layers import Convolution2D, Flatten, Dense
ENV_NAME = 'Breakout-v0' # Envi... |
import requests
import json
from bs4 import BeautifulSoup
from test_object import TestSongObject, TestAlbumObject
from test_io import song_test, album_test
# Constants to test being used by main functions
constants = {
"song_title_ignore": ("[Credits]", "[Tracklist + Album Art]","[Tracklist + Album Cover]", "[Book... |
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
import skimage, os
import SimpleITK as sitk
from scipy import ndimage
import matplotlib.pyplot as plt
get_ipython().magic(u'matplotlib inline')
import os
import zarr
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VIS... |
import difflib
import gzip
import json
import logging
import os
import tarfile
from enum import Enum, auto
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Union, Dict, Type, List
from data_as_code._metadata import validate_metadata
from data_as_code._step import Step
__all__ = ['Re... |
import os
import sys
import shutil
def main(cfg, out_dir, tgt_pfx, data_key="base"):
import ast
import logging
import numpy as np
import torch
from argparse import Namespace
import sacrebleu
from dataclasses import dataclass
from fairseq import utils, options, tasks, checkpoint_u... |
print("Loading...")
import sys
import numpy as np
from numpy import genfromtxt
import tkinter as tk
from tkinter import filedialog
import os
import pandas as pd
import matplotlib.pyplot as plt
import scipy.signal as signal
from scipy import interpolate
from scipy.stats import mode
from ipfx import feature_extractor
fro... |
# -*- coding: utf-8 -*-
from qa4sm_reader.img import QA4SMImg
import os
import numpy as np
import pandas as pd
import unittest
from qa4sm_reader import globals
class TestQA4SMImgBasicIntercomp(unittest.TestCase):
def setUp(self) -> None:
self.testfile = '3-ERA5_LAND.swvl1_with_1-C3S.sm_with_2-SMOS.Soil_... |
from subprocess import (Popen, PIPE)
import os
import csv
import json
from .ts import (convert_datetime, date_index)
import pandas as pd
from sensible.loginit import logger
log = logger(__name__)
#Git Globals
GIT_COMMIT_FIELDS = ['id', 'author_name', 'author_email', 'date', 'message']
GIT_LOG_FORMAT = ['%H', '%an',... |
# %%
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import k as kB, u
from latexplot import latexplot
import matplotlib as mpl
from pathlib import Path
import json
import cmocean as cmo
pgf_with_latex = { # setup matplotlib
"pgf.texsystem": "pdflatex",
"font.family... |
""" Tests for `typing_json.typechecking.to_json_obj` """
# pylint: disable = line-too-long, invalid-name, missing-docstring
# standard imports
import json
import typing
from typing import Union, Optional, List, Tuple, Set, FrozenSet, Mapping, Dict, NamedTuple, Deque
from decimal import Decimal
from collections import ... |
import tensorflow as tf
import scipy
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W, stride):
return tf.nn.conv2d(x, W, stride... |
import collections
import random
import re
import brave
import networkx as nx
from IPython.display import display as jupyter_display
import matplotlib.pyplot as plt
import scipy.spatial.distance as ssd
import scipy.cluster.hierarchy as sch
DETOKENIZE_RULES = (
(r' ([.,!?;:»%)\]\'])( ?)', r'\1\2'),
(r'( ?)(... |
import os
import random
import shutil
import ssl
import time
from argparse import ArgumentParser
from keras.applications import ResNet50, VGG16, VGG19, InceptionV3, \
MobileNetV2, InceptionResNetV2, Xception, \
NASNetMobile, DenseNet201, NASNetLarge
from keras.optimizers import SGD, RMSprop, Adam
import numpy a... |
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras import initializers
from tensorflow.keras import activations
# Embedding有关的层如各种PositionEmbedding等
class Embedding(tf.keras.layers.Embedding):
"""为call添加一个参数,可以当做unbias Dense使用,
用在语言模型的输出计算上。"""
def call(self, inputs, mode... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.