text stringlengths 3.07k 22.1k |
|---|
import argparse
import os
import subprocess
from copy import deepcopy
from warnings import warn
from pybdv.metadata import get_data_path
from .dataset_metadata import read_dataset_metadata, write_dataset_metadata
from .project_metadata import get_datasets, read_project_metadata, project_exists, write_project_metadata... |
import itertools
import pytest
import stix2.base
import stix2generator
import stix2generator.exceptions
import stix2generator.test.utils
import stix2generator.utils
import stix2generator.generation.object_generator
import stix2generator.generation.stix_generator
@pytest.mark.parametrize(
"seed_type", [
"... |
import random
import time
import sys
from random import randint
from colorama import init, Fore, Back, Style
import config
import math
import time
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
# https://stackoverflow.com/questions/4109552/python-class-definition-syntax#:~:text=In... |
#!venv/Scripts/python
import os, random
from string import capwords
import sys, traceback
import logging
logging.basicConfig(filename='birdquiz.log',level=logging.DEBUG)
def allImages(picDir, acceptedExtensions = [".ppm", ".jpg", ".jpeg", ".png"]):
'''
Returns a list of all images in picDir with acceptedExte... |
from __future__ import print_function
import sys
import math
from optparse import OptionParser
from lmfit import Parameters, minimize
from NISTModels import Models, ReadNistData
def ndig(a, b):
"precision for NIST values"
return round(-math.log10((abs(abs(a)-abs(b)) +1.e-15)/ abs(b)))
ABAR = ' |------------... |
import sys
import datetime
from pathlib import Path
current_path = Path(__file__).absolute()
abs_path = str(current_path.parent.parent)
sys.path.append(abs_path)
from capture import Capture
from utils import *
def from_api_to_db_deputados_detalhes(data_list, url):
func = lambda datum: dict(
num_l... |
# Copyright 2020 Google LLC.
#
# 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.
#
#... |
import logging
import typing
import discord
from discord.ext import commands
import main
from other import db
from utils.ext.formatter import formatMessage
class Events(commands.Cog):
def __init__(self, bot: main.Plyoox):
self.bot = bot
async def checkGuilds(self):
await self.bot.wait_until... |
"""
Parser for font qualifiers in a font string.
Font qualifiers are supplied within a font string. The FontQualifiers class is able to parse the
font qualifiers to extract the information held within them.
Usage details:
fq = FontQualifiers(font_string, need_trailing_space_on_matrix=False)
- This is eq... |
#
# License: BSD
# https://raw.githubusercontent.com/splintered-reality/py_trees/devel/LICENSE
#
##############################################################################
# Description
##############################################################################
"""
Simple colour definitions and syntax highli... |
import ipaddress
import time
from typing import Any, Optional, Iterable, Union
from netexp.pktgen import Pktgen
from netexp.helpers import get_ssh_client, posix_shell, remote_command, \
run_console_commands, watch_command
class DpdkConfig:
"""Represent DPDK command-line options.
Attributes:
co... |
# Copyright (c) 2019 PaddlePaddle Authors. 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 app... |
#!/usr/bin/python3
# Copyright (C) 2019 The Android Open Source Project
#
# 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 ... |
import os
import copy
import shutil
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
try:
from tqdm import tqdm # long waits are not fun
except:
print('tqdm not installed')
tqdm = lambda x: x
def detection_assessment(results_input, annofile, candfile = None):
if len(results_inpu... |
#!/usr/bin/env python
"""
@package ion.agents.platform.rsn.simulator.oms_simulator_server
@file ion/agents/platform/rsn/simulator/oms_simulator_server.py
@author <NAME>
@brief OMS simulator XML/RPC server. Program intended to be run outside of pyon.
USAGE:
$ bin/python ion/agents/platform/rsn/simulator/oms... |
#-*- coding:utf8 -*-
from collections import defaultdict
from itertools import combinations
class HashTree:
def __init__(self, items, lenItem, level): #zi items-->[[one trans]]一条事务各个项,lenItem-->项集长度,level-->树的高度;
self.length = lenItem
self.items = items
# print "init_self.items:%s" % self... |
import sys
import os
import glob
import csv
import time
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import tensorflow as tf
from matplotlib import patches
from matplotlib.pyplot import figure
from datetime import timedelta, date
from sklearn.metrics im... |
from django.db import transaction
from django.http import HttpResponseRedirect
from django import forms
from django.utils.functional import cached_property
from formtools.wizard.views import NamedUrlSessionWizardView
from core.helpers import user_is_moderator
from organisations.models import Organisation
from election... |
"""
为Pre-train G模型提供参数users_embedding, items_embeddings, items_bias
"""
import datetime
import sys,os
import pickle as cPickle
import numpy as np
from BASE_Gen import Generative
from time import time
import multiprocessing
cores = multiprocessing.cpu_count()
EMB_DIM=5 #dimensional of latent factor
USER_NUM=943
ITEM_... |
# Copyright (c) 2017-2020 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed... |
#!/usr/bin/env python3
__author__ = '<NAME>'
import argparse
from functools import partial
import numpy as np
import pandas as pd
from agreement import normalize
from oracle import wer_scorer
def extract_df(df_wer: pd.DataFrame, method: str, error: str) -> pd.DataFrame:
df = df_wer.sort_values(method + '_wer'... |
"""Galaxy redshift module.
This module provides facilities to sample galaxy redshifts using a number of
models.
"""
import numpy as np
import scipy.integrate
import scipy.special
from astropy import units
from ..utils import broadcast_arguments, dependent_argument
__all__ = [
'redshifts_from_comoving_density',... |
import numpy as np
from numpy import sin, cos, tan, pi, arcsin, arctan
from functools import lru_cache
import torch
from torch import nn
from torch.nn.parameter import Parameter
# Calculate kernels of SphereCNN
@lru_cache(None)
def get_xy(delta_phi, delta_theta):
return np.array([
[
(-tan(delta... |
from collections import defaultdict
import numpy as np
import torch
import torch.nn.init as init
import torch.nn as nn
def mask_softmax(matrix, mask):
if mask is None:
result = torch.nn.functional.softmax(matrix, dim=-1)
else:
raise NotImplementedError
return result
def initial_parameter(n... |
# All code written by <NAME>
# Imports
import numpy as np
from os.path import expanduser
import sys
from numpy.lib.npyio import save
from filehandler import *
from ditherer import *
from imagehandler import *
import PyQt5
from PyQt5.QtCore import QRect, Qt
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (
... |
"""
"""
from __future__ import annotations
from logging import getLogger
from typing import Callable, Dict, List, Optional, Set, Tuple
from gaphor.abc import Service
from gaphor.core import event_handler
from gaphor.core.modeling.element import Element, Handler
from gaphor.core.modeling.event import (
Associatio... |
from __future__ import annotations
from abc import ABC, abstractmethod
import asyncio
from collections import deque
import json
import logging
import time
from typing import Any
from aiohttp import ContentTypeError
from aiohttp.client_exceptions import ClientConnectionError
from homeassistant.const import ATTR_ENTITY... |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
"""prosper_config.py
Unified config parsing and option picking against config objects
"""
from os import path, getenv
import configparser
from configparser import ExtendedInterpolation
import logging
import re
import anyconfig
import anytemplate
JINJA_PATTERN = re.compile(r'.*{{\S*}}.*')
def render_secrets(
... |
import io
import os
import pytest
import flask
from flask.helpers import get_debug_flag
from flask.helpers import get_env
class FakePath:
"""Fake object to represent a ``PathLike object``.
This represents a ``pathlib.Path`` object in python 3.
See: https://www.python.org/dev/peps/pep-0519/
"""
... |
from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet as wn
def penn_to_wn(tag):
""" Convert between a Penn Treebank tag to a simplified Wordnet tag """
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if tag.startswith('J'):
return 'a'
if tag.startswith('R'):
re... |
# coding=utf-8
# Copyright 2018 The Gin-Config Authors.
#
# 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 la... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from os.path import join, dirname
sys.path.insert(0, join(dirname(__file__), '..'))
sys.path.insert(0, join(dirname(__file__), '../../'))
import os
import random
import argparse
import numpy as np
from PIL import Image
from datetime import datetime
import torc... |
from argparse import Namespace
from logging import Logger
import os
import pickle
from pprint import pformat
from typing import Callable, List, Tuple
from collections import Counter
import numpy as np
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.svm import SVC, SVR
from tqdm ... |
#!/usr/bin/env python2
'''
A WebSocket to TCP socket proxy with support for "wss://" encryption.
Copyright 2011 <NAME>
Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3)
You can make a cert/key with openssl using:
openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem
as taken from http://docs.py... |
import asyncio
import json
import logging
from copy import deepcopy
from datetime import datetime
from time import sleep, time
from typing import Literal
import clashroyale
import discord
from crtoolsdb.crtoolsdb import Constants
from discord.ext import tasks
from redbot.core import commands
from redbot.c... |
"""
Contains routines to traverse the parsed code and build graphs
"""
import copy
import networkx
from .drawing import COLOURS
from .graphbuilder import GraphBuilder
class Vertex():
""" Class defining a single tensor node vertex """
def __init__(self, ID, qubitID, age, localAge, graph, operation=None):
... |
import os, numpy as np
from matplotlib import pyplot as plt
from skimage.transform import radon
from math import *
from config import PYMICRO_XRAY_DATA_DIR
class Element:
"""A class to represent a chemical element described by its name, symbol and density."""
def __init__(self, name, symbol, density):
... |
# coding: utf-8
# (C) Copyright IBM Corp. 2019, 2020.
#
# 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 la... |
# Author: <NAME>
# Last Edited: 12/30/2017
import huffman
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from pathlib import Path
from math import log2
from enco... |
from re import L
import numpy as np
import matplotlib.pyplot as plt
import cv2
from PIL import Image
import scipy.fftpack
from tqdm import tqdm
class ImageInfo:
def __init__(self, x, y) -> None:
self.x = x
self.y = y
class Data:
def __init__(self) -> None:
self.y = None
self.... |
"""Generate fake SNR images.
Intended to be run within Hydrogen.
Based somewhat on
https://mxnet.incubator.apache.org/tutorials/unsupervised_learning/gan.html
For installing CUDA/CuDNN this was a useful guide:
https://www.pyimagesearch.com/2016/07/04/how-to-install-cuda-toolkit-and-cudnn-for-deep-learning/
"""
impor... |
import re
import os
import subprocess
import pdb
import numpy as np
import numpy.linalg as la
from optparse import OptionParser
import time
import limix
from .read_utils import readBimFile
from .read_utils import readCovarianceMatrixFile
from .read_utils import readPhenoFile
from .read_utils import readCovariatesFile
f... |
import os
import sys
import inspect
import logging
# TODO investigate setting PATH in Azure so can remove this
CURRENTDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
PARENTDIR = os.path.dirname(CURRENTDIR)
sys.path.insert(0, CURRENTDIR)
sys.path.insert(0, PARENTDIR)
from models import... |
import pytest
import numpy as np
from numpy.testing import TestCase, assert_array_equal
import scipy.sparse as sps
from scipy.optimize._constraints import (
Bounds, LinearConstraint, NonlinearConstraint, PreparedConstraint,
new_bounds_to_old, old_bound_to_new, strict_bounds)
class TestStrictBounds(TestCase):
... |
#!/usr/bin/env python
from argparse import ArgumentParser
from os import path, makedirs, getpid
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import torch
from colorama import Fore
from tqdm import tqdm, trange
from thesis import plot
from thesis.data.musdb import MusDBSamples
from thesi... |
import zipfile
import os
import json
import time
import uuid
from .osu_parser import OsuFileParser
from .imd_parser import ImdFileParser
from .music_helper import change_music_speed_with_ffmpeg
def get_tmp_dir():
with open(os.path.join("upload_dir", "now_dir.txt"), "r") as f:
return f.read()
def create_... |
import sys
import os
import os.path
from lxml import etree
import collections
import pickle
def create_folder(filepath):
directory = os.path.dirname(filepath)
if not os.path.exists(directory):
os.makedirs(directory)
def check_entry_dict(event_tokens, d):
if event_tokens in d:
return " ".... |
# Copyright 2019 The dm_control Authors.
#
# 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 i... |
#!/usr/bin/env python3
#
# validator.py
"""
Validate values obtained from the ``YAML`` file and coerce into the appropriate return types.
"""
#
# Copyright © 2020 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (... |
from math import log2
from typing import Optional, Union, List
from musicxml.xmlelement.xmlelement import * # type: ignore
from musicxml.xsd.xsdsimpletype import XSDSimpleTypeNoteheadValue # type: ignore
from musictree.accidental import Accidental
from musictree.core import MusicTree
__all__ = ['Midi', 'MidiNote',... |
import re
try:
from . import data_type
from . import i18n
from . import connect_core
from . import log
from . import screens
from . import exceptions
from . import command
from . import _api_util
except ModuleNotFoundError:
import data_type
import i18n
import connect_core
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 14 15:24:45 2017
@author: niels
"""
import matplotlib.pyplot as plt
from nifty import *
import scipy.optimize as so
import sys
#name of directory that results are stored in:
directory = sys.argv[1]
#name of file containing data:
data_file = sys... |
from app.models.base import BaseModel
from datetime import datetime
import math
def generate_news_feed(news_feed):
if news_feed[7]:
return {
'id': news_feed[0],
'content_type': news_feed[1],
'content': news_feed[2],
'owner_id':... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2022 Valory AG
# Copyright 2018-2021 Fetch.AI Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... |
###############################################################################
# Copyright (c) 2018-2019, National Research Foundation (Square Kilometre Array)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the ... |
import sys
sys.path.append('../')
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import numpy as np
import cv2
import os
import glob
from models.vaegan_models import encoder, build_encoder, generator
# from Thesis.losses import kl_loss
from keras.optimizers import Adam
from keras.models ... |
#!/usr/bin/env python3
import argparse
import boto3
import subprocess as sp
import os
import sys
import botocore
import getpass
from datetime import datetime, timedelta, timezone
import time
import re
import functools
import json
import shutil
import threading
from lib.calibration import *
from lib.multiview_runner im... |
################################################################################
# main-multiprocessing.py / pabloKalman #
# <NAME> - CNNs for object detection in subterranean environments #
################################################################################
# p... |
# -*- coding: utf-8 -*-
u"""elegant lattice parser
:copyright: Copyright (c) 2015 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkresource
from pykern.pkcollections import PKDict
fro... |
import torch
import torch.nn as nn
from torch.nn import ReLU
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch.nn.modules.utils import _pair
from torch.autograd import Function
from torch.autograd import Variable
import numpy as np
from halp.utils.utils import void_cast_func, single_to... |
"""
An example how to use this is shown in an IPython notebook:
https://github.com/transientskp/notebooks/blob/master/transients.ipynb
"""
from sqlalchemy import func, insert, delete
from sqlalchemy.orm import aliased
from tkp.db.model import Assocxtrsource, Extractedsource, Runningcatalog,\
Image, Newsource, Varm... |
#!/usr/bin/python
# Copyright (c) 2017, 2020 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
""" File with class batch with resnet network """
import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers import xavier_initializer_conv2d as xavier
from batchflow import action, model, Batch # pylint: disable=no-name-in-module
def conv_block(input_tensor, kernel, filters, name, strides=(2, 2)):
... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import abc
import dataclasses
from collections import OrderedDict
from copy import deepcopy
from io import BytesIO
from typing import List, NamedTuple, Optional, Tuple
import caffe2.python.onnx.backend
import onnx
import to... |
# Copyright 2015 Red Hat, Inc.
#
# 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... |
import argparse, sys, re, tempfile, os
import xml.dom, xml.dom.minidom
import grope
from pe_tools.pe_parser import parse_pe, IMAGE_DIRECTORY_ENTRY_RESOURCE
from pe_tools.rsrc import parse_pe_resources, pe_resources_prepack, parse_prelink_resources, KnownResourceTypes
from pe_tools.version_info import parse_version_info... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from common.skia import global_constants
DEPS = [
'ct_swarming',
'file',
'depot_tools/gclient',
'gsutil',
'recipe_engine/path',
'recipe_engine/... |
import autodepgraph as adg
from autodepgraph.graph_v2 import AutoDepGraph_DAG
import autodepgraph.node as n
import networkx as nx
import os
############################################
# This file generates and saves predefined
# graphs used in the tests.
############################################
test_dir = os.pa... |
from django.forms import model_to_dict
from backstage.models import SmAdminMenu, IndexInfo, CarouselDisplay, ColumnListsInfo, ContactInfo
from blog.models import Article
from core.basic_functions import DictMerge
from core.fields import MultilingualField
def getAdminMenuList(request):
"""
:param request:
... |
import math
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import pytorch_lightning as pl
from transformers import pipeline
from torchvision import models
from fairseq.optim.adafactor import Adafactor
class PositionalEncoding(nn.Module):
def __init__(self, d_model,... |
from datetime import datetime, timedelta
import json
import re
from typing import Callable, Dict, Set
from jinja2.exceptions import TemplateSyntaxError
from jinja2.sandbox import SandboxedEnvironment
from jinja2 import meta
from app.db import DBSession
from lib import metastore
from logic import admin as admin_logic
... |
# encoding: utf-8
"""
announce/ip.py
Created by <NAME> on 2015-06-04.
Copyright (c) 2009-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
from exabgp.protocol.ip import NoNextHop
from exabgp.rib.change import Change
from exabgp.bgp.message import OUT
from exabgp.protocol.... |
from typing import Callable
import numpy
import judo
from judo.data_types import dtype
from judo.functions.random import random_state
from judo.judo_tensor import tensor
from judo.typing import Tensor
AVAILABLE_FUNCTIONS = {
"l2_norm",
"relativize",
"get_alive_indexes",
"calculate_virtual_reward",
... |
# ##############################################################################
# linalg.py
# =========
# Author : <NAME> [<EMAIL>]
# ##############################################################################
"""
Linear algebra routines.
"""
import numpy as np
import scipy.linalg as linalg
import imot_tools.uti... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os.path as osp
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
import numpy as np
import pickle
import torch
import sys
import imp
import importlib
imp.reload(sys)
importlib.reload(sys)
THIS_PATH = osp.dirname(__... |
import mnist_loader as ml
import network
import tkinter as tk
import tkinter.filedialog
import threading
from PIL import Image, ImageDraw
class PaintCanvas(tk.Canvas):
def __init__(self, master=None):
super().__init__(master, width=280, height=280, bg="white")
super().scale(super(), 0, 0, 10, 10)
super().bind('... |
# -*- coding: utf-8 -*-
"""
Created: May 12, 2020
Author: <NAME>
Edited: May 26, 2020
"""
import pandas as pd
import geopandas
import numpy as np
import requests
import xml.etree.ElementTree as ET
import geojson
import json
import time
from datetime import datetime
pd.set_option('display.expa... |
import argparse
import tkinter as tk
from random import randint
from copy import deepcopy
from sys import platform
FONT = "Sans"
BOLD = True
WINDOW_BACKGROUND_COLOR = "#FAF8EF"
TITLE_TEXT_COLOR = "#776E65"
TITLE_FONT_SIZE = 70
SCORE_BACKROUND_COLOR = "#BBADA0"
SCORE_TEXT_COLOR = "#F9F6F2"
SCORE_LABEL_FONT_SIZE = 1... |
# Copyright 2015 Palo Alto Networks, Inc
#
# 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... |
# -*- coding: utf-8 -*-
import math
import torch
import torch.nn as nn
from torch import Tensor
from joeynmt.attention import KeyValRetAtt
# pylint: disable=arguments-differ
class MultiHeadedAttention(nn.Module):
"""
Multi-Head Attention module from "Attention is All You Need"
Implementation modified fro... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 20 12:04:20 2018
@author: smrak
"""
import numpy as np
import h5py
from datetime import datetime
from pkrasi import pkrasi as pa
from pkrasi import plotting as asiplot
from pyGnss import gnssUtils as gu
from scipy.interpolate import griddata
from pymap3d import aer2geodet... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
Pytest test configuration file.
Example command to run these tests:
pytest cmake/Platform/Windows/Packaging/Tests... |
# transformer的一层分为两个部分, 第一部分是selfattention,第二个部分是feedforward
# 以下代码首先编写self attention
# self attention
import torch
import torch.nn as nn
import math
import numpy as np
import torch.nn.functional as F
import random
from math import sqrt
Norm_dict = {"layer" : nn.LayerNorm,
"batch" : nn.BatchNorm1d}
cl... |
import numpy as np
import scipy
from .spectral import logical_mass_matrix, diag_logical_mass_matrix, logical_differentiation_matrix
from .interpolate import lagrange_interpolate
precomputed_massmats = {}
def mass_matrix(e, d):
global precomputed_massmats
p = e.num_points[d]
if not (p in precomputed_mas... |
import datetime
import random
import time
import numpy as np
import torch
import torch.utils.data
import utils
from datasets import load_dataset, load_metric
from reprod_log import ReprodLogger
from torch import nn
from transformers import AdamW, BertTokenizer, DataCollatorWithPadding, get_scheduler
from transformers.... |
import xarray as xr
import pandas as pd
import numpy as np
import gzip
import datetime as dt
def mask_to_int(mask):
""" Convert object array of mask strings to integers"""
if len(mask.shape) == 0:
mask_int = np.asarray([], dtype=int)
else:
try:
# mask is a plain integer
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019-2020 European Commission (JRC);
# Licensed under the EUPL (the 'Licence');
# You may not use this work except in compliance with the Licence.
# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl
import functools as fnt
import logging... |
"""
Parameter Estimation tests #4.
Variant of #3 but with sodium conductance pars being optimized.
Requires Dopri integrator because more computational power is needed!
<NAME>, March 2005.
"""
from __future__ import print_function
# PyDSTool imports
from PyDSTool import *
from PyDSTool.Toolbox.ParamE... |
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rtyper.annlowlevel import llhelper
from rpython.rlib.objectmodel import specialize, always_inline
from rpython.rlib.unroll import unrolling_iterable
from rpython.rlib.debug import ll_assert
from pypy.interpreter.error import OperationError
from pypy.modu... |
import json
import logging
import struct
from datetime import datetime
import weakref
import tornado.web
from plumbum import local
from easypy.bunch import Bunch
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop
from tornado.options import options
... |
from .score import Score
class Level:
EASY = 'Easy'
NORMAL = 'Normal'
HARD = 'Hard'
EXPERT = 'Expert'
EXPERT_PLUS = 'Expert+'
@classmethod
def get_all(cl):
return [Level.EASY, Level.NORMAL, Level.HARD, Level.EXPERT, Level.EXPERT_PLUS]
class Song:
""" A Be... |
# Copyright 2012 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... |
"""
A database for rules.
"""
import abc
from collections import defaultdict
from typing import Dict, Iterable, Iterator, List, MutableMapping, Optional, Set, Tuple
import tabulate
from logzero import logger
from comb_spec_searcher.equiv_db import EquivalenceDB
from comb_spec_searcher.exception import SpecificationNo... |
""" Utilities for running sphinx tasks in-process
"""
import sys
import os
from os.path import join as pjoin, isdir, split as psplit, isfile
import shutil
from contextlib import contextmanager
from copy import copy
from tempfile import mkdtemp
import pickle
import warnings
from docutils import nodes
from docutils.pa... |
# Copyright 2009 Canonical Ltd.
# This file is part of lazr.restfulclient.
#
# lazr.restfulclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) ... |
'''
Resposta em Python
GCC218 - 2019/02
Atividade: Implementacao 1
Grupo:
<NAME>, 14A, 201720357
<NAME>, 10A, 201720368
<NAME>, 10A, 201720364
Data: 06/09/2019
'''
from collections import deque
class Grafo:
def __init__(self, n):
# Cria a lista de adjacencia
self.list... |
# Copyright 2021 Dice Finding Authors. 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 applicabl... |
'''chromaterm.default_config tests'''
import os
import chromaterm.default_config
def assert_matches(positives, negatives, rule, match_count=1):
'''Assert that all positives are matched while negatives are not.'''
def permutate_data(data):
output = []
for entry in data if isinstance(data, lis... |
from genericpath import exists
from sys import path
from typing import List, Tuple, Iterator, Set, Dict, Callable
import random
import io
import os
from pathlib import Path
import pathlib
import time
import base64
import json
import csv
import math
__BOS = "<BOS>"
__EOS = "<EOS>"
def _process_lines(lines: List[str]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.