code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
from linlearn import BinaryClassifier, MultiClassifier
from linlearn.robust_means import Holland_catoni_estimator, gmom, alg2
import numpy as np
import gzip
import logging
import pickle
from datetime import datetime
import sys
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
from scipy.special ... | [
"logging.StreamHandler",
"gzip.open",
"numpy.log",
"numpy.array",
"numpy.einsum",
"os.cpu_count",
"logging.info",
"scipy.special.logsumexp",
"numpy.arange",
"linlearn.robust_means.Holland_catoni_estimator",
"os.path.exists",
"numpy.mean",
"itertools.chain.from_iterable",
"logging.FileHandl... | [((575, 635), 'logging.FileHandler', 'logging.FileHandler', ([], {'filename': '"""exp_archives/classif_exp.log"""'}), "(filename='exp_archives/classif_exp.log')\n", (594, 635), False, 'import logging\n'), ((653, 686), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (674, 686), ... |
import numpy
import matplotlib
import matplotlib.pyplot as plt
def plot_progress_kmeans(iteration, x_array, centroid_history, idx_history):
"""
A helper function that displays the progress of k-Means as it is running. It is intended for use
only with 2D data. It plots data points with colors assigned to e... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.xlabel",
"numpy.stack",
"matplotlib.colors.Normalize",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title"
] | [((1049, 1092), 'matplotlib.colors.Normalize', 'matplotlib.colors.Normalize', ([], {'vmin': '(0)', 'vmax': '(2)'}), '(vmin=0, vmax=2)\n', (1076, 1092), False, 'import matplotlib\n'), ((1447, 1522), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""major"""', 'axis': '"""both"""', 'linestyle': '"""... |
import numpy as np
from synthtext.config import load_cfg
class Curvature(object):
curve = lambda this, a: lambda x: a * x * x
differential = lambda this, a: lambda x: 2 * a * x
def __init__(self):
load_cfg(self)
def sample_curvature(self):
"""
Returns the functions for the ... | [
"synthtext.config.load_cfg",
"numpy.random.randn",
"numpy.random.rand"
] | [((222, 236), 'synthtext.config.load_cfg', 'load_cfg', (['self'], {}), '(self)\n', (230, 236), False, 'from synthtext.config import load_cfg\n'), ((396, 412), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (410, 412), True, 'import numpy as np\n'), ((473, 490), 'numpy.random.randn', 'np.random.randn', ([], {}... |
"""
Integrated gradient saliency maps
Created on 04/30/2020
@author: RH
"""
import saliency
import os
import sys
import cv2
import numpy as np
import tensorflow as tf
import data_input2 as data_input
# image to double
def im2double(im):
return cv2.normalize(im.astype('float'), None, 0.0, 1.0, cv2.NORM_MINMAX)
... | [
"InceptionV5.inceptionresnetv1",
"numpy.hstack",
"Scripts.Legacy.ResNet.resnet",
"InceptionV1.googlenet",
"tensorflow.nn.softmax",
"data_input2.DataSet",
"tensorflow.Graph",
"tensorflow.placeholder",
"tensorflow.Session",
"saliency.IntegratedGradients",
"InceptionV4.inceptionv4",
"tensorflow.C... | [((426, 472), 'cv2.applyColorMap', 'cv2.applyColorMap', (['heatmap_x', 'cv2.COLORMAP_JET'], {}), '(heatmap_x, cv2.COLORMAP_JET)\n', (443, 472), False, 'import cv2\n'), ((544, 580), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'name': '"""x"""'}), "(tf.float32, name='x')\n", (558, 580), True, 'import te... |
"""
python utilities for neuron
"""
# internal python imports
import os
# third party imports
import numpy as np
import matplotlib
# local (our) imports
def get_backend():
"""
Returns the currently used backend. Default is tensorflow unless the
NEURITE_BACKEND environment variable is set to 'pytorch'.
... | [
"numpy.unique",
"os.environ.get",
"matplotlib.colors.ListedColormap",
"numpy.exp",
"numpy.issubdtype",
"numpy.zeros",
"numpy.max",
"numpy.array"
] | [((786, 803), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (795, 803), True, 'import numpy as np\n'), ((826, 865), 'numpy.issubdtype', 'np.issubdtype', (['labels.dtype', 'np.integer'], {}), '(labels.dtype, np.integer)\n', (839, 865), True, 'import numpy as np\n'), ((2274, 2288), 'numpy.unique', 'np.uniq... |
'''
Author: <NAME> (@abodh_ltd)
MSEE, South Dakota State University
Last updated: August 26, 2020
'''
import numpy as np
import torch
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
import pdb
from datetime import date, datetime
import os
import time
from data_loading import loading, separate_... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"torch.nn.MSELoss",
"torch.cuda.is_available",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"model.Simple1DCNN",
"matplotlib.pyplot.yticks",
"numpy.random.seed",
"os.mkdir",
"utils.testing",
"torch.abs"... | [((185, 206), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (199, 206), False, 'import matplotlib\n'), ((672, 692), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (689, 692), False, 'import torch\n'), ((695, 712), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', ... |
import datetime
import h5py
import numpy as np
import os
import pytest
import random
import string
import time
import tempfile
import unittest
from labrad import types as T
from labrad import units as U
from twisted.internet import task
from datavault import backend, errors
def _unique_filename(suffix='.hdf5'):
... | [
"datavault.backend.CsvListData",
"numpy.int32",
"labrad.units.Complex",
"datavault.backend.Independent",
"datavault.backend.time_to_str",
"datavault.backend.IniData",
"datetime.datetime",
"twisted.internet.task.Clock",
"datavault.backend.labrad_urldecode",
"numpy.asarray",
"datavault.backend.lab... | [((329, 376), 'tempfile.mktemp', 'tempfile.mktemp', ([], {'prefix': '"""dvtest"""', 'suffix': 'suffix'}), "(prefix='dvtest', suffix=suffix)\n", (344, 376), False, 'import tempfile\n'), ((4492, 4577), 'datavault.backend.Independent', 'backend.Independent', ([], {'label': '"""FirstVariable"""', 'shape': '(1,)', 'datatype... |
# encoding=utf-8
import numpy as np
import pyqtgraph.opengl as gl
from pyqtgraph.Qt import QtCore, QtGui
class plot3d(object):
def __init__(self, title='null'):
"""
:param title:
"""
self.glview = gl.GLViewWidget()
coord = gl.GLAxisItem()
coord.setSize(1, 1, 1)
... | [
"pyqtgraph.Qt.QtGui.QVBoxLayout",
"pyqtgraph.opengl.GLLinePlotItem",
"numpy.ones",
"pyqtgraph.Qt.QtGui.QWidget",
"pyqtgraph.Qt.QtGui.QPushButton",
"numpy.random.rand",
"pyqtgraph.opengl.GLScatterPlotItem",
"pyqtgraph.opengl.GLViewWidget",
"numpy.max",
"numpy.array",
"pyqtgraph.Qt.QtGui.QApplicat... | [((2740, 2764), 'numpy.maximum', 'np.maximum', (['(1 - ratio)', '(0)'], {}), '(1 - ratio, 0)\n', (2750, 2764), True, 'import numpy as np\n'), ((2777, 2801), 'numpy.maximum', 'np.maximum', (['(ratio - 1)', '(0)'], {}), '(ratio - 1, 0)\n', (2787, 2801), True, 'import numpy as np\n'), ((2910, 2932), 'pyqtgraph.Qt.QtGui.QA... |
import pandas as pd
from tabulate import tabulate
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.interpolate import interp1d
#sns.set()
#sns.color_palette("mako")
df = pd.read_csv('bias_classifier.csv')
df = df.replace({'vanilla': 'Vanilla', 'end': 'EnD', 'rebias': 'ReBias', 'rubi... | [
"numpy.radians",
"tabulate.tabulate",
"numpy.mean",
"matplotlib.pyplot.savefig",
"pandas.read_csv",
"scipy.interpolate.interp1d",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.rc",
"matplotlib.pyplot.tight_layout",
"numpy.std",
"matplotlib.pyplot.subplot",
"numpy.arange",
"matplot... | [((207, 241), 'pandas.read_csv', 'pd.read_csv', (['"""bias_classifier.csv"""'], {}), "('bias_classifier.csv')\n", (218, 241), True, 'import pandas as pd\n'), ((1326, 1350), 'matplotlib.rc', 'rc', (['"""axes"""'], {'titlesize': '(18)'}), "('axes', titlesize=18)\n", (1328, 1350), False, 'from matplotlib import rc\n'), ((... |
import cloudpickle
import os
import numpy as np
import transformations as tf
import zlib, cPickle as pickle
#### For ZMQ ####
def send_zipped_pickle(socket, obj, flags=0, protocol=-1):
"""pickle an object, and zip the pickle before sending it"""
p = pickle.dumps(obj, protocol)
z = zlib.compress(p)
ret... | [
"numpy.abs",
"numpy.arccos",
"transformations.transformations.quaternion_from_matrix",
"cPickle.loads",
"os.path.join",
"zlib.compress",
"transformations.quaternion_matrix",
"transformations.quaternion_from_matrix",
"numpy.array",
"cPickle.dumps",
"transformations.transformations.quaternion_matr... | [((260, 287), 'cPickle.dumps', 'pickle.dumps', (['obj', 'protocol'], {}), '(obj, protocol)\n', (272, 287), True, 'import zlib, cPickle as pickle\n'), ((296, 312), 'zlib.compress', 'zlib.compress', (['p'], {}), '(p)\n', (309, 312), False, 'import zlib, cPickle as pickle\n'), ((482, 500), 'zlib.decompress', 'zlib.decompr... |
"""
These tests are the test fits that come with C mpfit
"""
import mpyfit
import unittest
import numpy
class LinearFunction( unittest.TestCase):
@staticmethod
def func(p, args):
x, y, error = args
return (y - p[0] - p[1]*x)/error
def test_fit(self):
x = numpy.array([-1.7237128E... | [
"numpy.ones",
"mpyfit.fit",
"numpy.asarray",
"numpy.exp",
"numpy.array",
"unittest.main"
] | [((6204, 6219), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6217, 6219), False, 'import unittest\n'), ((296, 435), 'numpy.array', 'numpy.array', (['[-1.7237128, 1.8712276, -0.96608055, -0.28394297, 1.3416969, 1.3757038, -\n 1.3703436, 0.042581975, -0.14970151, 0.82065094]'], {}), '([-1.7237128, 1.8712276, -... |
import os
import pandas as pd
import numpy as np
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
import matplotlib.pyplot as plt
import arviz as az
def make_dir_if_necessary(directory):
if not os.path.exists(directory):
os.makedirs(directory)
class ... | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.fill_between",
"numpy.argsort",
"numpy.array",
"numpy.arange",
"numpy.mean",
"os.path.exists",
"arviz.hpd",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.linspace",
"pandas.DataFrame",
"matplotlib.pyplot.ylim",
"sklearn.metrics.... | [((1263, 1280), 'numpy.array', 'np.array', (['history'], {}), '(history)\n', (1271, 1280), True, 'import numpy as np\n'), ((1298, 1325), 'numpy.mean', 'np.mean', (['history_np'], {'axis': '(0)'}), '(history_np, axis=0)\n', (1305, 1325), True, 'import numpy as np\n'), ((1342, 1368), 'numpy.std', 'np.std', (['history_np'... |
from keras.layers import Input, Dense, Flatten, Concatenate, Conv2D, Dropout
from keras.losses import mean_squared_error
from keras.models import Model, clone_model, load_model
from keras.optimizers import SGD, Adam, RMSprop
import numpy as np
class RandomAgent(object):
def __init__(self, color=1):
self.... | [
"numpy.mean",
"keras.layers.Conv2D",
"keras.layers.Flatten",
"keras.models.clone_model",
"numpy.random.choice",
"keras.layers.Concatenate",
"numpy.squeeze",
"numpy.stack",
"keras.layers.Input",
"numpy.random.randint",
"numpy.sum",
"keras.models.Model",
"numpy.array",
"numpy.std",
"keras.... | [((523, 546), 'numpy.random.choice', 'np.random.choice', (['moves'], {}), '(moves)\n', (539, 546), True, 'import numpy as np\n'), ((1270, 1284), 'keras.optimizers.RMSprop', 'RMSprop', ([], {'lr': 'lr'}), '(lr=lr)\n', (1277, 1284), False, 'from keras.optimizers import SGD, Adam, RMSprop\n'), ((1306, 1313), 'keras.models... |
from make_datasets_spark import DatasetConverter
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, DoubleType, StringType, IntegerType
from pyspark.sql.window import Window
from pyspark.sql.functions import dense_rank
i... | [
"logging.getLogger",
"pyspark.sql.functions.lit",
"json.loads",
"pyspark.sql.types.DoubleType",
"pyspark.sql.functions.unix_timestamp",
"pyspark.sql.types.IntegerType",
"pyspark.sql.functions.col",
"numpy.array",
"pyspark.sql.types.StringType"
] | [((402, 429), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (419, 429), False, 'import logging\n'), ((1314, 1352), 'pyspark.sql.functions.unix_timestamp', 'F.unix_timestamp', (['col_event_time', 'frmt'], {}), '(col_event_time, frmt)\n', (1330, 1352), True, 'import pyspark.sql.functions a... |
import numpy as np
def normalize_orders(image_data, trace, half_window=10, n=100):
"""
:param image_data: numpy.ndarray
:param trace: xwavecal.utils.trace_utils.Trace
:param half_window: int
the number of pixels above an below a diffraction order to try and normalize
:param... | [
"numpy.ones_like",
"numpy.isclose",
"numpy.sort",
"numpy.max",
"numpy.min",
"numpy.arange"
] | [((653, 680), 'numpy.max', 'np.max', (['image_data.shape[0]'], {}), '(image_data.shape[0])\n', (659, 680), True, 'import numpy as np\n'), ((704, 734), 'numpy.arange', 'np.arange', (['image_data.shape[1]'], {}), '(image_data.shape[1])\n', (713, 734), True, 'import numpy as np\n'), ((736, 766), 'numpy.arange', 'np.arange... |
import numpy as np
def init(A, b, c, rank, m):
A_b = A[:, (m-rank):]
A_n = A[:, :(m-rank)]
c_b = c[:, (m-rank):]
c_n = c[:, :(m-rank)]
A_b_inv = np.linalg.pinv(A_b)
b_ = A_b_inv @ b
tmp = c_b @ A_b_inv
ZC = tmp @ A_n - c_n
F = tmp @ b
# Get the Simplex Tabel
T1 = np.vsta... | [
"numpy.linalg.pinv",
"numpy.hstack",
"numpy.argmax",
"numpy.max",
"numpy.vstack",
"numpy.loadtxt",
"numpy.zeros_like"
] | [((168, 187), 'numpy.linalg.pinv', 'np.linalg.pinv', (['A_b'], {}), '(A_b)\n', (182, 187), True, 'import numpy as np\n'), ((313, 343), 'numpy.vstack', 'np.vstack', (['(A_b_inv @ A_n, ZC)'], {}), '((A_b_inv @ A_n, ZC))\n', (322, 343), True, 'import numpy as np\n'), ((398, 416), 'numpy.vstack', 'np.vstack', (['(b_, F)'],... |
# -*- coding: utf-8 -*-
#
# @author <NAME>
# @date 1 Feb 2019
import numpy as np
import pandas as pd
import itertools
from sklearn import svm
from data_handling import *
from data_stats import *
# Data paths
proj_dir = '/Users/nikhil/code/git_repos/compare-surf-tools/'
data_dir = proj_dir + 'data/'
demograph_file =... | [
"numpy.mean",
"pandas.merge",
"pandas.read_csv"
] | [((779, 817), 'pandas.read_csv', 'pd.read_csv', (['(data_dir + demograph_file)'], {}), '(data_dir + demograph_file)\n', (790, 817), True, 'import pandas as pd\n'), ((906, 949), 'pandas.read_csv', 'pd.read_csv', (['(data_dir + ants_file)'], {'header': '(2)'}), '(data_dir + ants_file, header=2)\n', (917, 949), True, 'imp... |
import cPickle
import numpy as np
import cv2
repository = []
for i in range(1, 6):
name = 'cifar/data_batch_'+str(i)
with open(name, 'rb') as fo:
data = cPickle.load(fo)
collect = data.get('data')
for j in collect:
red = []
green = []
blue = []
image = []
... | [
"numpy.array",
"cPickle.dump",
"cPickle.load"
] | [((709, 736), 'cPickle.dump', 'cPickle.dump', (['repository', 'f'], {}), '(repository, f)\n', (721, 736), False, 'import cPickle\n'), ((173, 189), 'cPickle.load', 'cPickle.load', (['fo'], {}), '(fo)\n', (185, 189), False, 'import cPickle\n'), ((644, 658), 'numpy.array', 'np.array', (['repo'], {}), '(repo)\n', (652, 658... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License
# Copyright (c) 2019 Ina (<NAME> & <NAME> - http://www.ina.fr/)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restrictio... | [
"cv2.dnn.blobFromImage",
"keras.preprocessing.image.img_to_array",
"pandas.DataFrame.from_records",
"cv2.warpAffine",
"cv2.dnn.readNetFromTensorflow",
"keras_vggface.vggface.VGGFace",
"dlib.rectangle",
"keras_vggface.utils.preprocess_input",
"dlib.correlation_tracker",
"dlib.shape_predictor",
"c... | [((1953, 1984), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'MP4V'"], {}), "(*'MP4V')\n", (1975, 1984), False, 'import dlib, cv2\n'), ((1995, 2063), 'cv2.VideoWriter', 'cv2.VideoWriter', (['file_name', 'fourcc', 'fps', '(frame_height, frame_width)'], {}), '(file_name, fourcc, fps, (frame_height, frame_width... |
import sys
import cPickle as cp
import random
import numpy as np
import networkx as nx
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--save_dir', help='Save directory.')
parser.add_argument('--max_n', type=int, help='Upper bound on graph size.')
parser.add_argument('--mi... | [
"cPickle.dump",
"networkx.disjoint_union",
"random.shuffle",
"argparse.ArgumentParser",
"networkx.connected_component_subgraphs",
"networkx.is_connected",
"numpy.random.randint",
"networkx.number_connected_components",
"networkx.erdos_renyi_graph"
] | [((135, 160), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (158, 160), False, 'import argparse\n'), ((792, 826), 'networkx.erdos_renyi_graph', 'nx.erdos_renyi_graph', ([], {'n': 'cur_n', 'p': 'p'}), '(n=cur_n, p=p)\n', (812, 826), True, 'import networkx as nx\n'), ((893, 914), 'random.shuffle... |
from autolens import decorator_util
import numpy as np
from autolens.data.array.util import mask_util
@decorator_util.jit()
def centres_from_shape_pixel_scales_and_origin(shape, pixel_scales, origin):
"""Determine the (y,x) arc-second central coordinates of an array from its shape, pixel-scales and origin.
... | [
"numpy.zeros",
"autolens.data.array.util.mask_util.total_sub_pixels_from_mask_and_sub_grid_size",
"autolens.data.array.util.mask_util.total_regular_pixels_from_mask",
"autolens.decorator_util.jit"
] | [((106, 126), 'autolens.decorator_util.jit', 'decorator_util.jit', ([], {}), '()\n', (124, 126), False, 'from autolens import decorator_util\n'), ((1270, 1290), 'autolens.decorator_util.jit', 'decorator_util.jit', ([], {}), '()\n', (1288, 1290), False, 'from autolens import decorator_util\n'), ((3165, 3185), 'autolens.... |
""" Helper module with methods for one-hot sequence encoding and generators to
to enable whole genome iteration """
import h5py
import numpy as np
import tensorflow as tf
from collections import defaultdict
class Sequence:
dic = {
"A": 0,
"T": 1,
"G": 2,
"C": 3
}
""" Meth... | [
"tensorflow.data.Dataset.from_tensors",
"tensorflow.io.parse_single_example",
"tensorflow.io.parse_tensor",
"h5py.File",
"numpy.array",
"numpy.zeros",
"tensorflow.io.FixedLenFeature",
"collections.defaultdict",
"tensorflow.concat",
"numpy.vstack",
"numpy.concatenate"
] | [((3844, 3857), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (3855, 3857), False, 'from collections import defaultdict\n'), ((3891, 3927), 'tensorflow.io.FixedLenFeature', 'tf.io.FixedLenFeature', (['[]', 'tf.string'], {}), '([], tf.string)\n', (3912, 3927), True, 'import tensorflow as tf\n'), ((3963, 39... |
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
# Imputation of missing values for numerical variables
# by the mode (the value that appears most often in a set of data values).
class ImputerNumericalVariable(BaseEstimator, TransformerMixin):
def __init__(self, var... | [
"numpy.log",
"pandas.concat"
] | [((3572, 3597), 'pandas.concat', 'pd.concat', (['[X, y]'], {'axis': '(1)'}), '([X, y], axis=1)\n', (3581, 3597), True, 'import pandas as pd\n'), ((1605, 1624), 'numpy.log', 'np.log', (['X[variable]'], {}), '(X[variable])\n', (1611, 1624), True, 'import numpy as np\n')] |
import tensorflow as tf
# Taken from https://www.tensorflow.org/guide/eager
# Eager execution works nicely with NumPy. NumPy operations accept tf.Tensor arguments.
# TensorFlow math operations convert Python objects and NumPy arrays to tf.Tensor objects.
# The tf.Tensor.numpy method returns the object's value as a Nu... | [
"numpy.multiply",
"tensorflow.add",
"tensorflow.constant",
"tensorflow.enable_eager_execution"
] | [((333, 360), 'tensorflow.enable_eager_execution', 'tf.enable_eager_execution', ([], {}), '()\n', (358, 360), True, 'import tensorflow as tf\n'), ((365, 394), 'tensorflow.constant', 'tf.constant', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (376, 394), True, 'import tensorflow as tf\n'), ((442, 454), 'tensorflo... |
import logging
import numpy
from PIL import Image
from dirs import dest
log = logging.getLogger()
def save_builtin(img, path):
# having blender save was turning the image back to black!
path.parent.mkdir(parents=True, exist_ok=True)
img.filepath = str(path).replace('.png', '-builtinsave.png')
img.fi... | [
"logging.getLogger",
"numpy.array"
] | [((79, 98), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (96, 98), False, 'import logging\n'), ((555, 578), 'numpy.array', 'numpy.array', (['img.pixels'], {}), '(img.pixels)\n', (566, 578), False, 'import numpy\n')] |
import numpy as np
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
from matplotlib import dates as md
from sklearn.linear_model import LinearRegression
from sklearn.svm import SVR
from sklearn.preprocessing import normalize, scale
import sklearn.metrics as metrics
import pickle
import stat_... | [
"configparser.ConfigParser",
"matplotlib.pyplot.ylabel",
"numpy.hstack",
"numpy.column_stack",
"numpy.nanmean",
"pytz.timezone",
"matplotlib.dates.epoch2num",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"os.path.isdir",
"os.mkdir",
"subprocess.call",
"n... | [((37, 58), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (51, 58), False, 'import matplotlib\n'), ((2059, 2069), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (2067, 2069), True, 'from matplotlib import pyplot as plt\n'), ((917, 944), 'configparser.ConfigParser', 'configparser.ConfigP... |
# Copyright (c) 2018 Spotify AB
#
# 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, s... | [
"numpy.random.normal",
"numpy.dot",
"random.gauss",
"annoy.AnnoyIndex"
] | [((695, 710), 'numpy.dot', 'numpy.dot', (['a', 'b'], {}), '(a, b)\n', (704, 710), False, 'import numpy\n'), ((934, 954), 'annoy.AnnoyIndex', 'AnnoyIndex', (['f', '"""dot"""'], {}), "(f, 'dot')\n", (944, 954), False, 'from annoy import AnnoyIndex\n'), ((1333, 1353), 'annoy.AnnoyIndex', 'AnnoyIndex', (['f', '"""dot"""'],... |
import numpy as np
arr_1 = [2, 3, 5, 7, 11]
arr_2 = [13, 17, 19, 23, 29]
arr_3 = np.array([arr_1, arr_2])
print(arr_3)
| [
"numpy.array"
] | [((83, 107), 'numpy.array', 'np.array', (['[arr_1, arr_2]'], {}), '([arr_1, arr_2])\n', (91, 107), True, 'import numpy as np\n')] |
import chainer
import chainer.functions as F
import numpy as np
import argparse
from chainer import cuda, serializers
from pathlib import Path
from model import Generator, Discriminator, VGG, SAGenerator, SAGeneratorWithGuide
from utils import set_optimizer
from dataset import DataLoader, RefineDataset
from evaluation... | [
"chainer.functions.mean_squared_error",
"chainer.functions.relu",
"dataset.RefineDataset",
"argparse.ArgumentParser",
"model.Discriminator",
"chainer.cuda.get_device",
"chainer.functions.concat",
"utils.set_optimizer",
"model.SAGeneratorWithGuide",
"chainer.serializers.save_npz",
"evaluation.Eva... | [((1946, 2036), 'dataset.DataLoader', 'DataLoader', (['data_path', 'sketch_path', 'digi_path'], {'extension': 'extension', 'img_size': 'img_size'}), '(data_path, sketch_path, digi_path, extension=extension, img_size\n =img_size)\n', (1956, 2036), False, 'from dataset import DataLoader, RefineDataset\n'), ((2222, 227... |
# -*- coding:utf-8 -*-
# author: gfjiangly
# time: 2019/5/6 18:40
# e-mail: <EMAIL>
# software: PyCharm
"""
General Dataset Classes
"""
import random
import torch
import torch.utils.data as data
import cv2
import numpy as np
class AnnotationTransform(object):
"""Transforms a ELEVATOR annotation into a Tensor of b... | [
"numpy.array",
"torch.from_numpy",
"cv2.imread",
"numpy.expand_dims"
] | [((3869, 3890), 'cv2.imread', 'cv2.imread', (['img_id[0]'], {}), '(img_id[0])\n', (3879, 3890), False, 'import cv2\n'), ((4260, 4276), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (4268, 4276), True, 'import numpy as np\n'), ((1086, 1126), 'numpy.array', 'np.array', (['[width, height, width, height]'], {}... |
# %load code/engram_functions.py
# Import dependencies
import xlrd
import numpy as np
from sympy.utilities.iterables import multiset_permutations
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
def permute_optimize_keys(fixed_letters, fixed_letter_indices, open_letter_indices,
... | [
"matplotlib.pyplot.ylabel",
"numpy.argsort",
"numpy.array",
"seaborn.distplot",
"numpy.where",
"matplotlib.pyplot.xlabel",
"numpy.max",
"sympy.utilities.iterables.multiset_permutations",
"numpy.min",
"numpy.ceil",
"numpy.average",
"numpy.size",
"matplotlib.pyplot.title",
"numpy.int",
"ma... | [((3034, 3058), 'numpy.zeros', 'np.zeros', (['(nkeys, nkeys)'], {}), '((nkeys, nkeys))\n', (3042, 3058), True, 'import numpy as np\n'), ((3810, 3840), 'sympy.utilities.iterables.multiset_permutations', 'multiset_permutations', (['letters'], {}), '(letters)\n', (3831, 3840), False, 'from sympy.utilities.iterables import... |
import pandas as pd
import numpy as np
class CorrectBias(object):
def __init__(self, taper_width, npv_observations):
self.taper_width = taper_width
self.sampled_controls_loc, self.sampled_controls_beta = self.get_data(npv_observations)
self.est_mean_alpha = np.mean(self.sampled_controls_be... | [
"numpy.mean",
"numpy.abs",
"numpy.reshape",
"pandas.read_csv",
"numpy.where",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.setdiff1d"
] | [((7861, 7895), 'pandas.read_csv', 'pd.read_csv', (['"""npv_obs_example.csv"""'], {}), "('npv_obs_example.csv')\n", (7872, 7895), True, 'import pandas as pd\n'), ((288, 323), 'numpy.mean', 'np.mean', (['self.sampled_controls_beta'], {}), '(self.sampled_controls_beta)\n', (295, 323), True, 'import numpy as np\n'), ((304... |
import numpy as np
def expected_calibration_error(y_pred, proba, y_true, n_bins=10):
intervals = np.linspace(0, 1, n_bins+1)
accuracy = (y_pred == y_true).astype(int)
num_predictions = y_pred.shape[0]
error = 0
for lower, upper in zip(intervals[:-1], intervals[1:]):
mask = np.logical_an... | [
"numpy.abs",
"numpy.linspace",
"numpy.logical_and"
] | [((104, 133), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(n_bins + 1)'], {}), '(0, 1, n_bins + 1)\n', (115, 133), True, 'import numpy as np\n'), ((307, 352), 'numpy.logical_and', 'np.logical_and', (['(proba > lower)', '(proba <= upper)'], {}), '(proba > lower, proba <= upper)\n', (321, 352), True, 'import numpy ... |
from dolo.numeric.tensor import sdot,mdot
import numpy as np
TOL = 1e-10
# credits : second_order_solver is adapted from <NAME>'s port of Uhlig's Toolkit.
def second_order_solver(FF,GG,HH):
from scipy.linalg import qz
from dolo.numeric.extern.qz import qzdiv
from numpy import array,mat,c_,r_,eye,z... | [
"numpy.eye",
"numpy.linalg.solve",
"scipy.linalg.qz",
"dolo.numeric.tensor.sdot",
"dolo.numeric.extern.qz.qzdiv",
"numpy.diag",
"numpy.kron",
"numpy.array",
"numpy.zeros",
"numpy.diagflat",
"numpy.real_if_close",
"slycot.sb04qd"
] | [((422, 431), 'numpy.array', 'array', (['FF'], {}), '(FF)\n', (427, 431), False, 'from numpy import array, mat, c_, r_, eye, zeros, real_if_close, diag, allclose, where, diagflat\n'), ((448, 458), 'numpy.array', 'array', (['(-GG)'], {}), '(-GG)\n', (453, 458), False, 'from numpy import array, mat, c_, r_, eye, zeros, r... |
# -*- coding: utf-8 -*-
"""Collection of mathematical functions."""
import numpy as np
from .core import (angle, besselI0, besselI1, besselK0, besselK1, cos,
cot, det, dot, exp, exp10, imag, log, log10, max, median,
min, pow, rand, randn, real, rms, round, rrms, sign,
... | [
"numpy.abs",
"numpy.sign"
] | [((1011, 1021), 'numpy.sign', 'np.sign', (['x'], {}), '(x)\n', (1018, 1021), True, 'import numpy as np\n'), ((988, 997), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (994, 997), True, 'import numpy as np\n'), ((1038, 1053), 'numpy.abs', 'np.abs', (['(x / tol)'], {}), '(x / tol)\n', (1044, 1053), True, 'import numpy as ... |
#! /usr/bin/env python
"""Basic Model Interface implementation for the pyMarshMorpho2D model."""
import numpy as np
from bmipy import Bmi
from pymarshmorpho2d import MarshEvolver
from landlab import load_params
_DEFAULT_PARAMETERS = {
'rel_sl_rise_rate': 0.001 / 365.0,
'tidal_range': 3.1,
}
class MarshMorp... | [
"numpy.finfo",
"numpy.array",
"numpy.zeros",
"landlab.load_params"
] | [((7366, 7459), 'numpy.array', 'np.array', (['[self.grid.number_of_node_rows, self.grid.number_of_node_columns]'], {'dtype': 'np.int'}), '([self.grid.number_of_node_rows, self.grid.number_of_node_columns],\n dtype=np.int)\n', (7374, 7459), True, 'import numpy as np\n'), ((7744, 7755), 'numpy.zeros', 'np.zeros', (['(... |
"""
Authors: <NAME>.
Copyright:
Copyright (c) 2021 Microsoft Research
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, mo... | [
"tests.utils.assert_almost_equal",
"onnx.helper.make_node",
"tests.utils.make_onnx_graph",
"pytest.mark.skip",
"pytest.param",
"tests.utils.Compiler",
"pytest.mark.parametrize",
"tests.utils.run_onnx",
"os.path.dirname",
"numpy.zeros",
"tests.utils.ONNXConfig",
"pytest.skip",
"numpy.random.r... | [((4021, 4066), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dtype"""', '[np.single]'], {}), "('dtype', [np.single])\n", (4044, 4066), False, 'import pytest\n'), ((6702, 6747), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dtype"""', '[np.single]'], {}), "('dtype', [np.single])\n", (6725, 6... |
import numpy as np
class Graph:
"""Class that specifies graph.
Graph is an object that consists of vertices and edges.
We can divide it into several objects, each object contains as many vertices
as the number of letters in alphabet.
We assign label to each vertex, in out case letters.
For ea... | [
"numpy.sum",
"numpy.arange"
] | [((977, 1007), 'numpy.arange', 'np.arange', (['self.objects_number'], {}), '(self.objects_number)\n', (986, 1007), True, 'import numpy as np\n'), ((1302, 1370), 'numpy.sum', 'np.sum', (['((char_image - self.string[:, i - char_width + 1:i + 1]) ** 2)'], {}), '((char_image - self.string[:, i - char_width + 1:i + 1]) ** 2... |
import dataclasses
import itertools
import operator
import xml.etree.ElementTree as ET
from abc import ABC, abstractmethod
import collections
from copy import deepcopy
from functools import reduce
from typing import Optional, Callable, List, Union, Iterable
import more_itertools.more
import numpy as np
from more_iter... | [
"pytest.approx",
"tests.util.only_fixed_rolls",
"collections.namedtuple",
"numpy.random.choice",
"examples.tree_search.hashmap.create_gamestate_hash",
"xml.etree.ElementTree.indent",
"more_itertools.collapse",
"numpy.array",
"numpy.zeros",
"xml.etree.ElementTree.Element",
"xml.etree.ElementTree.... | [((806, 925), 'collections.namedtuple', 'collections.namedtuple', (['"""HeuristicVector"""', "['score', 'tv_on_pitch', 'ball_position', 'ball_carried', 'ball_marked']"], {}), "('HeuristicVector', ['score', 'tv_on_pitch',\n 'ball_position', 'ball_carried', 'ball_marked'])\n", (828, 925), False, 'import collections\n'... |
import numpy as np
from .muscle_simulation_stepupdate import step_update_state
class MuscleTendonComplex:
def __init__(self, nameMuscle, frcmax, vmax, lslack, lopt,
lce, r, phiref, phimaxref, rho, dirAng, phiScale,
offsetCorr, timestep, angJoi, eref=0.04, act=0.01,
... | [
"numpy.arccos",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.cos",
"numpy.sin"
] | [((1671, 1696), 'numpy.zeros', 'np.zeros', (['self.typeMuscle'], {}), '(self.typeMuscle)\n', (1679, 1696), True, 'import numpy as np\n'), ((6950, 6970), 'numpy.array', 'np.array', (['(rTIAmax,)'], {}), '((rTIAmax,))\n', (6958, 6970), True, 'import numpy as np\n'), ((6988, 7010), 'numpy.array', 'np.array', (['(phirefTIA... |
'''interface with serlib.cparser module
We'll use platform defined C-types int (np.intc) and long long int
(np.ulonglong) for maximal portability because python C-api does not
support fixed width C types: https://docs.python.org/3/c-api/long.html
For numpy reference see
https://numpy.org/devdocs/user/basics.types.html... | [
"numpy.array",
"numpy.zeros"
] | [((2250, 2291), 'numpy.zeros', 'np.zeros', (['buffer_size'], {'dtype': 'np.ulonglong'}), '(buffer_size, dtype=np.ulonglong)\n', (2258, 2291), True, 'import numpy as np\n'), ((2964, 2996), 'numpy.array', 'np.array', (['address'], {'dtype': 'np.intc'}), '(address, dtype=np.intc)\n', (2972, 2996), True, 'import numpy as n... |
import os
import os.path as osp
import math
import numpy as np
# ---- load random results from 'process.txt' ----
random_res = []
for seed in range(10):
main_path = osp.join('Experiment', 'optimal', 'seed%d'%seed)
sub_p_res = []
for power in range(0, 35, 5):
fpath = osp.join(main_path, 'power%d'%p... | [
"os.makedirs",
"comms.Environment",
"os.path.join",
"numpy.array",
"run.test"
] | [((1385, 1421), 'os.path.join', 'osp.join', (['"""Resdata"""', '"""noise_compare"""'], {}), "('Resdata', 'noise_compare')\n", (1393, 1421), True, 'import os.path as osp\n'), ((1422, 1459), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (1433, 1459), False, 'import... |
import numpy as np
import sys
pp = "/Users/andres.perez/source/parametric_spatial_audio_processing"
sys.path.append(pp)
import parametric_spatial_audio_processing as psa
import matplotlib.pyplot as plt
import scipy.stats
from utils import *
from file_utils import build_result_dict_from_metadata_array, build_metadata_r... | [
"matplotlib.pyplot.grid",
"parametric_spatial_audio_processing.compute_energy_density",
"parametric_spatial_audio_processing.compute_DOA",
"sys.path.append",
"parametric_spatial_audio_processing.Stft.fromSignal",
"numpy.asarray",
"parametric_spatial_audio_processing.Stft",
"numpy.max",
"matplotlib.p... | [((100, 119), 'sys.path.append', 'sys.path.append', (['pp'], {}), '(pp)\n', (115, 119), False, 'import sys\n'), ((1116, 1175), 'parametric_spatial_audio_processing.Signal', 'psa.Signal', (['data[start_frame:end_frame].T', 'sr', '"""acn"""', '"""n3d"""'], {}), "(data[start_frame:end_frame].T, sr, 'acn', 'n3d')\n", (1126... |
import numpy as np
import pandas as pd
import pytest
import xarray as xr
from esmvalcore.experimental import Recipe
from esmvalcore.experimental.recipe_output import DataFile
from ewatercycle.forcing import generate, load
from ewatercycle.forcing._lisflood import LisfloodForcing
def test_plot():
f = LisfloodForc... | [
"ewatercycle.forcing.load",
"esmvalcore.experimental.recipe_output.DataFile",
"pytest.raises",
"ewatercycle.forcing.generate",
"ewatercycle.forcing._lisflood.LisfloodForcing",
"numpy.random.randn",
"pandas.date_range"
] | [((308, 411), 'ewatercycle.forcing._lisflood.LisfloodForcing', 'LisfloodForcing', ([], {'directory': '"""."""', 'start_time': '"""1989-01-02T00:00:00Z"""', 'end_time': '"""1999-01-02T00:00:00Z"""'}), "(directory='.', start_time='1989-01-02T00:00:00Z', end_time=\n '1999-01-02T00:00:00Z')\n", (323, 411), False, 'from ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Util functions
# @author <EMAIL>
from lxml import etree
from lxml.etree import tostring
from itertools import chain
from nltk.tokenize import wordpunct_tokenize
from random import shuffle
from sklearn import metrics
import numpy
import operator
import pandas
import re
impor... | [
"sklearn.metrics.f1_score",
"random.shuffle",
"pandas.read_csv",
"numpy.average",
"lxml.etree.SubElement",
"subprocess.Popen",
"lxml.etree.parse",
"torch.stack",
"lxml.etree.write",
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",
"subprocess.call",
"lxml.etree.fromstring",... | [((2212, 2233), 'lxml.etree.parse', 'etree.parse', (['filename'], {}), '(filename)\n', (2223, 2233), False, 'from lxml import etree\n'), ((2680, 2700), 'lxml.etree.write', 'etree.write', (['outfile'], {}), '(outfile)\n', (2691, 2700), False, 'from lxml import etree\n'), ((2733, 2765), 'pandas.DataFrame', 'pandas.DataFr... |
import os
import argparse
import numpy as np
import processors as pe
from paz.backend.camera import VideoPlayer
from paz.backend.camera import Camera
from demo_pipeline import DetectEigenFaces
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Real-time face classifier')
parser.add_argum... | [
"os.path.exists",
"os.listdir",
"demo_pipeline.DetectEigenFaces",
"argparse.ArgumentParser",
"os.makedirs",
"paz.backend.camera.VideoPlayer",
"os.path.join",
"processors.CalculateCosineSimilarity",
"numpy.load",
"paz.backend.camera.Camera"
] | [((235, 299), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Real-time face classifier"""'}), "(description='Real-time face classifier')\n", (258, 299), False, 'import argparse\n'), ((2071, 2119), 'os.path.join', 'os.path.join', (['args.database_path', '"""database.npy"""'], {}), "(args.... |
import os
import glob
import copy
import random
import time
import numpy as np
import numpy.ma as ma
import cv2
from PIL import Image
import matplotlib.pyplot as plt
import scipy.io as scio
from scipy.spatial.transform import Rotation as R
from sklearn.neighbors import KDTree
import torch
import torch.nn as nn
im... | [
"numpy.ma.masked_equal",
"cv2.projectPoints",
"torch.LongTensor",
"affpose.YCB_Aff.eval.eval_utils.get_error_metrics",
"scipy.io.loadmat",
"torch.max",
"time.sleep",
"cv2.imshow",
"affpose.YCB_Aff.utils.bbox.extract_bboxs_from_label.get_bbox",
"affpose.YCB_Aff.eval.eval_utils.get_obj_stats",
"li... | [((708, 736), 'sys.path.append', 'sys.path.append', (['"""../../../"""'], {}), "('../../../')\n", (723, 736), False, 'import sys\n'), ((2249, 2310), 'lib.network.PoseNet', 'PoseNet', ([], {'num_points': 'config.NUM_PT', 'num_obj': 'config.NUM_OBJECTS'}), '(num_points=config.NUM_PT, num_obj=config.NUM_OBJECTS)\n', (2256... |
from .output_base import OutputBase
import numpy as np
class InMemoryOutput(OutputBase):
_aliases = ["memory"]
def __init__(self):
super(InMemoryOutput,self).__init__()
self.rows = []
self.meta = {}
self.final_meta = {}
self.comments = []
def _write_parameters(self,... | [
"numpy.array"
] | [((868, 918), 'numpy.array', 'np.array', (['[row[column_index] for row in self.rows]'], {}), '([row[column_index] for row in self.rows])\n', (876, 918), True, 'import numpy as np\n')] |
import numpy
def entropy2(*args):
''' E = ENTROPY2(MTX,BINSIZE)
Compute the first-order sample entropy of MTX. Samples of VEC are
first discretized. Optional argument BINSIZE controls the
discretization, and defaults to 256/(max(VEC)-min(VEC)).
NOTE: This is a heavily ... | [
"numpy.where",
"numpy.array",
"numpy.log2"
] | [((469, 489), 'numpy.array', 'numpy.array', (['args[0]'], {}), '(args[0])\n', (480, 489), False, 'import numpy\n'), ((1062, 1087), 'numpy.where', 'numpy.where', (['(bincount > 0)'], {}), '(bincount > 0)\n', (1073, 1087), False, 'import numpy\n'), ((1137, 1150), 'numpy.log2', 'numpy.log2', (['H'], {}), '(H)\n', (1147, 1... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# https://yq.aliyun.com/articles/118726
np.random.seed(111)
rng = pd.date_range(start='2000', periods=209, freq='M')
ts = pd.Series(np.random.uniform(-10, 10, size=len(rng)), rng).cumsum()
ts.plot(c='b', title='Example T... | [
"matplotlib.pyplot.savefig",
"tensorflow.reset_default_graph",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.contrib.rnn.BasicRNNCell",
"tensorflow.nn.dynamic_rnn",
"tensorflow.global_variables_initializer",
"numpy.array",
"numpy.random.seed",
"tensorflow.reshape",
"tensorflow.laye... | [((138, 157), 'numpy.random.seed', 'np.random.seed', (['(111)'], {}), '(111)\n', (152, 157), True, 'import numpy as np\n'), ((165, 215), 'pandas.date_range', 'pd.date_range', ([], {'start': '"""2000"""', 'periods': '(209)', 'freq': '"""M"""'}), "(start='2000', periods=209, freq='M')\n", (178, 215), True, 'import pandas... |
import os
import sys
if sys.version_info[0] == 2:
import cPickle as pickle
else:
import pickle
import numpy as np
import torch
import torchvision.datasets as datasets
class CIFAR10NoisyLabels(datasets.CIFAR10):
"""CIFAR10 Dataset with noisy labels.
Args:
noise_type (string): Noise type (def... | [
"numpy.unique",
"numpy.where",
"torch.eye",
"os.path.join",
"numpy.asarray",
"pickle.load",
"numpy.random.multinomial",
"numpy.array",
"numpy.sum",
"numpy.random.seed",
"numpy.concatenate",
"numpy.random.uniform",
"torch.ones"
] | [((888, 940), 'numpy.asarray', 'np.asarray', (['[[9, 1], [2, 0], [4, 7], [3, 5], [5, 3]]'], {}), '([[9, 1], [2, 0], [4, 7], [3, 5], [5, 3]])\n', (898, 940), True, 'import numpy as np\n'), ((1530, 1555), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (1544, 1555), True, 'import numpy as np\... |
# This file implements spiking neural networks as described
# in the work:
# <NAME>, Coarse scale representation of spiking neural networks:
# backpropagation through spikes and applications to neuromorphic hardware,
# International Conference on Neuromorphic Systems (ICONS), 2020
import argparse
import t... | [
"torch.nn.functional.mse_loss",
"torch.rand_like",
"argparse.ArgumentParser",
"spikingnet.poisson_spikes",
"torch.nn.Conv2d",
"numpy.array",
"spikingnet.SpikingVextLayer",
"torch.nn.MaxPool2d",
"spikingnet.SpikingLayer",
"torch.cuda.is_available",
"torch.nn.Linear",
"torch.nn.functional.cross_... | [((13796, 13853), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""SpikingNet example"""'}), "(description='SpikingNet example')\n", (13819, 13853), False, 'import argparse\n'), ((16194, 16237), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda... |
# encoding=utf-8
from scipy.io import loadmat
import numpy as np
import pickle
"""
matrix shape: (577,272)
positive samples: 1583
negative samples: 155361
"""
m = loadmat("lda_interMatrix.mat")
interMatrix = m['interMatrix']
rows, cols = interMatrix.shape
print('matrix shape:', interMatrix.shape)
pos... | [
"scipy.io.loadmat",
"pickle.dump",
"numpy.save"
] | [((176, 206), 'scipy.io.loadmat', 'loadmat', (['"""lda_interMatrix.mat"""'], {}), "('lda_interMatrix.mat')\n", (183, 206), False, 'from scipy.io import loadmat\n'), ((695, 729), 'numpy.save', 'np.save', (['"""matrix.npy"""', 'interMatrix'], {}), "('matrix.npy', interMatrix)\n", (702, 729), True, 'import numpy as np\n')... |
#!/usr/bin/env python
"""
@author: <NAME>
"""
from spatialmath import SE3
from spatialmath.base.argcheck import getvector
from spatialmath.base import r2q
import numpy as np
import copy
_mpl = False
try:
from matplotlib import colors as mpc
_mpl = True
except ImportError: # pragma nocover
pass
CONST_... | [
"numpy.copy",
"numpy.eye",
"spatialmath.SE3",
"matplotlib.colors.to_rgba",
"spatialmath.base.argcheck.getvector",
"numpy.any",
"numpy.array",
"numpy.zeros",
"spatialmath.base.r2q",
"spatialmath.SE3.Rx",
"copy.copy"
] | [((325, 342), 'spatialmath.SE3.Rx', 'SE3.Rx', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (331, 342), False, 'from spatialmath import SE3\n'), ((734, 743), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (740, 743), True, 'import numpy as np\n'), ((763, 772), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (769, 772), True, ... |
from __future__ import print_function
import sys,inspect
import numpy as np
from flask import json
from collections import OrderedDict
class Evaluator:
def __init__(self,functionList):
self.generatedApp=[]
self.hasPlot=False
self.itemList=[]
self.evalGlobals={}
self.functionList = functionList
se... | [
"numpy.array",
"inspect.getdoc",
"inspect.getargspec"
] | [((3332, 3368), 'inspect.getdoc', 'inspect.getdoc', (['self.functionList[a]'], {}), '(self.functionList[a])\n', (3346, 3368), False, 'import sys, inspect\n'), ((3383, 3423), 'inspect.getargspec', 'inspect.getargspec', (['self.functionList[a]'], {}), '(self.functionList[a])\n', (3401, 3423), False, 'import sys, inspect\... |
import cv2
import numpy as np
import face_recognition
import datetime
from multiprocessing import Process
import Data.DataProcessing as dp
from os import path, mkdir
import MotionDetection
from datetime import datetime
import Database.Commands as db_commands
class FaceAnalyzer():
def __init__(self, t... | [
"os.path.exists",
"cv2.imwrite",
"cv2.warpAffine",
"cv2.getRotationMatrix2D",
"face_recognition.face_locations",
"cv2.resize",
"numpy.where",
"multiprocessing.Process",
"numpy.asarray",
"numpy.any",
"numpy.array",
"datetime.datetime.now",
"os.mkdir",
"face_recognition.compare_faces",
"fa... | [((524, 543), 'Data.DataProcessing.load_encodings', 'dp.load_encodings', ([], {}), '()\n', (541, 543), True, 'import Data.DataProcessing as dp\n'), ((699, 768), 'multiprocessing.Process', 'Process', ([], {'target': 'self.process_motions', 'args': '(MotionDetection.motions,)'}), '(target=self.process_motions, args=(Moti... |
import os
import numpy as np
import cv2 as cv
m = {}
for dir in ["rotgen/ok", "rotgen/ko"]:
for f in os.listdir(dir):
file = "%s/%s" %(dir,f)
img0 = cv.cvtColor(cv.imread(file), cv.COLOR_BGR2GRAY)
n = np.sum(img0)
if n in m:
m[n].append(file)
print("rm -v %s"... | [
"numpy.sum",
"os.listdir",
"cv2.imread"
] | [((106, 121), 'os.listdir', 'os.listdir', (['dir'], {}), '(dir)\n', (116, 121), False, 'import os\n'), ((230, 242), 'numpy.sum', 'np.sum', (['img0'], {}), '(img0)\n', (236, 242), True, 'import numpy as np\n'), ((182, 197), 'cv2.imread', 'cv.imread', (['file'], {}), '(file)\n', (191, 197), True, 'import cv2 as cv\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 12 11:00:26 2022
@author: jac
"""
from numpy import array
from pandas import read_csv, unique
from ProxyUQ import ProxyUQ
from pyplotfuncmc import PlotSolnsMC
cat = read_csv("AtmosphericRivers/AR_Cat.csv")
ARivers = []
for y in unique(cat['Yea... | [
"pyplotfuncmc.PlotSolnsMC",
"numpy.array",
"pandas.unique",
"pandas.read_csv"
] | [((241, 281), 'pandas.read_csv', 'read_csv', (['"""AtmosphericRivers/AR_Cat.csv"""'], {}), "('AtmosphericRivers/AR_Cat.csv')\n", (249, 281), False, 'from pandas import read_csv, unique\n'), ((305, 324), 'pandas.unique', 'unique', (["cat['Year']"], {}), "(cat['Year'])\n", (311, 324), False, 'from pandas import read_csv,... |
import random
import csv
from typing import Iterator, Union, List
from torch.utils.data.sampler import Sampler
import numpy as np
from ..datapaths import DATAPATHS_MAPPING
class LengthTrainSampler(Sampler):
def __init__(
self,
source: str,
field: str,
max_len: float, # 16K * 320... | [
"csv.DictReader",
"random.shuffle",
"numpy.logical_and",
"numpy.argsort",
"numpy.array"
] | [((2475, 2492), 'numpy.array', 'np.array', (['lengths'], {}), '(lengths)\n', (2483, 2492), True, 'import numpy as np\n'), ((2716, 2740), 'numpy.argsort', 'np.argsort', (['self.lengths'], {}), '(self.lengths)\n', (2726, 2740), True, 'import numpy as np\n'), ((4413, 4436), 'random.shuffle', 'random.shuffle', (['batches']... |
from collections import namedtuple
from itertools import islice
import numpy as np
import pandas as pd
from dataclasses import dataclass
@dataclass
class BinningInfo(object):
"""Docstring for BinningInfo."""
variable_extents: tuple
step: float
num_bins: int
bin_indicies: np.ndarray
def buil... | [
"numpy.atleast_2d",
"numpy.ceil",
"collections.namedtuple",
"numpy.reshape",
"numpy.unique",
"itertools.islice",
"numpy.searchsorted",
"numpy.diff",
"numpy.append",
"numpy.linspace",
"numpy.zeros",
"numpy.setdiff1d",
"numpy.nanmax",
"numpy.unravel_index",
"numpy.expand_dims",
"numpy.na... | [((18753, 18802), 'collections.namedtuple', 'namedtuple', (['"""RowColTuple"""', '"""num_rows num_columns"""'], {}), "('RowColTuple', 'num_rows num_columns')\n", (18763, 18802), False, 'from collections import namedtuple\n'), ((18838, 18927), 'collections.namedtuple', 'namedtuple', (['"""PaginatedGridIndexSpecifierTupl... |
import numpy as np
from util.math import abs_diff
# =============================================
# Metric Principle Component Analysis
# =============================================
# Generate vector between scaled by metric difference. Give the metric
# the indices of "vectors" in the provided matrix.
de... | [
"numpy.prod",
"numpy.median",
"sklearn.decomposition.PCA",
"numpy.argsort",
"numpy.sum",
"numpy.zeros",
"numpy.matmul",
"numpy.linalg.norm"
] | [((1154, 1179), 'numpy.zeros', 'np.zeros', (['points.shape[1]'], {}), '(points.shape[1])\n', (1162, 1179), True, 'import numpy as np\n'), ((2333, 2353), 'numpy.median', 'np.median', (['error_fix'], {}), '(error_fix)\n', (2342, 2353), True, 'import numpy as np\n'), ((3235, 3272), 'numpy.zeros', 'np.zeros', (['(num_vecs,... |
from functools import partial, update_wrapper
from math import exp
import numpy as np
from scipy.sparse import lil_matrix
from scipy.stats import rankdata
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics.pairwise import pairwise_distances, euclidean_distances
from sklearn.neighbors import NearestNei... | [
"numpy.random.default_rng",
"sklearn.metrics.pairwise.pairwise_distances",
"numpy.argsort",
"numpy.array",
"numpy.var",
"math.exp",
"numpy.arange",
"numpy.mean",
"scipy.sparse.lil_matrix",
"numpy.flatnonzero",
"sklearn.neighbors.NearestNeighbors",
"sklearn.preprocessing.MinMaxScaler",
"numpy... | [((589, 619), 'functools.partial', 'partial', (['func', '*args'], {}), '(func, *args, **kwargs)\n', (596, 619), False, 'from functools import partial, update_wrapper\n'), ((624, 658), 'functools.update_wrapper', 'update_wrapper', (['partial_func', 'func'], {}), '(partial_func, func)\n', (638, 658), False, 'from functoo... |
import argparse
import numpy as np
import tensorflow as tf
from tensorflow.contrib.rnn import BasicLSTMCell, LSTMStateTuple
from tensorflow.core.framework import attr_value_pb2
from tensorflow.core.framework import graph_pb2
from tensorflow.core.framework import node_def_pb2
from tensorflow.python.framework import gra... | [
"tensorflow.div",
"tensorflow.equal",
"tensorflow.nn.bidirectional_dynamic_rnn",
"tensorflow.get_variable",
"tensorflow.contrib.rnn.LSTMStateTuple",
"tensorflow.shape",
"tensorflow.reduce_sum",
"tensorflow.split",
"tensorflow.multiply",
"tensorflow.enable_eager_execution",
"tensorflow.gfile.Fast... | [((509, 543), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (528, 543), True, 'import numpy as np\n'), ((13733, 13753), 'tensorflow.core.framework.graph_pb2.GraphDef', 'graph_pb2.GraphDef', ([], {}), '()\n', (13751, 13753), False, 'from tensorflow.core.framework imp... |
import angr ,claripy
import numpy as np
class SimExtractParams(angr.SimProcedure):
def run(self, *args, pointers=None):
self.state.globals['args']=[]
for numb,typ in pointers.items():
argRes=None
if typ == 'intPointer':
addr=args[numb-1].ast.args[0]
... | [
"numpy.int32",
"claripy.BVV"
] | [((341, 385), 'numpy.int32', 'np.int32', (['self.state.mem[addr].long.concrete'], {}), '(self.state.mem[addr].long.concrete)\n', (349, 385), True, 'import numpy as np\n'), ((896, 918), 'claripy.BVV', 'claripy.BVV', (['value', '(32)'], {}), '(value, 32)\n', (907, 918), False, 'import angr, claripy\n'), ((1139, 1161), 'c... |
"""Create carbon regression scenarios."""
import argparse
import logging
import multiprocessing
import os
import subprocess
import sys
from osgeo import gdal
import pygeoprocessing
import numpy
import taskgraph
gdal.SetCacheMax(2**27)
logging.basicConfig(
level=logging.DEBUG,
format=(
'%(asctime)s (%... | [
"logging.basicConfig",
"logging.getLogger",
"subprocess.check_output",
"pygeoprocessing.warp_raster",
"numpy.unique",
"pygeoprocessing.new_raster_from_base",
"argparse.ArgumentParser",
"os.makedirs",
"subprocess.run",
"os.path.join",
"multiprocessing.cpu_count",
"numpy.zeros",
"pygeoprocessi... | [((213, 238), 'osgeo.gdal.SetCacheMax', 'gdal.SetCacheMax', (['(2 ** 27)'], {}), '(2 ** 27)\n', (229, 238), False, 'from osgeo import gdal\n'), ((238, 412), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': '"""%(asctime)s (%(relativeCreated)d) %(levelname)s %(name)s [%(funcName)s:... |
"""Utilities for the normal CHIME Bayes module
"""
from typing import TypeVar, Union
from numpy import exp
FloatLike = TypeVar("FloatLike") # Floats or integers
FloatLikeArray = TypeVar("FloatLikeArray") # Arrays of floats or integers
NormalDistVar = TypeVar("NormalDistVar") # Normally distributed random var
Norm... | [
"numpy.exp",
"typing.TypeVar"
] | [((121, 141), 'typing.TypeVar', 'TypeVar', (['"""FloatLike"""'], {}), "('FloatLike')\n", (128, 141), False, 'from typing import TypeVar, Union\n'), ((181, 206), 'typing.TypeVar', 'TypeVar', (['"""FloatLikeArray"""'], {}), "('FloatLikeArray')\n", (188, 206), False, 'from typing import TypeVar, Union\n'), ((256, 280), 't... |
from torch.utils.tensorboard import SummaryWriter
import os, glob
from utils import dict_send_to
from tqdm import tqdm
import time, datetime
import argparse
import json
import traceback
from hyperparams import hparams as hp
import torch
from concurrent.futures import ProcessPoolExecutor
from utils.transcribe import tra... | [
"hyperparams.hparams.to_json",
"time.sleep",
"torch.cuda.is_available",
"logging.info",
"torch.utils.tensorboard.SummaryWriter",
"os.path.exists",
"synthesize.eval_batch",
"logging.warn",
"numpy.mean",
"argparse.ArgumentParser",
"os.listdir",
"json.dumps",
"os.path.split",
"utils.checkpoin... | [((744, 778), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': '(4)'}), '(max_workers=4)\n', (763, 778), False, 'from concurrent.futures import ProcessPoolExecutor\n'), ((695, 732), 'faulthandler.register', 'faulthandler.register', (['signal.SIGUSR1'], {}), '(signal.SIGUSR1)\n', (71... |
"""This would provide postprocessing of results.
Libraries/Modules:
Would use: numpy\n
Would use: pandas\n
"""
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
from bin.NavierStokes import NavierStokes
class flo103_PostProcessor:
"""Not impleme... | [
"matplotlib.pyplot.contourf",
"numpy.abs",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.axes",
"numpy.min",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((1622, 1660), 'matplotlib.pyplot.plot', 'plt.plot', (['x[1:-1, 1:-1]', 'y[1:-1, 1:-1]'], {}), '(x[1:-1, 1:-1], y[1:-1, 1:-1])\n', (1630, 1660), True, 'from matplotlib import pyplot as plt\n'), ((1667, 1682), 'matplotlib.pyplot.title', 'plt.title', (['"""xc"""'], {}), "('xc')\n", (1676, 1682), True, 'from matplotlib i... |
'''
Library for 2-component Flory-Huggings theory.
Author: <NAME>
Date created: 23 March 2022
'''
import numpy as np
def help():
print('Here are the list of functions included in FH.py:\n')
print(' critical(n = 1): returns the critical concentration and critical interaction [phi_c, chi_c]\n')
print(' spinodal(c... | [
"numpy.copy",
"numpy.sqrt",
"numpy.power",
"numpy.exp",
"numpy.array"
] | [((907, 929), 'numpy.array', 'np.array', (['[phi_c, x_c]'], {}), '([phi_c, x_c])\n', (915, 929), True, 'import numpy as np\n'), ((2589, 2615), 'numpy.array', 'np.array', (['[pp, 1 - pp, xx]'], {}), '([pp, 1 - pp, xx])\n', (2597, 2615), True, 'import numpy as np\n'), ((4035, 4057), 'numpy.array', 'np.array', (['[p1, p2,... |
import enpix
import numpy as np
matrix = np.random.rand(341,765,3)
# print(matrix)
key="firstname.lastname@<EMAIL>.com-nameofuser-mobilenumber"
time=1000000
pic = enpix.encrypt(matrix,key,time)
# print(pic)
pic2 = enpix.decrypt(pic,key,time)
# print(pic2)
print((matrix==pic2).all()) | [
"enpix.decrypt",
"numpy.random.rand",
"enpix.encrypt"
] | [((42, 69), 'numpy.random.rand', 'np.random.rand', (['(341)', '(765)', '(3)'], {}), '(341, 765, 3)\n', (56, 69), True, 'import numpy as np\n'), ((166, 198), 'enpix.encrypt', 'enpix.encrypt', (['matrix', 'key', 'time'], {}), '(matrix, key, time)\n', (179, 198), False, 'import enpix\n'), ((218, 247), 'enpix.decrypt', 'en... |
# sphinx_gallery_thumbnail_number = 4
from __future__ import absolute_import
from . import _graph as __graph
from ._graph import *
from .. import Configuration
from . import opt
from . opt import multicut
from . opt import lifted_multicut
from . opt import mincut
from . opt import minstcut
import numpy
from functool... | [
"numpy.ones_like",
"numpy.ones",
"numpy.arange",
"numpy.where",
"numpy.require",
"numpy.random.random",
"networkx.draw_spring",
"networkx.Graph",
"numpy.stack",
"numpy.random.randint",
"numpy.dtype",
"networkx.draw"
] | [((1793, 1868), 'numpy.random.randint', 'numpy.random.randint', ([], {'low': '(0)', 'high': '(numberOfNodes - 1)', 'size': '(numberOfEdges * 2)'}), '(low=0, high=numberOfNodes - 1, size=numberOfEdges * 2)\n', (1813, 1868), False, 'import numpy\n'), ((3908, 3945), 'numpy.require', 'numpy.require', (['offsets'], {'dtype'... |
import numpy as np
from experiments.target_lnpdfs.Lnpdf import LNPDF
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
class PlanarRobot(LNPDF):
def __init__(self, num_links, num_goals, prior_std=2e-1, likelihood_std=1e-2):
self._num_dimensions = num_... | [
"tensorflow.stack",
"tensorflow.reduce_sum",
"numpy.ones",
"tensorflow.zeros"
] | [((549, 578), 'numpy.ones', 'np.ones', (['self._num_dimensions'], {}), '(self._num_dimensions)\n', (556, 578), True, 'import numpy as np\n'), ((359, 377), 'numpy.ones', 'np.ones', (['num_links'], {}), '(num_links)\n', (366, 377), True, 'import numpy as np\n'), ((457, 476), 'tensorflow.zeros', 'tf.zeros', (['num_links']... |
import numpy as np
from typing import List, Literal
from .constraint import Constraint
from .parameter import Parameter
class LinearConstraint(Constraint):
"""
Represents a linear constraint. Either an equality constraint :math:`Ax = b`, or an inequality constraint
:math:`Ax \\geq b`, where :math:`A \\i... | [
"numpy.concatenate"
] | [((1375, 1395), 'numpy.concatenate', 'np.concatenate', (['args'], {}), '(args)\n', (1389, 1395), True, 'import numpy as np\n')] |
import torch
from torch import nn
from torch.distributions import Categorical
from torch.optim import Adam, SGD, ASGD
import torch.multiprocessing as mp
import os
from multiprocessing import Process, Queue
import queue
import numpy
import argparse
import glob
#from matplotlib import pyplot as plot
import copy... | [
"numpy.random.rand",
"utils.copy_params",
"numpy.iinfo",
"torch.from_numpy",
"torch.exp",
"numpy.mod",
"gym.make",
"argparse.ArgumentParser",
"conv.Player",
"torch.set_num_threads",
"numpy.max",
"numpy.stack",
"ff.Value",
"torch.multiprocessing.set_start_method",
"conv.Value",
"torch.m... | [((638, 661), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (655, 661), False, 'import torch\n'), ((775, 794), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (787, 794), False, 'import torch\n'), ((799, 834), 'torch.set_num_threads', 'torch.set_num_threads', (['args.n_cores'],... |
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from scipy.stats import norm
import time
import os
from demoire.epll.epll import EPLLhalfQuadraticSplit
from demoire.epll.utils import get_gs_matrix
def process(noiseI, GS, matpath, DC):
patchSize = 8
noiseSD = 25/255
# same to... | [
"PIL.Image.open",
"matplotlib.pyplot.imsave",
"os.path.join",
"os.path.realpath",
"os.path.dirname",
"numpy.array",
"numpy.empty",
"os.path.basename",
"demoire.epll.utils.get_gs_matrix"
] | [((1508, 1542), 'demoire.epll.utils.get_gs_matrix', 'get_gs_matrix', ([], {'path': 'matpath', 'DC': 'DC'}), '(path=matpath, DC=DC)\n', (1521, 1542), False, 'from demoire.epll.utils import get_gs_matrix\n'), ((2604, 2645), 'matplotlib.pyplot.imsave', 'plt.imsave', (['resultpath', 'cleanI'], {'cmap': 'cmap'}), '(resultpa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 20:21:34 2020
@author: nickcostanzino
"""
def NN_structure(layers, perceptrons):
A = list()
for n in range(layers):
A.append(perceptrons)
return tuple(A)
def NN_structures(layers, perceptrons):
A = list()
for i ... | [
"numpy.random.normal",
"sklearn.model_selection.GridSearchCV",
"sklearn.neural_network.MLPRegressor",
"sklearn.model_selection.TimeSeriesSplit",
"sklearn.metrics.mean_squared_error",
"numpy.append",
"pandas.DataFrame",
"sklearn.linear_model.LinearRegression"
] | [((560, 596), 'sklearn.metrics.mean_squared_error', 'mean_squared_error', (['prediction', 'true'], {}), '(prediction, true)\n', (578, 596), False, 'from sklearn.metrics import r2_score, mean_squared_error\n'), ((889, 920), 'numpy.random.normal', 'np.random.normal', (['(0)', 'sigma_e', 'N'], {}), '(0, sigma_e, N)\n', (9... |
import sys
import os
import shutil
import time
import json
from typing import List, Union
import torch
from torch import nn
from torch.autograd import Variable
from torch.optim import SGD
import numpy as np
from torchmetrics import Accuracy, Precision, Recall
from Metrics import AreaUnderPrecisionCurve, T... | [
"numpy.clip",
"DataAugement.RandAugment",
"torchvision.transforms.transforms.ToPILImage",
"torch.nn.CrossEntropyLoss",
"torch.cuda.is_available",
"Metrics.ModifiedF1",
"Metrics.TprFpr",
"torchmetrics.Recall",
"Metrics.Time1000Samples",
"numpy.mean",
"os.listdir",
"numpy.exp",
"Metrics.SkAucR... | [((663, 696), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (686, 696), False, 'import warnings\n'), ((1254, 1316), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'size_average': '(False)', 'ignore_index': 'NO_LABEL'}), '(size_average=False, ignore_index=NO_LAB... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 14:36:02 2021
@author: endocv202<EMAIL>
"""
# import network
import os
import os.path as osp
import argparse
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
import skimage
from skimage import io
from skimage.transfor... | [
"models.get_model.get_arch",
"os.path.exists",
"torch.cuda.Event",
"os.listdir",
"numpy.mean",
"PIL.Image.open",
"argparse.ArgumentParser",
"numpy.sort",
"os.path.join",
"torch.cuda.synchronize",
"skimage.io.imread",
"torch.cuda.is_available",
"os.mkdir",
"torchvision.transforms.Normalize"... | [((708, 746), 'os.path.join', 'os.path.join', (['directoryName', 'task_type'], {}), '(directoryName, task_type)\n', (720, 746), False, 'import os\n'), ((814, 834), 'os.listdir', 'os.listdir', (['infolder'], {}), '(infolder)\n', (824, 834), False, 'import os\n'), ((1006, 1020), 'numpy.sort', 'np.sort', (['flist'], {}), ... |
from operator import mul
import sys
import matplotlib.pyplot as plt
import numpy as np
from holoviews import opts
from scipy.signal.ltisys import dfreqresp
from scipy.spatial import Voronoi
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from skl... | [
"IPython.display.display",
"sklearn.feature_selection.VarianceThreshold",
"holoviews.Graph.from_networkx",
"io.open",
"pandas.Index",
"matplotlib.pyplot.annotate",
"numpy.array",
"holoviews.opts.EdgePaths",
"sys.exit",
"seaborn.pairplot",
"pandas.to_datetime",
"pandas.date_range",
"pandas.re... | [((1152, 1174), 'seaborn.set', 'sns.set', ([], {'style': '"""ticks"""'}), "(style='ticks')\n", (1159, 1174), True, 'import seaborn as sns\n'), ((1175, 1196), 'holoviews.extension', 'hv.extension', (['"""bokeh"""'], {}), "('bokeh')\n", (1187, 1196), True, 'import holoviews as hv\n'), ((3500, 3563), 'matplotlib.pyplot.sc... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
# part 1
with open('input.txt') as f:
lines = f.readlines()
# [horizontal_pos, depth]
loc = np.array([0,0])
# [horizontal_pos, depth]
command = {'forward': np.array([1, 0]),
... | [
"numpy.array"
] | [((210, 226), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (218, 226), True, 'import numpy as np\n'), ((665, 684), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (673, 684), True, 'import numpy as np\n'), ((288, 304), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (296, 304),... |
import pickle
import os
import numpy as np
import torch
import warnings
from tqdm import tqdm
from Metrics import evaluateTracking
from dataset.dataLoader import Data_Loader_MOT
from network.tubetk import TubeTK
from post_processing.tube_nms import multiclass_nms
from apex import amp
import argparse
import multiprocess... | [
"apex.amp.initialize",
"torch.distributed.is_available",
"torch.distributed.barrier",
"os.path.exists",
"os.listdir",
"argparse.ArgumentParser",
"numpy.concatenate",
"dataset.dataLoader.Data_Loader_MOT",
"network.tubetk.TubeTK",
"torch.nn.parallel.DistributedDataParallel",
"torch.distributed.get... | [((426, 459), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (449, 459), False, 'import warnings\n'), ((751, 785), 'torch.distributed.get_world_size', 'torch.distributed.get_world_size', ([], {}), '()\n', (783, 785), False, 'import torch\n'), ((829, 856), 'torch.distribute... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
from mpl_toolkits.mplot3d import Axes3D
# Initialize webcam input
cap = cv2.VideoCapture(0)
# Initialize video input
####BSL Corpus#####
#cap = cv2.VideoCapture("C:/Users/liangx/Desktop/Trajectoreis_test/BSL Corpus Data Resul... | [
"cv2.rectangle",
"matplotlib.pyplot.ylabel",
"cv2.imshow",
"numpy.array",
"cv2.destroyAllWindows",
"cv2.CascadeClassifier",
"cv2.erode",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"cv2.line",
"cv2.contourArea",
"cv2.waitKey",
"cv2.drawContours",
"numpy.ones",
"matplotlib.pyplo... | [((165, 184), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (181, 184), False, 'import cv2\n'), ((1324, 1429), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""C:/Users/liangx/Documents/Dunhill Project Data/Single Sign/Stomach/FARM.mp4"""'], {}), "(\n 'C:/Users/liangx/Documents/Dunhill Project Data/Si... |
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
data = np.loadtxt("sample.dat")
mean = data.mean()
sigma = data.std()
x = np.linspace(data.min(), data.max(), 100)
y = np.exp(-0.5 * ((x -mean)/sigma)**2)
y = y/(np.sqrt(2.0* np.pi * sigma**2))
plt.hist(data, alpha=0.5, bin... | [
"matplotlib.pyplot.savefig",
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"matplotlib.pyplot.xlabel",
"numpy.exp",
"numpy.loadtxt",
"matplotlib.pyplot.legend"
] | [((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (32, 39), False, 'import matplotlib\n'), ((100, 124), 'numpy.loadtxt', 'np.loadtxt', (['"""sample.dat"""'], {}), "('sample.dat')\n", (110, 124), True, 'import numpy as np\n'), ((214, 254), 'numpy.exp', 'np.exp', (['(-0.5 * ((x - mean) / s... |
import os, sys
sys.path.append(os.path.dirname(os.path.realpath(f'{__file__}/..')))
import pathlib
import numpy as np
from time import sleep
from src.GymEnvs import GiadogEnv, TerrainScene, QuadrupedRobot, GiadogEasyEnv
from src.__env__ import CONTROLLER_LATENCY_STEPS, GRAVITY_VECTOR, \
HISTORIAL_DATA, NON_PRIV... | [
"pathlib.Path",
"matplotlib.pyplot.plot",
"src.simulation.hills",
"src.GymEnvs.QuadrupedRobot",
"os.path.realpath",
"src.GymEnvs.TerrainScene",
"numpy.array",
"numpy.zeros",
"numpy.random.uniform",
"pybullet_utils.bullet_client.BulletClient",
"matplotlib.pyplot.show"
] | [((1048, 1088), 'pybullet_utils.bullet_client.BulletClient', 'bullet_client.BulletClient', (['pybullet.GUI'], {}), '(pybullet.GUI)\n', (1074, 1088), False, 'from pybullet_utils import bullet_client\n'), ((1098, 1199), 'src.GymEnvs.QuadrupedRobot', 'QuadrupedRobot', (['quadruped_urdf', 'client', 'UPDATE_METHODS', 'STATE... |
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from cavsim.base.fluids.base_fluid import BaseFluid
class DummyFluid(BaseFluid):
def __init__(self, one, two, three=5):
super(DummyFluid, self).__init__(1, 2, 3, 4)
self._one = one
self._two = two
self._th... | [
"numpy.testing.assert_almost_equal",
"numpy.testing.assert_allclose",
"cavsim.base.fluids.base_fluid.BaseFluid",
"numpy.asarray"
] | [((1086, 1107), 'cavsim.base.fluids.base_fluid.BaseFluid', 'BaseFluid', (['(1)', '(2)', '(3)', '(4)'], {}), '(1, 2, 3, 4)\n', (1095, 1107), False, 'from cavsim.base.fluids.base_fluid import BaseFluid\n'), ((1935, 1962), 'cavsim.base.fluids.base_fluid.BaseFluid', 'BaseFluid', (['(9)', '(8)', '(7)', '(6)', '(5)', '(4)'],... |
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import itertools
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
import scipy.integrate
from sklearn.metrics import mean_squared_error
from scipy.linalg import svd
from scipy.... | [
"sys.path.insert",
"numpy.sqrt",
"numpy.linalg.pinv",
"numpy.array",
"numpy.cov",
"numpy.arange",
"holoviews.extension",
"numpy.dot",
"loader.query",
"numpy.random.normal",
"loader.convert_dates",
"sklearn.metrics.mean_squared_error",
"loader.load_data",
"scipy.linalg.svd",
"git.Repo",
... | [((515, 536), 'holoviews.extension', 'hv.extension', (['"""bokeh"""'], {}), "('bokeh')\n", (527, 536), True, 'import holoviews as hv\n'), ((567, 613), 'git.Repo', 'git.Repo', (['"""./"""'], {'search_parent_directories': '(True)'}), "('./', search_parent_directories=True)\n", (575, 613), False, 'import git\n'), ((641, 7... |
import cv2 as cv
import numpy as np
import time
import RPi.GPIO as GPIO
import sys
import select
import tracking
import drive
# Frame size
HEIGHT = 240
WIDTH = 320
#Filter
LOWER = np.array([68, 65, 31])
UPPER = np.array([100, 229, 167])
# Start capture
cap = cv.VideoCapture(0)
cap.set(3, WIDTH) # 3 CV_CAP_PROP_FRA... | [
"RPi.GPIO.cleanup",
"select.select",
"drive.backward",
"tracking.distance",
"drive.turn_right",
"time.sleep",
"numpy.array",
"drive.motor_setup",
"cv2.VideoCapture",
"drive.turn_left",
"drive.stop",
"tracking.steering_decision",
"drive.forward"
] | [((183, 205), 'numpy.array', 'np.array', (['[68, 65, 31]'], {}), '([68, 65, 31])\n', (191, 205), True, 'import numpy as np\n'), ((214, 239), 'numpy.array', 'np.array', (['[100, 229, 167]'], {}), '([100, 229, 167])\n', (222, 239), True, 'import numpy as np\n'), ((263, 281), 'cv2.VideoCapture', 'cv.VideoCapture', (['(0)'... |
import dash
import numpy as np
import pandas as pd
import dash_core_components as dcc
import dash_html_components as html
from plotly import tools
from dash.dependencies import Input, Output
from cachetools import cached, TTLCache
import plotly.graph_objs as go
import geojson
import geopandas as gpd
cache = TTLCache(m... | [
"dash_html_components.I",
"geopandas.read_file",
"pandas.read_csv",
"dash.dependencies.Output",
"dash.dependencies.Input",
"cachetools.TTLCache",
"cachetools.cached",
"dash_core_components.Dropdown",
"numpy.around",
"dash_html_components.H1",
"plotly.graph_objs.Figure",
"dash.Dash",
"dash_co... | [((310, 340), 'cachetools.TTLCache', 'TTLCache', ([], {'maxsize': '(100)', 'ttl': '(300)'}), '(maxsize=100, ttl=300)\n', (318, 340), False, 'from cachetools import cached, TTLCache\n'), ((374, 403), 'pandas.read_csv', 'pd.read_csv', (['"""ls_cleaned.csv"""'], {}), "('ls_cleaned.csv')\n", (385, 403), True, 'import panda... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module implements Deep QL with two networks: Q-network and target-network
the DQL uses an MLP Q-network
it is retrained only after 'episodes' iterations
the training uses replay memory
"""
from copy import deepcopy
import numpy as np
import loggin... | [
"DQL.clone.clone_model",
"numpy.amax",
"copy.deepcopy"
] | [((3334, 3363), 'numpy.amax', 'np.amax', (['q_prediction'], {'axis': '(1)'}), '(q_prediction, axis=1)\n', (3341, 3363), True, 'import numpy as np\n'), ((2259, 2279), 'copy.deepcopy', 'deepcopy', (['self.model'], {}), '(self.model)\n', (2267, 2279), False, 'from copy import deepcopy\n'), ((2331, 2354), 'DQL.clone.clone_... |
import pandas as pd
import time
import random
import numpy as np
from datetime import timedelta
from datetime import datetime
import MAUC
import argparse
parser = argparse.ArgumentParser(usage='python3 evalOneSubmission.py',
description=r'''
TADPOLE Evaluation Script:
The program computes the following matrics:
... | [
"numpy.mean",
"numpy.abs",
"MAUC.MAUC",
"numpy.ones",
"pandas.read_csv",
"argparse.ArgumentParser",
"datetime.datetime.strptime",
"numpy.argmax",
"numpy.sum",
"numpy.isnan"
] | [((164, 642), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'usage': '"""python3 evalOneSubmission.py"""', 'description': '"""\n TADPOLE Evaluation Script:\n The program computes the following matrics:\n\n Clinical diagnosis prediction:\n\n 1. Multiclass area under the receiver operating curve (mAUC)\... |
#-------by HYH -------#
import sys
sys.path.append('D:\\Python File\\robot\\P13')
import P13
import numpy as np
x=np.array([7,38,4,23,18])
x2=np.square(x)
x2mu=P13.compMean(x2)
xmu=P13.compMean(x)
xvar=P13.compVariance(x)
print('The Variance of X \t=%s \n'%xvar)
print('E[X^2]-E[X]^2 \t\t=%s \n'%(x2mu-np.square(xmu))) | [
"P13.compVariance",
"P13.compMean",
"numpy.square",
"numpy.array",
"sys.path.append"
] | [((35, 81), 'sys.path.append', 'sys.path.append', (['"""D:\\\\Python File\\\\robot\\\\P13"""'], {}), "('D:\\\\Python File\\\\robot\\\\P13')\n", (50, 81), False, 'import sys\n'), ((114, 142), 'numpy.array', 'np.array', (['[7, 38, 4, 23, 18]'], {}), '([7, 38, 4, 23, 18])\n', (122, 142), True, 'import numpy as np\n'), ((1... |
"""
See also:
https://github.com/danieljtait/jax_xla_adventures/blob/master/pybind11_register_custom_call/test.py
"""
import numpy as np
from jaxlib import xla_client
from . import _signal
for _name, _value in _signal.registrations().items():
xla_client.register_custom_call_target(_name, _value, platform="cpu")
de... | [
"jaxlib.xla_client.register_custom_call_target",
"numpy.frombuffer",
"numpy.dtype"
] | [((247, 316), 'jaxlib.xla_client.register_custom_call_target', 'xla_client.register_custom_call_target', (['_name', '_value'], {'platform': '"""cpu"""'}), "(_name, _value, platform='cpu')\n", (285, 316), False, 'from jaxlib import xla_client\n'), ((579, 594), 'numpy.dtype', 'np.dtype', (['dtype'], {}), '(dtype)\n', (58... |
# 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... | [
"tests.ut.python.utils.mock_net.Net",
"mindspore.dataset.GeneratorDataset",
"mindspore.nn.SoftmaxCrossEntropyWithLogits",
"mindspore.context.set_context",
"mindspore.train.Model",
"mindarmour.privacy.evaluation.MembershipInference",
"numpy.random.randint",
"numpy.random.randn"
] | [((896, 940), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.GRAPH_MODE'}), '(mode=context.GRAPH_MODE)\n', (915, 940), True, 'import mindspore.context as context\n'), ((1549, 1554), 'tests.ut.python.utils.mock_net.Net', 'Net', ([], {}), '()\n', (1552, 1554), False, 'from tests.ut.python.... |
import numpy as np
import os
from os import path as osp
import pybullet as p
import pybullet_data as pb_data
from pybullet_utils import bullet_client
current_file_path = osp.abspath(__file__)
def get_ycb_file_path(object_name: str):
""" Return the abspath of the urdf file given the object name (be aware of the u... | [
"os.path.dirname",
"numpy.array",
"pybullet.getQuaternionFromEuler",
"numpy.random.uniform",
"os.path.abspath"
] | [((172, 193), 'os.path.abspath', 'osp.abspath', (['__file__'], {}), '(__file__)\n', (183, 193), True, 'from os import path as osp\n'), ((442, 472), 'os.path.dirname', 'osp.dirname', (['current_file_path'], {}), '(current_file_path)\n', (453, 472), True, 'from os import path as osp\n'), ((1162, 1209), 'numpy.array', 'np... |
#!/usr/bin/env python3
import numpy as np
from matplotlib import pyplot as plt
import collections
def PolyCoefficients(x, coeffs):
""" Returns a polynomial for ``x`` values for the ``coeffs`` provided.
The coefficients must be in ascending order (``x**0`` to ``x**o``).
"""
o = len(coeffs)
# prin... | [
"matplotlib.pyplot.title",
"numpy.linspace",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((1626, 1636), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1634, 1636), True, 'from matplotlib import pyplot as plt\n'), ((1352, 1379), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(4)', '(3)', 'position'], {}), '(4, 3, position)\n', (1363, 1379), True, 'from matplotlib import pyplot as plt\n'), ((1591,... |
# Demo of a naive cart-pole control algorithm
import gym
import numpy as np
def naive_policy(obsv):
# The cart-pole simulator has four states: x, x_dot, theta, theta_dot
# In the simulator, action = 1 accelerates right, action = 0 accelerates left
theta = obsv[2]
# If the angle is positive (clockwise d... | [
"numpy.max",
"numpy.mean",
"gym.make",
"numpy.min"
] | [((483, 506), 'gym.make', 'gym.make', (['"""CartPole-v0"""'], {}), "('CartPole-v0')\n", (491, 506), False, 'import gym\n'), ((1038, 1053), 'numpy.mean', 'np.mean', (['totals'], {}), '(totals)\n', (1045, 1053), True, 'import numpy as np\n'), ((1067, 1081), 'numpy.min', 'np.min', (['totals'], {}), '(totals)\n', (1073, 10... |
#!/usr/bin/env python3
# -*- CoDing: utf-8 -*-
"""
Created on May 22 2019
Last Update May 22 2019
@author: simonvanvliet
Department of Zoology
University of Britisch Columbia
<EMAIL>
This recreates the data and figure for figure 2
By default data is loaded unless parameters have changes, to rerun model set override_... | [
"mls_general_code.calc_timescale",
"pathlib.Path",
"mls_general_code.set_fig_size_cm",
"matplotlib.cycler",
"joblib.Parallel",
"numpy.nanmean",
"numpy.linspace",
"matplotlib.style.use",
"matplotlib.pyplot.figure",
"matplotlib.rc",
"numpy.vstack",
"matplotlib.pyplot.tight_layout",
"datetime.d... | [((681, 700), 'pathlib.Path', 'Path', (['"""Data_Paper/"""'], {}), "('Data_Paper/')\n", (685, 700), False, 'from pathlib import Path\n'), ((714, 736), 'pathlib.Path', 'Path', (['"""Figures_Paper/"""'], {}), "('Figures_Paper/')\n", (718, 736), False, 'from pathlib import Path\n'), ((1597, 1627), 'mls_general_code.calc_t... |
# encoding: utf-8
from datetime import date, datetime, time
import motor.motor_asyncio
import numpy as np
import pandas as pd
from dateutil.relativedelta import relativedelta
from rqalpha.const import INSTRUMENT_TYPE
from rqalpha.model.instrument import Instrument
from rqalpha.utils.datetime_func import convert_date_t... | [
"dateutil.relativedelta.relativedelta",
"rqalpha.mod.rqalpha_mod_fxdayu_source.data_source.common.CacheMixin.__init__",
"rqalpha.mod.rqalpha_mod_fxdayu_source.utils.asyncio.get_asyncio_event_loop",
"rqalpha.mod.rqalpha_mod_fxdayu_source.utils.converter.DataFrameConverter.empty",
"numpy.searchsorted",
"dat... | [((5985, 6006), 'rqalpha.utils.py2.lru_cache', 'lru_cache', ([], {'maxsize': '(10)'}), '(maxsize=10)\n', (5994, 6006), False, 'from rqalpha.utils.py2 import lru_cache\n'), ((1346, 1369), 'rqalpha.mod.rqalpha_mod_fxdayu_source.share.mongo_handler.MongoHandler', 'MongoHandler', (['mongo_url'], {}), '(mongo_url)\n', (1358... |
import numpy
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import math
from itertools import cycle
SIZE_X = 128
I1 = 128
J1 = 128
H = 1/8##?
U = numpy.zeros((I1,J1))
F = numpy.zeros((I1,J1))
B = numpy.zeros((I1,J1))
for I in range(0,I1):
for J in range(0,J1):
# U[I,J] = 10
# ... | [
"matplotlib.pyplot.imshow",
"numpy.copyto",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.cla",
"math.sqrt",
"math.cos",
"numpy.zeros",
"math.fabs",
"numpy.linalg.norm",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.subplot"
] | [((175, 196), 'numpy.zeros', 'numpy.zeros', (['(I1, J1)'], {}), '((I1, J1))\n', (186, 196), False, 'import numpy\n'), ((200, 221), 'numpy.zeros', 'numpy.zeros', (['(I1, J1)'], {}), '((I1, J1))\n', (211, 221), False, 'import numpy\n'), ((225, 246), 'numpy.zeros', 'numpy.zeros', (['(I1, J1)'], {}), '((I1, J1))\n', (236, ... |
from helita.sim import rh15d
import matplotlib.pyplot as plt
import numpy as np
import os
import warnings # ignore tedious warnings
warnings.filterwarnings("ignore")
##############################################################
def load_rh_data(folder, print_attributes=False):
# reset IPython kernel
tr... | [
"IPython.get_ipython",
"numpy.mean",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"rh_kmean.create_kmean_from_data",
"matplotlib.pyplot.close",
"numpy.array",
"helita.sim.rh15d.Rh15dout",
"numpy.random.randint",
"n... | [((136, 169), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (159, 169), False, 'import warnings\n'), ((609, 631), 'helita.sim.rh15d.Rh15dout', 'rh15d.Rh15dout', (['folder'], {}), '(folder)\n', (623, 631), False, 'from helita.sim import rh15d\n'), ((1312, 1324), 'os.walk',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.