code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import glob import numpy as np import os def calc_noise_gradient_loss(net_type, target_noise_folder, faig_folder, save_faig_maskdenoisefilter_noise_loss_txt, save_faig_maskdeblurfilter_noise_loss_txt, ig_folder, save_ig_maskdenoisefilter_noise_loss_txt, save_i...
[ "numpy.load", "numpy.savetxt", "numpy.mean", "numpy.array", "os.path.join" ]
[((8812, 8854), 'numpy.array', 'np.array', (['faig_maskdeblurfilter_noise_loss'], {}), '(faig_maskdeblurfilter_noise_loss)\n', (8820, 8854), True, 'import numpy as np\n'), ((8895, 8938), 'numpy.array', 'np.array', (['faig_maskdenoisefilter_noise_loss'], {}), '(faig_maskdenoisefilter_noise_loss)\n', (8903, 8938), True, ...
"""Data-specific colormaps""" from itertools import cycle import logging from math import ceil from numbers import Real # colormath starts out at 0; needs to be set before init logger = logging.getLogger('colormath.color_conversions') if logger.level == 0: # otherwise it was probably set by user (DEBUG=10) logger...
[ "matplotlib.colors.LinearSegmentedColormap.from_list", "matplotlib.colors.to_rgba", "colormath.color_objects.LCHabColor", "matplotlib.colors.LinearSegmentedColormap", "matplotlib.cm.get_cmap", "math.ceil", "numpy.asarray", "matplotlib.colors.to_rgb", "numpy.any", "colormath.color_conversions.conve...
[((187, 235), 'logging.getLogger', 'logging.getLogger', (['"""colormath.color_conversions"""'], {}), "('colormath.color_conversions')\n", (204, 235), False, 'import logging\n'), ((1025, 1065), 'colormath.color_objects.LCHabColor', 'LCHabColor', (['lightness', 'chroma', '(hue * 360)'], {}), '(lightness, chroma, hue * 36...
import numpy as np import matplotlib.pyplot as plt import pandas as pd from utils import parse if __name__ == '__main__': config = parse() file_path_list = [] for i in range(config.num_of_clients): file_path = "clients/" + str(i) + "/log.csv" file_path_list.append(file_path) client_c...
[ "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "pandas.read_csv", "matplotlib.pyplot.legend", "matplotlib.pyplot.figure", "numpy.array", "utils.parse" ]
[((138, 145), 'utils.parse', 'parse', ([], {}), '()\n', (143, 145), False, 'from utils import parse\n'), ((339, 363), 'matplotlib.pyplot.figure', 'plt.figure', (['"""Loss of Gs"""'], {}), "('Loss of Gs')\n", (349, 363), True, 'import matplotlib.pyplot as plt\n'), ((704, 733), 'matplotlib.pyplot.legend', 'plt.legend', (...
# coding: utf-8 # ## Step03_TemplateMatching # # テストサンプルを1枚ずつ読み出してマッチングする # 混同行列と各クラスの認識率を表示する # In[ ]: from skimage import io import numpy as np # In[ ]: TrainingSampleNum = 2000 # 学習サンプル総数 TestSampleNum = 10000 # テストサンプル総数 ClassNum = 10 # クラス数(今回は10) ImageSize = 28 # 画像サイズ(今回は縦横ともに28) TrainingDataFile = '...
[ "numpy.fabs", "numpy.zeros", "numpy.sum", "skimage.io.imread" ]
[((541, 584), 'numpy.zeros', 'np.zeros', (['TrainingSampleNum'], {'dtype': 'np.uint8'}), '(TrainingSampleNum, dtype=np.uint8)\n', (549, 584), True, 'import numpy as np\n'), ((601, 668), 'numpy.zeros', 'np.zeros', (['(TrainingSampleNum, ImageSize, ImageSize)'], {'dtype': 'np.uint8'}), '((TrainingSampleNum, ImageSize, Im...
import concurrent.futures import copy import json import os import random from pathlib import Path import cv2 import numpy as np import pandas as pd IMAGE_WIDTH = 256 IMAGE_HEIGHT = 256 THREAD_COUNT = 32 loaded_ids = [] loaded_ids_target = [] index_csv = {} IMAGE_EXTS_LIST = ['jpg', 'png'] DATA_FORMATS_SPECIAL = [ '...
[ "copy.deepcopy", "json.loads", "cv2.cvtColor", "pandas.read_csv", "random.shuffle", "os.walk", "cv2.blur", "cv2.imread", "pathlib.Path", "numpy.array", "cv2.Sobel", "cv2.resize" ]
[((3523, 3560), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (3535, 3560), False, 'import cv2\n'), ((3576, 3605), 'cv2.blur', 'cv2.blur', (['grey_img', '(3, 3)', '(0)'], {}), '(grey_img, (3, 3), 0)\n', (3584, 3605), False, 'import cv2\n'), ((3623, 3686), 'cv2.Sobel...
# Copyright 2018 The Kubeflow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
[ "keras.optimizers.rmsprop", "argparse.ArgumentParser", "os.makedirs", "keras.layers.Activation", "os.path.isdir", "os.path.dirname", "pathlib.Path", "keras.models.model_from_json", "numpy.loadtxt", "keras.utils.to_categorical" ]
[((692, 765), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train classifier model using Keras"""'}), "(description='Train classifier model using Keras')\n", (715, 765), False, 'import argparse\n'), ((2259, 2302), 'numpy.loadtxt', 'np.loadtxt', (['args.training_set_features_path'], {}),...
import numpy as np from math import sqrt from sklearn.metrics import pairwise, auc, precision_recall_curve from scipy.special import betainc from scipy import stats def cosine_similarity(a,b): a = np.array(a) b = np.array(b) return pairwise.cosine_similarity([a,b])[0,1] def spearman(y,f): rs = stats.sp...
[ "numpy.tril_indices", "sklearn.metrics.pairwise.cosine_similarity", "numpy.corrcoef", "scipy.stats.spearmanr", "scipy.special.betainc", "numpy.zeros", "numpy.ones", "numpy.triu_indices", "sklearn.metrics.precision_recall_curve", "sklearn.metrics.auc", "numpy.diag_indices", "numpy.array" ]
[((201, 212), 'numpy.array', 'np.array', (['a'], {}), '(a)\n', (209, 212), True, 'import numpy as np\n'), ((221, 232), 'numpy.array', 'np.array', (['b'], {}), '(b)\n', (229, 232), True, 'import numpy as np\n'), ((470, 498), 'sklearn.metrics.precision_recall_curve', 'precision_recall_curve', (['y', 'f'], {}), '(y, f)\n'...
# Test reading hdf5 file that I created import numpy as np import Starfish from Starfish.grid_tools import HDF5Interface myHDF5 = HDF5Interface() wl = myHDF5.wl flux = myHDF5.load_flux(np.array([6100, 4.5, 0.0]))
[ "Starfish.grid_tools.HDF5Interface", "numpy.array" ]
[((132, 147), 'Starfish.grid_tools.HDF5Interface', 'HDF5Interface', ([], {}), '()\n', (145, 147), False, 'from Starfish.grid_tools import HDF5Interface\n'), ((187, 213), 'numpy.array', 'np.array', (['[6100, 4.5, 0.0]'], {}), '([6100, 4.5, 0.0])\n', (195, 213), True, 'import numpy as np\n')]
# encoding: UTF-8 import os, unittest, numpy from phyutil.phylib.fieldmap import fmdata from phyutil.phylib.fieldmap.impact import lrfdata, nrfdata DIRNAME = os.path.dirname(__file__) TESTA_E_DAT = os.path.join(DIRNAME, "testA_E.dat") class NRFDataTest(unittest.TestCase): COEFS = numpy.array([ ...
[ "phyutil.phylib.fieldmap.impact.lrfdata.convertFromFMData", "os.path.dirname", "phyutil.phylib.fieldmap.fmdata.readFromDatFile", "phyutil.phylib.fieldmap.impact.nrfdata.convertFromLRFData", "numpy.imag", "numpy.array", "numpy.real", "os.path.join" ]
[((163, 188), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (178, 188), False, 'import os, unittest, numpy\n'), ((204, 240), 'os.path.join', 'os.path.join', (['DIRNAME', '"""testA_E.dat"""'], {}), "(DIRNAME, 'testA_E.dat')\n", (216, 240), False, 'import os, unittest, numpy\n'), ((295, 1266),...
# -*- coding: utf-8 -*- """ An implementation of the policyValueNet in Tensorflow Tested in Tensorflow 1.4 and 1.5 @author: <NAME> """ import numpy as np import tensorflow as tf from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm from game import INPUT_STATE_CHANNEL_SIZE class PolicyValueNet...
[ "tensorflow.trainable_variables", "tensorflow.reshape", "tensorflow.multiply", "numpy.exp", "tensorflow.nn.relu", "tensorflow.variable_scope", "tensorflow.placeholder", "tensorflow.exp", "numpy.reshape", "tensorflow.losses.mean_squared_error", "tensorflow.train.Saver", "tensorflow.global_varia...
[((514, 524), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (522, 524), True, 'import tensorflow as tf\n'), ((8356, 8377), 'numpy.exp', 'np.exp', (['log_act_probs'], {}), '(log_act_probs)\n', (8362, 8377), True, 'import numpy as np\n'), ((9125, 9158), 'numpy.reshape', 'np.reshape', (['winner_batch', '(-1, 1)'], {})...
import gmshnics.contouring as contour import gmshnics.fractals as fractal import numpy as np class Shape: '''Gmsh shape for nested model''' tol = 1E-10 def __init__(self, as_one_surface=False): self.as_one_surface = as_one_surface self._com = None self._com_surfaces = None ...
[ "numpy.sin", "gmsh.fltk.run", "numpy.sum", "gmshnics.fractals.koch_snowflake", "gmshnics.contouring.wind_number_gen", "numpy.cross", "numpy.min", "numpy.mean", "numpy.array", "gmsh.fltk.initialize", "numpy.row_stack", "numpy.fromiter", "numpy.max", "numpy.linspace", "numpy.linalg.norm", ...
[((7251, 7268), 'gmsh.initialize', 'gmsh.initialize', ([], {}), '()\n', (7266, 7268), False, 'import gmsh\n'), ((7491, 7513), 'gmsh.fltk.initialize', 'gmsh.fltk.initialize', ([], {}), '()\n', (7511, 7513), False, 'import gmsh\n'), ((7518, 7533), 'gmsh.fltk.run', 'gmsh.fltk.run', ([], {}), '()\n', (7531, 7533), False, '...
import numpy as np def pred_next(time_steps: int, model, start_series, series_len=64): accumulator = [] # start_series::(1, series_len, 1) cur_out = model.predict(start_series).flatten()[0] accumulator.append(cur_out) i = 0 while i < time_steps-1: if i==0: next_serie...
[ "keras.models.load_model", "keras.layers.LSTM", "numpy.zeros", "keras.layers.Dense", "keras.models.Sequential" ]
[((791, 803), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (801, 803), False, 'from keras.models import Sequential\n'), ((984, 1005), 'keras.models.load_model', 'load_model', (['"""temp.h5"""'], {}), "('temp.h5')\n", (994, 1005), False, 'from keras.models import load_model\n'), ((818, 871), 'keras.layers....
'''One sense level of the HSA agent.''' # python from copy import copy from time import time # scipy from numpy.linalg import norm from numpy.random import choice, rand, randint, uniform from numpy import any, argmax, argmin, argsort, array, concatenate, eye, exp, hstack, linspace, \ logical_and, isinf, meshgrid, on...
[ "openravepy.matrixFromAxisAngle", "copy.copy", "numpy.zeros", "numpy.ones", "rl_agent_level.RlAgentLevel.__init__", "numpy.array", "numpy.linspace", "hand_descriptor.HandDescriptor", "numpy.concatenate" ]
[((726, 768), 'rl_agent_level.RlAgentLevel.__init__', 'RlAgentLevel.__init__', (['self', 'level', 'params'], {}), '(self, level, params)\n', (747, 768), False, 'from rl_agent_level import RlAgentLevel\n'), ((1977, 2031), 'numpy.concatenate', 'concatenate', (['(targImage, handImage, timeImage)'], {'axis': '(2)'}), '((ta...
from random import choice import numpy as np from .IndexAlgorithm import IndexAlgorithm class TS(IndexAlgorithm): """ The Thompson (Bayesian) index algorithm for bounded rewards. Ref: Analysis of Thompson sampling for the multi-armed bandit problem. <NAME>, <NAME> """ def __init__(self, nb_a...
[ "numpy.amax" ]
[((773, 787), 'numpy.amax', 'np.amax', (['index'], {}), '(index)\n', (780, 787), True, 'import numpy as np\n'), ((1306, 1320), 'numpy.amax', 'np.amax', (['index'], {}), '(index)\n', (1313, 1320), True, 'import numpy as np\n')]
""" MIT License Copyright (c) 2020 <NAME> Copyright (c) 2021 <NAME> 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 r...
[ "core.color.Color4f", "numpy.array", "vtk.vtkPolyDataMapper" ]
[((1378, 1394), 'core.color.Color4f', 'Color4f', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (1385, 1394), False, 'from core.color import Color4f\n'), ((1440, 1456), 'core.color.Color4f', 'Color4f', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (1447, 1456), False, 'from core.color import Color4f\n'), ((1510, 1533), 'vtk...
import os import stat import shutil import unittest import tempfile import numpy import logging logger = logging.getLogger() from articlass.model import ModelConfiguration, ClassifierModel, pred2str class TestModelCfg(unittest.TestCase): """Test the model config class.""" def setUp(self): self.dirpa...
[ "os.chmod", "articlass.model.pred2str", "os.path.join", "articlass.model.ModelConfiguration", "tempfile.mkdtemp", "numpy.array", "shutil.rmtree", "articlass.model.ClassifierModel", "logging.getLogger" ]
[((106, 125), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (123, 125), False, 'import logging\n'), ((325, 343), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (341, 343), False, 'import tempfile\n'), ((366, 386), 'articlass.model.ModelConfiguration', 'ModelConfiguration', ([], {}), '()\n', (38...
import sys, os import numpy as np import signal def handler(signum, frame): exit() # Set the signal handler signal.signal(signal.SIGINT, handler) pykin_path = os.path.abspath(os.path.dirname(__file__)+"../" ) sys.path.append(pykin_path) from pykin.kinematics.transform import Transform from pykin.kinematics.kinem...
[ "sys.path.append", "pykin.utils.transform_utils.compute_pose_error", "os.path.dirname", "pykin.kinematics.transform.Transform", "numpy.eye", "signal.signal" ]
[((113, 150), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'handler'], {}), '(signal.SIGINT, handler)\n', (126, 150), False, 'import signal\n'), ((215, 242), 'sys.path.append', 'sys.path.append', (['pykin_path'], {}), '(pykin_path)\n', (230, 242), False, 'import sys, os\n'), ((181, 206), 'os.path.dirname', 'os....
"""Test the Fourier transformation of Green's functions.""" import numpy as np import pytest import hypothesis.strategies as st from hypothesis import given, assume from hypothesis.extra.numpy import arrays from hypothesis_gufunc.gufunc import gufunc_args from .context import gftool as gt from .context import pole ...
[ "numpy.allclose", "pytest.fixture", "hypothesis.strategies.floats", "numpy.isclose", "pytest.mark.skipif", "numpy.arange", "numpy.exp", "numpy.linspace", "hypothesis.strategies.complex_numbers", "pytest.mark.filterwarnings", "hypothesis.assume" ]
[((3744, 3806), 'pytest.mark.filterwarnings', 'pytest.mark.filterwarnings', (['"""ignore:(overflow):RuntimeWarning"""'], {}), "('ignore:(overflow):RuntimeWarning')\n", (3770, 3806), False, 'import pytest\n'), ((4390, 4452), 'pytest.mark.filterwarnings', 'pytest.mark.filterwarnings', (['"""ignore:(overflow):RuntimeWarni...
import numpy as np import mdtraj as md import matplotlib.pyplot as plt from ramtools.structure.calc_number_density import calc_number_density def number_density(): """Calculate number density function of water on graphene surface""" trj = md.load('nvt.trr', top='nvt.gro')[5000:] gph_trj = trj.atom_slice(t...
[ "matplotlib.pyplot.xlim", "numpy.abs", "numpy.asarray", "mdtraj.load", "matplotlib.pyplot.text", "numpy.max", "numpy.where", "ramtools.structure.calc_number_density.calc_number_density", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots", "matplotlib.pyplot.sa...
[((369, 397), 'numpy.max', 'np.max', (['gph_trj.xyz[:, :, 2]'], {}), '(gph_trj.xyz[:, :, 2])\n', (375, 397), True, 'import numpy as np\n'), ((547, 601), 'ramtools.structure.calc_number_density.calc_number_density', 'calc_number_density', (['trj', 'area', 'dim', 'box_range', 'n_bins'], {}), '(trj, area, dim, box_range, ...
import numpy as np import _transformations as trans from abc import ABCMeta, abstractmethod from ratcave.utils.observers import IterObservable class Coordinates(IterObservable): def __init__(self, *args, **kwargs): super(Coordinates, self).__init__(**kwargs) self._array = np.array(args, dtype=np....
[ "numpy.radians", "_transformations.quaternion_from_matrix", "_transformations.quaternion_matrix", "numpy.degrees", "_transformations.translation_matrix", "_transformations.unit_vector", "numpy.cross", "numpy.identity", "_transformations.quaternion_from_euler", "numpy.array", "_transformations.eu...
[((7527, 7603), 'numpy.array', 'np.array', (['[[0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]]'], {}), '([[0, -vec[2], vec[1]], [vec[2], 0, -vec[0]], [-vec[1], vec[0], 0]])\n', (7535, 7603), True, 'import numpy as np\n'), ((8011, 8025), 'numpy.cross', 'np.cross', (['a', 'b'], {}), '(a, b)\n', (8019, 8...
import numpy as np from itertools import islice x = np.arange(0,100) def split_every(n, iterable): i = iter(iterable) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n)) for chunk in split_every(5, x): print(chunk)
[ "numpy.arange", "itertools.islice" ]
[((55, 72), 'numpy.arange', 'np.arange', (['(0)', '(100)'], {}), '(0, 100)\n', (64, 72), True, 'import numpy as np\n'), ((142, 154), 'itertools.islice', 'islice', (['i', 'n'], {}), '(i, n)\n', (148, 154), False, 'from itertools import islice\n'), ((214, 226), 'itertools.islice', 'islice', (['i', 'n'], {}), '(i, n)\n', ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import gc import visdom import os import time from os import listdir from PIL import Image from datetime import datetime import torch import torch.nn as nn import torch.optim as optim from t...
[ "gc.disable", "argparse.ArgumentParser", "visdom.Visdom", "torch.cat", "gc.collect", "numpy.arange", "torchvision.transforms.Normalize", "torch.utils.data.DataLoader", "os.path.exists", "torch.unbind", "datetime.datetime.now", "numpy.random.shuffle", "torch.mean", "numpy.ceil", "torch.au...
[((560, 585), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (583, 585), False, 'import argparse\n'), ((3952, 3964), 'gc.disable', 'gc.disable', ([], {}), '()\n', (3962, 3964), False, 'import gc\n'), ((4450, 4537), 'torch.utils.data.DataLoader', 'DataLoader', (['dm'], {'batch_size': 'batch_size...
import copy from typing import Callable, List, Literal, Optional, Tuple, Union, overload import numpy import openmm import openmm.app from openff.toolkit.topology import Topology from openmm import unit SystemGenerator = Callable[ [Topology, unit.Quantity, Literal["solvent-a", "solvent-b"]], openmm.System ] Open...
[ "openmm.Vec3", "copy.deepcopy", "openmm.LocalEnergyMinimizer.minimize", "openmm.LangevinIntegrator", "numpy.array", "openmm.Platform.getPlatformByName", "openmm.MonteCarloBarostat" ]
[((2117, 2138), 'copy.deepcopy', 'copy.deepcopy', (['system'], {}), '(system)\n', (2130, 2138), False, 'import copy\n'), ((2696, 2765), 'openmm.LangevinIntegrator', 'openmm.LangevinIntegrator', (['temperature', 'thermostat_friction', 'timestep'], {}), '(temperature, thermostat_friction, timestep)\n', (2721, 2765), Fals...
#!/usr/bin/env python # -*- coding: utf-8 -*- """AFN for time series from the Lorenz attractor. E1 saturates near an embedding dimension of 3. E2 != 1 at many values of d. Thus the series is definitely deterministic. The plot matches Fig. 3 of Cao (1997) rather nicely. """ from nolitsa import data, dimension impo...
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "nolitsa.data.lorenz", "matplotlib.pyplot.legend", "numpy.arange", "nolitsa.dimension.afn", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ]
[((436, 456), 'numpy.arange', 'np.arange', (['(1)', '(10 + 2)'], {}), '(1, 10 + 2)\n', (445, 456), True, 'import numpy as np\n'), ((465, 508), 'nolitsa.dimension.afn', 'dimension.afn', (['x'], {'tau': '(5)', 'dim': 'dim', 'window': '(20)'}), '(x, tau=5, dim=dim, window=20)\n', (478, 508), False, 'from nolitsa import da...
import logging logger = logging.getLogger(__name__) import numpy as np from centrosome.mode import mode import unittest class TestMode(unittest.TestCase): def test_00_00_empty(self): self.assertEqual(len(mode(np.zeros(0))), 0) def test_01_01_single_mode(self): result = mode([1, 1, 2]) ...
[ "numpy.zeros", "centrosome.mode.mode", "logging.getLogger", "timeit.timeit" ]
[((24, 51), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (41, 51), False, 'import logging\n'), ((304, 319), 'centrosome.mode.mode', 'mode', (['[1, 1, 2]'], {}), '([1, 1, 2])\n', (308, 319), False, 'from centrosome.mode import mode\n'), ((462, 483), 'centrosome.mode.mode', 'mode', (['[1,...
import numpy as np # Extract data from prediction file def get_labeled_im(pred_f, maxx, maxy): ''' Using the x.max and y.max from the color- file to populate the til and nec matrices. It is more reliable than doing so by using the prediction- file because there are some tiles that got skipped when doi...
[ "numpy.zeros", "numpy.round", "numpy.loadtxt", "numpy.unique" ]
[((696, 741), 'numpy.round', 'np.round', (['((x + patch_size / 2.0) / patch_size)'], {}), '((x + patch_size / 2.0) / patch_size)\n', (704, 741), True, 'import numpy as np\n'), ((750, 795), 'numpy.round', 'np.round', (['((y + patch_size / 2.0) / patch_size)'], {}), '((y + patch_size / 2.0) / patch_size)\n', (758, 795), ...
import numpy as np import torch import torch.nn as nn from network_tools import scale_tensor """ The MS-Net A Computationally Efficient Multiscale Neural Network The code to generate each individual conv model was modified from: https://github.com/tamarott/SinGAN """ def get_trainable_models(s...
[ "torch.nn.Parameter", "torch.ones", "network_tools.scale_tensor", "torch.nn.Sequential", "torch.nn.Conv3d", "torch.load", "torch.cat", "torch.save", "torch.nn.CELU", "numpy.arange", "torch.nn.InstanceNorm3d", "torch.is_tensor", "torch.set_grad_enabled", "torch.no_grad" ]
[((2193, 2208), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (2206, 2208), True, 'import torch.nn as nn\n'), ((6987, 7061), 'torch.save', 'torch.save', (['self.models', 'f"""savedModels/{self.net_name}/{self.net_name}.pt"""'], {}), "(self.models, f'savedModels/{self.net_name}/{self.net_name}.pt')\n", (6997...
from __future__ import print_function import sys import cv2 import h5py import numpy as np def convert_labels_to_probs(input_filename,output_filename,kernel_size=(11,11),kernel_sigma=3.0, display=True): # Load labels h5_input_file = h5py.File(input_filename,'r') frame_array = np.array(h5_input_file['frame...
[ "cv2.GaussianBlur", "h5py.File", "cv2.max", "cv2.waitKey", "numpy.zeros", "numpy.array", "cv2.imshow" ]
[((243, 273), 'h5py.File', 'h5py.File', (['input_filename', '"""r"""'], {}), "(input_filename, 'r')\n", (252, 273), False, 'import h5py\n'), ((291, 323), 'numpy.array', 'np.array', (["h5_input_file['frame']"], {}), "(h5_input_file['frame'])\n", (299, 323), True, 'import numpy as np\n'), ((342, 374), 'numpy.array', 'np....
#encoding=utf-8 import os import sys import shutil import random import argparse import numpy as np import random as rn from scipy import * import tensorflow as tf from keras.models import Model from keras import backend as K from keras.regularizers import l2 import keras.callbacks as callbacks from keras.models impo...
[ "keras.optimizers.rmsprop", "os.remove", "numpy.sum", "argparse.ArgumentParser", "numpy.argmax", "keras.callbacks.LearningRateScheduler", "os.path.exists", "numpy.max", "shutil.copyfile", "numpy.save", "keras.callbacks.ModelCheckpoint", "os.rename", "tensorflow.config.experimental.set_memory...
[((1000, 1063), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', ([], {'device_type': '"""GPU"""'}), "(device_type='GPU')\n", (1044, 1063), True, 'import tensorflow as tf\n'), ((1085, 1136), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimenta...
import numpy as np import cvxpy as cp from scipy import sparse def get_summers(L): """ Returns matrices that, when applied to sum the rows and columns of a sparse matrix L. """ assert isinstance( L, sparse.csr.csr_matrix), "L must be in CSR format. Use L.tocsr()." rows, cols = L.nonze...
[ "scipy.sparse.diags", "scipy.sparse.lil_matrix", "numpy.arange", "cvxpy.Variable", "cvxpy.Minimize" ]
[((386, 422), 'scipy.sparse.lil_matrix', 'sparse.lil_matrix', (['(n, nliabilities)'], {}), '((n, nliabilities))\n', (403, 422), False, 'from scipy import sparse\n'), ((437, 473), 'scipy.sparse.lil_matrix', 'sparse.lil_matrix', (['(n, nliabilities)'], {}), '((n, nliabilities))\n', (454, 473), False, 'from scipy import s...
""" Specifications: Videofile - video.mp4 Properties - Video: 25 fps, 160x160 RGB frames, Mouth approx. in center, face size should be comparable to frame size Audio: Mono audio, 16000 Hz sample rate Targetfile - video.txt Content - Text: THIS SENTENCE IS ONLY FOR ...
[ "data.utils.prepare_main_input", "utils.decoders.ctc_search_decode", "numpy.random.seed", "torch.manual_seed", "torch.load", "models.visual_frontend.VisualFrontend", "utils.decoders.ctc_greedy_decode", "torch.cuda.is_available", "torch.device", "paho.mqtt.client.Client", "torch.no_grad", "mode...
[((1370, 1398), 'numpy.random.seed', 'np.random.seed', (["args['SEED']"], {}), "(args['SEED'])\n", (1384, 1398), True, 'import numpy as np\n'), ((1399, 1430), 'torch.manual_seed', 'torch.manual_seed', (["args['SEED']"], {}), "(args['SEED'])\n", (1416, 1430), False, 'import torch\n'), ((1446, 1471), 'torch.cuda.is_avail...
# from https://stackoverflow.com/questions/5524179/how-to-detect-motion-between-two-pil-images-wxpython-webcam-integration-exampl import math, sys, numpy as np import PIL.Image, PIL.ImageChops sys.modules["Image"] = PIL.Image sys.modules["ImageChops"] = PIL.ImageChops #from scipy.misc import imread #from scipy...
[ "numpy.log2", "math.log", "numpy.histogramdd", "numpy.sum" ]
[((2437, 2493), 'numpy.histogramdd', 'np.histogramdd', (['a'], {'bins': '((16,) * 3)', 'range': '(((0, 256),) * 3)'}), '(a, bins=(16,) * 3, range=((0, 256),) * 3)\n', (2451, 2493), True, 'import math, sys, numpy as np\n'), ((2506, 2515), 'numpy.sum', 'np.sum', (['h'], {}), '(h)\n', (2512, 2515), True, 'import math, sys...
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F import os class geometricMeasures(): ## Class to measure geometric properties of the functions def __init__(self, info_dict, geom_loader): self.inp_dim = info_dict['inp_dim'] self.ou...
[ "torch.flatten", "os.mkdir", "torch.nn.MSELoss", "numpy.zeros", "numpy.transpose", "torch.nn.CrossEntropyLoss", "torch.nn.functional.softmax", "numpy.max", "numpy.linalg.svd", "numpy.matmul", "torch.zeros", "os.path.join", "torch.clone" ]
[((700, 726), 'os.mkdir', 'os.mkdir', (['self.folder_name'], {}), '(self.folder_name)\n', (708, 726), False, 'import os\n'), ((1976, 2010), 'numpy.matmul', 'np.matmul', (['W', 'all_weights_matr[-1]'], {}), '(W, all_weights_matr[-1])\n', (1985, 2010), True, 'import numpy as np\n'), ((2026, 2041), 'numpy.transpose', 'np....
# -*- coding: utf-8 -*- """ Created on Thu Nov 29 11:22:02 2018 @author: thiagoalmeida """ import numpy as np from TabelaGaussLegendre import TabelaGaussLegendre from metodos_numericos.LU import LU from metodos_numericos.Gauss import Gauss from metodos_numericos.Thomas import Thomas class ElementosFinitos: ...
[ "metodos_numericos.LU.LU", "numpy.zeros", "metodos_numericos.Thomas.Thomas", "TabelaGaussLegendre.TabelaGaussLegendre" ]
[((1234, 1289), 'numpy.zeros', 'np.zeros', (['(self.pontos_elementos,)'], {'dtype': 'self.dataType'}), '((self.pontos_elementos,), dtype=self.dataType)\n', (1242, 1289), True, 'import numpy as np\n'), ((3287, 3342), 'numpy.zeros', 'np.zeros', (['(self.pontos_polinomio,)'], {'dtype': 'self.dataType'}), '((self.pontos_po...
import os import matplotlib.pyplot as plt import numpy as np import pints import pints.io import pints.plot from nottingham_covid_modelling import MODULE_DIR def plot_figure6A(p, data, filename, plot=False): import matplotlib as mpl label_size = 24 mpl.rcParams['xtick.labelsize'] = label_size mpl.rcP...
[ "pints.plot.pairwise", "matplotlib.pyplot.show", "pints.io.load_samples", "numpy.array", "os.path.join", "matplotlib.pyplot.savefig" ]
[((426, 472), 'os.path.join', 'os.path.join', (['MODULE_DIR', '"""out-mcmc"""', 'filename'], {}), "(MODULE_DIR, 'out-mcmc', filename)\n", (438, 472), False, 'import os\n'), ((486, 533), 'pints.io.load_samples', 'pints.io.load_samples', (["(saveas + '-chain.csv')", '(3)'], {}), "(saveas + '-chain.csv', 3)\n", (507, 533)...
# -*- coding: utf-8 -*- """ Created on Sun Mar 31 16:39:41 2019 @author: kuangen """ import sys import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, 'models')) sys.path.append(os.path.join(BASE_DIR, 'utils')) sys.path.append(os.path.join(BASE_...
[ "sys.path.append", "os.path.abspath", "matplotlib.pyplot.show", "os.makedirs", "numpy.copy", "PlotClass.PlotClass.subplot_color_points", "os.path.exists", "datetime.datetime.now", "FileIO.FileIO.load_obj_file", "matplotlib.pyplot.figure", "numpy.array", "os.path.join", "matplotlib.pyplot.sav...
[((161, 186), 'sys.path.append', 'sys.path.append', (['BASE_DIR'], {}), '(BASE_DIR)\n', (176, 186), False, 'import sys\n'), ((569, 615), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(fig_size[0], fig_size[1])'}), '(figsize=(fig_size[0], fig_size[1]))\n', (579, 615), True, 'from matplotlib import pyplot a...
from tensorflow.keras.preprocessing.image import img_to_array from imutils import paths import numpy as np import argparse import cv2 import os ap = argparse.ArgumentParser() ap.add_argument("-tr", "--train", required=True, help="path to the trianing data") ap.add_argument("-te", "--test", required=True, help="path ...
[ "imutils.paths.list_images", "numpy.save", "numpy.uint8", "argparse.ArgumentParser", "cv2.cvtColor", "tensorflow.keras.preprocessing.image.img_to_array", "cv2.imread" ]
[((150, 175), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (173, 175), False, 'import argparse\n'), ((1704, 1742), 'numpy.save', 'np.save', (["args['train_arr']", 'train_data'], {}), "(args['train_arr'], train_data)\n", (1711, 1742), True, 'import numpy as np\n'), ((1743, 1785), 'numpy.save',...
""" This file contains constants and functions containing purely mathematical information / methods used in the package. """ import numpy as np import random import uncertainties from typing import Union def angle2rad(value): """ Interpret a unit of given angle value and return this value in radians. Val...
[ "numpy.arctan2", "numpy.sum", "numpy.allclose", "numpy.argsort", "numpy.sin", "numpy.arange", "numpy.linalg.norm", "numpy.interp", "numpy.cumsum", "random.seed", "numpy.arccos", "numpy.ones_like", "numpy.cross", "random.random", "numpy.cos", "numpy.vstack", "numpy.flip", "numpy.any...
[((1723, 1739), 'numpy.arccos', 'np.arccos', (['(z / r)'], {}), '(z / r)\n', (1732, 1739), True, 'import numpy as np\n'), ((1748, 1764), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (1758, 1764), True, 'import numpy as np\n'), ((1776, 1795), 'numpy.array', 'np.array', (['[r, p, a]'], {}), '([r, p, a])\n...
from abc import ABC, abstractmethod from collections import OrderedDict import copy import random import re import sys import numpy as np from mesa import Agent from sklearn.metrics.pairwise import cosine_similarity class SnetAgent(Agent, ABC): def __init__(self, unique_id, model, message, parameters): #...
[ "numpy.random.uniform", "copy.deepcopy", "sklearn.metrics.pairwise.cosine_similarity", "random.uniform", "numpy.asarray", "numpy.array", "collections.OrderedDict", "re.compile" ]
[((1994, 2036), 're.compile', 're.compile', (['"""^f\\\\d+\\\\.\\\\d+_\\\\d+_\\\\d+_\\\\d+"""'], {}), "('^f\\\\d+\\\\.\\\\d+_\\\\d+_\\\\d+_\\\\d+')\n", (2004, 2036), False, 'import re\n'), ((2065, 2096), 're.compile', 're.compile', (['"""^([a-zA-Z0-9]+)_?"""'], {}), "('^([a-zA-Z0-9]+)_?')\n", (2075, 2096), False, 'impo...
import numpy as np from scipy.optimize import minimize, Bounds import matplotlib.pyplot as plt # NMF, assuming each neuron is just a scaled version of a global signal class GlobalActivityEstimator: def __init__(self, data): self.nCell, self.nTrial, self.nTime = data.shape self.dataFlat = data.res...
[ "numpy.full", "numpy.random.uniform", "scipy.optimize.minimize", "numpy.outer", "matplotlib.pyplot.show", "numpy.zeros", "numpy.hstack", "numpy.min", "numpy.histogram", "matplotlib.pyplot.subplots" ]
[((390, 411), 'numpy.min', 'np.min', (['self.dataFlat'], {}), '(self.dataFlat)\n', (396, 411), True, 'import numpy as np\n'), ((574, 591), 'numpy.hstack', 'np.hstack', (['[a, b]'], {}), '([a, b])\n', (583, 591), True, 'import numpy as np\n'), ((1102, 1138), 'numpy.random.uniform', 'np.random.uniform', (['(1)', '(5)', '...
import numpy as np import pickle from konlpy.tag import Okt from scipy.sparse import lil_matrix from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import Rando...
[ "pickle.dump", "numpy.sum", "sklearn.naive_bayes.MultinomialNB", "sklearn.linear_model.SGDClassifier", "numpy.log", "numpy.zeros", "sklearn.tree.DecisionTreeClassifier", "numpy.mean", "numpy.array", "numpy.exp", "numpy.dot", "konlpy.tag.Okt" ]
[((396, 401), 'konlpy.tag.Okt', 'Okt', ([], {}), '()\n', (399, 401), False, 'from konlpy.tag import Okt\n'), ((3424, 3439), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {}), '()\n', (3437, 3439), False, 'from sklearn.naive_bayes import MultinomialNB\n'), ((3502, 3581), 'sklearn.linear_model.SGDClassifier'...
import tensorflow as tf import tensorflow_probability as tfp import numpy as np from collections import OrderedDict def create_network(num_inputs, num_outputs, num_layers, num_hidden_units, activation): layers = [] for i in range(num_layers): layers.append(tf.keras.layers.Dense(num...
[ "tensorflow.ones", "tensorflow.keras.layers.Dense", "tensorflow.convert_to_tensor", "tensorflow_probability.distributions.Normal", "numpy.reshape", "tensorflow.keras.models.Sequential", "tensorflow.math.abs" ]
[((428, 462), 'tensorflow.keras.models.Sequential', 'tf.keras.models.Sequential', (['layers'], {}), '(layers)\n', (454, 462), True, 'import tensorflow as tf\n'), ((367, 413), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['num_outputs', 'activation'], {}), '(num_outputs, activation)\n', (388, 413), True, '...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
[ "numpy.sum", "qiskit.transpiler.synthesis.cnot_synth", "numpy.allclose", "numpy.where", "numpy.array", "qiskit.circuit.exceptions.CircuitError", "numpy.linalg.det", "numpy.eye" ]
[((6235, 6261), 'numpy.eye', 'np.eye', (['nq', 'nq'], {'dtype': 'bool'}), '(nq, nq, dtype=bool)\n', (6241, 6261), True, 'import numpy as np\n'), ((4790, 4813), 'qiskit.transpiler.synthesis.cnot_synth', 'cnot_synth', (['self.linear'], {}), '(self.linear)\n', (4800, 4813), False, 'from qiskit.transpiler.synthesis import ...
import numpy as np from sklearn.metrics import euclidean_distances from Tools import Preprocess import numpy.linalg as LA def pca_error(X, Y): (n, m) = X.shape X2 = X - np.mean(X, axis=0) Y2 = Y - np.mean(Y, axis=0) distance = np.zeros((n, 1)) for i in range(0, n): distance[i] = np.linalg...
[ "Tools.Preprocess.knn", "numpy.sum", "numpy.maximum", "numpy.abs", "numpy.log", "numpy.zeros", "numpy.float", "numpy.ones", "numpy.transpose", "sklearn.metrics.euclidean_distances", "numpy.mean", "numpy.linalg.norm", "numpy.arccos" ]
[((246, 262), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (254, 262), True, 'import numpy as np\n'), ((444, 466), 'sklearn.metrics.euclidean_distances', 'euclidean_distances', (['X'], {}), '(X)\n', (463, 466), False, 'from sklearn.metrics import euclidean_distances\n'), ((476, 498), 'sklearn.metrics.eucl...
"""Flask blueprint for modular routes.""" from __future__ import absolute_import, division, print_function import gzip import hashlib import json import timeit import traceback import numpy as np from flask import ( Blueprint, abort, current_app, jsonify, make_response, request, send_file,...
[ "deepcell_label.exporters.Exporter", "flask.request.files.get", "deepcell_label.exporters.S3Exporter", "deepcell_label.loaders.URLLoader", "flask.jsonify", "deepcell_label.utils.add_frame_div_parent", "deepcell_label.models.Project.create", "flask.current_app.logger.error", "traceback.print_exc", ...
[((596, 624), 'flask.Blueprint', 'Blueprint', (['"""label"""', '__name__'], {}), "('label', __name__)\n", (605, 624), False, 'from flask import Blueprint, abort, current_app, jsonify, make_response, request, send_file\n'), ((1175, 1270), 'flask.current_app.logger.error', 'current_app.logger.error', (['"""Encountered %s...
""" Author: <NAME> Created: 01/06/2020 """ # EXAMPLE # General example on how to run the GaussianFieldGenerator # ---------------------------------------------------------- # README - REQUIREMENT # The file example.py required the following dependencies: # - Numpy # - Matplotlib # - turbogen.py = This file conta...
[ "matplotlib.pyplot.loglog", "matplotlib.pyplot.figure", "numpy.mean", "numpy.arange", "matplotlib.pyplot.axvline", "matplotlib.pyplot.yticks", "numpy.transpose", "matplotlib.pyplot.colorbar", "numpy.max", "matplotlib.pyplot.rc", "matplotlib.pyplot.xticks", "cmpspec.compute3Dspectrum", "matpl...
[((3390, 3401), 'time.time', 'time.time', ([], {}), '()\n', (3399, 3401), False, 'import time\n'), ((3565, 3630), 'turboGen.gaussian3Dcos', 'tg.gaussian3Dcos', (['lx', 'ly', 'lz', 'nx', 'ny', 'nz', 'nmodes', 'wn1', 'whichspect'], {}), '(lx, ly, lz, nx, ny, nz, nmodes, wn1, whichspect)\n', (3581, 3630), True, 'import tu...
import numpy as np def dist(x, y): """ Numpy implementation. """ return np.sqrt(np.sum(np.power(x-y, 2)))
[ "numpy.power" ]
[((96, 114), 'numpy.power', 'np.power', (['(x - y)', '(2)'], {}), '(x - y, 2)\n', (104, 114), True, 'import numpy as np\n')]
import os import sys import asyncio import numpy as np from caproto.server import ioc_arg_parser, run, pvproperty, PVGroup import simulacrum import zmq import time from zmq.asyncio import Context import pickle from scipy.stats import gaussian_kde #set up python logger L = simulacrum.util.SimulacrumLog(os.path.splitext(...
[ "pickle.load", "numpy.rot90", "numpy.arange", "numpy.random.normal", "numpy.exp", "zmq.Context", "numpy.meshgrid", "numpy.histogram2d", "numpy.append", "zmq.asyncio.Context.instance", "caproto.server.pvproperty", "asyncio.get_event_loop", "os.path.basename", "numpy.frombuffer", "os.path....
[((13296, 13320), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (13318, 13320), False, 'import asyncio\n'), ((13342, 13417), 'caproto.server.ioc_arg_parser', 'ioc_arg_parser', ([], {'default_prefix': '""""""', 'desc': '"""Simulated Profile Monitor Service"""'}), "(default_prefix='', desc='Simula...
# -*- coding: utf-8 -*- """Helper functions for the graph hash calculation""" import os from collections import defaultdict from typing import List, Tuple import networkx as nx import numpy as np import yaml from pymatgen.analysis.graphs import MoleculeGraph, StructureGraph from pymatgen.analysis.local_env import ( ...
[ "yaml.load", "networkx.MultiDiGraph", "pymatgen.core.Molecule", "collections.defaultdict", "pymatgen.analysis.local_env.MinimumDistanceNN", "networkx.connected_components", "numpy.mean", "networkx.is_isomorphic", "pymatgen.analysis.local_env.CrystalNN", "os.path.join", "numpy.unique", "pymatge...
[((971, 1011), 'pymatgen.analysis.local_env.CutOffDictNN', 'CutOffDictNN', ([], {'cut_off_dict': 'VESTA_CUTOFFS'}), '(cut_off_dict=VESTA_CUTOFFS)\n', (983, 1011), False, 'from pymatgen.analysis.local_env import BrunnerNN_relative, CrystalNN, CutOffDictNN, EconNN, JmolNN, MinimumDistanceNN, VoronoiNN\n'), ((1021, 1067),...
import numpy as np import pandas as pd from os.path import dirname, join from sklearn.preprocessing import LabelEncoder __all__ = ['load_monks'] def load_monks(dynamic=True, is_directed=True, include_waverers=False, encode_labels=True): """Loads Sampson's Monastery Network (1968).""" if dyna...
[ "numpy.empty", "os.path.dirname", "os.path.join", "sklearn.preprocessing.LabelEncoder" ]
[((714, 731), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (721, 731), False, 'from os.path import dirname, join\n'), ((762, 812), 'numpy.empty', 'np.empty', (['(n_time_steps, 18, 18)'], {'dtype': 'np.float64'}), '((n_time_steps, 18, 18), dtype=np.float64)\n', (770, 812), True, 'import numpy as np\...
""" Defines general coordinate system related functions including: - coords = coords_from_vector_1d(v_array) - coords = coordinate_system_from_vector_2d_tri(xyz1, xyz2, xyz3) - coords = coordinate_system_from_vector_2d_quad(xyz1, xyz2, xyz3, xyz4) - coords = coordinate_system_from_vector_2d_tri_theta(xyz1, xyz2, xy...
[ "numpy.hstack", "numpy.asarray", "numpy.atleast_2d" ]
[((775, 797), 'numpy.atleast_2d', 'np.atleast_2d', (['v_array'], {}), '(v_array)\n', (788, 797), True, 'import numpy as np\n'), ((1071, 1090), 'numpy.atleast_2d', 'np.atleast_2d', (['xyz1'], {}), '(xyz1)\n', (1084, 1090), True, 'import numpy as np\n'), ((1102, 1121), 'numpy.atleast_2d', 'np.atleast_2d', (['xyz2'], {}),...
import torch from torchvision import transforms import numpy as np from numpy import random import cv2 class Compose(object): """Composes several augmentations together. Args: transforms (List[Transform]): list of transforms to compose. Example: >>> augmentations.Compose([ >>> t...
[ "cv2.cvtColor", "numpy.random.uniform", "numpy.random.randint", "numpy.array" ]
[((1089, 1106), 'numpy.random.randint', 'random.randint', (['(2)'], {}), '(2)\n', (1103, 1106), False, 'from numpy import random\n'), ((1400, 1417), 'numpy.random.randint', 'random.randint', (['(2)'], {}), '(2)\n', (1414, 1417), False, 'from numpy import random\n'), ((2584, 2601), 'numpy.random.randint', 'random.randin...
# Databricks notebook source # MAGIC %md # MAGIC # Feature selection # MAGIC # MAGIC For both riverine and flash flooding # MAGIC Use Obiwlan for high speed comuptation (5mins run) # COMMAND ---------- # MAGIC %md # MAGIC ## Import libraries # COMMAND ---------- from delta.tables import DeltaTable import pandas...
[ "pyspark.ml.classification.LogisticRegression", "matplotlib.pyplot.figure", "pyspark.ml.feature.StandardScaler", "pyspark.ml.Pipeline", "azureml.core.Dataset.get_by_name", "numpy.linspace", "matplotlib.pyplot.legend", "pandas.Series", "pyspark.sql.functions.when", "matplotlib.pyplot.ylabel", "ma...
[((2992, 3047), 'azureml.core.Dataset.get_by_name', 'Dataset.get_by_name', (['ws', 'dataset_name'], {'version': '"""latest"""'}), "(ws, dataset_name, version='latest')\n", (3011, 3047), False, 'from azureml.core import Dataset\n'), ((4336, 4394), 'pyspark.ml.feature.VectorAssembler', 'VectorAssembler', ([], {'inputCols...
#!/usr/local/bin/python3 import numpy as np import matplotlib.pyplot as plt from scipy.spatial import distance as sd class Clusterers: def __init__(self, data_path): self._data_path = data_path self._points = list() self._clusters = list() self._centroids = list() self.loa...
[ "scipy.spatial.distance.cdist", "matplotlib.pyplot.show", "numpy.average", "matplotlib.pyplot.plot", "scipy.spatial.distance.squareform", "numpy.zeros", "numpy.argmin", "numpy.append", "scipy.spatial.distance.pdist", "numpy.array", "numpy.linalg.norm" ]
[((15462, 15496), 'numpy.array', 'np.array', (['[[1.8, 2.3], [2.3, 1.4]]'], {}), '([[1.8, 2.3], [2.3, 1.4]])\n', (15470, 15496), True, 'import numpy as np\n'), ((15670, 15724), 'numpy.array', 'np.array', (['[[1, 3.1], [2, 2.2], [1.5, 2.1], [3.1, 1.1]]'], {}), '([[1, 3.1], [2, 2.2], [1.5, 2.1], [3.1, 1.1]])\n', (15678, ...
import numpy as np from unittest.mock import patch, Mock import ramjet.photometric_database.derived.self_lensing_binary_synthetic_signals_light_curve_collection as module from ramjet.photometric_database.derived.self_lensing_binary_synthetic_signals_light_curve_collection import \ SelfLensingBinarySyntheticSignals...
[ "ramjet.photometric_database.derived.self_lensing_binary_synthetic_signals_light_curve_collection.ReversedSelfLensingBinarySyntheticSignalsLightCurveCollection", "unittest.mock.patch.object", "ramjet.photometric_database.derived.self_lensing_binary_synthetic_signals_light_curve_collection.SelfLensingBinarySynth...
[((413, 441), 'unittest.mock.patch.object', 'patch.object', (['module', '"""Path"""'], {}), "(module, 'Path')\n", (425, 441), False, 'from unittest.mock import patch, Mock\n'), ((1753, 1786), 'numpy.array', 'np.array', (['[0, 10, 20, 30, 40, 50]'], {}), '([0, 10, 20, 30, 40, 50])\n', (1761, 1786), True, 'import numpy a...
from __future__ import division from __future__ import absolute_import import numpy as np import time import logging from libensemble.libE_fields import libE_fields logger = logging.getLogger(__name__) #For debug messages - uncomment #logger.setLevel(logging.DEBUG) class HistoryException(Exception): pass class Hi...
[ "numpy.isscalar", "numpy.zeros", "numpy.setdiff1d", "time.time", "numpy.append", "numpy.arange", "logging.getLogger" ]
[((177, 204), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (194, 204), False, 'import logging\n'), ((4102, 4113), 'time.time', 'time.time', ([], {}), '()\n', (4111, 4113), False, 'import time\n'), ((4176, 4195), 'numpy.isscalar', 'np.isscalar', (['q_inds'], {}), '(q_inds)\n', (4187, 419...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 28 23:34:52 2021 @author: mlampert """ #Core modules import os import copy import flap import flap_nstx flap_nstx.register() import flap_mdsplus flap_mdsplus.register('NSTX_MDSPlus') thisdir = os.path.dirname(os.path.realpath(__file__)) fn = os...
[ "numpy.abs", "flap_mdsplus.register", "matplotlib.style.use", "numpy.argmax", "flap.CoordinateMode", "matplotlib.pyplot.figure", "numpy.arange", "os.path.join", "flap.delete_data_object", "flap.get_data_object_ref", "matplotlib.pyplot.close", "os.path.exists", "scipy.ndimage.zoom", "numpy....
[((179, 199), 'flap_nstx.register', 'flap_nstx.register', ([], {}), '()\n', (197, 199), False, 'import flap_nstx\n'), ((220, 257), 'flap_mdsplus.register', 'flap_mdsplus.register', (['"""NSTX_MDSPlus"""'], {}), "('NSTX_MDSPlus')\n", (241, 257), False, 'import flap_mdsplus\n'), ((318, 359), 'os.path.join', 'os.path.join...
# coding: utf-8 """ description: Scikit-learn compatible implementation of the Gibberish detector based on https://github.com/rrenaud/Gibberish-Detector original author: <EMAIL> author: <NAME> """ __all__ = ['GibberishDetectorClassifier'] from sklearn.base import BaseEstimator, Classifier...
[ "numpy.log", "numpy.exp", "sklearn.utils.validation.check_is_fitted" ]
[((3454, 3493), 'numpy.exp', 'np.exp', (['(log_prob / (transition_ct or 1))'], {}), '(log_prob / (transition_ct or 1))\n', (3460, 3493), True, 'import numpy as np\n'), ((3569, 3607), 'sklearn.utils.validation.check_is_fitted', 'check_is_fitted', (['self', '"""_log_prob_mat"""'], {}), "(self, '_log_prob_mat')\n", (3584,...
import cv2 as cv import streamlit as st import argparse import numpy as np modelPath = 'models/mobilenet_ssd_v1_coco/frozen_inference_graph.pb' configPath = 'models/mobilenet_ssd_v1_coco/ssd_mobilenet_v1_coco_2017_11_17.pbtxt' classNames = { 0: 'background', 1: 'person', 2: 'bicycle', 3: 'car', 4: 'motorcycle', 5...
[ "cv2.GaussianBlur", "argparse.ArgumentParser", "cv2.VideoWriter_fourcc", "cv2.vconcat", "streamlit.radio", "cv2.rectangle", "cv2.VideoWriter", "cv2.erode", "cv2.dnn.readNetFromTensorflow", "cv2.line", "streamlit.stop", "cv2.dilate", "cv2.cvtColor", "cv2.dnn.blobFromImage", "streamlit.but...
[((3530, 3680), 'cv2.getStructuringElement', 'cv.getStructuringElement', (['cv.MORPH_ELLIPSE', '(2 * params.dilationSize + 1, 2 * params.dilationSize + 1)', '(params.dilationSize, params.dilationSize)'], {}), '(cv.MORPH_ELLIPSE, (2 * params.dilationSize + 1, 2 *\n params.dilationSize + 1), (params.dilationSize, para...
import numpy as np import vtk, vtktools # inputs -------------------------------------- # filenames constructed from this filebase = 'Flowpast_2d_Re3900_' # how many files do we want to read in? nFiles = 3 #we have nFiles+1 time level, with 0 as initial state # how many physical dimensiona does our problem have? nDim...
[ "numpy.zeros", "numpy.max", "numpy.linalg.norm", "vtktools.vtu" ]
[((1441, 1467), 'numpy.linalg.norm', 'np.linalg.norm', (['field_data'], {}), '(field_data)\n', (1455, 1467), True, 'import numpy as np\n'), ((763, 785), 'vtktools.vtu', 'vtktools.vtu', (['filename'], {}), '(filename)\n', (775, 785), False, 'import vtk, vtktools\n'), ((1894, 1934), 'numpy.max', 'np.max', (['field_data[n...
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, <NAME> <<EMAIL>> 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...
[ "thermo.thermal_conductivity.ThermalConductivityGasMixture", "thermo.thermal_conductivity.ThermalConductivityLiquidMixture", "thermo.mixture.Mixture", "pytest.raises", "numpy.testing.assert_allclose", "fluids.numerics.assert_close1d", "fluids.numerics.assert_close" ]
[((4680, 4715), 'fluids.numerics.assert_close1d', 'assert_close1d', (['TP_data', 'recalc_pts'], {}), '(TP_data, recalc_pts)\n', (4694, 4715), False, 'from fluids.numerics import assert_close, assert_close1d\n'), ((8652, 8688), 'numpy.testing.assert_allclose', 'assert_allclose', (['TP_data', 'recalc_pts'], {}), '(TP_dat...
import numpy as np class _MPI: __is_frozen = False def __setattr__(self, key, value): if self.__is_frozen and not hasattr(self, key): raise TypeError(f'{self.__class__.__name__} is a frozen class') object.__setattr__(self, key, value) def __freeze(self): self.__is_fr...
[ "numpy.copy", "numpy.append", "numpy.array", "numpy.arange", "numpy.array_split" ]
[((1182, 1208), 'numpy.array', 'np.array', (['data'], {'copy': '(False)'}), '(data, copy=False)\n', (1190, 1208), True, 'import numpy as np\n'), ((2001, 2027), 'numpy.array', 'np.array', (['data'], {'copy': '(False)'}), '(data, copy=False)\n', (2009, 2027), True, 'import numpy as np\n'), ((2048, 2077), 'numpy.copy', 'n...
#Author: <NAME> #Date: September 20,2020. from fastapi import FastAPI import uvicorn import numpy as np import re import math import requests from bs4 import BeautifulSoup from fastapi.responses import PlainTextResponse app = FastAPI() def result(res): return {"result":res} @app.get("/") async def main(): r...
[ "numpy.average", "numpy.amin", "math.pow", "numpy.amax", "numpy.mean", "uvicorn.run", "numpy.array", "requests.get", "bs4.BeautifulSoup", "re.search", "fastapi.FastAPI" ]
[((228, 237), 'fastapi.FastAPI', 'FastAPI', ([], {}), '()\n', (235, 237), False, 'from fastapi import FastAPI\n'), ((616, 630), 'math.pow', 'math.pow', (['a', 'b'], {}), '(a, b)\n', (624, 630), False, 'import math\n'), ((1105, 1119), 'numpy.average', 'np.average', (['ls'], {}), '(ls)\n', (1115, 1119), True, 'import num...
from flask import Flask, jsonify import FinanceDataReader as fdr import torch import torch.nn as nn from datetime import datetime, timedelta, date import numpy as np import json def load_scaler(): with open('model/model_info.json', 'r') as f: model_info = json.load(f) f.close() scaler = model_info...
[ "torch.nn.GRU", "json.load", "datetime.datetime.today", "torch.load", "flask.Flask", "datetime.date.today", "torch.nn.Linear", "flask.jsonify", "numpy.array", "datetime.timedelta", "torch.device", "torch.nn.LSTM", "torch.no_grad" ]
[((3780, 3795), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (3785, 3795), False, 'from flask import Flask, jsonify\n'), ((1548, 1567), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1560, 1567), False, 'import torch\n'), ((4466, 4481), 'flask.jsonify', 'jsonify', (['result'], {}), '(...
import unittest import numpy as np from deicode.matrix_completion import MatrixCompletion from deicode.preprocessing import rclr from deicode.optspace import OptSpace from skbio.stats.composition import clr from simulations import build_block_model from nose.tools import nottest @nottest def create_test_table(): ...
[ "unittest.main", "skbio.stats.composition.clr", "deicode.preprocessing.rclr", "simulations.build_block_model", "numpy.array", "deicode.optspace.OptSpace", "deicode.matrix_completion.MatrixCompletion" ]
[((336, 461), 'simulations.build_block_model', 'build_block_model', ([], {'rank': '(2)', 'hoced': '(20)', 'hsced': '(20)', 'spar': '(2000.0)', 'C_': '(2000.0)', 'num_samples': '(50)', 'num_features': '(500)', 'mapping_on': '(False)'}), '(rank=2, hoced=20, hsced=20, spar=2000.0, C_=2000.0,\n num_samples=50, num_featu...
# Run like: ## heroku run --size=performance-l python user_summary.py -r heroku # Or run in the background like: ## heroku run:detached --size=performance-l python user_summary.py -r heroku import pandas as pd import numpy as np import os import json import gspread from datetime import datetime from app import get_db...
[ "os.remove", "package.Package.query.get", "pandas.read_csv", "gspread.service_account", "user_summary_rules.rule_new_users", "os.path.isfile", "user_summary_rules.rule_required_data", "numpy.unique", "pandas.DataFrame", "hubspot.HubSpot", "json.loads", "user_summary_rules.rule_not_using", "a...
[((421, 430), 'hubspot.HubSpot', 'HubSpot', ([], {}), '()\n', (428, 430), False, 'from hubspot import HubSpot\n'), ((1520, 1633), 'pandas.DataFrame', 'pd.DataFrame', (['rows'], {'columns': "['institution_id', 'name', 'created', 'is_consortium', 'consortium_id',\n 'ror_id']"}), "(rows, columns=['institution_id', 'nam...
import numpy as np class ReactionForceManager(object): def __init__(self, contact, maximum_rf_z_max, robot): self._contact = contact self._robot = robot self._maximum_rf_z_max = maximum_rf_z_max self._minimum_rf_z_max = 0.001 self._starting_rf_z_max = contact.rf_z_max ...
[ "numpy.clip" ]
[((814, 888), 'numpy.clip', 'np.clip', (['current_time', 'self._start_time', '(self._start_time + self._duration)'], {}), '(current_time, self._start_time, self._start_time + self._duration)\n', (821, 888), True, 'import numpy as np\n'), ((1882, 1956), 'numpy.clip', 'np.clip', (['current_time', 'self._start_time', '(se...
import numpy as np import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go import pickle def load_model(path): with open(path, 'rb') as p: return pickle.load(p) def save_model(model, path): with open(path + '.pkl', 'wb') as p: pickle.dump(model, p) def pl...
[ "numpy.random.uniform", "pickle.dump", "numpy.random.triangular", "plotly.graph_objects.Figure", "numpy.random.exponential", "pickle.load", "numpy.random.normal" ]
[((515, 526), 'plotly.graph_objects.Figure', 'go.Figure', ([], {}), '()\n', (524, 526), True, 'import plotly.graph_objects as go\n'), ((197, 211), 'pickle.load', 'pickle.load', (['p'], {}), '(p)\n', (208, 211), False, 'import pickle\n'), ((291, 312), 'pickle.dump', 'pickle.dump', (['model', 'p'], {}), '(model, p)\n', (...
import os import zarr import numpy as np import torch import torch.distributed as dist import torch.multiprocessing as mp from torch.utils.data import DataLoader from torch.utils.data.distributed import DistributedSampler from torch.nn.parallel import DistributedDataParallel as DDP from tqdm import tqdm from empanada...
[ "empanada.inference.filters.remove_small_objects", "torch.cuda.device_count", "os.path.isfile", "torch.distributed.get_world_size", "torch.multiprocessing.Pipe", "empanada.inference.tracker.InstanceTracker", "os.path.expanduser", "zarr.open", "torch.utils.data.DataLoader", "empanada.inference.filt...
[((773, 801), 'torch.hub.set_dir', 'torch.hub.set_dir', (['MODEL_DIR'], {}), '(MODEL_DIR)\n', (790, 801), False, 'import torch\n'), ((727, 750), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (745, 750), False, 'import os\n'), ((953, 1077), 'torch.distributed.init_process_group', 'dist.init_p...
import os import cv2,PIL import multiprocessing import pandas as pd import numpy as np from tqdm import tqdm from functools import partial from torch.utils.data import DataLoader,Dataset from iterstrat.ml_stratifiers import MultilabelStratifiedKFold from hpasegmentator import * data_dir = './input/hpa-single-cell-im...
[ "numpy.stack", "functools.partial", "tqdm.tqdm", "os.makedirs", "torch.utils.data.DataLoader", "pandas.read_csv", "cv2.imwrite", "os.path.exists", "numpy.zeros", "PIL.Image.open", "cv2.imread", "iterstrat.ml_stratifiers.MultilabelStratifiedKFold", "os.path.join", "cv2.resize", "multiproc...
[((356, 408), 'os.makedirs', 'os.makedirs', (['"""./input/hpa-512/train/"""'], {'exist_ok': '(True)'}), "('./input/hpa-512/train/', exist_ok=True)\n", (367, 408), False, 'import os\n'), ((409, 460), 'os.makedirs', 'os.makedirs', (['"""./input/hpa-512/test/"""'], {'exist_ok': '(True)'}), "('./input/hpa-512/test/', exist...
from gpytorch import constraints from numbers import Number import numpy as np def atleast_2d(ten): if ten.ndimension() == 1: ten = ten.unsqueeze(0) return ten def constraint_from_tuple(bounds, default=None): if bounds is None: return default elif isinstance(bounds, Number): ...
[ "numpy.around", "gpytorch.constraints.Interval" ]
[((486, 522), 'gpytorch.constraints.Interval', 'constraints.Interval', (['lbound', 'ubound'], {}), '(lbound, ubound)\n', (506, 522), False, 'from gpytorch import constraints\n'), ((1157, 1194), 'numpy.around', 'np.around', (['transformed'], {'around': 'around'}), '(transformed, around=around)\n', (1166, 1194), True, 'i...
import itertools import numpy as np from tensorpack.dataflow import * from tensorpack.dataflow.base import DataFlow, ProxyDataFlow from tensorpack.dataflow.dftools import dump_dataflow_to_lmdb import data.utils class SubData(DataFlow): """ DataFlow wrapper which only contains a subset of the wrapped data ...
[ "numpy.asarray", "numpy.zeros" ]
[((1872, 1916), 'numpy.zeros', 'np.zeros', (['(bsize, maxlen, feats[0].shape[1])'], {}), '((bsize, maxlen, feats[0].shape[1]))\n', (1880, 1916), True, 'import numpy as np\n'), ((2417, 2436), 'numpy.asarray', 'np.asarray', (['indices'], {}), '(indices)\n', (2427, 2436), True, 'import numpy as np\n'), ((2450, 2468), 'num...
""" File: seismo_transformer.py Author: <NAME> Email: <EMAIL> Github: https://github.com/jamm1985 Description: model layers, model itself and auxiliary functions """ import h5py from sklearn.model_selection import train_test_split import tensorflow as tf from tensorflow import keras from tensorflow.keras import layer...
[ "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Dense", "sklearn.model_selection.train_test_split", "tensorflow.maximum", "tensorflow.keras.layers.LayerNormalization", "kapre.Magnitude", "einops.layers.tensorflow.Rearrange", "tensorflow.keras.layers.concatenate", "tensorflow.reduce_...
[((727, 751), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (736, 751), False, 'import h5py\n'), ((1415, 1447), 'numpy.unique', 'np.unique', (['Y'], {'return_counts': '(True)'}), '(Y, return_counts=True)\n', (1424, 1447), True, 'import numpy as np\n'), ((1629, 1718), 'sklearn.model_selec...
# # Copyright 2016, 2020 <NAME> # 2018-2019 <NAME> # # ### MIT license # # 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...
[ "numpy.zeros_like", "numpy.abs", "numpy.ones_like", "numpy.arctan2", "numpy.asarray", "numpy.logical_not", "numpy.arcsin", "numpy.arctan", "numpy.sqrt" ]
[((4388, 4404), 'numpy.zeros_like', 'np.zeros_like', (['r'], {}), '(r)\n', (4401, 4404), True, 'import numpy as np\n'), ((4414, 4430), 'numpy.zeros_like', 'np.zeros_like', (['r'], {}), '(r)\n', (4427, 4430), True, 'import numpy as np\n'), ((4444, 4460), 'numpy.zeros_like', 'np.zeros_like', (['r'], {}), '(r)\n', (4457, ...
import numpy as np from scipy.special import comb from scipy.optimize import brentq as uniroot from scipy.stats import gamma def checkCoeffAllPositive(coeff): '''check all entries in coeff vector positive ''' if isinstance(coeff, (int, float)): return( coeff > 0) return ( all(i >0 for i in coe...
[ "numpy.roots", "numpy.cumprod", "scipy.optimize.brentq", "numpy.copy", "scipy.stats.gamma.cdf", "scipy.special.comb", "numpy.zeros", "numpy.append", "numpy.arange", "numpy.math.factorial", "numpy.linalg.det", "numpy.linalg.solve" ]
[((1553, 1576), 'numpy.arange', 'np.arange', (['(1)', '(2 * p + 1)'], {}), '(1, 2 * p + 1)\n', (1562, 1576), True, 'import numpy as np\n'), ((1992, 2007), 'numpy.arange', 'np.arange', (['(1)', 'n'], {}), '(1, n)\n', (2001, 2007), True, 'import numpy as np\n'), ((2426, 2444), 'numpy.copy', 'np.copy', (['cumul_vec'], {})...
#!/usr/bin/env python3 import os import cv2 import torch import numpy as np import torchvision from PIL import Image from matplotlib import cm import matplotlib.colors as mc from matplotlib import pyplot as plt import kornia.geometry.conversions as C from matplotlib.animation import FuncAnimation class Visualizer():...
[ "matplotlib.colors.get_named_colors_mapping", "cv2.VideoWriter_fourcc", "matplotlib.cm.get_cmap", "matplotlib.pyplot.figure", "cv2.imshow", "os.path.join", "matplotlib.colors.Normalize", "matplotlib.pyplot.close", "matplotlib.pyplot.imshow", "cv2.destroyAllWindows", "datetime.datetime.now", "m...
[((4081, 4114), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'self.fig_size'}), '(figsize=self.fig_size)\n', (4091, 4114), True, 'from matplotlib import pyplot as plt\n'), ((4232, 4248), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (4241, 4248), True, 'from matplotlib import p...
# -*- coding:utf-8 -*- """ @version: 1.0 @author: kevin @license: Apache Licence @contact: <EMAIL> @site: @software: PyCharm Community Edition @file: adios_train.py @time: 17/05/03 17:39 """ import json import os import time from math import ceil import sys import os import numpy as np from sklearn import linear_model ...
[ "utils.hiso.HISO", "utils.metrics.Coverage", "torch.nn.BCELoss", "torch.utils.data.DataLoader", "utils.metrics.Ranking_loss", "utils.metrics.F1_measure", "utils.metrics.Hamming_loss", "torch.cuda.is_available", "time.localtime", "utils.hiso.HisoLoss", "numpy.mean", "utils.metrics.Average_preci...
[((1173, 1198), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1196, 1198), False, 'import torch\n'), ((1617, 1634), 'utils.hiso.HISO', 'hiso.HISO', (['params'], {}), '(params)\n', (1626, 1634), False, 'from utils import hiso\n'), ((1653, 1674), 'utils.hiso.HisoLoss', 'hiso.HisoLoss', (['param...
import numpy as np from computeCost import * def gradient_descent(X, y, theta, alpha, num_iters): # Initialize some useful values m = y.size J_history = np.zeros(num_iters) for i in range(0, num_iters): # ===================== Your Code Here ===================== # Instructions : Perf...
[ "numpy.dot", "numpy.zeros", "numpy.sum" ]
[((167, 186), 'numpy.zeros', 'np.zeros', (['num_iters'], {}), '(num_iters)\n', (175, 186), True, 'import numpy as np\n'), ((893, 912), 'numpy.zeros', 'np.zeros', (['num_iters'], {}), '(num_iters)\n', (901, 912), True, 'import numpy as np\n'), ((536, 576), 'numpy.sum', 'np.sum', (['(X * error[:, np.newaxis])'], {'axis':...
from collections import Counter import librosa import tensorflow as tf import numpy as np import os from tqdm import tqdm from multiprocessing import Lock from joblib import Parallel, delayed, dump from argparse import ArgumentParser from speechpy.feature import mfe, mfcc, extract_derivative_feature import warnings fr...
[ "numpy.abs", "argparse.ArgumentParser", "multiprocessing.Lock", "joblib.dump", "numpy.mean", "tensorflow.train.FloatList", "librosa.feature.melspectrogram", "os.path.join", "speechpy.feature.mfcc", "librosa.feature.mfcc", "numpy.pad", "warnings.simplefilter", "numpy.std", "os.path.dirname"...
[((383, 477), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': '"""PySoundFile failed. Trying audioread instead"""'}), "('ignore', message=\n 'PySoundFile failed. Trying audioread instead')\n", (406, 477), False, 'import warnings\n'), ((508, 517), 'collections.Counter', 'Counter',...
import math import numpy as np class DatasetLoader: def __init__(self, file, delimiter=','): self.csv = file self.csv_delimiter = delimiter def load(self, split_percent=0.1): dataset = np.loadtxt(self.csv, delimiter=self.csv_delimiter) bound = math.ceil(len(dataset) * split_p...
[ "numpy.loadtxt" ]
[((221, 271), 'numpy.loadtxt', 'np.loadtxt', (['self.csv'], {'delimiter': 'self.csv_delimiter'}), '(self.csv, delimiter=self.csv_delimiter)\n', (231, 271), True, 'import numpy as np\n')]
# transmon.py # # This file is part of scqubits. # # Copyright (c) 2019 and later, <NAME> and <NAME> # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. ####################################################...
[ "os.path.abspath", "scqubits.core.discretization.Grid1d", "numpy.abs", "math.sqrt", "scqubits.utils.plot_defaults.wavefunction1d_discrete", "numpy.empty", "numpy.asarray", "scqubits.core.descriptors.WatchedProperty", "numpy.max", "numpy.sin", "numpy.arange", "numpy.exp", "numpy.cos", "nump...
[((1848, 1899), 'scqubits.core.descriptors.WatchedProperty', 'descriptors.WatchedProperty', (['"""QUANTUMSYSTEM_UPDATE"""'], {}), "('QUANTUMSYSTEM_UPDATE')\n", (1875, 1899), True, 'import scqubits.core.descriptors as descriptors\n'), ((1909, 1960), 'scqubits.core.descriptors.WatchedProperty', 'descriptors.WatchedProper...
#!/usr/bin/env python3 """ Usage: add_frequencies.py [options] Add word frequency information to CoNLL files in MISC column. Options: -f, --freqfile FREQFILE JSON file with word frequencies by language. [default: ../data/ud2.5-frequencies.json.gz] --debug Show de...
[ "unicodedata.normalize", "pycountry.languages.lookup", "gzip.open", "json.load", "docopt.docopt", "os.path.basename", "os.path.realpath", "logzero.LogFormatter", "logzero.logger.exception", "numpy.percentile", "pyconll.load_from_file", "glob.glob", "logzero.loglevel", "logzero.logger.error...
[((626, 652), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (642, 652), False, 'import os\n'), ((1459, 1481), 'pycountry.languages.lookup', 'languages.lookup', (['lang'], {}), '(lang)\n', (1475, 1481), False, 'from pycountry import languages\n'), ((3105, 3120), 'docopt.docopt', 'docopt', (...
import numpy as np def leaky_relu(z): ''' This is the activation function used by default in all our neural networks. ''' return z*(z > 0) + 0.01*z*(z < 0) class Network: def read_in(self, npz_path): ''' read in the weights and biases parameterizing a particular neural network. ...
[ "numpy.load", "numpy.einsum" ]
[((503, 539), 'numpy.load', 'np.load', (['npz_path'], {'allow_pickle': '(True)'}), '(npz_path, allow_pickle=True)\n', (510, 539), True, 'import numpy as np\n'), ((1687, 1733), 'numpy.einsum', 'np.einsum', (['"""ij,j->i"""', 'w_array_0', 'scaled_labels'], {}), "('ij,j->i', w_array_0, scaled_labels)\n", (1696, 1733), Tru...
# -*- coding: utf-8 -*- # @Time : 2020/12/7 19:39 # @Author : cds # @Site : https://github.com/SkyLord2?tab=repositories # @Email: <EMAIL> # @File : YOLOv22.py # @Software: PyCharm import sys import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.backend as K import config as cfg from tensorfl...
[ "tensorflow.reduce_sum", "tensorflow.print", "tensorflow.maximum", "tensorflow.keras.optimizers.SGD", "tensorflow.reshape", "tensorflow.keras.layers.LeakyReLU", "tensorflow.keras.layers.concatenate", "tensorflow.keras.layers.MaxPool2D", "numpy.arange", "tensorflow.keras.layers.Lambda", "tensorfl...
[((610, 633), 'tensorflow.keras.backend.set_floatx', 'K.set_floatx', (['"""float32"""'], {}), "('float32')\n", (622, 633), True, 'import tensorflow.keras.backend as K\n'), ((1908, 1937), 'tensorflow.keras.backend.clear_session', 'keras.backend.clear_session', ([], {}), '()\n', (1935, 1937), True, 'import tensorflow.ker...
import os #os.environ["CUDA_VISIBLE_DEVICES"]="-1" import numpy as np from math import sqrt from numpy import zeros import re import math from .batch_object import batch_object from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split import pdb import random import tim...
[ "tensorflow.identity", "sklearn.model_selection.train_test_split", "tensorflow.contrib.layers.flatten", "tensorflow.reshape", "tensorflow.saved_model.utils.build_tensor_info", "numpy.random.set_state", "tensorflow.matmul", "pathlib.Path", "numpy.around", "tensorflow.nn.conv1d", "tensorflow.nn.le...
[((4358, 4377), 'os.fsencode', 'os.fsencode', (['tr_dir'], {}), '(tr_dir)\n', (4369, 4377), False, 'import os\n'), ((4815, 4836), 'os.listdir', 'os.listdir', (['directory'], {}), '(directory)\n', (4825, 4836), False, 'import os\n'), ((7654, 7721), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x_dat...
""" Copyright (c) 2019 Imperial College London. 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. """ import argparse import pathlib from argparse import ArgumentParser import h5py import numpy as n...
[ "tqdm.tqdm", "h5py.File", "argparse.ArgumentParser", "runstats.Statistics", "numpy.hstack", "numpy.mean", "numpy.linalg.norm", "matplotlib.pyplot.imsave", "os.path.join" ]
[((571, 596), 'numpy.mean', 'np.mean', (['((gt - pred) ** 2)'], {}), '((gt - pred) ** 2)\n', (578, 596), True, 'import numpy as np\n'), ((4457, 4472), 'tqdm.tqdm', 'tqdm', (['tgt_files'], {}), '(tgt_files)\n', (4461, 4472), False, 'from tqdm import tqdm\n'), ((6544, 6614), 'argparse.ArgumentParser', 'ArgumentParser', (...
# -*- coding: utf-8 -*- import argparse from os.path import join import matplotlib import matplotlib.pyplot as plt import myfuncs as my import numpy as np import pandas as pd from src.utilities import mkdir_if_needed matplotlib = my.utilities.set_mpl_defaults(matplotlib) def plot_psychometric( choices, ax=None,...
[ "argparse.ArgumentParser", "os.path.join", "myfuncs.plots.hist", "pandas.read_csv", "src.utilities.mkdir_if_needed", "matplotlib.pyplot.cm.colors.TwoSlopeNorm", "myfuncs.utilities.cm2inch", "pandas.cut", "numpy.mean", "numpy.array", "numpy.arange", "matplotlib.pyplot.cm.coolwarm", "matplotli...
[((232, 273), 'myfuncs.utilities.set_mpl_defaults', 'my.utilities.set_mpl_defaults', (['matplotlib'], {}), '(matplotlib)\n', (261, 273), True, 'import myfuncs as my\n'), ((571, 609), 'pandas.cut', 'pd.cut', (["choices['delta_ev']"], {'bins': 'bins'}), "(choices['delta_ev'], bins=bins)\n", (577, 609), True, 'import pand...
import numpy as np import cv2 class Thresholder(): def __init__(self): pass def sat_value(self, lane): hsv = cv2.cvtColor(lane, cv2.COLOR_BGR2HSV) hls = cv2.cvtColor(lane, cv2.COLOR_BGR2HLS) combined = np.zeros(lane.shape[:2]) s = hls[:,:,-1] v = hsv[:,:,-1] combined[((s >= 70 )) & ((v >= 150))] = 1 ...
[ "numpy.zeros_like", "cv2.bitwise_and", "cv2.cvtColor", "cv2.threshold", "numpy.zeros", "numpy.array", "cv2.inRange" ]
[((116, 153), 'cv2.cvtColor', 'cv2.cvtColor', (['lane', 'cv2.COLOR_BGR2HSV'], {}), '(lane, cv2.COLOR_BGR2HSV)\n', (128, 153), False, 'import cv2\n'), ((162, 199), 'cv2.cvtColor', 'cv2.cvtColor', (['lane', 'cv2.COLOR_BGR2HLS'], {}), '(lane, cv2.COLOR_BGR2HLS)\n', (174, 199), False, 'import cv2\n'), ((214, 238), 'numpy.z...
import glob import numpy as np import cv2 import csv filenames=glob.glob("*.jpg") largeArray=[] nfile='annotations.npy' parts=['nose','head','neck','tail','tailEnd','FrontLeftA','FrontLeftB','FrontLeftC','FrontRightA','FrontRightB','FrontRightC','RearLeftA','RearLeftB','RearLeftC','RearRightA','RearRightB','RearRigh...
[ "cv2.resize", "numpy.save", "cv2.circle", "cv2.waitKey", "cv2.imwrite", "cv2.destroyAllWindows", "cv2.imread", "cv2.setMouseCallback", "numpy.array", "glob.glob", "cv2.imshow", "cv2.namedWindow" ]
[((64, 82), 'glob.glob', 'glob.glob', (['"""*.jpg"""'], {}), "('*.jpg')\n", (73, 82), False, 'import glob\n'), ((1065, 1085), 'numpy.array', 'np.array', (['largeArray'], {}), '(largeArray)\n', (1073, 1085), True, 'import numpy as np\n'), ((1086, 1108), 'numpy.save', 'np.save', (['nfile', 'out_np'], {}), '(nfile, out_np...
# testDriver.py """Volume 1A: QR 1 (Decomposition). Test driver.""" # Decorator =================================================================== import signal from functools import wraps def _timeout(seconds): """Decorator for preventing a function from running for too long. Inputs: seconds (int)...
[ "scipy.linalg.solve", "numpy.set_printoptions", "inspect.getsourcelines", "numpy.triu", "numpy.dot", "numpy.allclose", "scipy.linalg.qr", "numpy.linalg.matrix_rank", "numpy.random.randint", "scipy.linalg.det", "functools.wraps", "signal.alarm", "numpy.eye", "signal.signal" ]
[((1350, 1397), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)', 'suppress': '(True)'}), '(precision=3, suppress=True)\n', (1369, 1397), True, 'import numpy as np\n'), ((819, 830), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (824, 830), False, 'from functools import wraps\n'), ((50...
#import random import numpy as np from deap import creator, base, tools, algorithms #code originally from 1eesh BASEORDER = list("ACGT") def getRandomBase(randomizer,args) : return randomizer.choice(BASEORDER , p=args['nucleotide_frequency'] ) def fitness(motif, individual): return (''.join(individual).count(moti...
[ "numpy.random.seed", "deap.base.Toolbox", "numpy.zeros", "deap.algorithms.varAnd", "numpy.shape", "deap.creator.create", "deap.tools.selBest" ]
[((856, 873), 'numpy.zeros', 'np.zeros', (['numSeqs'], {}), '(numSeqs)\n', (864, 873), True, 'import numpy as np\n'), ((1148, 1226), 'deap.algorithms.varAnd', 'algorithms.varAnd', (['population', 'toolbox'], {'cxpb': "args['cspb']", 'mutpb': "args['mutpb']"}), "(population, toolbox, cxpb=args['cspb'], mutpb=args['mutpb...
from careless.io.asu import ReciprocalASU,ReciprocalASUCollection import pytest import numpy as np import reciprocalspaceship as rs import gemmi @pytest.mark.parametrize('anomalous', [True, False]) @pytest.mark.parametrize('dmin', [10., 5.]) def test_reciprocal_asu(dmin, anomalous, cell_and_spacegroups): for cell...
[ "reciprocalspaceship.utils.compute_structurefactor_multiplicity", "reciprocalspaceship.utils.generate_reciprocal_asu", "numpy.concatenate", "numpy.unique", "careless.io.asu.ReciprocalASU", "numpy.isfinite", "careless.io.asu.ReciprocalASUCollection", "pytest.mark.parametrize", "numpy.all", "recipro...
[((148, 199), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""anomalous"""', '[True, False]'], {}), "('anomalous', [True, False])\n", (171, 199), False, 'import pytest\n'), ((201, 245), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dmin"""', '[10.0, 5.0]'], {}), "('dmin', [10.0, 5.0])\n", (224...
# -------------- import pandas as pd import numpy as np import math import cmath #Code starts here class complex_numbers(object): def __init__(self,real,imag): self.real=real self.imag=imag def __repr__(self): if self.real == 0.0 and self.imag == 0.0: ret...
[ "numpy.angle", "math.sqrt" ]
[((1294, 1336), 'math.sqrt', 'math.sqrt', (['(self.real ** 2 + self.imag ** 2)'], {}), '(self.real ** 2 + self.imag ** 2)\n', (1303, 1336), False, 'import math\n'), ((1420, 1441), 'numpy.angle', 'np.angle', (['z'], {'deg': '(True)'}), '(z, deg=True)\n', (1428, 1441), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense from tf2rl.algos.ddpg import DDPG from tf2rl.misc.target_update_ops import update_target_variables class Critic(tf.keras.Model): def __init__(self, state_shape, action_dim, units=(400, 300), name="Critic"): super().__ini...
[ "tensorflow.abs", "tensorflow.math.mod", "tensorflow.clip_by_value", "tensorflow.keras.layers.Dense", "tf2rl.misc.target_update_ops.update_target_variables", "tensorflow.stop_gradient", "tensorflow.device", "numpy.zeros", "tensorflow.concat", "tensorflow.reduce_mean", "tensorflow.minimum", "te...
[((354, 380), 'tensorflow.keras.layers.Dense', 'Dense', (['units[0]'], {'name': '"""L1"""'}), "(units[0], name='L1')\n", (359, 380), False, 'from tensorflow.keras.layers import Dense\n'), ((399, 425), 'tensorflow.keras.layers.Dense', 'Dense', (['units[1]'], {'name': '"""L2"""'}), "(units[1], name='L2')\n", (404, 425), ...
from slm_lab.agent import Agent from slm_lab.lib import util import numpy as np import os import pandas as pd import pydash as ps import pytest def test_calc_ts_diff(): ts1 = '2017_10_17_084739' ts2 = '2017_10_17_084740' ts_diff = util.calc_ts_diff(ts2, ts1) assert ts_diff == '0:00:01' def test_cast...
[ "slm_lab.lib.util.is_jupyter", "slm_lab.lib.util.to_opencv_image", "slm_lab.lib.util.cast_list", "pytest.mark.parametrize", "slm_lab.lib.util.calc_ts_diff", "slm_lab.lib.util.set_attr", "slm_lab.lib.util.cast_df", "os.path.abspath", "slm_lab.lib.util.read", "pydash.is_string", "os.path.dirname",...
[((775, 1251), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""d,flat_d"""', "[({'a': 1}, {'a': 1}), ({'a': {'b': 1}}, {'a.b': 1}), ({'level1': {'level2':\n {'level3': 0, 'level3b': 1}, 'level2b': {'level3': [2, 3]}}}, {\n 'level1.level2.level3': 0, 'level1.level2.level3b': 1,\n 'level1.level2b.lev...
import asyncio import json import os import cv2 import platform import sys from time import sleep import time from aiohttp import web from av import VideoFrame from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack, RTCIceServer, RTCConfiguration from aiohttp_basicauth import BasicAuthMiddleware ...
[ "numpy.ones", "json.dumps", "cv2.warpAffine", "cv2.imencode", "os.path.join", "cv2.getRotationMatrix2D", "asyncio.gather", "aiohttp_basicauth.BasicAuthMiddleware", "aiohttp.web.StreamResponse", "aiohttp.web.Response", "numpy.zeros_like", "cv2.filter2D", "cv2.dilate", "aiortc.RTCIceServer",...
[((418, 445), 'numpy.ones', 'np.ones', (['(10, 10)', 'np.uint8'], {}), '((10, 10), np.uint8)\n', (425, 445), True, 'import numpy as np\n'), ((8981, 9033), 'aiohttp.web.Response', 'web.Response', ([], {'content_type': '"""text/html"""', 'text': 'content'}), "(content_type='text/html', text=content)\n", (8993, 9033), Fal...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime from seir.wrapper import MultiPopWrapper from seir.utils import plot_solution # read calibration data # actual_infections = pd.read_excel('../../Calibration.xlsx',sheet_name='Confirmed cases') # actual_infections['Date'] = [pd.to_...
[ "seir.wrapper.MultiPopWrapper", "numpy.sum", "pandas.read_csv", "datetime.date", "datetime.timedelta", "numpy.exp", "numpy.linspace", "numpy.concatenate" ]
[((765, 819), 'pandas.read_csv', 'pd.read_csv', (['"""data/Startpop_2density_0comorbidity.csv"""'], {}), "('data/Startpop_2density_0comorbidity.csv')\n", (776, 819), True, 'import pandas as pd\n'), ((7921, 11186), 'seir.wrapper.MultiPopWrapper', 'MultiPopWrapper', ([], {'pop_categories': "{'age': ['0-9', '10-19', '20-2...
import os import numpy as np import pandas as pd ROOT = os.path.dirname(os.path.dirname(__file__)) RESULTS = os.path.join(ROOT, 'Results', 'Thesis') def results_table(experiment_path, metric, view_by, subjects, pivot): sessions = True if view_by in 'sessions' else False # Sort according to name not timesta...
[ "pandas.DataFrame", "numpy.minimum", "pandas.MultiIndex.from_tuples", "pandas.read_csv", "os.path.dirname", "numpy.array", "pandas.concat", "os.path.join", "os.listdir", "numpy.issubdtype", "numpy.sqrt" ]
[((111, 150), 'os.path.join', 'os.path.join', (['ROOT', '"""Results"""', '"""Thesis"""'], {}), "(ROOT, 'Results', 'Thesis')\n", (123, 150), False, 'import os\n'), ((74, 99), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (89, 99), False, 'import os\n'), ((339, 353), 'pandas.DataFrame', 'pd.Da...
# Have you ever seen a more complicated way to massage a gym env into something # else, only to make it a gym env again internally? You're welcome. import os if os.environ.get("USE_PY_NATIVERL"): import pathmind_training.pynativerl as nativerl else: import nativerl import math import random import numpy as ...
[ "nativerl.Discrete", "random.uniform", "numpy.asarray", "math.sin", "os.environ.get", "nativerl.Continuous", "math.cos" ]
[((163, 196), 'os.environ.get', 'os.environ.get', (['"""USE_PY_NATIVERL"""'], {}), "('USE_PY_NATIVERL')\n", (177, 196), False, 'import os\n'), ((1263, 1312), 'nativerl.Continuous', 'nativerl.Continuous', (['[-math.inf]', '[math.inf]', '[4]'], {}), '([-math.inf], [math.inf], [4])\n', (1282, 1312), False, 'import nativer...
# -*- coding: utf-8 -*- """ Created on Mon Apr 19 15:09:38 2021 @author: Alison """ import numpy as np from landlab import Component, FieldError class Underground_Flow_Routing(Component): """ Calculate steady-state groundwater head distribution and groundwater flux under constant head or constant flu...
[ "numpy.zeros", "numpy.ones" ]
[((4009, 4036), 'numpy.ones', 'np.ones', (['mg.number_of_nodes'], {}), '(mg.number_of_nodes)\n', (4016, 4036), True, 'import numpy as np\n'), ((5632, 5672), 'numpy.ones', 'np.ones', (['mg.number_of_nodes'], {'dtype': 'float'}), '(mg.number_of_nodes, dtype=float)\n', (5639, 5672), True, 'import numpy as np\n'), ((8756, ...