arxiv_id stringlengths 0 16 | text stringlengths 10 1.65M |
|---|---|
import sys
from os.path import join, normpath, dirname
# import packages in trainer
sys.path.append(join(dirname(__file__), '..', 'trainer'))
from preprocessor import PreProcessor
import tensorflow as tf
import numpy as np
import pandas as pd
import news_classes
import pickle
import news_classes
from jsonrpclib.Simpl... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: image.py
# Author: Qian Ge <geqian1001@gmail.com>
import scipy.misc
import numpy as np
from PIL import Image
def resize_image_with_smallest_side(image, small_size):
"""
Resize single image array with smallest side = small_size and
keep the original asp... | |
# This file is part of GenMap and released under the MIT License, see LICENSE.
# Author: Takuya Kojima
import networkx as nx
import copy
ALU_node_exp = "ALU_{pos[0]}_{pos[1]}"
SE_node_exp = "SE_{id}_{name}_{pos[0]}_{pos[1]}"
CONST_node_exp = "CONST_{index}"
IN_PORT_node_exp = "IN_PORT_{index}"
OUT_PORT_node_exp = "... | |
from collections import deque
import random
import numpy as np
import sys
print("Init...")
class RingBuf:
def __init__(self, size):
# Pro-tip: when implementing a ring buffer, always allocate one extra element,
# this way, self.start == self.end always means the buffer is EMPTY, whereas
# ... | |
import networkx as nx
from network2tikz import plot
from graphNxUtils import nxWeightedGraphFromFile
from collections import deque
#https://networkx.github.io/documentation/stable/tutorial.html
#https://pypi.org/project/network2tikz/
g = nxWeightedGraphFromFile("./testCases/input007.txt")
#print(g.edges.data())
#re... | |
import numpy as np
from sklearn.datasets import load_diabetes
diabetes = load_diabetes()
columns_names = diabetes.feature_names
y = diabetes.target
X = diabetes.data
# Splitting features and target datasets into: train and test
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y... | |
''' Agents: stop/random/shortest/seq2seq '''
import json
import sys
import numpy as np
import random
from collections import namedtuple
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch.distributions as D
from utils import vocab_pad_idx, vocab_eos_id... | |
# Copyright 2021 Ibrahim Ayed, Emmanuel de Bézenac, Mickaël Chen, Jean-Yves Franceschi, Sylvain Lamprier, Patrick Gallinari
# 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.ap... | |
import numpy as np
from src.functions import sigmoid, softmax, relu
from src.estimators import mse, cross_entropy
from src.optimizers import adam_default, momentum_default
from src.progressive import Progressive
from random import randint
from utilities import get_device_data, scale_output_0_1, get_accuracy
import pand... | |
from transformers import Trainer
from transformers.trainer_callback import TrainerState
import datasets
import os
import torch
from torch.utils.data import RandomSampler, Sampler, Dataset, DataLoader
from typing import Iterator, Optional, Sequence, List, TypeVar, Generic, Sized
import numpy as np
import math
f... | |
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import time
import serial
import threading
sample_amount = 2000
time_buffer = [0 for x in range(sample_amount)]
data_buffer = [0 for x in range(sample_amount)]
trigger_buffer = [0 for x in range(sample_amount)]
full_samples =... | |
import tempfile
import unittest
from pathlib import Path
import torch
import numpy as np
import SimpleITK as sitk
from ..utils import TorchioTestCase
from torchio.data import io
class TestIO(TorchioTestCase):
"""Tests for `io` module."""
def setUp(self):
super().setUp()
self.write_dicom()
... | |
"""
from __future__ import print_function
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torch.optim as optim
import os,argparse
import numpy as np
class EvoCNNModel(nn.Module):
def __init__(self):
super(Evo... | |
import numpy as np
from copy import deepcopy
from matchingmarkets.algorithms.basic import arbitraryMatch
"""
Meta Algorithms define the time of matching
They also dictate who gets passed into a matching algorithm
Inputs are a Market object
output is a dict of directed matches
"""
def meta_always(Market, ... | |
'''
testing hysteretic_q learning on the boutilier
'''
from matplotlib import pyplot as plt
import numpy as np
from environments.env_boutilier import Boutilier
from learning_algorithms.hysteretic_q_boutilier import HystereticAgentBoutilier
episodes = 1000
epochs = 300
exp_rate = 0.01
exp_rate_decay = 0.999
def run_... | |
__author__ = 'mangalbhaskar'
__version__ = '2.0'
"""
## Description:
# --------------------------------------------------------
# Utility functions
# - Uses 3rd paty lib `arrow` for timezone and timestamp handling
# - http://zetcode.com/python/arrow/
# --------------------------------------------------------
# Copy... | |
from __future__ import print_function, division
from sympy.core import S, Add, Mul, sympify, Symbol, Dummy
from sympy.core.compatibility import u
from sympy.core.exprtools import factor_terms
from sympy.core.function import (Function, Derivative, ArgumentIndexError,
AppliedUndef)
from sympy.core.numbers import pi
... | |
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~##
## ##
## This file forms part of the Underworld geophysics modelling application. ##
## ... | |
import threading
import unittest
from queue import Queue, Empty
from typing import Iterable
import numpy as np
from cltl.combot.infra.event import Event
from cltl.combot.infra.event.memory import SynchronousEventBus
from cltl.backend.api.microphone import AudioParameters
from cltl.backend.spi.audio import AudioSource... | |
import SocketServer
import threading
import numpy as np
import cv2
import sys
import serial
from keras.models import load_model
from self_driver_helper import SelfDriver
ultrasonic_data = None
# BaseRequestHandler is used to process incoming requests
class UltrasonicHandler(SocketServer.BaseRequestHandler):
dat... | |
import matplotlib.pyplot as plt
import numpy as np
import quantecon as qe
import seaborn as sb
from wald_class import *
c = 1.25
L0 = 25
L1 = 25
a0, b0 = 2.5, 2.0
a1, b1 = 2.0, 2.5
m = 25
f0 = np.clip(st.beta.pdf(np.linspace(0, 1, m), a=a0, b=b0), 1e-6, np.inf)
f0 = f0 / np.sum(f0)
f1 = np.clip(st.beta.pdf(np.linspa... | |
# A simple convolutional layer
# @Time: 12/5/21
# @Author: lnblanke
# @Email: fjh314.84@gmail.com
# @File: conv.py.py
from .layer import Layer
import numpy as np
class Conv(Layer):
def __init__(self, kernal_size: int, filters: int, padding: str, name = None):
super().__init__(name)
self.kernel_s... | |
import numpy as np
from pypropack import svdp
from scipy.sparse import csr_matrix
np.random.seed(0)
# Create a random matrix
A = np.random.random((10, 20))
# compute SVD via propack and lapack
u, sigma, v = svdp(csr_matrix(A), 3)
u1, sigma1, v1 = np.linalg.svd(A, full_matrices=False)
# print the results
np.set_pri... | |
'''
Orthogonal polynomials
'''
import numpy as np
def evaluate_orthonormal_polynomials(X, max_degree, measure, interval=(0, 1),derivative = 0):
r'''
Evaluate orthonormal polynomials in :math:`X`.
The endpoints of `interval` can be specified when `measure` is uniform or Chebyshev.
:param X: Locatio... | |
from CHECLabPy.core.io import HDF5Reader, HDF5Writer
from sstcam_sandbox import get_data
from os.path import dirname, abspath
import numpy as np
import pandas as pd
from IPython import embed
DIR = abspath(dirname(__file__))
def process(path, output):
with HDF5Reader(path) as reader:
df = reader.read("da... | |
"""Module for handling operations on both databases: media and clusters."""
import itertools
import logging
import multiprocessing
from pathlib import Path
import pandas as pd
from filecluster.configuration import Config, CLUSTER_DF_COLUMNS
from filecluster.filecluster_types import ClustersDataFrame
from filecluster.... | |
'''
This is based on efficientdet's evaluator.py https://github.com/rwightman/efficientdet-pytorch/blob/678bae1597eb083e05b033ee3eb585877282279a/effdet/evaluator.py
This altered version removes the required distributed code because Determined's custom reducer will handle all distributed training.
'''
import torch
imp... | |
#!python
# -*- coding: utf-8 -*-
"""
Plot elevation and azimuth or a star for a given time range, e.g. an observation night.
You may have to run "pip install astroplan astropy" to install required libraries.
"""
from astroplan import Observer
from astropy.time import Time
from astropy.coordinates import SkyCoord, Ea... | |
"""Fitting peaks data with theoretical curve: 'A_0 + A · (t - t_0) · exp(- k · (t - t_0))'.
Fitting peaks data with theoretical curve: 'A_0 + A · (t - t_0) · exp(- k · (t - t_0))' using
Levenberg–Marquardt (LM) algorithm
(see. https://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm).
Typical usage exa... | |
import numpy as np
from bokeh.plotting import figure, output_file, show
output_file("image.html", title="image.py example")
x = np.linspace(0, 10, 250)
y = np.linspace(0, 10, 250)
xx, yy = np.meshgrid(x, y)
d = np.sin(xx)*np.cos(yy)
p = figure(width=400, height=400)
p.x_range.range_padding = p.y_range.range_padding... | |
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau
import tensorflow.keras.backend as K
import numpy as np
import pickle
import json
from data.data import load_data
from modeling.model import build_model
from modeling.helpers import load_confi... | |
import pandas as pd
import numpy as np
print(pd.options.display.max_rows) #by default it is 60
pd.options.display.max_rows = 5
print(pd.options.display.max_rows) #Now it is 10
df = pd.read_csv('/media/nahid/New Volume/GitHub/Pandas/sample.csv')
print(df)
'''
company numEmps category ... state fundedDate r... | |
"""
Pre-training Bidirectional Encoder Representations from Transformers
=========================================================================================
This example shows how to pre-train a BERT model with Gluon NLP Toolkit.
@article{devlin2018bert,
title={BERT: Pre-training of Deep Bidirectional Transform... | |
import networkx as nx
import itertools
import math
import random
def empty_graph(num_nodes):
g = nx.Graph()
g.add_nodes_from(range(num_nodes))
return g
def complete_graph(num_nodes):
g = empty_graph(num_nodes)
edges = itertools.combinations(range(num_nodes), 2)
g.add_edges_from(edges)
re... | |
import sys
import numpy as np
from .__about__ import __copyright__, __version__
from .main import Mapper
def main(argv=None):
# Parse command line arguments.
parser = _get_parser()
args = parser.parse_args(argv)
import meshio
mapper = Mapper(verbose=args.verbose)
mesh_source = meshio.read... | |
import gym
import grid_game_env
import numpy as np
import os
import sys
sys.path.append('../../core/q_learning/')
import q_table_learning
env = gym.make("CliffWalking-v0") # 0 up, 1 right, 2 down, 3 left
env = grid_game_env.CliffWalkingWapper(env)
model_path = 'model/cliff_walking.csv'
'''
env = gym.make("FrozenLak... | |
from MeshProcess.ReadOBJ import *
from MeshProcess.ReadPLY import *
from MeshProcess.WriteOBJ import *
from MeshProcess.WriteOBJ_WithVT import *
from MeshProcess.WritePLY import *
import numpy as np
def MoveToCenterOBJ(filename):
[vertrices, faces, vt] = ReadOBJ(filename)
vxMax = np.max(vertrices.T[0])
vxMin = np... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 22 14:10:33 2017
@author: yanrpi
"""
# %%
import glob
import numpy as np
import nibabel as nib
import random
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from os import path
# from scipy.misc impo... | |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import pandas as pd
import numpy as np
class KineticTrajectory(object):
"""A trajectory is a list of x,y,z and time coordinates for a single
atom in a kinetic Monte Carlo simulation, which has the val... | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .lr_scheduler import WarmupMultiStepLR
# add by kevin.cao at 20.01.08
import torch.optim as optim
import numpy as np
def make_optimizer(cfg, model):
params = []
for key, value in model.named_parameters():
if not... | |
import numpy as np
from scipy.spatial.distance import pdist, squareform, cdist
import theano
import theano.tensor as T
from theano_utils import floatX, sharedX
def comm_func_eval(samples, ground_truth):
samples = np.copy(samples)
ground_truth = np.copy(ground_truth)
def ex():
f0 = np.mean(sample... | |
###########################################################################
# Created by: CASIA IVA
# Email: jliu@nlpr.ia.ac.cn
# Copyright (c) 2018
###########################################################################
import numpy as np
import torch
import math
from torch.nn import Module, Sequential, Conv2d, R... | |
# -*- coding: utf-8 -*-
import sys
import numpy as np
import smuthi.particles as part
import smuthi.layers as lay
import smuthi.initial_field as init
import smuthi.simulation as simul
import smuthi.postprocessing.far_field as farf
import smuthi.utility.automatic_parameter_selection as autoparam
import smuthi.fields as... | |
################################################################################
# Copyright (c) 2009-2020, National Research Foundation (SARAO)
#
# 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 License at
#
# ... | |
import numpy as np
class MockRandomState():
"""
Numpy RandomState is actually extremely slow, requiring about 300 microseconds
for any operation involving state. Therefore, when reproducibility is not
necessary, this class should be used to immensly improve efficiency.
Tests were run for Pl... | |
"""
Created on Thu Aug 22 19:18:53 2019
@authors: Dr. M. S. Ramkarthik and Dr. Pranay Barkataki
"""
import numpy as np
import math
from QuantumInformation import RecurNum
from QuantumInformation import LinearAlgebra as LA
from QuantumInformation import QuantumMechanics as QM
import scipy.linalg.lapack as la
import re... | |
# Copyright 2020 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... | |
import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as plt
import pandas as pd
F0 = np.zeros((4,3))
F0[0,2] = 10
F0[3,2] = 6
Fa = np.c_[F0, np.zeros((4,6-2))] #c_ acrescenta coluna
Fa = np.r_[Fa, [np.ones(np.shape(Fa)[1])]] #r_ acrescenta linha
print(np.shape(F0)[0])
print(F0, F0[:,1])
... | |
"""
Copyright StrangeAI Authors @2019
original forked from deepfakes repo
edit and promoted by StrangeAI authors
"""
from __future__ import print_function
import argparse
import os
import cv2
import numpy as np
import torch
import torch.utils.data
from torch import nn, optim
from torch.autograd i... | |
# required python version: 3.6+
import os
import sys
import src.load_data as load_data
from src import plot_data
from src import layer
from src.network import NeuralNetwork_Dumpable as NN
import src.network as network
import matplotlib.pyplot as plt
import numpy
import os
import pickle
# format of data
# disitstrain... | |
import os
import sys
import time
import logging
import pickle
import numpy as np
import matplotlib
if "DISPLAY" not in os.environ:
print("No DISPLAY found. Switching to noninteractive matplotlib backend...")
print("Old backend is: {}".format(matplotlib.get_backend()))
matplotlib.use('Agg')
print("New ba... | |
""" Convolution module: gathers functions that define a convolutional operator.
"""
# Authors: Hamza Cherkaoui <hamza.cherkaoui@inria.fr>
# License: BSD (3-clause)
import numpy as np
import numba
from scipy import linalg
from .atlas import get_indices_from_roi
@numba.jit((numba.float64[:, :], numba.float64[:, :], nu... | |
import datetime
import faulthandler
import unittest
import numpy as np
faulthandler.enable() # to debug seg faults and timeouts
import cf
from cf import Units
class DatetimeTest(unittest.TestCase):
def test_Datetime(self):
cf.dt(2003)
cf.dt(2003, 2)
cf.dt(2003, 2, 30, calendar="360_day... | |
import statsmodels.api as sm
import itertools
from dowhy.causal_estimators.regression_estimator import RegressionEstimator
class GeneralizedLinearModelEstimator(RegressionEstimator):
"""Compute effect of treatment using a generalized linear model such as logistic regression.
Implementation uses statsmodels.... | |
import numpy as np
__doc__ = """
https://math.stackexchange.com/questions/351913/probability-that-a-stick-randomly-broken-in-five-places-can-form-a-tetrahedron
Choose 5 locations on a stick to break it into 6 pieces. What is the probability that these 6 pieces can be edge-lengths of a
tetrahedron (3D symplex).
"""
... | |
import cfpq_data
import networkx as nx
from project import write_graph_to_dot
def test_graph_isomorphism(tmpdir):
n, m = 52, 48
edge_labels = ("a", "b")
file = tmpdir.mkdir("test_dir").join("two_cycles.dot")
graph = cfpq_data.labeled_two_cycles_graph(
n, m, edge_labels=edge_labels, verbose=Fa... | |
"""
Reader for the hashtable, in combination with the
:class:`SpatialRegion` objects from ``regions.py``.
Use the :class:`SpatialLoader` class to set up and
read from the hashtables.
Note that all large data is actually contained in the
region objects, and the loader class is really just
a convenience object.
"""
fr... | |
import tensorflow as tf
import numpy as np
import time
import os
import random
from datetime import datetime
from model import AudioWord2Vec
from utils import *
import operator
from tqdm import tqdm
class Solver(object):
def __init__(self, examples, labels, utters, batch_size, feat_dim, gram_num, memory_dim,
... | |
"""Module containing low-level functions to classify gridded
radar / lidar measurements.
"""
from collections import namedtuple
import numpy as np
import numpy.ma as ma
from cloudnetpy import utils
from cloudnetpy.categorize import droplet
from cloudnetpy.categorize import melting, insects, falling, freezing
def clas... | |
import collections
import logging
from time import sleep
import numpy as np
from tqdm import tqdm
from oscml.utils.util import smiles2mol, concat
def get_atoms_BFS(graph):
def bfs(visited, graph, node):
visited.append(node.GetIdx())
queue.append(node)
while queue:
s = queue.po... | |
from mysorts import *
from numpy import random
from pygame.locals import ( #for tracking specific keypresses
K_ESCAPE,
KEYDOWN,
)
from pygame import time
#START LOGIC
#print the menu
sortType, arrSize = printMenu()
#start pygame
pygame.init()
#set the popup screen up
screen = pygame.display.set_mode([SCR... | |
# ___________________________________________________________________________
#
# EGRET: Electrical Grid Research and Engineering Tools
# Copyright 2019 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain r... | |
#! /usr/bin/env python3
#
# Author: Martin Schreiber
# Email: schreiberx@gmail.com
# Date: 2017-06-18
#
import sys
import math
import mule_local.rexi.EFloat as ef
#
# Supported Functions to approximate
#
class Functions:
def phiNDirect(
self,
n: int,
z: float
):
"""
... | |
"""Sanity check the EEG data.
This script should run without giving any errors.
"""
# %%
# Imports
import mne
import numpy as np
import pandas as pd
from config import DATA_DIR_EXTERNAL, STREAMS
from utils import get_sourcedata
# %%
# Load data
for sub in range(1, 33):
for stream in STREAMS:
print(f"Che... | |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import argparse
import pandas as pd
import yaml
import os
params = {'axes.labelsize': 14,
'axes.titlesize': 16,
'xtick.labelsize': 12,
'ytick.labelsize': 12,
'legend.fontsize': 14}
plt.rcParams.update(para... | |
import argparse
import os
parser = argparse.ArgumentParser(description='Model Trainer')
parser.add_argument('--path', help='Path to data folder.', required=True)
parser.add_argument('--lite', help='Generate lite Model.', action='store_true')
args = parser.parse_args()
if args.path:
import cv2
import numpy as ... | |
"""
name: interpolation.py
Goal: resume all interpolation functions
author: HOUNSI Madouvi antoine-sebastien
date: 14/03/2022
"""
import sys
from os.path import dirname, join
import matplotlib.pyplot as plt
import numpy as np
from interpolation.polynom import Polynom
from interpolation.polynome import P... | |
import numpy as np
import torch
import torch.nn.functional as F
import torchvision
import PIL
import itertools
import datetime
import random
import skimage
from skimage import filters
def noise_permute(datapoint):
"""Permutes the pixels of an img and assigns the label (label, 'permuted').
The input should... | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Copied from https://github.com/facebookresearch/detectron2 and modified
import logging
import numpy as np
import cv2
import torch
Image = np.ndarray
Boxes = torch.Tensor
class MatrixVisualizer(object):
"""
Base visualizer for matrix dat... | |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class AdalineGD(object):
def __init__(self, eta=0.01, n_iter=50, random_state=1):
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
self._DataShuffled = False
self.cost_track = []
... | |
import pandas as pd
import numpy as np
import scipy.stats
from inferelator import utils
from inferelator.regression import bayes_stats
from inferelator.regression import base_regression
from inferelator.regression import mi
from inferelator.distributed.inferelator_mp import MPControl
# Default number of predictors to... | |
#Load dependencies
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from matplotlib import*
import matplotlib.pyplot as plt
from matplotlib.cm import register_cmap
from scipy import stats
from sklearn.decomposition import PCA
import seaborn
import os
import glob
def getPCAEigenPa... | |
# Copyright 2022 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, ... | |
import colorsys
import random
import matplotlib.colors as mplc
import numpy as np
from numpy.core.shape_base import block
from skimage import measure
from matplotlib.patches import Polygon, Rectangle
import matplotlib
import matplotlib.pyplot as plt
from typing import List, Dict, Tuple, Union
from enum import Enum
from... | |
import numpy as np
from scipy import *
from scipy.sparse import *
from itertools import izip
import operator
def sort_dic_by_value(dic, reverse=False):
return sorted(dic.iteritems(), key=operator.itemgetter(1), reverse=reverse)
# Maximum value of a dictionary
def dict_max(dic):
aux = dict(map(lambda item: ... | |
import os
import torch
import torch.nn as nn
import torchvision.transforms.functional as tvf
from torch.optim import Adam, lr_scheduler
from torch.utils.data import DataLoader
import gdown
from PIL import Image
import json
from .unet import Unet
from .dataset import NoisyDataset
from PIL import Image
import numpy as np... | |
import pathlib
import numpy as np
import pytest
from neatmesh.analyzer import Analyzer3D
from neatmesh.reader import assign_reader
h5py = pytest.importorskip("h5py")
def test_hex_one_cell():
this_dir = pathlib.Path(__file__).resolve().parent
mesh = assign_reader(this_dir / "meshes" / "one_hex_cell.med")
... | |
import dask.dataframe as ddf
import dask.multiprocessing
import numpy as np
#import os, psutil
types = {
'Email': object,
'Affiliation': object,
'Department': object,
'Institution': object,
'ZipCode': object,
'Location': object,
'Country': object,
'City': object,
'State': object,... | |
from typing import List, Tuple, Any
from six import int2byte
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
import gym
import sys
import copy
from collections import deque
import random
import pandas as pd
def construct_model(input_shape=(5,)) -> tf.keras.Model:
input... | |
import socket
from BD_2 import BancoDeDados
from datetime import datetime
from datetime import timedelta
import numpy as np
def dataHora():
'''
:return: Retorna a data e a hora do PC no momento
'''
data_e_hora_atuais = datetime.now()
return data_e_hora_atuais.strftime("%d/%m/%Y %H:%M:%... | |
r"""
.. _conditional:
Conditional Independence Testing
********************************
Conditional independence testing is similar to independence testing but introduces
the presence of a third conditioning variable. Consider random variables :math:`X`,
:math:`Y`, and :math:`Z` with distributions :math:`F_X`, :math:... | |
from abc import ABCMeta, abstractmethod
import numpy as np
from . import dataset
class ThreatModel(metaclass=ABCMeta):
@abstractmethod
def check(self, original, perturbed):
'''
Returns whether the perturbed image is a valid perturbation of the
original under the threat model.
... | |
#!/usr/bin/env python3
# Copyright 2020 Christian Henning, Maria Cervera
#
# 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 ... | |
#!/usr/bin/python
#
# XMLMessageVacuumAddExpenditureWorld.py
#
# Created on: 7 March, 2011
# Author: black
#
# Methods for the class that keeps track of the information
# specific to the commander. This is information that the
# commander sends to the planner to let the planner know what
# ... | |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
import seaborn as sns
from sklearn.cluster import DBSCAN
from sklearn.preprocessing import StandardScaler
from sklearn.manifold import TSNE
from sklearn.metrics import silhouette_score, calinski_harabaz_score
from sklearn... | |
"""Lambdata is a collection of Data Science helper functions"""
import pandas as pd
import numpy as np
print("lambdata has been successfully imported!") | |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import os
import sys
import math
sys.path.insert(0, '../libraries')
import pprint
import rospy
from copy import deepcopy
from baxter_interface import (RobotEnable, Gripper, CameraController, Limb)
from baxter_core_msgs.srv import (SolvePositionIK, Solv... | |
# from napari_segment_blobs_and_things_with_membranes import threshold, image_arithmetic
# add your tests here...
import numpy as np
def test_something():
from napari_segment_blobs_and_things_with_membranes import gaussian_blur, \
subtract_background,\
threshold_otsu,\
threshold_yen,\
... | |
"""
Welcome to CS375! This is the starter file for assignment 2 in which you will
train unsupervised networks. Since you should be familiar with tfutils by now
from assignment 1 the only thing that we provide is the config for the
dataprovider and the dataproviders themselves as you will be also training
and testing... | |
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, accuracy_score
import random
def generate_random_results(size):
return np.random.randint(2, size=size)
def get_baseline_performance(root_folder, test_file, target, no_trails = 5):
np... | |
#!/usr/bin/env python3
import math
import numpy as np
import argparse
import sys
import matplotlib.pyplot as plt
g_apply_scaling = False
g_apply_normalization = False
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.decomposi... | |
#!/usr/bin/env python3
import numpy as np
import sympy as sym
from sympy.physics.quantum.cg import CG as sym_cg
from sympy.physics.wigner import wigner_6j as sym_wigner_6j
# transition and drive operators, exact
def trans_op_exact(dim, L, M):
if L >= dim or abs(M) > L: return np.zeros((dim,dim))
L, M = sym.S(... | |
import pytest
from tempfile import NamedTemporaryFile
from mlflow.store.artifact.artifact_repository_registry import get_artifact_repository
from mlflow.store.artifact.sftp_artifact_repo import SFTPArtifactRepository
from mlflow.utils.file_utils import TempDir
import os
import mlflow
import posixpath
pytestmark = pyt... | |
import numpy as np
"""
For conv2D methods:
Weights shape must be in form of (o, i, k_h, k_w), where 'o' stands for number of outputs, 'i' number of inputs, 'k_h'
is kernel height and 'k_w' is kernel width
fMaps stands for Feature Maps, or input images, its shape must be in form of (i, h,... | |
# -*- coding: ascii -*-
"""
Evolves the sun and earth where the sun will lose mass every 220th step.
"""
from __future__ import print_function
import numpy
from amuse.community.hermite.interface import Hermite
# from amuse.community.sse.interface import SSE
from amuse import datamodel
from amuse.units import units
from... | |
# coding=utf-8 python3.6
# ================================================================
# Copyright (C) 2019 * Ltd. All rights reserved.
# license='MIT License'
# Author : haibingshuai
# Created date: 2019/10/29 18:05
# Description :
# ===============================================================... | |
import numpy as np
import os
import pandas as pd
import pytest
import tiledbvcf
# Directory containing this file
CONTAINING_DIR = os.path.abspath(os.path.dirname(__file__))
# Test inputs directory
TESTS_INPUT_DIR = os.path.abspath(
os.path.join(CONTAINING_DIR, "../../../libtiledbvcf/test/inputs")
)
def _check_d... | |
# Copyright (c) 2018 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 appli... | |
from sigpipes.sources import SynergyLP
from sigpipes.sigoperator import Print, Sample, FeatureExtractor, ChannelSelect, Fft, MVNormalization, \
RangeNormalization, FFtAsSignal
from sigpipes.plotting import Plot, FftPlot, GraphOpts
from sigpipes.sigoperator import CSVSaver, Hdf5
from glob import iglob
from pathlib i... | |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import sqlite3
from datetime import datetime
from matplotlib.dates import DateFormatter, HourLocator, MinuteLocator
fs = 8
conn = sqlite3.connect('astrodek.sqlite')
cur = conn.cursor()
sql_script = ('''SELECT time, demand, ev_demand, pv_generatio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.