code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import numpy as np
from mcts import MCTS
class Evaluator(object):
def __init__(self, env, action_num):
self.env = env
self.action_num = action_num
self.is_terminated = False
def __call__(self, state):
return np.ones([self.action_num]), 0
'''
# TODO: prior for r... | [
"numpy.random.uniform",
"mcts.MCTS",
"numpy.ones",
"numpy.argmax"
] | [((2766, 2811), 'mcts.MCTS', 'MCTS', (['env', 'evaluator', 'root_node'], {'action_num': '(2)'}), '(env, evaluator, root_node, action_num=2)\n', (2770, 2811), False, 'from mcts import MCTS\n'), ((2960, 2984), 'numpy.argmax', 'np.argmax', (['mcts.root.ucb'], {}), '(mcts.root.ucb)\n', (2969, 2984), True, 'import numpy as ... |
# Copyright 2020 The TensorFlow Probability 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 o... | [
"functools.partial",
"tensorflow.compat.v2.stack",
"tensorflow_probability.python.internal.test_util.main",
"inference_gym.targets.lorenz_system.ConvectionLorenzBridgeUnknownScales",
"inference_gym.targets.lorenz_system.ConvectionLorenzBridge",
"inference_gym.targets.lorenz_system.LorenzSystemUnknownScale... | [((2089, 2142), 'functools.partial', 'functools.partial', (['_make_dataset', '_full_observed_data'], {}), '(_make_dataset, _full_observed_data)\n', (2106, 2142), False, 'import functools\n'), ((7402, 7422), 'tensorflow_probability.python.internal.test_util.main', 'tfp_test_util.main', ([], {}), '()\n', (7420, 7422), Tr... |
# Authors: <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import os.path as op
import numpy as np
from numpy.testing import assert_array_almost_equal
from nose.tools import assert_true, assert_raises
from mne.io import read_raw_fif
from mne.io.pick import pick_types
from mne.event import read_events
from mne.epochs im... | [
"mne.preprocessing.stim.fix_stim_artifact",
"mne.io.read_raw_fif",
"numpy.ceil",
"os.path.dirname",
"mne.event.read_events",
"numpy.diff",
"mne.io.pick.pick_types",
"numpy.mean",
"nose.tools.assert_raises",
"numpy.where",
"numpy.array",
"mne.epochs.Epochs",
"os.path.join",
"numpy.all"
] | [((475, 509), 'os.path.join', 'op.join', (['data_path', '"""test_raw.fif"""'], {}), "(data_path, 'test_raw.fif')\n", (482, 509), True, 'import os.path as op\n'), ((524, 558), 'os.path.join', 'op.join', (['data_path', '"""test-eve.fif"""'], {}), "(data_path, 'test-eve.fif')\n", (531, 558), True, 'import os.path as op\n'... |
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# -... | [
"numpy.random.uniform",
"dragon.core.framework.config.config",
"numpy.random.seed"
] | [((5408, 5437), 'numpy.random.seed', 'numpy.random.seed', (['self._seed'], {}), '(self._seed)\n', (5425, 5437), False, 'import numpy\n'), ((2908, 2923), 'dragon.core.framework.config.config', 'config.config', ([], {}), '()\n', (2921, 2923), False, 'from dragon.core.framework import config\n'), ((4557, 4590), 'numpy.ran... |
"""Utility functions """
#%%
import os
import shutil
import numpy as np
from collections import OrderedDict
import natural_bm.backend as B
#%%
def dict_2_OrderedDict(d):
"""Convert a standard dict to a sorted, OrderedDict """
od = OrderedDict()
if d is not None:
keys = list(d.keys())
ke... | [
"os.mkdir",
"os.path.exists",
"numpy.zeros",
"natural_bm.backend.epsilon",
"numpy.max",
"numpy.min",
"os.path.normpath",
"collections.OrderedDict",
"shutil.rmtree",
"os.path.join"
] | [((244, 257), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (255, 257), False, 'from collections import OrderedDict\n'), ((490, 503), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (501, 503), False, 'from collections import OrderedDict\n'), ((638, 649), 'natural_bm.backend.epsilon', 'B.epsil... |
import os
import syft as sy
import torch
import syfertext
from pathlib import Path
import numpy as np
hook = sy.TorchHook(torch)
me = hook.local_worker
nlp = syfertext.load("en_core_web_lg", owner=me)
def test_lazy_language_model_load():
"""Test the the language model vectors are loaded only after
the first... | [
"numpy.zeros",
"syft.TorchHook",
"syfertext.load"
] | [((110, 129), 'syft.TorchHook', 'sy.TorchHook', (['torch'], {}), '(torch)\n', (122, 129), True, 'import syft as sy\n'), ((160, 202), 'syfertext.load', 'syfertext.load', (['"""en_core_web_lg"""'], {'owner': 'me'}), "('en_core_web_lg', owner=me)\n", (174, 202), False, 'import syfertext\n'), ((1145, 1167), 'numpy.zeros', ... |
import sys
import numpy as np
import asm_ops as asm
def from_hex_to_ascii(my_hex):
"""
O arquivo binario eh complicado de ler,
preciso converter manualmente do Hex para
String, lidando com palavras comecadas por 0.
"""
counter = 0
single_instr = ""
result = np.array([])
for x in range(0,len(my... | [
"numpy.append",
"asm_ops.getRegis",
"numpy.array",
"asm_ops.getName"
] | [((280, 292), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (288, 292), True, 'import numpy as np\n'), ((2925, 2937), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2933, 2937), True, 'import numpy as np\n'), ((3098, 3110), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3106, 3110), True, 'import numpy a... |
# standard library imports
from typing import Union, List, Tuple, Optional, Callable, Iterable, TYPE_CHECKING, Any
import warnings
# third party imports
import numpy as np
import pyro.infer.mcmc.util
import torch as th
from pyro.infer import NUTS, MCMC
import arviz as az
from loguru import logger
import time
import co... | [
"probeye.subroutines.stream_to_logger",
"pyro.infer.MCMC",
"arviz.from_pyro",
"probeye.subroutines.print_dict_in_rows",
"warnings.simplefilter",
"probeye.inference.torch_.noise_models.translate_noise_model",
"warnings.catch_warnings",
"probeye.inference.torch_.priors.translate_prior_template",
"torc... | [((1669, 1708), 'probeye.subroutines.check_for_uninformative_priors', 'check_for_uninformative_priors', (['problem'], {}), '(problem)\n', (1699, 1708), False, 'from probeye.subroutines import check_for_uninformative_priors\n'), ((2807, 2856), 'loguru.logger.debug', 'logger.debug', (['"""Checking parameter\'s dependenci... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Slice a 3D field.
@author: <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
def nearest(x, x0):
"""
Find the nearest point to x0 from a 1D array x and return index.
Parameters
----------
x : 1D numpy array
Axis.
x0 : sca... | [
"numpy.abs",
"numpy.meshgrid",
"matplotlib.pyplot.contourf",
"matplotlib.pyplot.axis"
] | [((1624, 1666), 'numpy.meshgrid', 'np.meshgrid', (['xyz[0]', 'xyz[1]'], {'indexing': '"""ij"""'}), "(xyz[0], xyz[1], indexing='ij')\n", (1635, 1666), True, 'import numpy as np\n'), ((1671, 1702), 'matplotlib.pyplot.contourf', 'plt.contourf', (['X', 'Y', 'a'], {}), '(X, Y, a, **kwargs)\n', (1683, 1702), True, 'import ma... |
import numpy as np
np.set_printoptions(linewidth=200)
import matplotlib.pyplot as plt
import time
plt.ion()
fig = plt.figure()
ax = fig.gca()
ax.plot([0,1],[0,1])
plt.show()
time.sleep(1)
| [
"numpy.set_printoptions",
"matplotlib.pyplot.show",
"time.sleep",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.figure"
] | [((19, 53), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'linewidth': '(200)'}), '(linewidth=200)\n', (38, 53), True, 'import numpy as np\n'), ((99, 108), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (106, 108), True, 'import matplotlib.pyplot as plt\n'), ((116, 128), 'matplotlib.pyplot.figure', 'plt... |
# Graphs of the cost C(x), revenue R(x) and the profit P(x), in thousands of dollars, are shown, where x is the number of thousands of items produced.
from sympy import solve, symbols, lambdify, diff
import matplotlib.pyplot as plt
import numpy as np
x1, y1 = symbols( 'x1, y1', positive = True )
g_xlim = [ 1, 1... | [
"sympy.symbols",
"sympy.solve",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"sympy.diff",
"sympy.lambdify",
"numpy.linspace"
] | [((267, 299), 'sympy.symbols', 'symbols', (['"""x1, y1"""'], {'positive': '(True)'}), "('x1, y1', positive=True)\n", (274, 299), False, 'from sympy import solve, symbols, lambdify, diff\n'), ((528, 540), 'sympy.symbols', 'symbols', (['"""x"""'], {}), "('x')\n", (535, 540), False, 'from sympy import solve, symbols, lamb... |
# -*- coding:utf-8 -*-
"""
Module docstring
square brackets: alt 5 []
curly brackets: alt 8 {}
backslash: alt shift 7 \
tilde: alt n ~
"""
import numpy as np
# #############################################################################
# # HELPERS
# #############################################################... | [
"numpy.zeros",
"numpy.eye",
"numpy.array"
] | [((655, 674), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (663, 674), True, 'import numpy as np\n'), ((811, 820), 'numpy.eye', 'np.eye', (['(5)'], {}), '(5)\n', (817, 820), True, 'import numpy as np\n'), ((984, 1011), 'numpy.zeros', 'np.zeros', (['(3)'], {'dtype': 'np.int32'}), '(3, dtype=np.int32)... |
from __future__ import division
import numpy as np
import cmath
#Array of wavelength[nm] and epsilon.real
# [486...1098]nm
wl_eps_real = np.array([
[486.78458, 0.99541223],
[487.88348, 1.7356131],
[489.5089, 2.2385597],
[490.06662, 2.8269281],
[490.62323, 3.3868268],
[491.71103, 3.8328402],
... | [
"numpy.array"
] | [((138, 4783), 'numpy.array', 'np.array', (['[[486.78458, 0.99541223], [487.88348, 1.7356131], [489.5089, 2.2385597], [\n 490.06662, 2.8269281], [490.62323, 3.3868268], [491.71103, 3.8328402],\n [492.5311, 4.2788568], [493.7464, 4.5564227], [494.5582, 4.784171], [\n 497.3759, 4.954956], [499.39362, 5.21116], [... |
from sklearn.tree import DecisionTreeClassifier
import numpy as np
import pandas as pd
import serial
import time
if __name__ == "__main__":
serialPort = '/dev/ttyACM0'
port = 9600
dataset = pd.read_json("./data.json")
x = np.array([])
y = np.array([])
for value in enumerate(dataset["LIGHT_VAL... | [
"serial.Serial",
"numpy.array",
"pandas.read_json",
"sklearn.tree.DecisionTreeClassifier"
] | [((203, 230), 'pandas.read_json', 'pd.read_json', (['"""./data.json"""'], {}), "('./data.json')\n", (215, 230), True, 'import pandas as pd\n'), ((240, 252), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (248, 252), True, 'import numpy as np\n'), ((261, 273), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (269,... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import os, sys
import numpy
os.environ['CC'] = 'g++'
if sys.platform == 'darwin':
os.environ['CC'] = 'clang++' # maxflow must be compiled by clang++ on OSX
coop_dir = 'coop-cut'
coop_files = ['coop_c... | [
"numpy.get_include",
"os.path.join"
] | [((449, 474), 'os.path.join', 'os.path.join', (['coop_dir', 'f'], {}), '(coop_dir, f)\n', (461, 474), False, 'import os, sys\n'), ((761, 780), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (778, 780), False, 'import numpy\n')] |
import matplotlib.pyplot as plt
import numpy as np
from skimage import morphology
def plot_img_and_mask(img, mask):
classes = mask.shape[2] if len(mask.shape) > 2 else 1
fig, ax = plt.subplots(1, classes + 1)
ax[0].set_title('Input image')
ax[0].imshow(img)
if classes > 1:
for i in range(c... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.yticks",
"numpy.logical_not",
"numpy.rot90",
"numpy.array",
"skimage.morphology.binary_hit_or_miss",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"numpy.all"
] | [((190, 218), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(classes + 1)'], {}), '(1, classes + 1)\n', (202, 218), True, 'import matplotlib.pyplot as plt\n'), ((547, 557), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (555, 557), True, 'import matplotlib.pyplot as plt\n'), ((593, 636), 'numpy.array... |
"""Implementations of single-source and all-pairs shortest path algorithms.
These algorithms are correct with negative edge lengths, unlike Dijkstra.
These algorithms provide further examples of dynamic programming.
"""
import numpy as np
from collections import defaultdict
def read_edge_file(filename):
"""Co... | [
"pandas.DataFrame",
"numpy.zeros",
"numpy.ones",
"time.time",
"numpy.vstack"
] | [((1624, 1644), 'numpy.zeros', 'np.zeros', (['(n + 1, n)'], {}), '((n + 1, n))\n', (1632, 1644), True, 'import numpy as np\n'), ((2826, 2846), 'numpy.vstack', 'np.vstack', (['all_pairs'], {}), '(all_pairs)\n', (2835, 2846), True, 'import numpy as np\n'), ((3407, 3425), 'numpy.ones', 'np.ones', (['(2, n, n)'], {}), '((2... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 6 12:13:22 2020
@author: <NAME>
ReScale the data
"""
# Import library
import pandas as pd
import numpy as np
import itertools
from sklearn.preprocessing import MinMaxScaler
from sklearn.mixture import GaussianMixture
def rescale (adata, gate=None, return_gates=False, f... | [
"pandas.DataFrame",
"numpy.abs",
"sklearn.preprocessing.MinMaxScaler",
"numpy.setdiff1d",
"sklearn.mixture.GaussianMixture",
"numpy.percentile",
"numpy.mean",
"pandas.concat",
"numpy.log1p"
] | [((1108, 1177), 'pandas.DataFrame', 'pd.DataFrame', (['adata.X'], {'columns': 'adata.var.index', 'index': 'adata.obs.index'}), '(adata.X, columns=adata.var.index, index=adata.obs.index)\n', (1120, 1177), True, 'import pandas as pd\n'), ((6545, 6559), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (6557, 6559), T... |
# coding=utf-8
# Copyright 2020 The Trax 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 a... | [
"functools.partial",
"absl.testing.absltest.main",
"numpy.random.randn",
"numpy.not_equal",
"parameterized.parameterized.expand",
"numpy.testing.assert_allclose"
] | [((1278, 1368), 'parameterized.parameterized.expand', 'parameterized.parameterized.expand', (['[(1, 100, 8), (1, 1, 8), (1, 100, 1), (2, 100, 8)]'], {}), '([(1, 100, 8), (1, 1, 8), (1, 100, 1), (2,\n 100, 8)])\n', (1312, 1368), False, 'import parameterized\n'), ((1732, 1807), 'parameterized.parameterized.expand', 'p... |
# Copyright 2021, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | [
"numpy.random.default_rng",
"absl.logging.info",
"collections.OrderedDict",
"generalization.utils.client_data_utils.convert_list_of_elems_to_tensor_slices",
"tensorflow_federated.simulation.datasets.TestClientData"
] | [((1640, 1667), 'numpy.random.default_rng', 'np.random.default_rng', (['seed'], {}), '(seed)\n', (1661, 1667), True, 'import numpy as np\n'), ((1981, 2024), 'absl.logging.info', 'logging.info', (['"""Starting unpacking dataset."""'], {}), "('Starting unpacking dataset.')\n", (1993, 2024), False, 'from absl import loggi... |
import numpy as np
import copy
import pytest
from ogusa import tax
from ogusa.parameters import Specifications
p = Specifications()
new_param_values = {
'S': 4,
'J': 1,
'T': 4,
'eta': (np.ones((4, 1)) / (4 * 1))
}
p.update_specifications(new_param_values)
p.retire = [3, 3, 3, 3, 3, 3, 3, 3]
p1 = copy.... | [
"copy.deepcopy",
"ogusa.tax.MTR_income",
"numpy.allclose",
"numpy.ones",
"ogusa.tax.ETR_wealth",
"ogusa.parameters.Specifications",
"ogusa.tax.replacement_rate_vals",
"ogusa.tax.MTR_wealth",
"ogusa.tax.ETR_income",
"numpy.array",
"ogusa.tax.get_biz_tax",
"numpy.reshape",
"ogusa.tax.total_tax... | [((117, 133), 'ogusa.parameters.Specifications', 'Specifications', ([], {}), '()\n', (131, 133), False, 'from ogusa.parameters import Specifications\n'), ((315, 331), 'copy.deepcopy', 'copy.deepcopy', (['p'], {}), '(p)\n', (328, 331), False, 'import copy\n'), ((337, 353), 'copy.deepcopy', 'copy.deepcopy', (['p'], {}), ... |
"""Fitting Tools Library
@author: <NAME>
@date: 15 Jan 2018
"""
import warnings
import numpy as np
from scipy.signal import tf2ss
import scipy.linalg as scalg
import scipy.optimize as scopt
import multiprocessing as mpr
import itertools
def fpoly(kv,B0,B1,B2,dyv,ddyv):
return B0+B1*dyv+B2*ddyv
def fpade(kv,C... | [
"numpy.roots",
"numpy.abs",
"numpy.sum",
"scipy.optimize.leastsq",
"numpy.exp",
"numpy.polyval",
"numpy.polyder",
"scipy.signal.tf2ss",
"numpy.max",
"itertools.product",
"scipy.linalg.block_diag",
"scipy.optimize.differential_evolution",
"numpy.hstack",
"multiprocessing.Pool",
"numpy.con... | [((2287, 2307), 'numpy.polyval', 'np.polyval', (['cnum', 'zv'], {}), '(cnum, zv)\n', (2297, 2307), True, 'import numpy as np\n'), ((2314, 2334), 'numpy.polyval', 'np.polyval', (['cden', 'zv'], {}), '(cden, zv)\n', (2324, 2334), True, 'import numpy as np\n'), ((3389, 3406), 'numpy.abs', 'np.abs', (['(Yfit - Yv)'], {}), ... |
import numpy as np
import scipy
#from scipy import signal
from scipy.signal import find_peaks, peak_widths, peak_prominences
class PeakDetection():
#Peakutils
def __init__(self, Intensity, prom):
self.set_x(Intensity, prom)
def get_Peaks(self):
return self.__Peaks
def get_Valleys(sel... | [
"numpy.array"
] | [((638, 650), 'numpy.array', 'np.array', (['In'], {}), '(In)\n', (646, 650), True, 'import numpy as np\n'), ((904, 916), 'numpy.array', 'np.array', (['In'], {}), '(In)\n', (912, 916), True, 'import numpy as np\n'), ((724, 736), 'numpy.array', 'np.array', (['In'], {}), '(In)\n', (732, 736), True, 'import numpy as np\n')... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 10 13:42:17 2019
@author: vpandey
This function implements the density and ratio feedback control heuristics
"""
import gym
import numpy as np
import pandas as pd
#import seaborn as sns; sns.set()
import gym_meme
#import matplotlib.pyplot as plt
i... | [
"argparse.ArgumentParser",
"gym.make",
"time.time",
"random.random",
"numpy.array",
"random.seed",
"numpy.linspace"
] | [((432, 500), 'gym.make', 'gym.make', (['"""meme-v0"""'], {'netname': 'netName', 'objective': 'objective', 'seed': 'seed'}), "('meme-v0', netname=netName, objective=objective, seed=seed)\n", (440, 500), False, 'import gym\n'), ((1092, 1109), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1103, 1109), True, ... |
import torch
import os, sys
import torch.nn.functional as F
import numpy as np
from ..langevin import Langevin
from torch.utils.data import DataLoader
from .config_getters import get_models, get_optimizers, get_datasets, get_plotter, get_logger
import datetime
from tqdm import tqdm
from .ema import EMAHelper
from . imp... | [
"os.mkdir",
"numpy.random.seed",
"torch.sqrt",
"torch.randn",
"torch.nn.ModuleDict",
"numpy.mean",
"torch.no_grad",
"torch.distributions.categorical.Categorical",
"torch.utils.data.DataLoader",
"numpy.std",
"numpy.geomspace",
"torch.load",
"os.path.exists",
"random.seed",
"numpy.linspace... | [((781, 830), 'accelerate.Accelerator', 'Accelerator', ([], {'fp16': '(False)', 'cpu': "(args.device == 'cpu')"}), "(fp16=False, cpu=args.device == 'cpu')\n", (792, 830), False, 'from accelerate import Accelerator, DistributedType\n'), ((1676, 1693), 'torch.sum', 'torch.sum', (['gammas'], {}), '(gammas)\n', (1685, 1693... |
import os
from typing import Iterator, List
import yaml
import numpy as np
from google.protobuf.json_format import MessageToDict
from jina.proto import jina_pb2
from jina.drivers.helper import array2pb
def load_config():
try:
with open('config.yml') as f:
config = yaml.safe_load(f)
r... | [
"jina.proto.jina_pb2.Document",
"os.makedirs",
"os.path.dirname",
"os.path.isfile",
"numpy.random.random",
"yaml.safe_load"
] | [((1083, 1126), 'os.makedirs', 'os.makedirs', (["env['FILE_DIR']"], {'exist_ok': '(True)'}), "(env['FILE_DIR'], exist_ok=True)\n", (1094, 1126), False, 'import os\n'), ((1907, 1932), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1922, 1932), False, 'import os\n'), ((2667, 2686), 'jina.proto... |
from __future__ import print_function
import torch
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
from modules.stn import STN
from modules.gridgen import AffineGridGen, CylinderGridGen, CylinderGridGenV2, DenseAffine3DGridGen, DenseAffine3DGridGen_rotate
import time
nframes = 64
height... | [
"modules.stn.STN",
"modules.gridgen.AffineGridGen",
"torch.autograd.Variable",
"time.time",
"numpy.array",
"torch.zeros",
"torch.cuda.device"
] | [((367, 412), 'torch.zeros', 'torch.zeros', (['nframes', 'height', 'width', 'channels'], {}), '(nframes, height, width, channels)\n', (378, 412), False, 'import torch\n'), ((421, 459), 'torch.zeros', 'torch.zeros', (['nframes', 'height', 'width', '(2)'], {}), '(nframes, height, width, 2)\n', (432, 459), False, 'import ... |
#!/usr/bin/env python
import numpy as np
import os
import matplotlib as mpl
from matplotlib import pyplot as plt
from mpl_tools.helpers import savefig
import pytest
from gna.unittest import allure_attach_file, savegraph
from load import ROOT as R
from gna import constructors as C
@pytest.mark.parametrize('strategy',... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.close",
"gna.unittest.allure_attach_file",
"gna.constructors.Points",
"matplotlib.pyplot.figure",
"mpl_tools.helpers.savefig",
"numpy.arange",
"numpy.exp",
"numpy.linspace",
"pytest.mark.parametrize",
"gna.unittest.savegraph"
] | [((285, 408), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""strategy"""', '[R.GNA.Interpolation.Strategy.Extrapolate, R.GNA.Interpolation.Strategy.\n Constant]'], {}), "('strategy', [R.GNA.Interpolation.Strategy.\n Extrapolate, R.GNA.Interpolation.Strategy.Constant])\n", (308, 408), False, 'import p... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
def moving_average(data, window_size=10):
''' Calculate moving average with given window size.
Args:
data: List of floats.
window_size: Integer size of moving window.
Returns:
List of rolling averages with g... | [
"matplotlib.pyplot.show",
"numpy.std",
"numpy.insert",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.min",
"numpy.max",
"matplotlib.pyplot.savefig"
] | [((1630, 1657), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 7)'}), '(figsize=(10, 7))\n', (1640, 1657), True, 'import matplotlib.pyplot as plt\n'), ((5236, 5260), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plots.png"""'], {}), "('plots.png')\n", (5247, 5260), True, 'import matplotlib.pyplot ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pdb
import os
class neuralnetwork(object):
def __init__(self, x, t, hDim=20):
#pdb.set_trace()
# 入力データの次元
xDim = x.shape[1]
# 隠れ層のノード数
hDim = hDim
# カテゴリ数
tDim = t.shape[1]
... | [
"numpy.random.seed",
"numpy.sum",
"pandas.read_csv",
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"numpy.exp",
"pandas.DataFrame",
"numpy.std",
"numpy.append",
"numpy.max",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"numpy.random.permutation",
"mat... | [((5414, 5431), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (5428, 5431), True, 'import numpy as np\n'), ((5458, 5489), 'numpy.random.permutation', 'np.random.permutation', (['data_num'], {}), '(data_num)\n', (5479, 5489), True, 'import numpy as np\n'), ((6148, 6200), 'numpy.append', 'np.append', (['... |
from .physical_constants import unit_registry
from .tools import dict_to_quantity
from .tools import vprint, mean
import numpy as np
ALLOWED_VARIABLES = ['x','y','z','t','r','theta','px','py','pz','pr','ptheta','xp','yp']
def get_variables(varstr):
if(varstr):
varstr=varstr.strip()
variables = v... | [
"numpy.power",
"numpy.zeros",
"numpy.sin",
"numpy.cos",
"numpy.sqrt"
] | [((4646, 4659), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (4652, 4659), True, 'import numpy as np\n'), ((4668, 4681), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (4674, 4681), True, 'import numpy as np\n'), ((6898, 6932), 'numpy.zeros', 'np.zeros', (['beam[variables[1]].shape'], {}), '(beam[variable... |
# -*- encoding:utf-8 -*-
"""
交易执行模块
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import logging
import numpy as np
import pandas as pd
from ..UtilBu import ABuDateUtil, AbuProgress
from ..TradeBu.ABuMLFeature import AbuMlFeature
# noinspection ... | [
"logging.info",
"numpy.where",
"pandas.to_datetime",
"numpy.arange",
"numpy.array",
"numpy.round",
"pandas.concat"
] | [((2686, 2711), 'pandas.to_datetime', 'pd.to_datetime', (['dates_fmt'], {}), '(dates_fmt)\n', (2700, 2711), True, 'import pandas as pd\n'), ((3430, 3463), 'numpy.round', 'np.round', (['c_ss.values'], {'decimals': '(2)'}), '(c_ss.values, decimals=2)\n', (3438, 3463), True, 'import numpy as np\n'), ((3567, 3619), 'numpy.... |
"""
Some utility functions need to generate PathConstraints. Most are
specific to different scenarios.
"""
import logging, coloredlogs
import numpy as np
LOGGER = logging.getLogger(__name__)
def setup_logging(level="WARN"):
""" Setup basic logging facility to console.
"""
coloredlogs.install(logger=loggi... | [
"numpy.copy",
"numpy.isscalar",
"logging.getLogger",
"numpy.diff",
"numpy.array",
"numpy.linspace",
"numpy.vstack"
] | [((164, 191), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (181, 191), False, 'import logging, coloredlogs\n'), ((1031, 1058), 'numpy.vstack', 'np.vstack', (['(J_trans, J_rot)'], {}), '((J_trans, J_rot))\n', (1040, 1058), True, 'import numpy as np\n'), ((1851, 1865), 'numpy.isscalar', '... |
import numpy as np
import matplotlib.pyplot as plt
import os
import shutil
import imageio
def plotAndSave(X, Y, path):
plt.cla()
plt.bar(X, Y)
plt.savefig(path)
def checkfile(path):
if not os.path.exists(path):
os.mkdir(path)
else:
shutil.rmtree(path)
os.mkdir(path)
if ... | [
"os.mkdir",
"imageio.mimsave",
"matplotlib.pyplot.bar",
"imageio.imread",
"os.path.exists",
"numpy.random.randint",
"matplotlib.pyplot.cla",
"shutil.rmtree",
"matplotlib.pyplot.savefig"
] | [((125, 134), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (132, 134), True, 'import matplotlib.pyplot as plt\n'), ((139, 152), 'matplotlib.pyplot.bar', 'plt.bar', (['X', 'Y'], {}), '(X, Y)\n', (146, 152), True, 'import matplotlib.pyplot as plt\n'), ((157, 174), 'matplotlib.pyplot.savefig', 'plt.savefig', (['p... |
from textwrap import dedent
import numpy as np
import pytest
import astropy.units as u
from astropy.io import fits
from sunpy.map import Map
from sunpy.map.sources.hinode import SOTMap
from sunpy.util.exceptions import SunpyMetadataWarning
@pytest.fixture
def sot():
raw_header = dedent("""\
SIMPLE = ... | [
"textwrap.dedent",
"sunpy.map.Map",
"pytest.warns",
"astropy.io.fits.Header.fromstring",
"numpy.random.rand"
] | [((289, 6456), 'textwrap.dedent', 'dedent', (['""" SIMPLE = T / created Wed Oct 21 17:17:46 2015\n BITPIX = 16\n NAXIS = 2\n NAXIS1 = 2048\n NAXIS2 = 1024\n EXTEND = ... |
from matchingmarkets.agent import Agent
from matchingmarkets.market import Market
from matchingmarkets.simulations import simulation
from matchingmarkets.algorithms import *
from matchingmarkets.metaalgorithms import *
from matchingmarkets.generators.basic import *
def FullTest():
"""
Runs tests on ... | [
"numpy.random.randint",
"numpy.random.random_sample",
"numpy.random.random"
] | [((526, 544), 'numpy.random.randint', 'rng.randint', (['(1)', '(25)'], {}), '(1, 25)\n', (537, 544), True, 'import numpy.random as rng\n'), ((2355, 2372), 'numpy.random.randint', 'rng.randint', (['(1)', '(5)'], {}), '(1, 5)\n', (2366, 2372), True, 'import numpy.random as rng\n'), ((2805, 2822), 'numpy.random.randint', ... |
#!/usr/bin/env python
# encoding: utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2013-2015 CNRS
#
# 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 li... | [
"logging.debug",
"numpy.log",
"numpy.median",
"subprocess.check_output",
"lxml.objectify.fromstring",
"six.iteritems"
] | [((7263, 7296), 'numpy.median', 'np.median', (['durations[:number + 1]'], {}), '(durations[:number + 1])\n', (7272, 7296), True, 'import numpy as np\n'), ((2326, 2393), 'subprocess.check_output', 'subprocess.check_output', (["[lsdvd, '-Ox', '-avs', self.dvd]"], {'stderr': 'f'}), "([lsdvd, '-Ox', '-avs', self.dvd], stde... |
'''
Created on 24.05.2021
@author: HD
'''
import numpy as np
from scipy.integrate import odeint # solve ode
from lmfit import minimize, Parameters, Parameter, report_fit # fitting
class Modeler:
def __init__(self):
'''
Helper Class to model data from EnzymeML document
Args:
'''
... | [
"scipy.integrate.odeint",
"numpy.max",
"numpy.mean",
"lmfit.minimize"
] | [((648, 680), 'scipy.integrate.odeint', 'odeint', (['f', 'w0', 't'], {'args': '(params,)'}), '(f, w0, t, args=(params,))\n', (654, 680), False, 'from scipy.integrate import odeint\n'), ((2845, 2866), 'numpy.max', 'np.max', (['v_all'], {'axis': '(0)'}), '(v_all, axis=0)\n', (2851, 2866), True, 'import numpy as np\n'), (... |
import sounddevice
import numpy
class Noise():
def __init__(self,
sample_rate=16000,
duration=0.5):
"""Noise measurement.
:param sample_rate: Sample rate in Hz
:param duraton: Duration, in seconds, of noise sample capture
"""
self.durati... | [
"numpy.fft.rfft",
"numpy.mean"
] | [((1368, 1400), 'numpy.mean', 'numpy.mean', (['magnitude[start:end]'], {}), '(magnitude[start:end])\n', (1378, 1400), False, 'import numpy\n'), ((2611, 2655), 'numpy.mean', 'numpy.mean', (['magnitude[noise_floor:mid_start]'], {}), '(magnitude[noise_floor:mid_start])\n', (2621, 2655), False, 'import numpy\n'), ((2674, 2... |
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2015-2018 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the Licen... | [
"openquake.commonlib.util.compose_arrays",
"openquake.commonlib.util.get_assets",
"openquake.commonlib.calc.convert_to_array",
"openquake.hazardlib.gsim.base.ContextMaker",
"numpy.isnan",
"openquake.commonlib.source.capitalize",
"numpy.mean",
"openquake.baselib.python3compat.decode",
"numpy.std",
... | [((4648, 4686), 'numpy.dtype', 'numpy.dtype', (["(pairs + [('counts', int)])"], {}), "(pairs + [('counts', int)])\n", (4659, 4686), False, 'import numpy\n'), ((11617, 11641), 'openquake.baselib.general.humansize', 'humansize', (["attrs['sent']"], {}), "(attrs['sent'])\n", (11626, 11641), False, 'from openquake.baselib.... |
from typing import *
import numpy as np
from numpy import ndarray
from . import _tensor
if TYPE_CHECKING:
from _tensor import Tensor
def filter_types(objs, types: Union[Type, Tuple[Type]]):
return filter(lambda x: isinstance(x, types), objs)
class Context:
def __setitem__(self, key, value):
sel... | [
"numpy.ndarray",
"_tensor.Tensor"
] | [((7358, 7370), 'numpy.ndarray', 'np.ndarray', ([], {}), '()\n', (7368, 7370), True, 'import numpy as np\n'), ((2973, 2982), '_tensor.Tensor', 'Tensor', (['(0)'], {}), '(0)\n', (2979, 2982), False, 'from _tensor import Tensor\n'), ((3481, 3490), '_tensor.Tensor', 'Tensor', (['(0)'], {}), '(0)\n', (3487, 3490), False, '... |
import streamlit as st
import mediapipe as mp
import cv2
import numpy as np
import tempfile
import time
from PIL import Image
from Utils.Visualizer import show_image
from mediapipe.python.solutions import pose as mp_pose
from ParseClassifier import avengers_assemble
font = cv2.FONT_HERSHEY_SIMPLEX
test = False
# org
... | [
"streamlit.sidebar.slider",
"streamlit.sidebar.subheader",
"cv2.VideoWriter_fourcc",
"streamlit.title",
"streamlit.sidebar.title",
"streamlit.sidebar.selectbox",
"cv2.VideoWriter",
"streamlit.sidebar.button",
"streamlit.stop",
"streamlit.cache",
"streamlit.sidebar.checkbox",
"cv2.cvtColor",
... | [((584, 604), 'ParseClassifier.avengers_assemble', 'avengers_assemble', (['(0)'], {}), '(0)\n', (601, 604), False, 'from ParseClassifier import avengers_assemble\n'), ((738, 803), 'streamlit.title', 'st.title', (['"""Pose Corrector AI Trainer Application using MediaPipe"""'], {}), "('Pose Corrector AI Trainer Applicati... |
from datetime import datetime
startTime = datetime.now()
import pandas as pd
import numpy as np
import sys
sys.path.insert(0, '')
import MAIN.Basics as basics
import MAIN.Reinforcement as RL
import tensorflow as tf
import seaborn as sns
#import matplotlib.pyplot as plt
from UTIL import FileIO
from STRATEGY.Cointegrat... | [
"pickle.dump",
"tensorflow.ones_initializer",
"pandas.read_csv",
"MAIN.Reinforcement.ContextualBandit",
"pickle.load",
"numpy.arange",
"numpy.mean",
"STRATEGY.Cointegration.EGCointegration.clean_data",
"pandas.DataFrame",
"numpy.savetxt",
"tensorflow.placeholder",
"datetime.datetime.now",
"t... | [((42, 56), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (54, 56), False, 'from datetime import datetime\n'), ((108, 130), 'sys.path.insert', 'sys.path.insert', (['(0)', '""""""'], {}), "(0, '')\n", (123, 130), False, 'import sys\n'), ((477, 506), 'UTIL.FileIO.read_yaml', 'FileIO.read_yaml', (['config_pat... |
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import sys
# mpl.use('MACOSX')
mpl.rcParams["errorbar.capsize"] = 2
BIGGER_SIZE = 23
plt.rc('font', size=BIGGER_SIZE) # controls default text sizes
plt.rc('axes', titlesize=BIGGER_SIZE) ... | [
"pandas.read_csv",
"numpy.std",
"matplotlib.pyplot.subplots",
"numpy.mean",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig"
] | [((207, 239), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': 'BIGGER_SIZE'}), "('font', size=BIGGER_SIZE)\n", (213, 239), True, 'import matplotlib.pyplot as plt\n'), ((279, 316), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'titlesize': 'BIGGER_SIZE'}), "('axes', titlesize=BIGGER_SIZE)\n", (285, 316... |
# -*- coding: utf8 -*-
# board
# helper class for cuatro
# <NAME> 2021
version = 'board.v.1.0.0'
import numpy as np
from classes.rotate import Rotate
class Board:
"""the instance of this class represents the board
instance attributes:
rotor: instance of Rotor class
colors: tuple of two tuples of thr... | [
"numpy.array",
"classes.rotate.Rotate",
"numpy.concatenate"
] | [((1284, 1292), 'classes.rotate.Rotate', 'Rotate', ([], {}), '()\n', (1290, 1292), False, 'from classes.rotate import Rotate\n'), ((2547, 2561), 'numpy.array', 'np.array', (['cube'], {}), '(cube)\n', (2555, 2561), True, 'import numpy as np\n'), ((3965, 4004), 'numpy.concatenate', 'np.concatenate', (['self.polygons3d'],... |
# -*- coding: utf-8 -*-
"""reVX RPM unit test module
"""
from click.testing import CliRunner
import json
import numpy as np
import os
import pytest
import pandas as pd
import tempfile
import traceback
from rex.utilities.loggers import LOGGERS
from rex.utilities.utilities import check_tz
from reVX import TESTDATADIR
f... | [
"json.dump",
"tempfile.TemporaryDirectory",
"reVX.rpm.rpm_manager.RPMClusterManager.run_clusters_and_profiles",
"os.path.basename",
"pandas.read_csv",
"numpy.allclose",
"pytest.fixture",
"traceback.print_exception",
"pandas.to_datetime",
"rex.utilities.loggers.LOGGERS.clear",
"pytest.mark.parame... | [((435, 497), 'os.path.join', 'os.path.join', (['TESTDATADIR', '"""reV_gen"""', '"""gen_ri_pv_2012_x000.h5"""'], {}), "(TESTDATADIR, 'reV_gen', 'gen_ri_pv_2012_x000.h5')\n", (447, 497), False, 'import os\n'), ((535, 597), 'os.path.join', 'os.path.join', (['TESTDATADIR', '"""ri_exclusions"""', '"""ri_exclusions.h5"""'],... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 9 11:21:10 2020
@author: <NAME>
"""
import sys
import numpy as np
import Organization as og
import data_manager as dm
import matplotlib.pyplot as plt
import datetime as dt
from numpy.random import default_rng
# Create the random number generator
rng = default_rng()
de... | [
"data_manager.generate_levels",
"sys.platform.startswith",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.tight_layout",
"numpy.sum",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"datetime.datetime.now",
"data_manager.mean_culture_lev... | [((303, 316), 'numpy.random.default_rng', 'default_rng', ([], {}), '()\n', (314, 316), False, 'from numpy.random import default_rng\n'), ((3504, 3526), 'numpy.sum', 'np.sum', (['is_pop'], {'axis': '(1)'}), '(is_pop, axis=1)\n', (3510, 3526), True, 'import numpy as np\n'), ((3744, 3761), 'datetime.datetime.now', 'dt.dat... |
import numpy as np
import pandas as pd
from precise.skatertools.m6.covarianceforecasting import m6_cov
from precise.skatertools.m6.tilting import affection_tilt
# M6 Quintile probability estimates by Monte Carlo
def what_pctl_number_of(x, a, pctls=[20,40,60,80]):
return np.argmax(np.sign(np.append(np.percentile(... | [
"pandas.DataFrame",
"numpy.quantile",
"precise.skatertools.m6.tilting.affection_tilt",
"numpy.zeros",
"numpy.searchsorted",
"numpy.shape",
"numpy.percentile",
"precise.skatertools.m6.covarianceforecasting.m6_cov",
"numpy.mean",
"numpy.array",
"numpy.random.multivariate_normal"
] | [((492, 582), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['mu', 'sgma'], {'size': 'n_samples', 'check_valid': '"""warn"""', 'tol': '(1e-08)'}), "(mu, sgma, size=n_samples, check_valid='warn',\n tol=1e-08)\n", (521, 582), True, 'import numpy as np\n'), ((890, 902), 'numpy.array', 'np.array'... |
""" Base mutual information estimators. """
from numpy import sum, sqrt, isnan, exp, mean, eye, ones, dot, cumsum, \
hstack, newaxis, maximum, prod, abs, arange, log
from numpy.linalg import norm
from scipy.spatial.distance import pdist, squareform
from scipy.special import factorial
from scipy.linal... | [
"numpy.sum",
"numpy.maximum",
"numpy.abs",
"numpy.ones",
"numpy.isnan",
"numpy.mean",
"ite.shared.copula_transformation",
"numpy.exp",
"scipy.spatial.distance.pdist",
"numpy.arange",
"numpy.prod",
"ite.shared.compute_dcov_dcorr_statistics",
"scipy.special.factorial",
"scipy.sparse.linalg.e... | [((3191, 3246), 'ite.shared.compute_dcov_dcorr_statistics', 'compute_dcov_dcorr_statistics', (['y[:, :ds[0]]', 'self.alpha'], {}), '(y[:, :ds[0]], self.alpha)\n', (3220, 3246), False, 'from ite.shared import compute_dcov_dcorr_statistics, median_heuristic, copula_transformation, compute_matrix_r_kcca_kgv\n'), ((3259, 3... |
'''2. Un programa pide la edad de 5 personas, se almacenan en 5 variables (no hemos visto arreglos). El programa entrega el promedio, la suma y la desviación estándar de las edades. Tanto el promedio como la desv. estándar deben ser calculados por su fórmula y no usando las funciones que trae python'''
import numpy
#... | [
"numpy.std"
] | [((1178, 1195), 'numpy.std', 'numpy.std', (['edades'], {}), '(edades)\n', (1187, 1195), False, 'import numpy\n')] |
# -*- coding: utf-8 -*-
""" Sahana Eden Vulnerability Model
@copyright: 2012 (c) Sahana Software Foundation
@license: MIT
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 with... | [
"gluon.storage.Storage",
"numpy.median"
] | [((8904, 9080), 'gluon.storage.Storage', 'Storage', ([], {'vulnerability_resilience_id': 'self.vulnerability_resilience_id', 'vulnerability_ids': 'self.vulnerability_ids', 'vulnerability_resilience': 'self.vulnerability_resilience'}), '(vulnerability_resilience_id=self.vulnerability_resilience_id,\n vulnerability_id... |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | [
"numpy.maximum",
"tensorflow.multiply",
"tensorflow.ConfigProto",
"numpy.mean",
"skimage.transform.resize",
"numpy.tile",
"input_data.read_clip_and_label",
"tensorflow.get_variable",
"guided_backpro.GuideBackPro",
"tensorflow.nn.softmax",
"c3d_model.inference_c3d_full_conv",
"tensorflow.nn.avg... | [((1793, 1817), 'tensorflow.nn.bias_add', 'tf.nn.bias_add', (['conv', '(-b)'], {}), '(conv, -b)\n', (1807, 1817), True, 'import tensorflow as tf\n'), ((1827, 1906), 'tensorflow.nn.conv3d_transpose', 'tf.nn.conv3d_transpose', (['temp', 'w', 'shape'], {'strides': '[1, 1, 1, 1, 1]', 'padding': '"""SAME"""'}), "(temp, w, s... |
import cv2 as cv
import numpy as np
IMAGE = cv.imread('D:\@Semester 06\Digital Image Processing\Lab\Manuals\Figures\lab7\_img1.png', 0)
print(IMAGE.shape)
def padding(axis, _m, p): # Padd extra row/cow to end of img so that whole img has now equal size blocks
while axis % _m != 0: # If rows/cols cannot be di... | [
"numpy.pad",
"cv2.waitKey",
"cv2.destroyAllWindows",
"numpy.zeros",
"numpy.shape",
"cv2.imread",
"numpy.mean",
"cv2.imshow"
] | [((45, 153), 'cv2.imread', 'cv.imread', (['"""D:\\\\@Semester 06\\\\Digital Image Processing\\\\Lab\\\\Manuals\\\\Figures\\\\lab7\\\\_img1.png"""', '(0)'], {}), "(\n 'D:\\\\@Semester 06\\\\Digital Image Processing\\\\Lab\\\\Manuals\\\\Figures\\\\lab7\\\\_img1.png'\n , 0)\n", (54, 153), True, 'import cv2 as cv\n')... |
import numpy
from numba import prange
from .._common import dist2d, jitted
@jitted("f8(f8[:], f8[:], f8[:, :], f8, f8, f8, f8, f8, f8)")
def _vinterp2d(x, y, v, xq, yq, xsrc, ysrc, vzero, fval):
"""Perform bilinear apparent velocity interpolation."""
condx = x[0] <= xq <= x[-1]
condy = y[0] <= yq <= y[-1... | [
"numpy.abs",
"numpy.empty",
"numpy.searchsorted",
"numpy.shape",
"numba.prange"
] | [((2841, 2877), 'numpy.empty', 'numpy.empty', (['nq'], {'dtype': 'numpy.float64'}), '(nq, dtype=numpy.float64)\n', (2852, 2877), False, 'import numpy\n'), ((2891, 2901), 'numba.prange', 'prange', (['nq'], {}), '(nq)\n', (2897, 2901), False, 'from numba import prange\n'), ((383, 424), 'numpy.searchsorted', 'numpy.search... |
import numpy as np
from ..lump import Lump, LumpType, LumpInfo
class EdgeLump(Lump):
LUMP_TYPE = LumpType.LUMP_EDGES
def __init__(self, info: LumpInfo):
super().__init__(info)
self.values = np.array([])
def parse(self):
self.values = np.frombuffer(self.buffer.read(self.info.leng... | [
"numpy.array"
] | [((218, 230), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (226, 230), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
#
# blob_detection.py
#
"""Framework for image BLOB detection."""
import sys
import numpy as np
from skimage import measure
def blob_detection(
image, th=None, black_blobs=True, min_area=None, max_area=None
):
"""Perform detection of BLOBs in binary image.
Args:
... | [
"numpy.copy",
"numpy.trim_zeros",
"numpy.logical_not",
"numpy.float",
"numpy.shape",
"numpy.array",
"numpy.arange"
] | [((688, 703), 'numpy.shape', 'np.shape', (['image'], {}), '(image)\n', (696, 703), True, 'import numpy as np\n'), ((1002, 1027), 'numpy.trim_zeros', 'np.trim_zeros', (['areas', '"""b"""'], {}), "(areas, 'b')\n", (1015, 1027), True, 'import numpy as np\n'), ((2148, 2173), 'numpy.trim_zeros', 'np.trim_zeros', (['areas', ... |
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpathes
import random
class boxplot:
def boxplot(ax,
Data,
outlier=True,
box_facecolor='white',
box_edgecolor='k',
outlier_facecolor='r',
... | [
"numpy.quantile",
"matplotlib.pyplot.show",
"matplotlib.patches.Rectangle",
"random.uniform",
"matplotlib.patches.FancyArrowPatch",
"matplotlib.patches.Ellipse"
] | [((2844, 2854), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2852, 2854), True, 'import matplotlib.pyplot as plt\n'), ((5900, 5910), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5908, 5910), True, 'import matplotlib.pyplot as plt\n'), ((9682, 9692), 'matplotlib.pyplot.show', 'plt.show', ([], {})... |
import numpy as np
import pandas as pd
import tensorflow as tf
import time
max_len = 12 # maximum peptide length
k = 5 # k-mer length
pad = '_'
#alphabet = ['V', 'H', 'L', 'A', 'N', 'P', 'Y', 'W', 'T', 'E', 'Q', 'G', 'M', 'S', 'R', 'D', 'C', 'I', 'K', 'F',pad]
alphabet = [pad,'V', 'H', 'L', 'A', 'N', 'P', 'Y', 'W', '... | [
"tensorflow.reduce_sum",
"pandas.HDFStore",
"numpy.argmax",
"tensorflow.math.floor",
"tensorflow.reshape",
"tensorflow.zeros_like",
"numpy.arange",
"tensorflow.unique",
"tensorflow.reduce_max",
"pandas.DataFrame",
"tensorflow.nn.max_pool_with_argmax",
"numpy.eye",
"tensorflow.logical_and",
... | [((1023, 1034), 'numpy.array', 'np.array', (['a'], {}), '(a)\n', (1031, 1034), True, 'import numpy as np\n'), ((1137, 1168), 'numpy.argmax', 'np.argmax', (['one_hot_vec'], {'axis': '(-1)'}), '(one_hot_vec, axis=-1)\n', (1146, 1168), True, 'import numpy as np\n'), ((2635, 2657), 'numpy.array', 'np.array', (['kmer_one_ho... |
import time
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import itertools
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn as nn
import torchvision.transforms as transforms
import torch.utils.data as torchdata
import os
from PIL import Image
def... | [
"numpy.random.seed",
"torch.cat",
"numpy.random.randint",
"torch.arange",
"torchvision.transforms.Normalize",
"torch.utils.data.DataLoader",
"torch.cuda.FloatTensor",
"numpy.transpose",
"torch.cuda.LongTensor",
"torchvision.transforms.RandomHorizontalFlip",
"torch.manual_seed",
"torch.cuda.man... | [((2648, 2675), 'numpy.random.randint', 'np.random.randint', (['(1)', '(10000)'], {}), '(1, 10000)\n', (2665, 2675), True, 'import numpy as np\n'), ((2711, 2731), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2725, 2731), True, 'import numpy as np\n'), ((2737, 2760), 'torch.manual_seed', 'torch.ma... |
from pymoo.algorithms.nsga2 import NSGA2
from pymoo.factory import get_problem
from pymoo.optimize import minimize
import numpy as np
problem = get_problem("zdt3", n_var=5)
np.random.seed(10)
print(np.random.random())
def my_callback(method):
X = np.loadtxt("gen_%s.csv" % method.n_gen)
_X = method.pop.get("... | [
"numpy.random.seed",
"numpy.abs",
"pymoo.optimize.minimize",
"numpy.random.random",
"numpy.loadtxt",
"pymoo.algorithms.nsga2.NSGA2",
"pymoo.factory.get_problem"
] | [((145, 173), 'pymoo.factory.get_problem', 'get_problem', (['"""zdt3"""'], {'n_var': '(5)'}), "('zdt3', n_var=5)\n", (156, 173), False, 'from pymoo.factory import get_problem\n'), ((175, 193), 'numpy.random.seed', 'np.random.seed', (['(10)'], {}), '(10)\n', (189, 193), True, 'import numpy as np\n'), ((398, 467), 'pymoo... |
from .Gaits import GaitController
from .StanceController import StanceController
from .SwingLegController import SwingController
from .Utilities import clipped_first_order_filter
from .State import BehaviorState, State
from ..spot_micro_kinematics.utilities.transformations import rotz
import numpy as np
#from transfor... | [
"numpy.array",
"numpy.zeros"
] | [((767, 778), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (775, 778), True, 'import numpy as np\n'), ((1942, 1958), 'numpy.zeros', 'np.zeros', (['(3, 4)'], {}), '((3, 4))\n', (1950, 1958), True, 'import numpy as np\n'), ((7148, 7180), 'numpy.array', 'np.array', (['[0, 0, command.height]'], {}), '([0, 0, command.... |
# import packages
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import time
import datetime as dt
import json
from path... | [
"feature_engineering_functions.drop_rows_value",
"feature_engineering_functions.add_list_as_column",
"sklearn.preprocessing.StandardScaler",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"pathlib.Path",
"feature_engineering_functions.add_parent_name",
"os.path.join",
"feature_engine... | [((384, 417), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (407, 417), False, 'import warnings\n'), ((1256, 1301), 'feature_engineering_functions.drop_rows_value', 'fef.drop_rows_value', (['df', '"""state"""', '"""suspended"""'], {}), "(df, 'state', 'suspended')\n", (127... |
import numpy as np
import scipy.sparse as sp
import re
# argmax over csr sparse matrix, inspired from:
# http://stackoverflow.com/questions/30742572/argmax-of-each-row-or-column-in-scipy-sparse-matrix
# http://stackoverflow.com/questions/22124332/group-argmax-argmin-over-partitioning-indices-in-numpy
def csr_csc_argm... | [
"matplotlib.pylab.colorbar",
"matplotlib.pylab.show",
"numpy.zeros",
"numpy.ones",
"numpy.searchsorted",
"re.match",
"numpy.diff",
"re.findall",
"numpy.arange",
"numpy.repeat",
"matplotlib.pylab.title",
"numpy.maximum.reduceat",
"re.search",
"matplotlib.pylab.figure"
] | [((590, 607), 'numpy.diff', 'np.diff', (['X.indptr'], {}), '(X.indptr)\n', (597, 607), True, 'import numpy as np\n'), ((792, 830), 'numpy.zeros', 'np.zeros', (['(major_size,)'], {'dtype': 'X.dtype'}), '((major_size,), dtype=X.dtype)\n', (800, 830), True, 'import numpy as np\n'), ((861, 898), 'numpy.maximum.reduceat', '... |
"""
Contains class "Logger"
"""
import logging
import numpy as np
from prettytable import PrettyTable
from ..cnls_solve.cnls_solution import CNLSSolution, OptimizationStatus
COLUMN_NAMES = ["Iteration",
"Cost ",
"Constraint violation ",
"Stepsize (|... | [
"logging.FileHandler",
"logging.StreamHandler",
"numpy.linalg.norm",
"prettytable.PrettyTable",
"logging.getLogger"
] | [((925, 944), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (942, 944), False, 'import logging\n'), ((1313, 1338), 'prettytable.PrettyTable', 'PrettyTable', (['COLUMN_NAMES'], {}), '(COLUMN_NAMES)\n', (1324, 1338), False, 'from prettytable import PrettyTable\n'), ((1701, 1718), 'numpy.linalg.norm', 'np.li... |
import numpy
from numpy import angle, unwrap, diff, pi
from matplotlib import pyplot
from detune_coeff_calc import detune_pulse, rf_waveforms
"""
Find Lorentz coefficient by curve-fitting
Works because there's a nice broad-band term,
and the excitation term is relatively narrow-band
g: cavity field in MV/m
ssmi: s... | [
"matplotlib.pyplot.title",
"detune_coeff_calc.detune_pulse",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"matplotlib.pyplot.plot",
"numpy.polyfit",
"numpy.polyval",
"numpy.angle",
"matplotlib.pyplot.figure",
"numpy.diff",
"numpy.arange",
"matplotlib.pyplot.subplots",
"detune_coeff_c... | [((455, 485), 'numpy.polyfit', 'numpy.polyfit', (['fit_x', 'fit_y', '(1)'], {}), '(fit_x, fit_y, 1)\n', (468, 485), False, 'import numpy\n'), ((502, 527), 'numpy.polyval', 'numpy.polyval', (['pp', '(g ** 2)'], {}), '(pp, g ** 2)\n', (515, 527), False, 'import numpy\n'), ((1927, 1949), 'detune_coeff_calc.detune_pulse', ... |
"""
Construct smoothed LPCFG parameters,
as described in section 3.2.6 and 3.2.7 in my dissertation.
"""
from math import sqrt
from collections import Counter
from copy import deepcopy
import config
import numpy as np
from tqdm import tqdm
from training.rule import Rule3, Rule1
__author__ = '<NAME>'
__email__ = '<EMA... | [
"tqdm.tqdm",
"copy.deepcopy",
"training.rule.Rule3",
"math.sqrt",
"training.rule.Rule1",
"numpy.einsum",
"collections.Counter"
] | [((1142, 1188), 'tqdm.tqdm', 'tqdm', (['config.train'], {'desc': '"""Constructing L-PCFG"""'}), "(config.train, desc='Constructing L-PCFG')\n", (1146, 1188), False, 'from tqdm import tqdm\n'), ((1063, 1072), 'collections.Counter', 'Counter', ([], {}), '()\n', (1070, 1072), False, 'from collections import Counter\n'), (... |
import numpy as np
import torch
def compute_dynamics_curiosity(episodes, dynamics, device, dyn_params, inverse=False, benchmark=None):
if inverse:
raise NotImplementedError
return compute_inv_dynamics_curiosity(episodes, dynamics, device)
second_order_update = dynamics.second_order_update
k... | [
"torch.zeros",
"numpy.minimum",
"torch.cat",
"numpy.clip"
] | [((795, 817), 'torch.zeros', 'torch.zeros', (['rew.shape'], {}), '(rew.shape)\n', (806, 817), False, 'import torch\n'), ((3599, 3621), 'torch.zeros', 'torch.zeros', (['rew.shape'], {}), '(rew.shape)\n', (3610, 3621), False, 'import torch\n'), ((1164, 1208), 'torch.cat', 'torch.cat', (['[obs[:-1, t], act[:-1, t]]'], {'d... |
from inspect import signature
import numpy as np
import pytest
import scipy.sparse as sp
import kaczmarz
np.random.seed(0)
strategies = []
for name in dir(kaczmarz):
if name.startswith("_"):
continue
attr = getattr(kaczmarz, name)
if attr == kaczmarz.Base:
continue
if not issubclass(... | [
"numpy.random.seed",
"scipy.sparse.csr_matrix",
"numpy.array",
"numpy.linalg.norm",
"inspect.signature",
"pytest.mark.parametrize"
] | [((108, 125), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (122, 125), True, 'import numpy as np\n'), ((1721, 1766), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""A,x_exact"""', 'systems'], {}), "('A,x_exact', systems)\n", (1744, 1766), False, 'import pytest\n'), ((1768, 1815), 'pytest.m... |
import pandas as pd
import numpy as np
import holidays
import statsmodels.formula.api as sm
import time
from Helper import helper
import datetime
class DR(object):
def __init__(self, dataframe):
df = dataframe.copy()
self.lm_data = helper.DR_Temp_data_cleaning(df)
self.name = 'DR'
de... | [
"pandas.DataFrame",
"pandas.read_csv",
"time.time",
"numpy.mean",
"pandas.to_datetime",
"numpy.exp",
"datetime.timedelta",
"statsmodels.formula.api.ols",
"Helper.helper.DR_Temp_data_cleaning",
"numpy.array"
] | [((3414, 3431), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (3425, 3431), True, 'import pandas as pd\n'), ((255, 287), 'Helper.helper.DR_Temp_data_cleaning', 'helper.DR_Temp_data_cleaning', (['df'], {}), '(df)\n', (283, 287), False, 'from Helper import helper\n'), ((2439, 2459), 'numpy.mean', 'np.mean... |
'''Prints out files that have same hashes in a format as required by GraphVisualization2.py
Variable 'path' specifies the directory that is to be scanned'''
import os
import numpy as np
import operator
from py_essentials import hashing as hs
path = '../Desktop'
'''same hash'''
filetimes = []
files = []
'''scannin... | [
"os.path.abspath",
"numpy.asarray",
"py_essentials.hashing.fileChecksum",
"os.walk",
"os.path.splitext",
"os.path.join"
] | [((355, 368), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (362, 368), False, 'import os\n'), ((795, 812), 'numpy.asarray', 'np.asarray', (['files'], {}), '(files)\n', (805, 812), True, 'import numpy as np\n'), ((549, 570), 'os.path.join', 'os.path.join', (['r', 'file'], {}), '(r, file)\n', (561, 570), False, 'imp... |
# Copyright 2019 Intel Corporation.
import functools
import inspect
import logging
import math
import os
from collections import defaultdict
from contextlib import contextmanager
import six
import numpy as np
import scipy.stats
import plaidml2 as plaidml
import plaidml2.edsl as edsl
import plaidml2.exec as plaidml_e... | [
"plaidml2.edsl.TensorIndexes",
"plaidml2.op.max",
"plaidml2.Buffer",
"collections.defaultdict",
"plaidml2.op.variance",
"numpy.arange",
"plaidml2.op.tile",
"plaidml2.op.cumprod",
"plaidml2.edsl.LogicalShape",
"plaidml2.op.hard_sigmoid",
"plaidml2.op.sum",
"plaidml2.edsl.pow",
"plaidml2.op.mi... | [((544, 571), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (561, 571), False, 'import logging\n'), ((696, 712), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (707, 712), False, 'from collections import defaultdict\n'), ((865, 903), 'plaidml2.settings.get', 'plaidml... |
import pandas as pd
from utils import *
from keras.preprocessing.sequence import pad_sequences
from keras.utils import np_utils
import numpy as np
from args import Args
class LoadData:
def __init__(self):
self.maxlen = Args.maxlen
self.sents = read_pickle(r'sents.pickle')
self.... | [
"keras.preprocessing.sequence.pad_sequences",
"numpy.random.uniform",
"keras.utils.np_utils.to_categorical",
"pandas.read_csv"
] | [((1002, 1041), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['self.labels', '(2)'], {}), '(self.labels, 2)\n', (1025, 1041), False, 'from keras.utils import np_utils\n'), ((2147, 2218), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['x'], {'maxlen': 'self.maxlen', 'padding': '""... |
import numpy as np
import torch
import torch.nn as nn
import math
import matplotlib.pyplot as plt
class Env:
def __init__(self, hp, nw_len_seqs=None, nw_size_seqs=None,
seed=42, render=False, end='no_new_job'):
self.hp = hp
self.render = render
self.end = end... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.random.seed",
"numpy.sum",
"matplotlib.pyplot.imshow",
"torch.manual_seed",
"numpy.unique",
"numpy.zeros",
"numpy.ones",
"numpy.all",
"matplotlib.pyplot.figure",
"numpy.where",
"numpy.reshape",
"numpy.random.rand",
"numpy.rand... | [((2704, 2733), 'numpy.zeros', 'np.zeros', (['simu_len'], {'dtype': 'int'}), '(simu_len, dtype=int)\n', (2712, 2733), True, 'import numpy as np\n'), ((2757, 2805), 'numpy.zeros', 'np.zeros', (['(simu_len, self.hp.num_res)'], {'dtype': 'int'}), '((simu_len, self.hp.num_res), dtype=int)\n', (2765, 2805), True, 'import nu... |
#!/usr/bin/env python3
import glob
import os
import re
import sys
from argparse import Namespace
# https://github.com/OrdnanceSurvey/GeoDataViz-Toolkit/tree/master/Colours
g_geodata_qualitative = [
"#FF1F5B", "#00CD6C", "#009ADE", "#AF58BA", "#FFC61E", "#F28522",
"#A0B1BA", "#A6761D", "#E9002D", "#FFAA00", "#... | [
"sys.stdout.write",
"cycler.cycler",
"numpy.random.seed",
"numpy.arctan2",
"numpy.clip",
"numpy.argsort",
"matplotlib.pyplot.figure",
"os.path.isfile",
"sys.stdout.flush",
"numpy.arange",
"numpy.histogram",
"numpy.random.randint",
"numpy.sin",
"scipy.interpolate.interp1d",
"os.path.join"... | [((400, 421), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (414, 421), False, 'import matplotlib\n'), ((1255, 1277), 're.compile', 're.compile', (['"""([0-9]+)"""'], {}), "('([0-9]+)')\n", (1265, 1277), False, 'import re\n'), ((1644, 1663), 'sys.stdout.write', 'sys.stdout.write', (['s'], {}), '... |
import os
import json
import math
import random
import os.path as osp
from glob import glob
import numpy as np
import torch
import skimage.io
import numpy.linalg as LA
import matplotlib.pyplot as plt
import skimage.transform
from torch.utils.data import Dataset
from torch.utils.data.dataloader import default_collate
... | [
"random.randint",
"math.sqrt",
"random.uniform",
"random.shuffle",
"numpy.genfromtxt",
"random.random",
"numpy.linalg.norm",
"numpy.array",
"random.seed",
"numpy.rollaxis",
"glob.glob",
"os.path.join",
"torch.tensor"
] | [((1439, 1499), 'numpy.genfromtxt', 'np.genfromtxt', (['f"""{rootdir}/scannetv2_{split}.txt"""'], {'dtype': 'str'}), "(f'{rootdir}/scannetv2_{split}.txt', dtype=str)\n", (1452, 1499), True, 'import numpy as np\n'), ((3074, 3124), 'numpy.genfromtxt', 'np.genfromtxt', (['f"""{rootdir}/{split}.txt"""'], {'dtype': 'str'}),... |
"""
Note: this file should probably be run with python2 because StringIO
"""
import numpy as np
from unrealcv import client
from matplotlib import pyplot as plt
import time
import io
import sys
from scipy.misc import toimage
import os
import math
from tqdm import tqdm
base_folder = '/scratch/sdonne/data/unrealDTU/'
b... | [
"os.mkdir",
"numpy.abs",
"numpy.arctan2",
"unrealcv.client.request",
"unrealcv.client.disconnect",
"numpy.ones",
"numpy.sin",
"numpy.linalg.norm",
"unrealcv.client.connect",
"numpy.arange",
"scipy.misc.toimage",
"numpy.multiply",
"numpy.copy",
"math.radians",
"numpy.power",
"numpy.tran... | [((557, 586), 'numpy.array', 'np.array', (['(0.0, -20.0, -90.0)'], {}), '((0.0, -20.0, -90.0))\n', (565, 586), True, 'import numpy as np\n'), ((589, 616), 'numpy.array', 'np.array', (['(0.0, 80.0, 50.0)'], {}), '((0.0, 80.0, 50.0))\n', (597, 616), True, 'import numpy as np\n'), ((669, 720), 'numpy.array', 'np.array', (... |
import numpy
import torch
from .isnumpy import *
from .istorch import *
def transpose(tensor):
"""
Transposes the input tensor
Parameters
----------
tensor : Tensor
a nxm tensor
Returns
-------
Tensor
a mxn tensor
Raises
------
AssertError
if tens... | [
"torch.t",
"numpy.transpose"
] | [((408, 431), 'numpy.transpose', 'numpy.transpose', (['tensor'], {}), '(tensor)\n', (423, 431), False, 'import numpy\n'), ((471, 486), 'torch.t', 'torch.t', (['tensor'], {}), '(tensor)\n', (478, 486), False, 'import torch\n')] |
import scipy as sp
import scipy.linalg as la
import numpy as np
'''
U,s,Vh = la.svd(A)
S = sp.diag(s)
S = S*(S>tol)
r = sp.count_nonzero(S)
B = sp.dot(U,sp.sqrt(S))
C = sp.dot(sp.sqrt(S),Vh)
B = B[:,0:r]
C = C[0:r,:]
'''
#Problem 3
#When I feed the second example matrix into my function,
#it comes out with "almost" t... | [
"scipy.count_nonzero",
"scipy.sqrt",
"scipy.eye",
"scipy.diag",
"scipy.absolute",
"scipy.linalg.svd",
"numpy.linalg.matrix_power",
"scipy.linalg.det",
"scipy.dot"
] | [((905, 923), 'scipy.eye', 'sp.eye', (['A.shape[0]'], {}), '(A.shape[0])\n', (911, 923), True, 'import scipy as sp\n'), ((614, 624), 'scipy.linalg.svd', 'la.svd', (['CB'], {}), '(CB)\n', (620, 624), True, 'import scipy.linalg as la\n'), ((637, 647), 'scipy.diag', 'sp.diag', (['s'], {}), '(s)\n', (644, 647), True, 'impo... |
""" Stores Utility Functions """
import cv2
import sys
import itertools
import numpy as np
import scipy.spatial.qhull as qhull
from scipy.misc import imresize
from scipy.spatial import ConvexHull, convex_hull_plot_2d
from skimage import filters
from sklearn.mixture import GaussianMixture
from sklearn.cluster import KM... | [
"cv2.GaussianBlur",
"numpy.abs",
"cv2.bitwise_and",
"cv2.getPerspectiveTransform",
"numpy.ones",
"sklearn.mixture.GaussianMixture",
"skimage.measure.block_reduce",
"numpy.mean",
"cv2.imshow",
"cv2.inRange",
"cv2.warpPerspective",
"cv2.dilate",
"cv2.cvtColor",
"sklearn.cluster.KMeans",
"c... | [((946, 967), 'numpy.reshape', 'np.reshape', (['K', '(3, 3)'], {}), '(K, (3, 3))\n', (956, 967), True, 'import numpy as np\n'), ((1204, 1227), 'cv2.imshow', 'cv2.imshow', (['"""test"""', 'img'], {}), "('test', img)\n", (1214, 1227), False, 'import cv2\n'), ((1232, 1246), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0... |
from retro_contest.local import make
from time import sleep
from gym import spaces
from os import listdir, rename
from sys import argv
from PIL import Image
import tensorflow as tf
import csv, pickle
import numpy, math, random
import os.path
import msvcrt
SCREEN_X = 320
SCREEN_Y = 224
H_SCREEN_X = 160
... | [
"tensorflow.image.rgb_to_grayscale",
"csv.reader",
"random.sample",
"tensorflow.reset_default_graph",
"tensorflow.reshape",
"tensorflow.ConfigProto",
"tensorflow.matmul",
"tensorflow.nn.conv2d",
"tensorflow.sqrt",
"tensorflow.reduce_max",
"tensorflow.nn.conv2d_transpose",
"tensorflow.truncated... | [((906, 926), 'numpy.asarray', 'numpy.asarray', (['[ret]'], {}), '([ret])\n', (919, 926), False, 'import numpy, math, random\n'), ((974, 1049), 'tensorflow.nn.conv2d_transpose', 'tf.nn.conv2d_transpose', (['i', 'W', 'shape', '[1, stride, stride, 1]'], {'padding': '"""SAME"""'}), "(i, W, shape, [1, stride, stride, 1], p... |
import torch, numpy as np, torch.nn as nn, matplotlib.pyplot as plt
from models import Reservoir, CUDAvoir
from optimizers import Force
'''
Runs naive reservoir model 'steps' number of
timesteps. Returns entire state vector history
when 'record' is set to True.
'''
def run_naive_net(net,steps,record=False):
state... | [
"models.CUDAvoir",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.asarray",
"torch.cat",
"optimizers.Force"
] | [((827, 865), 'optimizers.Force', 'Force', ([], {'targ': 'func', 'dt': '(0.1)', 'a': '(3)', 'n': 'net.n'}), '(targ=func, dt=0.1, a=3, n=net.n)\n', (832, 865), False, 'from optimizers import Force\n'), ((1558, 1603), 'models.CUDAvoir', 'CUDAvoir', ([], {'n': 'n', 'p': 'p', 'sig': 'sig', 'o': '(0.0)', 'bias': '(True)'}),... |
'''
Standard Case Simulation - Case 1:
Small size simulation with N >> I >> P
individuals: 1000
covaraites: 3 binary (0.2), 3 Normal(0, 1)
theta: -0.9, 0.2, 0, -0.4, 1.1, 0
censoring: ~ 0.74
runs: 200 - Seed = 1, 2, ..., 200
'''
# Modules
# =================================================... | [
"os.mkdir",
"numpy.random.seed",
"torch.mm",
"matplotlib.pyplot.step",
"numpy.random.normal",
"shutil.rmtree",
"pyro.clear_param_store",
"numpy.round",
"os.chdir",
"probcox.PCox",
"matplotlib.pyplot.close",
"numpy.random.choice",
"matplotlib.pyplot.show",
"numpy.random.binomial",
"torch.... | [((725, 758), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (748, 758), False, 'import warnings\n'), ((811, 831), 'numpy.random.seed', 'np.random.seed', (['(2309)'], {}), '(2309)\n', (825, 831), True, 'import numpy as np\n'), ((832, 854), 'torch.manual_seed', 'torch.manua... |
# This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
__name__ = "biotite.sequence"
__author__ = "<NAME>"
__all__ = ["find_subsequence", "find_symbol", "find_symbol_first",
"find_symbol_last"]
import numpy ... | [
"numpy.min",
"numpy.max",
"numpy.array",
"numpy.where",
"numpy.array_equal"
] | [((1533, 1556), 'numpy.array', 'np.array', (['match_indices'], {}), '(match_indices)\n', (1541, 1556), True, 'import numpy as np\n'), ((2568, 2583), 'numpy.min', 'np.min', (['match_i'], {}), '(match_i)\n', (2574, 2583), True, 'import numpy as np\n'), ((3123, 3138), 'numpy.max', 'np.max', (['match_i'], {}), '(match_i)\n... |
"""
Test capabilities of QuickLook pipeline
python -m desispec.test.test_ql
"""
import os, sys
import shutil
from uuid import uuid4
import unittest
import yaml
import numpy as np
from desispec.util import runcmd
from desispec.io.raw import write_raw
from desispec.io import empty_fibermap
from desispec.io.fibermap imp... | [
"unittest.main",
"desispec.io.raw.write_raw",
"desispec.io.empty_fibermap",
"uuid.uuid4",
"os.remove",
"os.makedirs",
"os.path.abspath",
"desispec.io.fibermap.write_fibermap",
"os.path.isdir",
"os.getcwd",
"yaml.dump",
"os.path.exists",
"numpy.zeros",
"shutil.rmtree",
"os.path.join",
"... | [((9245, 9260), 'unittest.main', 'unittest.main', ([], {}), '()\n', (9258, 9260), False, 'import unittest\n'), ((1238, 1269), 'os.path.join', 'os.path.join', (['cls.topDir', '"""bin"""'], {}), "(cls.topDir, 'bin')\n", (1250, 1269), False, 'import os, sys\n'), ((2236, 2282), 'os.path.join', 'os.path.join', (["os.environ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 11 00:51:01 2021
@author: trabz
"""
from xmlParser import Parser
import glob
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
import cv2
def augmentator(image):
img=image.copy()
img=random(tf.image.random_brig... | [
"tensorflow.image.flip_left_right",
"tensorflow.image.rgb_to_grayscale",
"matplotlib.pyplot.figure",
"glob.glob",
"tensorflow.image.adjust_contrast",
"matplotlib.pyplot.tight_layout",
"tensorflow.image.central_crop",
"tensorflow.image.adjust_jpeg_quality",
"tensorflow.image.rot90",
"tensorflow.ima... | [((1059, 1074), 'glob.glob', 'glob.glob', (['path'], {}), '(path)\n', (1068, 1074), False, 'import glob\n'), ((1366, 1394), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 12)'}), '(figsize=(12, 12))\n', (1376, 1394), True, 'from matplotlib import pyplot as plt\n'), ((1608, 1666), 'matplotlib.pyplot.sa... |
import tensorly as tl
from tensorly.testing import assert_array_almost_equal
from numpy import array, matmul, transpose
from numpy.linalg import norm
from ..density_tensor import DensityTensor
err_tol = 4
def test_validate_subsystems():
square_subsystems = [[3, 2, 5], [3, 2, 5]]
column_subsystems = [[1, 7,... | [
"tensorly.testing.assert_array_almost_equal",
"numpy.transpose",
"tensorly.zeros",
"numpy.array",
"numpy.linalg.norm",
"tensorly.tensor",
"tensorly.reshape",
"tensorly.randn"
] | [((399, 415), 'tensorly.randn', 'tl.randn', (['(4, 4)'], {}), '((4, 4))\n', (407, 415), True, 'import tensorly as tl\n'), ((782, 798), 'tensorly.zeros', 'tl.zeros', (['(8, 1)'], {}), '((8, 1))\n', (790, 798), True, 'import tensorly as tl\n'), ((912, 928), 'tensorly.zeros', 'tl.zeros', (['(4, 4)'], {}), '((4, 4))\n', (9... |
import tensorflow as tf
import numpy as np
import pandas as pd
from collections import Counter
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
def move_accuracy(y_test, y_pred):
return np.mean(y_test[y_pred == np.max(y_pred, axis=1, keepdims=True)])
np... | [
"numpy.random.seed",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"numpy.max",
"tensorflow.keras.Sequential",
"collections.Counter"
] | [((318, 338), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (332, 338), True, 'import numpy as np\n'), ((347, 380), 'pandas.read_csv', 'pd.read_csv', (['"""tictactoe-data.csv"""'], {}), "('tictactoe-data.csv')\n", (358, 380), True, 'import pandas as pd\n'), ((751, 792), 'sklearn.model_selection.t... |
# -*- coding: utf-8 -*-
import numpy as np
from sklearn import metrics
def intersection_over_union_matrix(label_image_x, label_image_y):
"""
Generate a matrix with intersection over union of all label pairs.
How it works: The overlap matrix is a lookup table of the area of intersection
between each ... | [
"numpy.sum",
"numpy.isnan"
] | [((1881, 1919), 'numpy.sum', 'np.sum', (['overlap'], {'axis': '(0)', 'keepdims': '(True)'}), '(overlap, axis=0, keepdims=True)\n', (1887, 1919), True, 'import numpy as np\n'), ((1940, 1978), 'numpy.sum', 'np.sum', (['overlap'], {'axis': '(1)', 'keepdims': '(True)'}), '(overlap, axis=1, keepdims=True)\n', (1946, 1978), ... |
import numpy as np
import math
def factorial_2(k, p=None, contrasts=None, randomize=None, seed=None):
""" Generate :math:`2^{k}` and :math:`2^{k-p}` factorial designs
For the 2^{8 - 3}, we set k=8 and p=3.
There are three contrasts that we need to define (p). Each contrast is a
list
Args:
... | [
"numpy.random.seed",
"numpy.transpose",
"math.copysign",
"numpy.array",
"numpy.random.shuffle"
] | [((2876, 2908), 'numpy.random.shuffle', 'np.random.shuffle', (['design_matrix'], {}), '(design_matrix)\n', (2893, 2908), True, 'import numpy as np\n'), ((2621, 2637), 'numpy.array', 'np.array', (['design'], {}), '(design)\n', (2629, 2637), True, 'import numpy as np\n'), ((2712, 2728), 'numpy.array', 'np.array', (['desi... |
"""
Copyright 2016 Max Planck Society, <NAME>, <NAME>. All rights reserved.
This software is provided for research purposes only.
By using this software you agree to the terms of the SMPLify license here:
http://smplify.is.tue.mpg.de/license
This script implements the interpenetration error term. It uses the caps... | [
"capsule_body.get_capsules",
"chumpy.vstack",
"smpl_webuser.lbs.verts_core",
"capsule_body.set_sphere_centers",
"chumpy.sum",
"capsule_body.capsule_dist",
"capsule_body.get_sphere_bweights",
"numpy.concatenate"
] | [((999, 1017), 'chumpy.vstack', 'ch.vstack', (['centers'], {}), '(centers)\n', (1008, 1017), True, 'import chumpy as ch\n'), ((1045, 1092), 'capsule_body.get_sphere_bweights', 'get_sphere_bweights', (['self.sph_vs', 'self.capsules'], {}), '(self.sph_vs, self.capsules)\n', (1064, 1092), False, 'from capsule_body import ... |
import sys
import numpy as np
import json
import os.path
import subprocess
import random
from operator import itemgetter
import sklearn.metrics as metrics
import matplotlib.pyplot as plt
from os import listdir
import os.path
for i in range(1,200):
J = iter(list(map(str.strip,subprocess.check_output(['ls results/p... | [
"numpy.argmax",
"numpy.isscalar",
"numpy.genfromtxt",
"sklearn.metrics.recall_score",
"sklearn.metrics.matthews_corrcoef",
"sklearn.metrics.precision_score",
"numpy.concatenate"
] | [((1284, 1298), 'numpy.argmax', 'np.argmax', (['MCC'], {}), '(MCC)\n', (1293, 1298), True, 'import numpy as np\n'), ((1304, 1327), 'numpy.isscalar', 'np.isscalar', (['argmax_mcc'], {}), '(argmax_mcc)\n', (1315, 1327), True, 'import numpy as np\n'), ((415, 431), 'numpy.genfromtxt', 'np.genfromtxt', (['j'], {}), '(j)\n',... |
# (c) 2021 <NAME>
import numpy as np
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import pickle as pkl
from jax import lax
from typing import Callable, Tuple
from myriad.custom_types import State, States, Control, Controls, DState
from myriad.utils import integrate, integrate_time_independent, i... | [
"numpy.stack",
"jax.random.uniform",
"jax.numpy.array",
"myriad.utils.integrate_time_independent_in_parallel",
"matplotlib.pyplot.show",
"jax.numpy.isinf",
"matplotlib.pyplot.plot",
"jax.random.normal",
"jax.numpy.concatenate",
"matplotlib.pyplot.close",
"jax.numpy.arange",
"jax.numpy.isfinite... | [((3114, 3149), 'matplotlib.pyplot.plot', 'plt.plot', (['interval_us'], {'color': '"""blue"""'}), "(interval_us, color='blue')\n", (3122, 3149), True, 'import matplotlib.pyplot as plt\n'), ((3334, 3358), 'jax.random.split', 'jax.random.split', (['hp.key'], {}), '(hp.key)\n', (3350, 3358), False, 'import jax\n'), ((4052... |
# Copyright 2016 Conchylicultor. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | [
"deepmusic.songstruct.Note",
"numpy.argmax",
"deepmusic.songstruct.Song",
"random.shuffle",
"numpy.zeros",
"numpy.ones",
"operator.attrgetter",
"numpy.random.randint",
"random.randrange",
"deepmusic.songstruct.Track",
"numpy.random.shuffle"
] | [((13619, 13631), 'deepmusic.songstruct.Song', 'music.Song', ([], {}), '()\n', (13629, 13631), True, 'import deepmusic.songstruct as music\n'), ((13653, 13666), 'deepmusic.songstruct.Track', 'music.Track', ([], {}), '()\n', (13664, 13666), True, 'import deepmusic.songstruct as music\n'), ((15822, 15834), 'deepmusic.son... |
import random
import numpy as np
import mask
import sklearn
from joblib import Parallel, delayed
import tensorflow as tf
import math as m
import ColorGenerator
import histogram
class ImagePatchGenerator:
def __init__(self, folder="PNG_canonical/", patch_size=(48, 48), uv=False, reduce_mean=True):
self.r... | [
"random.shuffle",
"mask.draw_new_line",
"tensorflow.zeros_like",
"tensorflow.image.decode_png",
"tensorflow.image.per_image_standardization",
"visualizer.create_mask",
"tensorflow.reduce_max",
"ColorGenerator.ColorGenerator",
"numpy.unique",
"tensorflow.random.uniform",
"tensorflow.concat",
"t... | [((1117, 1191), 'tensorflow.random.uniform', 'tf.random.uniform', (['[]'], {'minval': '(0)', 'maxval': 'self.patch_size[1]', 'dtype': 'tf.int32'}), '([], minval=0, maxval=self.patch_size[1], dtype=tf.int32)\n', (1134, 1191), True, 'import tensorflow as tf\n'), ((1210, 1284), 'tensorflow.random.uniform', 'tf.random.unif... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
my_dataset = pd.read_excel('Smith_glass_post_NYT_data.xlsx', sheet_name='Supp_traces')
hist, bin_edges = np.histogram(my_dataset['Zr'], bins= 20, density=True)
modal_value = (bin_edges[hist.argmax()] + bin_edges[hist.argmax()+1])/2
print ('modal... | [
"pandas.read_excel",
"numpy.histogram",
"matplotlib.pyplot.subplots"
] | [((85, 158), 'pandas.read_excel', 'pd.read_excel', (['"""Smith_glass_post_NYT_data.xlsx"""'], {'sheet_name': '"""Supp_traces"""'}), "('Smith_glass_post_NYT_data.xlsx', sheet_name='Supp_traces')\n", (98, 158), True, 'import pandas as pd\n'), ((178, 231), 'numpy.histogram', 'np.histogram', (["my_dataset['Zr']"], {'bins':... |
import gym
import numpy as np
import time
import pygame
import sys
from pygame.locals import *
class Game:
stan = 0;
def step(self, action):
reward = -0.04
done = False
info = False
if (action == 0) and ((self.stan % 4) != 0):
self.stan -= 1
if (action == ... | [
"pygame.font.SysFont",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.draw.rect",
"numpy.random.randn",
"numpy.zeros",
"pygame.init",
"time.sleep",
"pygame.display.update",
"numpy.max",
"pygame.display.set_caption"
] | [((1337, 1350), 'pygame.init', 'pygame.init', ([], {}), '()\n', (1348, 1350), False, 'import pygame\n'), ((1358, 1400), 'pygame.font.SysFont', 'pygame.font.SysFont', (['"""monospace"""', '(29)', '(True)'], {}), "('monospace', 29, True)\n", (1377, 1400), False, 'import pygame\n'), ((1411, 1446), 'pygame.display.set_mode... |
import numpy as np
import pysal.viz.mapclassify as classify
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm
"""
Utility functions for lightweight visualizations in splot
"""
__author__ = ("<NAME> <<EMAIL>>")
def moran_hot_cold_spots(moran_loc, p=0.05):
sig = 1 * (moran_loc.p_... | [
"matplotlib.pyplot.register_cmap",
"matplotlib.colors.LinearSegmentedColormap",
"matplotlib.cm.get_cmap",
"numpy.any",
"numpy.array",
"numpy.linspace",
"bokeh.models.Legend"
] | [((4874, 4911), 'numpy.array', 'np.array', (['[bin_labels[c] for c in yb]'], {}), '([bin_labels[c] for c in yb])\n', (4882, 4911), True, 'import numpy as np\n'), ((5728, 5804), 'bokeh.models.Legend', 'Legend', ([], {'items': 'items', 'location': '"""top_left"""', 'margin': '(0)', 'orientation': '"""horizontal"""'}), "(... |
# -*- coding: utf-8 -*-
import unittest
import numpy as np
from votesim.votemethods import condorcet
class TestSmith(unittest.TestCase):
def test_smithset1(self):
# M N C K
d = [[ 0, 16, -20, -7, 2],
[-16, 0, 13, 17, 2],
[ 20, -13, 0, 7, 2],
... | [
"unittest.main",
"votesim.votemethods.condorcet.smith_minimax",
"numpy.random.RandomState",
"votesim.votemethods.condorcet.condcalcs.condorcet_check_one",
"numpy.array",
"votesim.votemethods.condorcet.smith_minimax_matrix",
"numpy.all",
"votesim.votemethods.condorcet.smith_set"
] | [((3861, 3886), 'unittest.main', 'unittest.main', ([], {'exit': '(False)'}), '(exit=False)\n', (3874, 3886), False, 'import unittest\n'), ((423, 434), 'numpy.array', 'np.array', (['d'], {}), '(d)\n', (431, 434), True, 'import numpy as np\n'), ((447, 472), 'votesim.votemethods.condorcet.smith_set', 'condorcet.smith_set'... |
"""Python implementation of Lostruct, which calculates local population structure of a genome"""
from enum import Enum
from itertools import islice
import numpy as np
import sparse
from cyvcf2 import VCF
from numba import jit
import jax.numpy as jnp
import jax
from multiprocessing import Pool
from jax.config import c... | [
"numpy.sum",
"jax.numpy.take",
"numpy.isnan",
"numpy.linalg.norm",
"numpy.nanmean",
"numpy.multiply",
"jax.numpy.where",
"numpy.power",
"numpy.linalg.eig",
"jax.numpy.linalg.norm",
"numpy.reshape",
"numpy.triu_indices_from",
"jax.config.config.update",
"jax.numpy.sum",
"jax.numpy.square"... | [((354, 391), 'jax.config.config.update', 'config.update', (['"""jax_enable_x64"""', '(True)'], {}), "('jax_enable_x64', True)\n", (367, 391), False, 'from jax.config import config\n'), ((5795, 5843), 'numba.jit', 'jit', ([], {'nopython': '(True)', 'parallel': '(True)', 'fastmath': '(True)'}), '(nopython=True, parallel... |
# Copyright 2021 INRIA
#!/usr/bin/env python
import numpy as np
import siconos.numerics as sn
def mcp_function(z):
M = np.array([[2., 1.],
[1., 2.]])
q = np.array([-5., -6.])
return np.dot(M,z) + q
def mcp_Nablafunction(z):
M = np.array([[2., 1.],
[1., 2.]])
... | [
"siconos.numerics.mcp_old_driver_reset",
"siconos.numerics.numerics_set_verbose",
"siconos.numerics.MCP_old",
"numpy.zeros",
"siconos.numerics.SolverOptions",
"numpy.array",
"numpy.linalg.norm",
"numpy.dot",
"siconos.numerics.mcp_old_FischerBurmeister",
"siconos.numerics.mcp_old_driver_init"
] | [((350, 382), 'numpy.array', 'np.array', (['[4.0 / 3.0, 7.0 / 3.0]'], {}), '([4.0 / 3.0, 7.0 / 3.0])\n', (358, 382), True, 'import numpy as np\n'), ((386, 406), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (394, 406), True, 'import numpy as np\n'), ((126, 160), 'numpy.array', 'np.array', (['[[2.0,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.