arxiv_id stringlengths 0 16 | text stringlengths 10 1.65M |
|---|---|
# -*- coding: utf-8 -*-
from unittest import mock
import warnings
import pytest
import hypothesis as hyp
import hypothesis.strategies as hyp_st
import hypothesis.extra.numpy as hyp_np
import numpy as np
import numpy.testing as npt
import pandas as pd
import sympy as sp
from endaq.calc import shock
wn, fn, wi, fi,... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
visualization_features.py
Script to produce visualizations of the features used for the GAN discriminator
tests.
Author: Miguel Simão (miguel.simao@uc.pt)
"""
import numpy as np
from sklearn import preprocessing
from sklearn.decomposition import PCA
from sklearn.... | |
import spira
import numpy as np
from spira import param
from copy import copy, deepcopy
from spira.gdsii.elemental.port import PortAbstract
from spira.core.initializer import ElementalInitializer
class Term(PortAbstract):
"""
Terminals are horizontal ports that connect SRef instances
in the horizontal pl... | |
#%%
import pandas as pd
import networkx as nx
import numpy as np
import graspologic as gs
data_path = "networks-course/data/celegans/male_chem_A_self_undirected.csv"
meta_path = "networks-course/data/celegans/master_cells.csv"
cells_path = "networks-course/data/celegans/male_chem_self_cells.csv"
adj = pd.read_csv(data... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
### Example of use
###, L. Darme 02/07/2019
import matplotlib.pyplot as plt
import numpy as np
# Importing additional user-defined function
import UsefulFunctions as uf
import Amplitudes as am
import Production as br
import Detection as de
import LimitsList as lim
######... | |
import pickle
import numpy as np
import matplotlib.pyplot as plt
cumulative_rewards = pickle.load(open('cum_rewards_history-12.pkl', 'rb'))
epsilons = pickle.load(open('epsilon_history-12.pkl', 'rb'))
# Set general font size
plt.rcParams['font.size'] = '24'
ax = plt.subplot(211)
plt.title("Cumulative Rewards over E... | |
#!/usr/bin/env python
# coding: utf-8
# ## Thank you for visiting my Karnel !
# I have just started with this dataset that impiles House Sales in King County, USA. My Karnel will be sometime updated by learning from many excellent analysts.
#
# * I am not native in English, so very sorry to let you read poor one.
... | |
###########################################
# This file is based on the jupyter notebook
# https://github.com/udacity/deep-reinforcement-learning/blob/master/p1_navigation/Navigation.ipynb
# provided by udacity
###########################################
import numpy as np
from unityagents import UnityEnvironment
from ... | |
import theano.tensor as T
import numpy as np
__all__ = ['var']
def var(name, label=None, observed=False, const=False, vector=False, lower=None, upper=None):
if vector and not observed:
raise ValueError('Currently, only observed variables can be vectors')
if observed and const:
raise ValueErr... | |
import numpy as np
import numpy.testing as npt
import pytest
import torch
def test_distance():
import espaloma as esp
distribution = torch.distributions.normal.Normal(
loc=torch.zeros(5, 3), scale=torch.ones(5, 3)
)
x0 = distribution.sample()
x1 = distribution.sample()
npt.assert_al... | |
import os
import numpy as np
from PIL import Image
import torch
from torch.autograd import Variable
import rospy
from affordance_gym.simulation_interface import SimulationInterface
from affordance_gym.perception_policy import Predictor, end_effector_pose
from affordance_gym.utils import parse_policy_arguments, parse_m... | |
# -*- coding: utf-8 -*-
from __future__ import print_function
from pyqtgraph.metaarray import MetaArray as MA
from numpy import ndarray, loadtxt
from .FileType import FileType
from six.moves import range
#class MetaArray(FileType):
#@staticmethod
#def write(self, dirHandle, fileName, **args):
#self.da... | |
import re
import pandas as pd
import numpy as np
import scipy as sp
from scipy.spatial.distance import pdist
import sys
import warnings
import sklearn
import importlib
if (sys.version_info < (3, 0)):
warnings.warn("As of version 0.29.0 shapLundberg only supports Python 3 (not 2)!")
import_errors = {}
def assert_... | |
def from_sparse_to_file(filename, array, deli1=" ", deli2=":", ytarget=None):
from scipy.sparse import csr_matrix
import numpy as np
zsparse = csr_matrix(array)
indptr = zsparse.indptr
indices = zsparse.indices
data = zsparse.data
print(" data lenth %d" % (len(data)))
print(" indices l... | |
# -*- coding: utf-8 -*-
from ninolearn.IO.read_post import data_reader
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import pearsonr
from ninolearn.private import plotdir
from os.path import join
plt.close("all")
reader = data_reader(startdate='1980-02')
nino34 = reader.read_csv('nino3.4S')
m... | |
import os
import math
import pygame
import numpy as np
import matplotlib.pyplot as plt
from gym_scarecrow.params import *
def quinary_to_int(obs):
value = 0
quin = [5**i for i in reversed(range(len(obs)))]
for i, ob in enumerate(obs):
value += ob * quin[i]
return value
def get_grid(positio... | |
# -*- coding: utf-8 -*-
""" dati_selezione.ipynb
Extraction of data from ISS weekly covid-19 reports
https://www.epicentro.iss.it/coronavirus/aggiornamenti
See example pdf:
https://www.epicentro.iss.it/coronavirus/bollettino/Bollettino-sorveglianza-integrata-COVID-19_12-gennaio-2022.pdf
Requirements:
Python 3.6+, Gh... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
import json
import numpy as np
import tensorflow as tf
from tensorflow.python.client import timeline
from keras import backend as K
from keras.datasets import cifar10
from keras.utils impo... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*
import sys
import rospy
import numpy as np
import os
import time
import matplotlib.pyplot as plt
import pandas as pd
from geometry_msgs.msg import PoseWithCovarianceStamped
from turtlesim.msg import Pose
from scipy.spatial import KDTree
from tf.transformations import euler_f... | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional
from parlai.core.params import ParlaiParser
from parlai.core.opt import Opt
import ... | |
from __future__ import print_function
import math
import pickle
import torch
import torch.nn as nn
import numpy as np
from collections import Counter, namedtuple
from .projection import NICETrans, LSTMNICE
from .dmv_viterbi_model import DMVDict
from torch.nn import Parameter
from .utils import log_sum_exp, \
... | |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 4 23:27:57 2019
@author: DavidFelipe
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import scipy
from scipy import ndimage
#%matplotlib inline
class Color:
def __init__(self, image):
self.subset_image = image
... | |
"""
This module is responsible to generate features from the data/logfiles
"""
import os
import math
import itertools
from pathlib import Path
import numpy as np
import pandas as pd
from scipy import stats
import setup_dataframes as sd
import synthesized_data
feature_names = [] # Set below
_verbose = True
hw = ... | |
import argparse
import csv
import os.path
import numpy as np
import torch
from sklearn.model_selection import train_test_split
from torchtext.data.utils import get_tokenizer
from torchtext.datasets import AG_NEWS
from torchtext.vocab import build_vocab_from_iterator
from MIA.Attack.ConfVector import ConfVector
from M... | |
# %load ../../src/feature/feature_utils.py
# %%writefile ../../src/features/feature_utils.py
"""
Author: Jim Clauwaert
Created in the scope of my PhD
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from statsmodels import robust
from math import ceil
def lowess(x, y, f=... | |
import numpy as np
from bayesfast import ModuleBase
from ._commander import _commander_f, _commander_j, _commander_fj
import os
__all__ = ['Commander']
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__))
foo = np.load(os.path.join(CURRENT_PATH, 'data/commander.npz'))
cl2x = foo['cl2x']
mu = foo['mu']
cov = foo... | |
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
import math
from scipy.interpolate import interp1d
def generateTraj(fit_type='square', coeff=0.5, num=3):
##Observations
x_obs = np.tile(np.linspace(1, 8, num=8, endpoint=True), (num,1))
y_obs = np.zeros((num, ... | |
import os
import albumentations as albu
#import cv2# not using due to issue in loading using cv2.imread for few images
import keras
from keras.preprocessing.image import load_img
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
def read_image(img_path):
#img = cv2.im... | |
import streamlit as st
from streamlit_ace import st_ace
import types
import sympy as sm
from sympy.abc import *
from pchem import solve
# See
# https://discuss.streamlit.io/t/take-code-input-from-user/6413/2?u=ryanpdwyer
# import random, string
# import importlib
# import os
# def import_code(code, name):
# ... | |
# allows to import own functions
import sys
import os
import re
root_project = re.findall(r'(^\S*TFM)', os.getcwd())[0]
sys.path.append(root_project)
from src.utils.help_func import get_model_data, results_estimator
from keras import backend as K
from kerastuner.tuners import RandomSearch
from kerastuner import Objec... | |
import pandas as pd
import numpy as np
import xlrd
df = pd.read_excel('Koln-Airport-Scripted.xlsx')
df2 = pd.read_excel('Cologne - Bonn Airport.xlsx')
df_merge_col = pd.merge(df, df2, on='Parking Address')
print(df_merge_col)
writer = pd.ExcelWriter('Koln-Airport-refactored.xlsx', engine= 'xlsxwriter')
df_merge_col.... | |
# %% Day 10
import numpy as np
def normalized(vector):
a, b = sorted(np.abs(vector))
if a == b == 0:
return tuple(vector)
if a == 0:
return tuple(vector // b)
while a := a % b:
a, b = b, a
return tuple(vector // b)
with open("day_10.input", "r") as input_data:
aster... | |
import logging
from os.path import join
import numpy as np
import pandas as pd
import xgboost as xgb
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
logger = logging.getLogger(__name__)
def infer_missing(df, target_column, inference_type, figures_dir, verbose=False):
""... | |
import numpy as np
import math
import time
import threading
import matplotlib.pyplot as plt
import vlc
import datetime
import xlsxwriter
import ems_constants
# current best settings: 155 ms. 10 intensity. bpm 110. never double up strokes direct. You can triple stroke indirect tho.
def play_rhythm(ems_serial, contact_... | |
"""
File: examples/expander/derivative_expander.py
Author: Keith Tauscher
Date: 1 Jul 2020
Description: Example of how to create and use a DerivativeExpander object,
which performs a finite difference calculation on its inputs.
"""
from __future__ import division
import os
import numpy as np
import numpy.... | |
import networkx.algorithms.tree.tests.test_operations
import pytest
from graphscope.nx.utils.compat import import_as_graphscope_nx
import_as_graphscope_nx(networkx.algorithms.tree.tests.test_operations,
decorators=pytest.mark.usefixtures("graphscope_session")) | |
import numpy as np
import os
import random
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from tensorflow import keras
from keras.utils import to_categorical
from keras_preprocessing.image import ImageDataGenerator
from PIL import Image
import glob
best_model = keras.models.load_model('/content/... | |
import numpy as np
def roll_zeropad(a, shift, axis=None):
"""
Roll array elements along a given axis.
Elements off the end of the array are treated as zeros.
Parameters
----------
a : array_like
Input array.
shift : int
The number of places by which elements are shifted.
... | |
from utils.decorators import timer, debug
from utils.task import Task
import numpy as np
from copy import deepcopy
import bisect
CONVERT_TABLE = {
"A": 2,
"B": 3,
"C": 4,
"D": 5
}
COST_TABLE = {
"A": 1,
"B": 10,
"C": 100,
"D": 1000
}
class Amphipod:
def __init__(self, kind: str,... | |
# -*- coding: utf-8 -*-
"""SVD ROUTINES.
This module contains methods for thresholding singular values.
:Author: Samuel Farrens <samuel.farrens@cea.fr>
"""
import numpy as np
from scipy.linalg import svd
from scipy.sparse.linalg import svds
from modopt.base.transform import matrix2cube
from modopt.interface.error... | |
import numpy as np
import env
import os
from tensorflow.keras.utils import Sequence
from core.helpers.video import get_video_data_from_file
from typing import List, Tuple
class BatchGenerator(Sequence):
__video_mean = np.array([env.MEAN_R, env.MEAN_G, env.MEAN_B])
__video_std = np.array([env.STD_R, env.STD_G... | |
# -*- coding: utf-8 -*-
"""CICID1.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1q-T0VLplhSabpHZXApgXDZsoW7aG3Hnw
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.... | |
# -*- coding: utf-8 -*-
## @package npr_sfs.methods.lumo
#
# Lumo [Johnston et al. 2002].
# @author tody
# @date 2015/07/29
"""Usage: lumo.py [<input>] [-h] [-o] [-q]
<input> Input image.
-h --help Show this help.
-o --output Save output files. [default: False]
-q --quiet No GUI. [de... | |
"""
This module contains an interface to the index files provided
by the GDAC. It is related to the :module:`argopandas.netcdf`
module in that there is an index subclass for each
:class:`argopandas.netcdf.NetCDFWrapper` subclass. Indexes
are ``pandas.DataFrame`` subclasses with a few accessors
that load data from each.... | |
#! /g/kreshuk/pape/Work/software/conda/miniconda3/envs/inferno/bin/python
import os
import json
import argparse
import h5py
from concurrent import futures
import numpy as np
from inferno.trainers.basic import Trainer
from inferno.utils.io_utils import yaml2dict
from skunkworks.inference import SimpleInferenceEngine
... | |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve
def gain_plot(y_actual, y_pred):
"""Returns a lift chart or gains plot against True Positive Rate vs False Positive Rate"""
f, ax = plt.subplots()
fpr, tpr, _ = roc_curve(y_act... | |
from pandas import DataFrame
import logging
import sys
from numpy import arange, histogram
import matplotlib.pyplot as plt
def read_vcf(fh):
'''
Read the VCF file obtained from any program included into Parliment2. Adds columns to the records if they are lacking.
Args:
fh (file): a VCF file.
Returns:
DF (pa... | |
"""
First N False Reducer
--------------------
This module is designed to reduce boolean-valued extracts e.g.
:mod:`panoptes_aggregation.extractors.all_tasks_empty_extractor`.
It returns true if and only if the first N extracts are `False`.
"""
from .reducer_wrapper import reducer_wrapper
import numpy as np
DEFAULTS =... | |
# -*- coding: utf-8 -*-
"""
Functionality for parcellating data
"""
import nibabel as nib
from nilearn.input_data import NiftiLabelsMasker
import numpy as np
from neuromaps.datasets import ALIAS, DENSITIES
from neuromaps.images import construct_shape_gii, load_gifti
from neuromaps.resampling import resample_images
fr... | |
import numpy as np
from sklearn import svm
from sklearn.metrics import f1_score, recall_score, precision_score
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from classify.preprocess import process_data
# Utility function to move the midpoint of... | |
#!/usr/bin/env python3
import importlib
import numpy as np
import math
import gc
import sys
import arkouda as ak
ak.verbose = False
if len(sys.argv) > 1:
ak.connect(server=sys.argv[1], port=sys.argv[2])
else:
ak.connect()
a = ak.arange(0, 10, 1)
b = np.linspace(10, 20, 10)
c = ak.array(b)
d = a + c
e = d.to... | |
import pickle
import numpy as np
from keras.preprocessing import sequence
from random import shuffle
def genData(filePathX, filePathY, maxlen = 200, minValue = 1, maxValue = 20000):
with open (filePathX, 'rb') as fp:
X_full = pickle.load(fp)
with open (filePathY, 'rb') as fp:
Y_full = pickle.l... | |
# --------------------------------------------------------
# Fine Refine Online Gushing
# Copyright (c) 2018 KAUST IVUL
# Licensed under The MIT License [see LICENSE for details]
# Written by Frost XU
# --------------------------------------------------------
"""The layer used during training to get proposal la... | |
# ABSOLUTE MAG -> APPARENT MAG WITH DISTANCE INFO.
#============================================================
import glob
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import ascii, fits
from astropy.table import Table, vstack
from astropy import units as u
def abs2app(M, Mer, d, der):
m = M +... | |
'''
lambdata - a collection of data science helper functions
'''
import numpy as np
import pandas as pd
# sample code
ONES = pd.DataFrame(np.ones(10))
ZEROS = pd.DataFrame(np.zeros(50)) | |
import numpy as np
import pandas as pd
class Metrics:
def __init__(self):
pass
@staticmethod
def pearson_correlation(y_true, y_pred, **kwargs):
# return(tf.linalg.trace(tfp.stats.correlation(y_pred, y_true))/3)
pd_series = pd.core.series.Series
# Change type if required
... | |
##############################################################################
#######################bibliotecas
##############################################################################
import pandas as pd
import numpy as np
# from eod_historical_data import (get_api_key,
# ... | |
"""Model fitting engines
.. autosummary::
:toctree:
bayespy
numpy
"""
from . import bayespy
from . import numpy | |
import numpy as np
import os
import pickle
from delfi.summarystats.BaseSummaryStats import BaseSummaryStats
from scipy.signal import resample
class ChannelOmniStats(BaseSummaryStats):
"""SummaryStats class for Channel model
Calculates summary statistics based on PC reconstruction coefficients
"""
de... | |
# coding: UTF-8
import numpy as np
import cPickle
import gzip
import random
import matplotlib.pyplot as plt
from copy import deepcopy
def relu(z):
return np.maximum(z, 0)
def relu_prime(z):
return np.heaviside(z, 0)
def sigmoid(z):
sigmoid_range = 34.538776394910684
z = np.clip(z, -sigmoid_range... | |
from __future__ import division
import numpy as np
from scipy import signal , linalg
from scipy.linalg import cho_factor, cho_solve
#from sep import extract
x, y = np.meshgrid(range(-1, 2), range(-1, 2), indexing="ij")
x, y = x.flatten(), y.flatten()
AT = np.vstack((x*x, y*y, x*y, x, y, np.ones_like(x)))
C = np.iden... | |
import time
import serial
import re
from matplotlib import pyplot as plt
import numpy as np
from matplotlib import style
import numpy
import openpyxl
from openpyxl import Workbook
# set up the serial line
ser = serial.Serial('COM8', 9600)
print(ser)
time.sleep(3)
CO2Final = []
TimeFinal = []
A0_A4V_Final = []
A1_A5... | |
import json
import pickle
import datetime
import pprint
import logging
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import ray
import genetic as ga
from copy import deepcopy
from ray import tune
from IPython.display import clear_output
from ray.tune.registry import register_env
from ray.tune.l... | |
import pathlib
from functools import partial
from itertools import tee
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from matplotlib.patches import Patch
from scipy.interpolate import interp1d
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
nex... | |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
from scipy import stats
import re
import os
def plot_approx(X_data, Y_data, input_function, plot_name='plot_name', plot_title='plot_title', x_label='x_label', y_label='y_label', Y_absolute_sigma = 0, scientific... | |
import numpy as np
import pandas as pd
import os
import csv
import sklearn
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from torch.utils.data import TensorDataset
from sklearn.metrics import f1_score
import random
from transformers import BertForSequenceClassification
from torch.utils.... | |
import time
import numpy as np
from pySerialTransfer import pySerialTransfer as txfer
# please make sure to pip install pySerialTransfer==1.2
# connection will not work with pySerialTransfer==2.0
# requirement: pip install pyserial (works with 3.4 and most likely newer but not much older versions)
# on teensy: in... | |
import numpy as np
import matplotlib.pyplot as plt
import torch
from torchvision.utils import make_grid
"""
Creates an object to sample and visualize the effect of the LSFs
by sampling from the conditional latent distributions.
"""
class vis_LatentSpace:
def __init__(self, model, mu, sd, latent_dim=10, latent_r... | |
#!/usr/bin/env nemesis
#
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://g... | |
# -*- coding: utf-8 -*-
import numpy as np
import array_comparison as ac
# Initial empty gamestate
_initial_gamestate = [
["-", "-", "-"],
["-", "-", "-"],
["-", "-", "-"]
]
class GameState:
def __init__(self, array=_initial_gamestate):
self.state = np.array(array)
try:
... | |
import os
import tempfile
import numpy as np
import pytest
import tensorboardX
from numpy.testing import assert_almost_equal
from tbparse import SummaryReader
from torch.utils.tensorboard import SummaryWriter
R = 5
N_STEPS = 100
@pytest.fixture
def prepare(testdir):
# Use torch for main tests, logs for tensorboa... | |
import numpy as np
import pandas as pd
def repeat_df(df: pd.DataFrame, times: int) -> pd.DataFrame:
"""Repeat a DataFrame vertically and cyclically.
Parameters:
df : DataFrame to be repeated.
times : The number of times to repeat ``df``.
Returns:
New DataFrame whose rows are the ... | |
"""track_to_track_association
The module tests two tracks for track association. It uses hypothesis testing to decide whether the two tracks are of
the same target. See report for more mathematical derivation.
"""
import numpy as np
from scipy.stats.distributions import chi2
def test_association_independent_tracks(t... | |
import numpy as np
import pandas as pd
from .. import categorizer as cat
from ..census_helpers import Census
# TODO DOCSTRINGS!!
class Starter:
"""
This is a recipe for getting the marginals and joint distributions to use
to pass to the synthesizer using simple categories - population, age,
race, and... | |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
data = np.loadtxt("onda.dat")
print(np.shape(data))
x = np.linspace(0.0, 1.0, np.shape(data)[1])
t = np.linspace(0.0, 6.0, np.shape(data)[0])
X, T = np.meshgrid(x,t)
fig = plt.figure(figsize=(13,5))
a... | |
#!/usr/bin/env python
from __future__ import print_function
import sys
sys.path.append('../')
import skimage as skimage
from skimage import transform, color, exposure
from skimage.viewer import ImageViewer
import random
from random import choice
import numpy as np
from collections import deque
import time
import csv
... | |
from microprediction import MicroWriter
import numpy as np
from pprint import pprint
import matplotlib.pyplot as plt
import random
import time
import warnings
warnings.filterwarnings('ignore')
from copulas.multivariate import GaussianMultivariate
import pandas as pd
# Grab the Github secret
import os
WRITE_KEY = o... | |
import sys
sys.path.append('../')
import utils
import numpy as np
import imageio
import os
class NucleiDataset(utils.Dataset):
"""Override:
load_image()
load_mask()
image_reference()
"""
def add_nuclei(self, root_dir, mode, split_ratio=0.9):
# Add classes
... | |
import unittest
import scanner.logSetup as logSetup
from bitstring import Bits
import numpy as np
import random
random.seed()
import scanner.hashFile as hashFile
import scanner.unitConverters as unitConverters
def b2i(binaryStringIn):
if len(binaryStringIn) != 64:
raise ValueError("Input strings must be 64 chars... | |
import numpy as np
from rltools.policy import Policy
STAY_ON_ONE_LEG, PUT_OTHER_DOWN, PUSH_OFF = 1, 2, 3
SPEED = 0.29 # Will fall forward on higher speed
SUPPORT_KNEE_ANGLE = +0.1
class MultiWalkerHeuristicPolicy(Policy):
def __init__(self, observation_space, action_space):
super(MultiWalkerHeuristicP... | |
#!/usr/bin/env python3
import sys
import subprocess
import re
import os
from distutils.version import LooseVersion, StrictVersion
if sys.version_info < (3, 0):
print("Error: Python 2 is not supported")
sys.exit(1)
print("Python:", sys.version_info)
try:
import numpy
except ImportError:
print("Error: Fai... | |
""" a modified version of CRNN torch repository https://github.com/bgshih/crnn/blob/master/tool/create_dataset.py """
import fire
import os
import lmdb
import cv2
import numpy as np
def checkImageIsValid(imageBin):
if imageBin is None:
return False
imageBuf = np.frombuffer(imageBin, dtype=np.uint8)
... | |
from ldaUtils import LdaEncoder,LdaEncoding,createLabeledCorpDict
import numpy as np
from gensim import models
import pickle
import heapq
#Andrew O'Harney 28/04/14
#This scripts produces nExemplars for each of the topic models
#(Ordered by probability of belonging to a topic)
nExemplars = 10
labeledDocuments = #
im... | |
r"""Markov chain Monte Carlo methods for inference.
"""
import hypothesis
import numpy as np
import torch
from hypothesis.engine import Procedure
from hypothesis.summary.mcmc import Chain
from torch.distributions.multivariate_normal import MultivariateNormal
from torch.distributions.normal import Normal
from torch.mu... | |
from pathlib import Path
import configparser
import cv2
import numpy as np
import tensorflow as tf
import threading
import video_utils
import sys
import streamlit as st
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
from object_detection.utils impor... | |
"""
Tests for numba.utils.
"""
from __future__ import print_function, absolute_import
from numba import utils
from numba import unittest_support as unittest
class C(object):
def __init__(self, value):
self.value = value
def __eq__(self, o):
return self.value == o.value
def __ne__(self,... | |
#! /usr/bin/env python
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import numpy as np
import array
import matplotlib.cm as cm
from mpl_toolkits.basemap import Basemap
import glob
import struct
import time
import sys
from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic
from scipy import interp... | |
from numpy import array
data = array([
[0.1, 1.0],
[0.2, 0.9],
[0.3, 0.8],
[0.4, 0.7],
[0.5, 0.6],
[0.6, 0.5],
[0.7, 0.4],
[0.8, 0.3],
[0.9, 0.2],
[1.0, 0.1]])
data = data.reshape(1, 10, 2)
print(data.shape) | |
import scipy.io
import os
import numpy as np
def load_data(name, n, data_dir="data/steady", non_dim=True, scale_q=1.0):
""" loads dataset n"""
data = scipy.io.loadmat(data_dir + "/%s_exp%d.mat" %(name, n))
Q = data['Q'][0][0]
K_truth = data['K'][0][0]
x_data = data['xexp'][:,0]
u_data ... | |
# 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... | |
"""Truncated exponential distribution."""
import numpy
from scipy import special
from ..baseclass import SimpleDistribution, ShiftScaleDistribution
class truncexpon(SimpleDistribution):
"""Truncated exponential distribution."""
def __init__(self, b):
super(truncexpon, self).__init__(dict(b=b))
... | |
'''
Module:
Clip the input data
'''
import numpy as np
def set_clip(args, data, which='fore', dmin=0, dmax=1):
# data value range
dlen = dmax - dmin
if which == 'fore':
pmin = dmin + (1.0 - float(args.cperc) / 100.0) * 0.5 * dlen
pmax = dmax - (1.0 - float(args.cperc) / 100.0... | |
#import libraries
import tensorflow as tf
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
#import dataset
diabets_... | |
import numpy as np
def _weighted_misclassification_error(values: np.ndarray, labels: np.ndarray) -> float:
"""
Evaluate performance under misclassification loss function
return sum of abs of labels, where sign(labels)!=sign(values).
values are in (1,-1), labels don't have to be.
Parameters
----... | |
"""
Linear least-square solvers
===========================
This module contains specialized solvers that works for the cases where the
value of the modelled properties depend linearly on all the model parameters.
This is definitely the most robust solvers among all the solvers, just it
requires the model to be linear... | |
import mock
import numpy as np
import matplotlib.pyplot as plt
from neupy import plots, layers, algorithms
from neupy.exceptions import InvalidConnection
from base import BaseTestCase
class SaliencyMapTestCase(BaseTestCase):
single_thread = True
def setUp(self):
super(SaliencyMapTestCase, self).set... | |
__author__ = "Angel Jimenez Escobar"
import sys
import networkx as nx
MaxNodes = pow(10, 5)
MaxColors = pow(10, 5)
colors = []
numbers_nodes = 0
G = nx.Graph()
def read_file(filename):
""" This is the method to read the file, and contain all the core of this program
I use a library call networkx
... | |
# -*- coding: utf-8 -*-
"""photometr.py - Simple Aperture photometry. Very old code, superceded by
astropy affiliated package `photutils.`
"""
# FIXME: kind of a stupid class dependence.
# Ideally a photometer object should take an image and a region object
# as arguments, where the region object is an instance of a... | |
"""Classes for handling telescope and eyepiece properties."""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams.update({'font.size': 14})
matplotlib.rcParams.update({'xtick.direction':'in'})
matplotlib.rcParams.update({'ytick.direction':'in'})
matplotlib.rcParams.update({'xtick.m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.