code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import joblib
import numpy as np
import pandas as pd
import streamlit as st
APP_FILE = "app.py"
MODEL_JOBLIB_FILE = "model.joblib"
def main():
"""This function runs/ orchestrates the Machine Learning App Registry"""
st.markdown(
"""
# Machine Learning App
The main objective of this app is buildin... | [
"streamlit.checkbox",
"streamlit.markdown",
"pandas.read_csv",
"streamlit.number_input",
"streamlit.balloons",
"streamlit.button",
"streamlit.write",
"numpy.array",
"streamlit.success",
"joblib.load"
] | [((229, 592), 'streamlit.markdown', 'st.markdown', (['"""\n# Machine Learning App \n\nThe main objective of this app is building a customer segmentation based on credit card \npayments behavior during the last six months to define marketing strategies. \nYou can find the source code for this project in the following [G... |
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
import scipy
class PlaceCells(object):
def __init__(self, options):
self.Np = options.Np
self.sigma = options.place_cell_rf
self.surround_scale = options.surround_scale
self.box_width = options.box_width
se... | [
"tensorflow.random.uniform",
"tensorflow.reduce_min",
"numpy.roll",
"tensorflow.random.set_seed",
"tensorflow.transpose",
"tensorflow.reduce_sum",
"scipy.interpolate.griddata",
"numpy.linspace",
"numpy.zeros",
"tensorflow.gather",
"tensorflow.nn.softmax",
"tensorflow.reshape",
"tensorflow.ma... | [((509, 530), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(0)'], {}), '(0)\n', (527, 530), True, 'import tensorflow as tf\n'), ((545, 637), 'tensorflow.random.uniform', 'tf.random.uniform', (['(self.Np,)', '(-self.box_width / 2)', '(self.box_width / 2)'], {'dtype': 'tf.float64'}), '((self.Np,), -self.box_wid... |
import numpy as np
#--------------------------------------------------------------------------
# nx = 29
# ny = 44
# R = (30.0 / (1000.0 * 3600.0)) # [m/s]
# da = 900 # [m2]
# dur = (75 * 60) # [sec] (75 minutes or 4500 sec)
# A = (nx * ny * da)
# vol_tot = (A * R * dur)
# print( vol_tot )
#-----------------------... | [
"numpy.fromfile",
"numpy.zeros"
] | [((2214, 2265), 'numpy.fromfile', 'np.fromfile', (['grid_unit'], {'count': 'n_values', 'dtype': 'dtype'}), '(grid_unit, count=n_values, dtype=dtype)\n', (2225, 2265), True, 'import numpy as np\n'), ((1140, 1175), 'numpy.zeros', 'np.zeros', (['(ny, nx)'], {'dtype': '"""float32"""'}), "((ny, nx), dtype='float32')\n", (11... |
"""
Classes for lighting in renderer
Author: <NAME>
"""
import numpy as np
from autolab_core import RigidTransform
class Color(object):
WHITE = np.array([255, 255, 255])
BLACK = np.array([0, 0, 0])
RED = np.array([255, 0, 0])
GREEN = np.array([0, 255, 0])
BLUE = np.array([0, 0, 255])
class Mat... | [
"numpy.array",
"numpy.eye",
"numpy.ones",
"numpy.zeros"
] | [((150, 175), 'numpy.array', 'np.array', (['[255, 255, 255]'], {}), '([255, 255, 255])\n', (158, 175), True, 'import numpy as np\n'), ((188, 207), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (196, 207), True, 'import numpy as np\n'), ((220, 241), 'numpy.array', 'np.array', (['[255, 0, 0]'], {}), '(... |
# -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2021
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
#... | [
"nibabel.save",
"nibabel.load",
"numpy.dot",
"numpy.savetxt",
"nibabel.Nifti1Image",
"numpy.loadtxt"
] | [((9689, 9716), 'numpy.savetxt', 'np.savetxt', (['trffile', 'affine'], {}), '(trffile, affine)\n', (9699, 9716), True, 'import numpy as np\n'), ((10278, 10298), 'nibabel.load', 'nibabel.load', (['imfile'], {}), '(imfile)\n', (10290, 10298), False, 'import nibabel\n'), ((10313, 10335), 'nibabel.load', 'nibabel.load', ([... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
def canny(image):
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
canny = cv2.Canny(blur, 50, 150)
return canny
def display_lines(image, lines):
line_image = np.zeros_like(image)
if lines is no... | [
"numpy.copy",
"cv2.fillPoly",
"cv2.Canny",
"cv2.line",
"numpy.zeros_like",
"cv2.bitwise_and",
"cv2.imshow",
"numpy.array",
"cv2.cvtColor",
"cv2.GaussianBlur",
"cv2.waitKey",
"cv2.imread"
] | [((786, 814), 'cv2.imread', 'cv2.imread', (['"""test_image.jpg"""'], {}), "('test_image.jpg')\n", (796, 814), False, 'import cv2\n'), ((828, 842), 'numpy.copy', 'np.copy', (['image'], {}), '(image)\n', (835, 842), True, 'import numpy as np\n'), ((871, 899), 'cv2.imshow', 'cv2.imshow', (['"""result"""', 'canny1'], {}), ... |
import numpy as np #we use numpy for lots of things
def main():
i=0 #integers can be declared with a number
n=10 #here is another integer
x=119.0 #floating point nums are declared with a "."
#we can use numpy to declare arrays quickly
y=np.zeros(n,dtype=float)
#we cn use for loops to iterate... | [
"numpy.zeros"
] | [((262, 286), 'numpy.zeros', 'np.zeros', (['n'], {'dtype': 'float'}), '(n, dtype=float)\n', (270, 286), True, 'import numpy as np\n')] |
#!/usr/bin/env python
"""
File: DataSet
Date: 5/1/18
Author: <NAME> (<EMAIL>)
This file provides loading of the BraTS datasets
for ease of use in TensorFlow models.
"""
import os
import pandas as pd
import numpy as np
import nibabel as nib
from tqdm import tqdm
from BraTS.Patient import *
from BraTS.structure impo... | [
"os.path.join",
"os.listdir",
"numpy.empty"
] | [((2138, 2164), 'numpy.empty', 'np.empty', ([], {'shape': 'mris_shape'}), '(shape=mris_shape)\n', (2146, 2164), True, 'import numpy as np\n'), ((2186, 2212), 'numpy.empty', 'np.empty', ([], {'shape': 'segs_shape'}), '(shape=segs_shape)\n', (2194, 2212), True, 'import numpy as np\n'), ((5800, 5836), 'os.path.join', 'os.... |
import numpy as np
import pandas as pd
import pytest
import numpy.testing as npt
import matplotlib.pyplot as plt
from pulse2percept.viz import scatter_correlation, correlation_matrix
def test_scatter_correlation():
x = np.arange(100)
_, ax = plt.subplots()
ax = scatter_correlation(x, x, ax=ax)
npt.as... | [
"numpy.zeros",
"pytest.raises",
"pulse2percept.viz.scatter_correlation",
"pandas.DataFrame",
"pulse2percept.viz.correlation_matrix",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((226, 240), 'numpy.arange', 'np.arange', (['(100)'], {}), '(100)\n', (235, 240), True, 'import numpy as np\n'), ((253, 267), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (265, 267), True, 'import matplotlib.pyplot as plt\n'), ((277, 309), 'pulse2percept.viz.scatter_correlation', 'scatter_correlatio... |
#!/usr/bin/env python
"""Computes the result of a stats cPickle file.
A stats cPickle file has the following format:
- List of N elements, each representing a track.
- Each position (or track) contains the rank index of the covers
corresponding to this position.
The results this script computes are:
- Mean Avera... | [
"pylab.title",
"numpy.mean",
"argparse.ArgumentParser",
"numpy.where",
"numpy.asarray",
"pylab.xlabel",
"pylab.legend",
"utils.load_pickle",
"pylab.figure",
"utils.configure_logger",
"numpy.zeros",
"numpy.sum",
"numpy.isnan",
"pylab.ylabel",
"numpy.arange",
"pylab.show"
] | [((2950, 2965), 'numpy.mean', 'np.mean', (['mean_r'], {}), '(mean_r)\n', (2957, 2965), True, 'import numpy as np\n'), ((3236, 3251), 'numpy.mean', 'np.mean', (['mean_r'], {}), '(mean_r)\n', (3243, 3251), True, 'import numpy as np\n'), ((3321, 3338), 'numpy.asarray', 'np.asarray', (['ranks'], {}), '(ranks)\n', (3331, 33... |
import warnings
import numpy as np
from . import dispatch, B, Numeric
from ..shape import unwrap_dimension
from ..types import NPDType, NPRandomState, Int
__all__ = []
@dispatch
def create_random_state(_: NPDType, seed: Int = 0):
return np.random.RandomState(seed=seed)
@dispatch
def global_random_state(_: NP... | [
"warnings.warn",
"numpy.random.RandomState"
] | [((246, 278), 'numpy.random.RandomState', 'np.random.RandomState', ([], {'seed': 'seed'}), '(seed=seed)\n', (267, 278), True, 'import numpy as np\n'), ((561, 630), 'warnings.warn', 'warnings.warn', (['"""Casting random number of type float to type integer."""'], {}), "('Casting random number of type float to type integ... |
"""
Author: <NAME>
Affiliation: NAIST & OSX
"""
from __future__ import annotations
import inspect
import random
from abc import ABC, abstractmethod, abstractstaticmethod
from itertools import count
from typing import Dict, Iterator, List, Optional, Type
import gym
import jax
import numpy as np
import structlog
from c... | [
"structlog.get_logger",
"jax.random.PRNGKey",
"inspect.getmembers",
"random.seed",
"itertools.count",
"numpy.random.seed"
] | [((915, 923), 'itertools.count', 'count', (['(0)'], {}), '(0)\n', (920, 923), False, 'from itertools import count\n'), ((1931, 1985), 'inspect.getmembers', 'inspect.getmembers', (['solver'], {'predicate': 'inspect.ismethod'}), '(solver, predicate=inspect.ismethod)\n', (1949, 1985), False, 'import inspect\n'), ((2280, 2... |
import torch
from collections import defaultdict, OrderedDict
import numba
import numpy as np
def _group_by(keys, values) -> dict:
"""Group values by keys.
:param keys: list of keys
:param values: list of values
A key value pair i is defined by (key_list[i], value_list[i]).
:return: OrderedDict w... | [
"numpy.array",
"collections.OrderedDict",
"collections.defaultdict"
] | [((390, 407), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (401, 407), False, 'from collections import defaultdict, OrderedDict\n'), ((610, 629), 'collections.OrderedDict', 'OrderedDict', (['result'], {}), '(result)\n', (621, 629), False, 'from collections import defaultdict, OrderedDict\n'), (... |
from collections import defaultdict
import numpy as np
import pandas as pd
from scipy.stats import chi2_contingency, fisher_exact, f_oneway
from .simulations import classifier_posterior_probabilities
from .utils.crosstabs import (crosstab_bayes_factor,
crosstab_ztest,
... | [
"pandas.Series",
"scipy.stats.chi2_contingency",
"scipy.stats.f_oneway",
"scipy.stats.fisher_exact",
"pandas.crosstab",
"numpy.array",
"numpy.linspace",
"collections.defaultdict",
"numpy.percentile"
] | [((1443, 1467), 'scipy.stats.f_oneway', 'f_oneway', (['*score_vectors'], {}), '(*score_vectors)\n', (1451, 1467), False, 'from scipy.stats import chi2_contingency, fisher_exact, f_oneway\n'), ((6640, 6657), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (6651, 6657), False, 'from collections impo... |
# Importing Necessary projects
import cv2
import numpy as np
# Creating the video capture object
cap = cv2.VideoCapture(0)
# Defining upper and lower ranges for yellow color
# If you don't have a yellow marker feel free to change the RGB values
Lower = np.array([20, 100, 100])
Upper = np.array([30, 255, 255])
# Defi... | [
"numpy.ones",
"cv2.flip",
"numpy.full",
"cv2.inRange",
"cv2.erode",
"cv2.line",
"cv2.imshow",
"numpy.array",
"cv2.morphologyEx",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.cvtColor",
"cv2.bitwise_or",
"cv2.findContours",
"cv2.bitwise_not",
"cv2.dilate",
"cv2.waitKey",
"cv2.b... | [((103, 122), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (119, 122), False, 'import cv2\n'), ((255, 279), 'numpy.array', 'np.array', (['[20, 100, 100]'], {}), '([20, 100, 100])\n', (263, 279), True, 'import numpy as np\n'), ((288, 312), 'numpy.array', 'np.array', (['[30, 255, 255]'], {}), '([30, 25... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) <NAME>.
# Distributed under the terms of the Modified BSD License.
__all__ = [
"example_function",
]
import numpy as np
def example_function(ax, data, above_color="r", below_color="k", **kwargs):
"""
An example function that makes a scatter plot with... | [
"numpy.array"
] | [((833, 872), 'numpy.array', 'np.array', (['([above_color] * data.shape[0])'], {}), '([above_color] * data.shape[0])\n', (841, 872), True, 'import numpy as np\n')] |
import cv2
import math
import numpy as np
from utils.pPose_nms import pose_nms
def get_3rd_point(a, b):
"""Return vector c that perpendicular to (a - b)."""
direct = a - b
return b + np.array([-direct[1], direct[0]], dtype=np.float32)
def get_dir(src_point, rot_rad):
"""Rotate the point by `rot_rad` ... | [
"numpy.array",
"numpy.sin",
"numpy.mean",
"numpy.greater",
"numpy.asarray",
"numpy.max",
"cv2.addWeighted",
"numpy.dot",
"numpy.tile",
"numpy.floor",
"numpy.argmax",
"numpy.squeeze",
"numpy.cos",
"cv2.cvtColor",
"numpy.sign",
"utils.pPose_nms.pose_nms",
"math.atan2",
"cv2.resize",
... | [((706, 740), 'numpy.array', 'np.array', (['[0, 0]'], {'dtype': 'np.float32'}), '([0, 0], dtype=np.float32)\n', (714, 740), True, 'import numpy as np\n'), ((1089, 1128), 'numpy.array', 'np.array', (['[0, dst_w * -0.5]', 'np.float32'], {}), '([0, dst_w * -0.5], np.float32)\n', (1097, 1128), True, 'import numpy as np\n')... |
import numpy as np
from collections import OrderedDict
from alfred.utils.misc import keep_two_signif_digits, check_params_defined_twice
from alfred.utils.directory_tree import DirectoryTree
from pathlib import Path
import packageName
# (1) Enter the algorithms to be run for each experiment
ALG_NAMES = ['simpleMLP']
... | [
"numpy.random.uniform",
"pathlib.Path"
] | [((1889, 1903), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (1893, 1903), False, 'from pathlib import Path\n'), ((1973, 1999), 'pathlib.Path', 'Path', (['packageName.__file__'], {}), '(packageName.__file__)\n', (1977, 1999), False, 'from pathlib import Path\n'), ((1148, 1186), 'numpy.random.uniform', 'n... |
import numpy
import numpy.fft
import pytest
import numpy.testing
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import librosa
import librosa.display
import pandas
import emlearn
import eml_audio
FFT_SIZES = [
64,
128,
256,
512,
1024,
]
@pytest.mark.parametrize('n_... | [
"numpy.log10",
"numpy.random.rand",
"librosa.util.example_audio_file",
"eml_audio.melspectrogram",
"numpy.array",
"numpy.arange",
"librosa.load",
"numpy.mean",
"numpy.testing.assert_allclose",
"numpy.fft.fft",
"eml_audio.sparse_filterbank",
"eml_audio.melfilter",
"numpy.testing.assert_almost... | [((86, 107), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (100, 107), False, 'import matplotlib\n'), ((293, 336), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n_fft"""', 'FFT_SIZES'], {}), "('n_fft', FFT_SIZES)\n", (316, 336), False, 'import pytest\n'), ((6340, 6366), 'pytest.mar... |
import numpy as np
import matplotlib.pyplot as plt
#Heat equation
A1 = np.array([[4,-1,0,-1,0,0,0,0,0],
[-1,4,-1,0,-1,0,0,0,0],
[0,-1,4,0,0,-1,0,0,0],
[-1,0,0,4,-1,0,-1,0,0],
[0,-1,0,-1,4,-1,0,-1,0],
[0,0,-1,0,-1,4,0,0,-1],
[0,0,0,-1,0,0,4,-1,0],
[0,0,0,0,-1,0,-1,4,-1],
[0,0,0,0,0,-1,0,-1,4]])
b= np... | [
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.plot",
"numpy.append",
"numpy.array",
"numpy.linalg.inv",
"numpy.matmul",
"matplotlib.pyplot.scatter",
"numpy.sin",
"matplotlib.pyp... | [((74, 382), 'numpy.array', 'np.array', (['[[4, -1, 0, -1, 0, 0, 0, 0, 0], [-1, 4, -1, 0, -1, 0, 0, 0, 0], [0, -1, 4, \n 0, 0, -1, 0, 0, 0], [-1, 0, 0, 4, -1, 0, -1, 0, 0], [0, -1, 0, -1, 4, -\n 1, 0, -1, 0], [0, 0, -1, 0, -1, 4, 0, 0, -1], [0, 0, 0, -1, 0, 0, 4, -1,\n 0], [0, 0, 0, 0, -1, 0, -1, 4, -1], [0, 0... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.applications import imagenet_utils
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.preprocessing.image import load_i... | [
"tensorflow.keras.preprocessing.image.load_img",
"progressbar.Bar",
"sklearn.preprocessing.LabelEncoder",
"random.shuffle",
"matplotlib.pyplot.show",
"pathlib.Path",
"numpy.array",
"progressbar.Percentage",
"numpy.vstack",
"tensorflow.keras.applications.ResNet50",
"progressbar.ETA",
"numpy.exp... | [((1038, 1135), 'pathlib.Path', 'Path', (['"""D:\\\\Docs\\\\Python_code\\\\ParkinsonsSketch\\\\178338_401677_bundle_archive\\\\drawings"""'], {}), "(\n 'D:\\\\Docs\\\\Python_code\\\\ParkinsonsSketch\\\\178338_401677_bundle_archive\\\\drawings'\n )\n", (1042, 1135), False, 'from pathlib import Path\n'), ((1286, 13... |
from operator import le
import os
import math
import warnings
warnings.filterwarnings('ignore', 'The iteration is not making good progress')
import numpy as np
np.set_printoptions(suppress=True)
import scipy
import scipy.stats
from scipy.stats import poisson, uniform, norm
from scipy.fftpack import fft, ifft
from scip... | [
"numpy.clip",
"numpy.convolve",
"numpy.sqrt",
"numpy.random.rand",
"numpy.log",
"scipy.signal.savgol_filter",
"numpy.random.exponential",
"numpy.isin",
"numpy.array",
"numpy.einsum",
"scipy.fftpack.fft",
"scipy.stats.norm.logpdf",
"numpy.linalg.norm",
"scipy.stats.norm.cdf",
"numpy.arang... | [((62, 140), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""', '"""The iteration is not making good progress"""'], {}), "('ignore', 'The iteration is not making good progress')\n", (85, 140), False, 'import warnings\n'), ((161, 195), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress... |
import numpy as np
import pandas as pd
import sys
import hashlib
import io
import os
from . import glob_var
from . import structures
from . import type_conversions
def decompress_motifs_from_bitstring(bitstring):
motifs_list = []
total_length = len(bitstring)
current_spot = 0
while current_spot < t... | [
"numpy.uint8",
"numpy.prod",
"numpy.packbits",
"os.path.exists",
"numpy.reshape",
"hashlib.md5",
"os.makedirs",
"numpy.unpackbits",
"numpy.array",
"numpy.zeros",
"sys.exit",
"numpy.frombuffer",
"io.StringIO"
] | [((7489, 7527), 'numpy.array', 'np.array', (['profiles_list'], {'dtype': 'np.bool'}), '(profiles_list, dtype=np.bool)\n', (7497, 7527), True, 'import numpy as np\n'), ((10325, 10363), 'numpy.array', 'np.array', (['profiles_list'], {'dtype': 'np.bool'}), '(profiles_list, dtype=np.bool)\n', (10333, 10363), True, 'import ... |
import numpy as np
class StateAggregation:
"""Combine multiple states into groups
and provide linear feature vector for function approximation"""
def __init__(self, N_states, group_size, N_actions=1):
"""
Args:
N_states: Total number of states
group_size: Combine th... | [
"numpy.zeros"
] | [((1302, 1321), 'numpy.zeros', 'np.zeros', (['self.size'], {}), '(self.size)\n', (1310, 1321), True, 'import numpy as np\n'), ((1937, 1956), 'numpy.zeros', 'np.zeros', (['self.size'], {}), '(self.size)\n', (1945, 1956), True, 'import numpy as np\n')] |
from collections import namedtuple
import numpy as np
from untwist import data, utilities, transforms
Anchors = namedtuple('Anchors', ['Distortion',
'Artefacts',
'Interferer',
'Quality'],
)
class ... | [
"collections.namedtuple",
"numpy.random.choice",
"untwist.transforms.ISTFT",
"numpy.array",
"untwist.transforms.STFT",
"untwist.utilities.conversion.nearest_bin",
"numpy.unravel_index",
"scipy.signal.get_window",
"untwist.utilities.conversion.db_to_amp"
] | [((114, 189), 'collections.namedtuple', 'namedtuple', (['"""Anchors"""', "['Distortion', 'Artefacts', 'Interferer', 'Quality']"], {}), "('Anchors', ['Distortion', 'Artefacts', 'Interferer', 'Quality'])\n", (124, 189), False, 'from collections import namedtuple\n'), ((2279, 2318), 'scipy.signal.get_window', 'signal.get_... |
import tensorflow as tf
import numpy as np
from tqdm import tqdm
from tf_metric_learning.utils.index import AnnoyDataIndex
class AnnoyEvaluatorCallback(AnnoyDataIndex):
"""
Callback, extracts embeddings, add them to AnnoyIndex and evaluate them as recall.
"""
def __init__(
self,
mod... | [
"tensorflow.nn.l2_normalize",
"numpy.asarray"
] | [((3161, 3196), 'numpy.asarray', 'np.asarray', (["self.results['default']"], {}), "(self.results['default'])\n", (3171, 3196), True, 'import numpy as np\n'), ((1770, 1814), 'tensorflow.nn.l2_normalize', 'tf.nn.l2_normalize', (['embeddings_store'], {'axis': '(1)'}), '(embeddings_store, axis=1)\n', (1788, 1814), True, 'i... |
import os
import numpy as np
import pandas as pd
from PIL import Image
import torch
from torchvision import transforms
from tqdm import tqdm
from torchvision import models
from numpy.testing import assert_almost_equal
from typing import List
from constants import PATH_IMAGES_CNN, PATH_IMAGES_RAW
clas... | [
"os.path.exists",
"os.listdir",
"PIL.Image.open",
"os.makedirs",
"torchvision.transforms.Resize",
"os.path.join",
"torchvision.models.resnet18",
"numpy.inner",
"os.path.isfile",
"torchvision.transforms.Normalize",
"numpy.linalg.norm",
"pandas.DataFrame",
"torchvision.transforms.ToTensor",
... | [((655, 674), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (667, 674), False, 'import torch\n'), ((1013, 1034), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1032, 1034), False, 'from torchvision import transforms\n'), ((1061, 1136), 'torchvision.transforms.Normalize'... |
import tempfile
import unittest
import numpy as np
import pystan
from pystan.tests.helper import get_model
def validate_data(fit):
la = fit.extract(permuted=True) # return a dictionary of arrays
mu, tau, eta, theta = la['mu'], la['tau'], la['eta'], la['theta']
np.testing.assert_equal(mu.shape, (2000,))... | [
"numpy.mean",
"numpy.testing.assert_equal",
"pystan.stan",
"tempfile.NamedTemporaryFile",
"pystan.tests.helper.get_model"
] | [((278, 320), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['mu.shape', '(2000,)'], {}), '(mu.shape, (2000,))\n', (301, 320), True, 'import numpy as np\n'), ((325, 368), 'numpy.testing.assert_equal', 'np.testing.assert_equal', (['tau.shape', '(2000,)'], {}), '(tau.shape, (2000,))\n', (348, 368), True, 'imp... |
import random
import unittest
import numpy as np
import torch
from elasticai.creator.brevitas.brevitas_model_comparison import (
BrevitasModelComparisonTestCase,
)
from elasticai.creator.brevitas.brevitas_representation import BrevitasRepresentation
from elasticai.creator.systemTests.brevitas_representation.model... | [
"torch.manual_seed",
"elasticai.creator.brevitas.brevitas_representation.BrevitasRepresentation.from_pytorch",
"random.seed",
"elasticai.creator.systemTests.brevitas_representation.models_definition.create_qtorch_model",
"numpy.random.seed",
"unittest.main",
"elasticai.creator.systemTests.brevitas_repre... | [((1380, 1395), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1393, 1395), False, 'import unittest\n'), ((663, 683), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (680, 683), False, 'import torch\n'), ((692, 706), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (703, 706), False, 'impor... |
"""
get_offset determines the optimal p-site offset for each read-length on the top 10 most abundant ORFs in the bam-file
usage:
python get_offset.py --bam <bam-file> --orfs <ribofy orfs-file> --output <output-file>
By default, get_offset analyses reads between 25 and 35 nt,
but this is customizable with the --min_... | [
"pandas.Series",
"pandas.DataFrame",
"pandas.read_csv",
"collections.Counter",
"numpy.sum",
"pysam.Samfile",
"pandas.concat"
] | [((1757, 1791), 'pandas.Series', 'pd.Series', (['d'], {'index': '[i for i in d]'}), '(d, index=[i for i in d])\n', (1766, 1791), True, 'import pandas as pd\n'), ((3114, 3128), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (3126, 3128), True, 'import pandas as pd\n'), ((3144, 3158), 'pandas.DataFrame', 'pd.DataF... |
from pyimagesearch import datasets
from pyimagesearch import models
from sklearn.model_selection import train_test_split
from keras.layers.core import Dense
from keras.models import Model
from keras.optimizers import Adam
from keras.layers import concatenate
import tensorflow as tf
from tensorflow import feature_column... | [
"numpy.ma.masked_equal",
"tensorflow.feature_column.indicator_column",
"pyimagesearch.datasets.load_data",
"os.listdir",
"tensorflow.keras.layers.DenseFeatures",
"cv2.threshold",
"pyimagesearch.datasets.load_wrist_images",
"numpy.asarray",
"tensorflow.feature_column.numeric_column",
"numpy.ma.fill... | [((670, 694), 'os.listdir', 'os.listdir', (['"""demo\\\\data"""'], {}), "('demo\\\\data')\n", (680, 694), False, 'import os\n'), ((3732, 3821), 'pyimagesearch.datasets.load_data', 'datasets.load_data', (['"""C:\\\\Users\\\\User\\\\Desktop\\\\Peter\\\\Bone_density\\\\demo\\\\demo.xlsx"""'], {}), "(\n 'C:\\\\Users\\\\... |
import numpy as np
import os
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# has to change whenever noise_width and noise_height change in the PerlinNoise.hpp file
DIMENSION1 = 200
DIMENSION2 = 200
# works if the working directory is set
path = os.path.dirname(os.path.realpath(__file__)... | [
"matplotlib.pyplot.colorbar",
"os.path.realpath",
"matplotlib.pyplot.figure",
"numpy.meshgrid",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((294, 320), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (310, 320), False, 'import os\n'), ((560, 581), 'numpy.arange', 'np.arange', (['DIMENSION1'], {}), '(DIMENSION1)\n', (569, 581), True, 'import numpy as np\n'), ((591, 612), 'numpy.arange', 'np.arange', (['DIMENSION2'], {}), '(DIME... |
# import numpy as np
# import os
# import skimage.io as io
# import skimage.transform as trans
# import numpy as np
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
import tensorflow as tf
import numpy as np
from skimage.morphology import label
from ... | [
"numpy.mean",
"numpy.histogram",
"numpy.unique",
"skimage.morphology.label",
"numpy.sum",
"numpy.expand_dims",
"tensorflow.py_func",
"numpy.arange"
] | [((458, 480), 'skimage.morphology.label', 'label', (['(y_true_in > 0.5)'], {}), '(y_true_in > 0.5)\n', (463, 480), False, 'from skimage.morphology import label\n'), ((494, 516), 'skimage.morphology.label', 'label', (['(y_pred_in > 0.5)'], {}), '(y_pred_in > 0.5)\n', (499, 516), False, 'from skimage.morphology import la... |
from random import randint as rand
import matplotlib.pyplot as plt
import numpy as np
from math import factorial
import pandas as pd
#creating a variable for number of coins
global coins
global trial
#taking input from the user
coins = int(input("enter number of coins:"))
trial = int(input("enter th... | [
"matplotlib.pyplot.ylabel",
"math.factorial",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.array",
"pandas.DataFrame",
"random.randint",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((1161, 1179), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (1173, 1179), True, 'import pandas as pd\n'), ((1509, 1530), 'pandas.DataFrame', 'pd.DataFrame', (['data_th'], {}), '(data_th)\n', (1521, 1530), True, 'import pandas as pd\n'), ((1590, 1610), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""... |
import numpy as np
from sklearn.cluster import DBSCAN
from faster_particles.ppn_utils import crop as crop_util
from faster_particles.display_utils import extract_voxels
class CroppingAlgorithm(object):
"""
Base class for any cropping algorithm, they should inherit from it
and implement crop method (see be... | [
"numpy.clip",
"numpy.unique",
"faster_particles.ppn_utils.crop",
"numpy.flipud",
"numpy.where",
"numpy.arange",
"numpy.logical_and",
"numpy.ones",
"numpy.argmax",
"numpy.logical_or",
"numpy.array",
"numpy.zeros",
"numpy.concatenate",
"faster_particles.display_utils.extract_voxels",
"skle... | [((6234, 6282), 'numpy.concatenate', 'np.concatenate', (['[border_idx, padded_idx]'], {'axis': '(0)'}), '([border_idx, padded_idx], axis=0)\n', (6248, 6282), True, 'import numpy as np\n'), ((6764, 6794), 'numpy.array', 'np.array', (['artificial_gt_pixels'], {}), '(artificial_gt_pixels)\n', (6772, 6794), True, 'import n... |
import jax.numpy as jnp
import numpy as np
import matplotlib.pyplot as plt
import jax
from jax.experimental.optimizers import adam
from dataclasses import dataclass
@dataclass
class InterceptSettings:
min_duration: float = 0.02
min_duration_final: float = 0.05
duration: float = 0
distance: float = 1.0
... | [
"numpy.sqrt",
"numpy.array",
"numpy.arctan2",
"numpy.sin",
"numpy.nanargmin",
"jax.numpy.sin",
"jax.experimental.optimizers.adam",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots",
"jax.value_and_grad",
"jax.numpy.cos",
"matplotlib.pyplot.gca",
"jax.numpy.linalg.norm",
"numpy.cos",
... | [((2796, 2853), 'jax.vmap', 'jax.vmap', (['calc_route'], {'in_axes': '[0, None, None]', 'out_axes': '(0)'}), '(calc_route, in_axes=[0, None, None], out_axes=0)\n', (2804, 2853), False, 'import jax\n'), ((2867, 2935), 'jax.vmap', 'jax.vmap', (['loss_func'], {'in_axes': '[0, None, None, None, None]', 'out_axes': '(0)'}),... |
# May 2018 xyz
import numpy as np
import numba
def Rx( x ):
# ref to my master notes 2015
# anticlockwise, x: radian
Rx = np.zeros((3,3))
Rx[0,0] = 1
Rx[1,1] = np.cos(x)
Rx[1,2] = np.sin(x)
Rx[2,1] = -np.sin(x)
Rx[2,2] = np.cos(x)
return Rx
def Ry( y ):
# anticlockwise, y: radi... | [
"numpy.array",
"numpy.linalg.norm",
"numpy.sin",
"numpy.max",
"numpy.matmul",
"numpy.empty",
"numpy.concatenate",
"numpy.min",
"numpy.tile",
"numpy.eye",
"numpy.abs",
"numpy.floor",
"numba.jit",
"numpy.isnan",
"numpy.cos",
"numpy.sign",
"numpy.transpose",
"numpy.sum",
"numpy.zero... | [((477, 501), 'numba.jit', 'numba.jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (486, 501), False, 'import numba\n'), ((135, 151), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (143, 151), True, 'import numpy as np\n'), ((181, 190), 'numpy.cos', 'np.cos', (['x'], {}), '(x)\n', (187, 190), True, ... |
import numpy as np
import scipy.integrate
from scipy.interpolate import interp1d, interp2d, RectBivariateSpline,UnivariateSpline,griddata
from scipy.spatial import Delaunay, ConvexHull
from matplotlib.collections import LineCollection
from scipy.interpolate import splprep,splev
from scipy.optimize import fmin
from matp... | [
"numpy.sqrt",
"numpy.hstack",
"matplotlib.collections.LineCollection",
"numpy.array",
"numpy.arctan2",
"numpy.sin",
"scipy.optimize.fmin",
"scipy.interpolate.RectBivariateSpline",
"numpy.max",
"numpy.dot",
"numpy.linspace",
"scipy.interpolate.splev",
"numpy.vstack",
"numpy.min",
"numpy.a... | [((885, 929), 'numpy.array', 'np.array', (['[[1, 0, 0], [0, -1, 0], [0, 0, 1]]'], {}), '([[1, 0, 0], [0, -1, 0], [0, 0, 1]])\n', (893, 929), True, 'import numpy as np\n'), ((934, 978), 'numpy.array', 'np.array', (['[[-1, 0, 0], [0, 1, 0], [0, 0, 1]]'], {}), '([[-1, 0, 0], [0, 1, 0], [0, 0, 1]])\n', (942, 978), True, 'i... |
import numpy as np
from .utils import gaussian_pdf, mutation_kernel, resize_to_exp_limits_det
from .utils import prob_low_det_high_measurement
from .model_parameters import low_en_exp_cutoff, high_en_exp_cutoff, low_en_threshold
class det_pop:
'''
Deterministic population function class. This class implement... | [
"numpy.copy",
"numpy.convolve",
"numpy.exp",
"numpy.sum",
"numpy.dot",
"numpy.min",
"numpy.zeros_like",
"numpy.arange"
] | [((2458, 2487), 'numpy.arange', 'np.arange', (['xlim_m', 'xlim_p', 'dx'], {}), '(xlim_m, xlim_p, dx)\n', (2467, 2487), True, 'import numpy as np\n'), ((3722, 3779), 'numpy.arange', 'np.arange', (["par['xlim_minus']", "par['xlim_plus']", "par['dx']"], {}), "(par['xlim_minus'], par['xlim_plus'], par['dx'])\n", (3731, 377... |
# -*- coding: utf-8 -*-
"""
@author: <NAME> <<EMAIL>>
@brief:
"""
from __future__ import print_function
import os
import re
import sys
import shutil
import tempfile
import subprocess
import numpy as np
import scipy.sparse as sps
from pylightgbm.utils import io_utils
from sklearn.base import BaseEstimator, ClassifierMix... | [
"os.path.join",
"scipy.sparse.issparse",
"re.findall",
"pylightgbm.utils.io_utils.dump_data",
"numpy.zeros",
"tempfile.mkdtemp",
"numpy.vstack",
"numpy.savetxt",
"shutil.rmtree",
"numpy.loadtxt",
"os.path.expanduser"
] | [((3334, 3352), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (3350, 3352), False, 'import tempfile\n'), ((3372, 3387), 'scipy.sparse.issparse', 'sps.issparse', (['X'], {}), '(X)\n', (3384, 3387), True, 'import scipy.sparse as sps\n'), ((3572, 3622), 'pylightgbm.utils.io_utils.dump_data', 'io_utils.dump_dat... |
# Copyright 2021 Southwest Research Institute
# Licensed under the Apache License, Version 2.0
# Imports for ros
from inspect import EndOfBlock
from operator import truediv
import rospy
# import tf
import numpy as np
import matplotlib.pyplot as plt
from colorama import Fore, Back, Style
from rospkg import RosPack
from... | [
"rospy.logerr",
"geometry_msgs.msg.TransformStamped",
"rospy.init_node",
"geometry_msgs.msg.Wrench",
"tf2_ros.StaticTransformBroadcaster",
"numpy.array",
"controller_manager_msgs.srv.ListControllers",
"rospy.Rate",
"tf2_geometry_msgs.do_transform_pose",
"numpy.sin",
"numpy.mod",
"geometry_msgs... | [((43659, 43714), 'rospy.init_node', 'rospy.init_node', (['"""demo_assembly_application_compliance"""'], {}), "('demo_assembly_application_compliance')\n", (43674, 43714), False, 'import rospy\n'), ((1019, 1118), 'rospy.Publisher', 'rospy.Publisher', (['"""/cartesian_compliance_controller/target_wrench"""', 'WrenchStam... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
use this code to extract these four metrics:
1. ROUGE
2. METEOR
3. REPETITION WITHIN SUMMARY
4. OVERLAP WITH ARTICLE
5. AVG SENTS and LEN SUMMARIES
"""
import os
import glob
import json
import pyrouge
import hashlib
import logging
import subproces... | [
"subprocess.check_output",
"os.path.exists",
"logging.getLogger",
"hashlib.md5",
"sklearn.feature_extraction.text.CountVectorizer",
"tensorflow.logging.info",
"os.path.join",
"collections.Counter",
"pyrouge.Rouge155",
"numpy.sum",
"os.path.isdir",
"nltk.ngrams",
"glob.glob",
"os.remove"
] | [((3759, 3776), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {}), '()\n', (3774, 3776), False, 'from sklearn.feature_extraction.text import CountVectorizer\n'), ((653, 680), 'os.path.isdir', 'os.path.isdir', (['article_path'], {}), '(article_path)\n', (666, 680), False, 'import os\n'), ((9... |
# Start by loading packages
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib
import time
import ot
import scipy
from scipy import linalg
from scipy import sparse
import gromovWassersteinAveraging as gwa
import spectralGW as sgw
from geodesicVisualization import *
import seabor... | [
"scipy.stats.bartlett",
"numpy.log",
"seaborn.catplot",
"numpy.var",
"matplotlib.style.use",
"networkx.betweenness_centrality",
"ot.gromov.gromov_barycenters",
"numpy.mean",
"pandas.DataFrame",
"matplotlib.pyplot.savefig",
"numpy.random.choice",
"networkx.adjacency_matrix",
"pickle.load",
... | [((518, 551), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (541, 551), False, 'import warnings\n'), ((729, 739), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (737, 739), True, 'import networkx as nx\n'), ((745, 755), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (75... |
# -*- coding: utf-8 -*-
from Models import Regression
import pandas as pd
import numpy as np
dataset = pd.read_csv('Data.csv')
X = np.array([[14,41,1020,72], [10,40,1010,90]])
best_model = None
for regression in Regression.__subclasses__():
model = regression(dataset)
model.train_regressor()
if best_model... | [
"numpy.array",
"Models.Regression.__subclasses__",
"pandas.read_csv"
] | [((104, 127), 'pandas.read_csv', 'pd.read_csv', (['"""Data.csv"""'], {}), "('Data.csv')\n", (115, 127), True, 'import pandas as pd\n'), ((132, 182), 'numpy.array', 'np.array', (['[[14, 41, 1020, 72], [10, 40, 1010, 90]]'], {}), '([[14, 41, 1020, 72], [10, 40, 1010, 90]])\n', (140, 182), True, 'import numpy as np\n'), (... |
import copy
import time
import optuna
import warnings
import numpy as np
import pandas as pd
from datetime import datetime
from sklearn.model_selection import KFold
from sklearn.metrics import SCORERS
class OptunaGridSearch:
def __init__(self, model, cv=KFold(n_splits=10), scoring='accuracy', verbose=0, timeout=... | [
"numpy.mean",
"copy.deepcopy",
"numpy.log2",
"optuna.integration.XGBoostPruningCallback",
"optuna.integration.LightGBMPruningCallback",
"numpy.std",
"datetime.datetime.today",
"optuna.samplers.TPESampler",
"sklearn.model_selection.KFold",
"time.time"
] | [((261, 279), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(10)'}), '(n_splits=10)\n', (266, 279), False, 'from sklearn.model_selection import KFold\n'), ((17055, 17080), 'copy.deepcopy', 'copy.deepcopy', (['self.model'], {}), '(self.model)\n', (17068, 17080), False, 'import copy\n'), ((17920, 17935), '... |
import numpy as np
from cumm import tensorview as tv
from spconv.utils import Point2VoxelCPU3d
from spconv.pytorch.utils import PointToVoxel, gather_features_by_pc_voxel_id
import torch
import numpy as np
np.random.seed(50051)
# voxel gen source code: spconv/csrc/sparse/pointops.py
gen = PointToVoxel(vsize_xyz=[1, 1... | [
"numpy.array",
"spconv.pytorch.utils.PointToVoxel",
"numpy.random.seed",
"torch.from_numpy"
] | [((208, 229), 'numpy.random.seed', 'np.random.seed', (['(50051)'], {}), '(50051)\n', (222, 229), True, 'import numpy as np\n'), ((292, 440), 'spconv.pytorch.utils.PointToVoxel', 'PointToVoxel', ([], {'vsize_xyz': '[1, 1, 4]', 'coors_range_xyz': '[-10, -4, -2, 10, 4, 2]', 'num_point_features': '(4)', 'max_num_voxels': '... |
## An Eve optimizer implementation in Chainer
# By <NAME>
# https://github.com/muupan/chainer-eve
# Modified by <NAME>
from __future__ import division
import math
import numpy
from chainer import optimizer
from chainer.optimizers import adam
_default_hyperparam = optimizer.Hyperparameter()
_default_hyperparam.alp... | [
"numpy.clip",
"math.pow",
"math.sqrt",
"chainer.optimizer.HyperparameterProxy",
"chainer.optimizer.Hyperparameter"
] | [((270, 296), 'chainer.optimizer.Hyperparameter', 'optimizer.Hyperparameter', ([], {}), '()\n', (294, 296), False, 'from chainer import optimizer\n'), ((3911, 3949), 'chainer.optimizer.HyperparameterProxy', 'optimizer.HyperparameterProxy', (['"""alpha"""'], {}), "('alpha')\n", (3940, 3949), False, 'from chainer import ... |
import cantera as ct
import numpy as np
import funcs.simulation.cell_size as cs
relTol = 1e-4
absTol = 1e-6
# noinspection PyProtectedMember
class TestAgainstDemo:
# Test calculated values against demo script
original_cell_sizes = {
'Gavrikov': 1.9316316546518768e-02,
'Ng': 6.564482596891476... | [
"numpy.allclose",
"numpy.isclose",
"numpy.ones",
"subprocess.check_call",
"funcs.simulation.cell_size.CellSize",
"cantera.Solution",
"tests.test_simulation.test_database.remove_stragglers"
] | [((6643, 6662), 'tests.test_simulation.test_database.remove_stragglers', 'remove_stragglers', ([], {}), '()\n', (6660, 6662), False, 'from tests.test_simulation.test_database import remove_stragglers\n'), ((706, 719), 'funcs.simulation.cell_size.CellSize', 'cs.CellSize', ([], {}), '()\n', (717, 719), True, 'import func... |
try:
import numpy as np
except ImportError:
raise RuntimeError('cannot import numpy, make sure numpy package is installed')
from carla.client import VehicleControl
from carla.agent import Agent
import matplotlib.pyplot as plt
import psutil
import gc
gc.enable()
import pickle
import time
import os
import ZG... | [
"numpy.sqrt",
"torch.max",
"psutil.virtual_memory",
"fcn.prepare_EncNet.get_encnet_resnet101_ade",
"fcn.prepare_psp.get_psp_resnet50_ade",
"sys.path.append",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.waitforbuttonpress",
"gc.enable",
"torchvision.transforms.ToTensor",
"numpy.random.choice",... | [((261, 272), 'gc.enable', 'gc.enable', ([], {}), '()\n', (270, 272), False, 'import gc\n'), ((2097, 2113), 'carla.client.VehicleControl', 'VehicleControl', ([], {}), '()\n', (2111, 2113), False, 'from carla.client import VehicleControl\n'), ((9683, 9695), 'gc.collect', 'gc.collect', ([], {}), '()\n', (9693, 9695), Fal... |
from os.path import join
from numpy import sqrt, pi, linspace, array, zeros
from numpy.testing import assert_almost_equal
from multiprocessing import cpu_count
import pytest
from SciDataTool.Functions.Plot.plot_2D import plot_2D
from pyleecan.Classes.OPdq import OPdq
from pyleecan.Classes.Simu1 import Simu1
from p... | [
"pytest.approx",
"numpy.sqrt",
"pyleecan.Classes.Simu1.Simu1",
"pyleecan.Classes.OPdq.OPdq",
"os.path.join",
"multiprocessing.cpu_count",
"pyleecan.Classes.Electrical.Electrical",
"pyleecan.Classes.MagFEMM.MagFEMM",
"numpy.array",
"numpy.linspace",
"numpy.zeros",
"numpy.testing.assert_almost_e... | [((1139, 1188), 'pyleecan.Classes.Simu1.Simu1', 'Simu1', ([], {'name': '"""test_EEC_PMSM"""', 'machine': 'Toyota_Prius'}), "(name='test_EEC_PMSM', machine=Toyota_Prius)\n", (1144, 1188), False, 'from pyleecan.Classes.Simu1 import Simu1\n'), ((1450, 1538), 'pyleecan.Classes.MagFEMM.MagFEMM', 'MagFEMM', ([], {'is_periodi... |
import numpy as np
class ClusterProcessor(object):
def __init__(self, dataset):
self.dataset = dataset
self.dtype = np.float32
def __len__(self):
return self.dataset.size
def build_adj(self, node, edge):
node = list(node)
abs2rel = {}
rel2abs = {}
... | [
"numpy.eye"
] | [((442, 454), 'numpy.eye', 'np.eye', (['size'], {}), '(size)\n', (448, 454), True, 'import numpy as np\n')] |
from pgmpy.models import MarkovModel
from pgmpy.factors.discrete import JointProbabilityDistribution, DiscreteFactor
from itertools import combinations
from flyingsquid.helpers import *
import numpy as np
import math
from tqdm import tqdm
import sys
import random
class Mixin:
'''
Functions to compute observabl... | [
"numpy.prod",
"pgmpy.factors.discrete.JointProbabilityDistribution"
] | [((688, 758), 'pgmpy.factors.discrete.JointProbabilityDistribution', 'JointProbabilityDistribution', (['Ys_ordered', 'cardinalities', 'class_balance'], {}), '(Ys_ordered, cardinalities, class_balance)\n', (716, 758), False, 'from pgmpy.factors.discrete import JointProbabilityDistribution, DiscreteFactor\n'), ((2783, 27... |
import numpy as np
from hand import Hand
iterations = 250000
starting_size = 8 #inclusive
mullto = 7 #inclusive
hand = Hand("decklists/affinity.txt")
hand_types = ["t1 2-drop", "t1 3-drop"]
hand_counts = np.zeros(((starting_size + 1) - mullto,len(hand_types)))
totals = np.zeros(((starting_size + 1) - mullto,1))
zero_... | [
"numpy.flip",
"numpy.zeros",
"hand.Hand"
] | [((120, 150), 'hand.Hand', 'Hand', (['"""decklists/affinity.txt"""'], {}), "('decklists/affinity.txt')\n", (124, 150), False, 'from hand import Hand\n'), ((271, 312), 'numpy.zeros', 'np.zeros', (['(starting_size + 1 - mullto, 1)'], {}), '((starting_size + 1 - mullto, 1))\n', (279, 312), True, 'import numpy as np\n'), (... |
from collections import Counter
from imblearn.datasets import make_imbalance
from imblearn.metrics import classification_report_imbalanced
from imblearn.pipeline import make_pipeline
from imblearn.under_sampling import ClusterCentroids
from imblearn.under_sampling import NearMiss
import matplotlib.pyplot as plt
from ... | [
"sklearn.datasets.load_iris",
"matplotlib.pyplot.contourf",
"numpy.unique",
"matplotlib.pyplot.show",
"sklearn.model_selection.train_test_split",
"sklearn.svm.LinearSVC",
"imblearn.datasets.make_imbalance",
"matplotlib.pyplot.figure",
"pandas.DataFrame",
"imblearn.under_sampling.NearMiss",
"matp... | [((1686, 1733), 'matplotlib.pyplot.contourf', 'plt.contourf', (['xx1', 'xx2', 'Z'], {'alpha': '(0.4)', 'cmap': 'cmap'}), '(xx1, xx2, Z, alpha=0.4, cmap=cmap)\n', (1698, 1733), True, 'import matplotlib.pyplot as plt\n'), ((2215, 2226), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (2224, 2226), False, 'fr... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import math
import numpy as np
import states.area
import states.face
import states.fail
import states.success
from challenge import Challenge
class NoseState:
MAXIMUM_DURATION_IN_SECONDS = 10
AREA_BOX_T... | [
"numpy.histogram2d",
"numpy.linalg.norm",
"numpy.reshape",
"numpy.polyfit"
] | [((3767, 3829), 'numpy.polyfit', 'np.polyfit', (['nose_trajectory_x', 'nose_trajectory_y', '(2)'], {'full': '(True)'}), '(nose_trajectory_x, nose_trajectory_y, 2, full=True)\n', (3777, 3829), True, 'import numpy as np\n'), ((4311, 4405), 'numpy.histogram2d', 'np.histogram2d', (['original_landmarks_x', 'original_landmar... |
# This file was generated
import array
import ctypes
import datetime
import threading
import nitclk._attributes as _attributes
import nitclk._converters as _converters
import nitclk._library_singleton as _library_singleton
import nitclk._visatype as _visatype
import nitclk.errors as errors
# Used for __repr__ and __... | [
"nitclk._visatype.ViBoolean",
"ctypes.pointer",
"datetime.timedelta",
"nitclk._visatype.ViAttr",
"nitclk.errors.handle_error",
"threading.Lock",
"pprint.PrettyPrinter",
"nitclk._attributes.AttributeViReal64",
"nitclk._converters.convert_timedelta_to_seconds_real64",
"nitclk._visatype.ViSession",
... | [((345, 375), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(4)'}), '(indent=4)\n', (365, 375), False, 'import pprint\n'), ((427, 443), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (441, 443), False, 'import threading\n'), ((1612, 1644), 'nitclk._attributes.AttributeViString', '_attributes.A... |
from random import random
import numpy as np
from math import e
def degrau(u):
if u>=0:
return 1
else:
return 0
def degrauBipolar(u):
if u>0:
return 1
elif u==0:
return 0
else:
return -1
def linear(u):
return u
def logistica(u,beta):
return 1/(1 + e*... | [
"numpy.array",
"random.random",
"numpy.prod"
] | [((4321, 4345), 'numpy.array', 'np.array', (['entrada_e_peso'], {}), '(entrada_e_peso)\n', (4329, 4345), True, 'import numpy as np\n'), ((3896, 3918), 'numpy.prod', 'np.prod', (['linha'], {'axis': '(1)'}), '(linha, axis=1)\n', (3903, 3918), True, 'import numpy as np\n'), ((4008, 4016), 'random.random', 'random', ([], {... |
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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... | [
"numpy.ceil",
"qf_lib.containers.dataframe.qf_dataframe.QFDataFrame.from_dict",
"qf_lib.backtesting.contract.contract.Contract",
"qf_lib.common.utils.dateutils.timer.SettableTimer",
"pandas.read_csv",
"qf_lib.common.utils.logging.qf_parent_logger.qf_logger.getChild",
"qf_lib.documents_utils.document_exp... | [((2685, 2720), 'qf_lib.common.utils.error_handling.ErrorHandling.class_error_logging', 'ErrorHandling.class_error_logging', ([], {}), '()\n', (2718, 2720), False, 'from qf_lib.common.utils.error_handling import ErrorHandling\n'), ((5596, 5648), 'qf_lib.analysis.strategy_monitoring.pnl_calculator.PnLCalculator', 'PnLCa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import numpy as np
from mindboggle.mio.colors import distinguishable_colors, label_adjacency_matrix
if __name__ == "__main__":
description = ('calculate colormap for labeled image;'
'calculated result is stored in outpu... | [
"os.makedirs",
"argparse.ArgumentParser",
"os.path.join",
"mindboggle.mio.colors.distinguishable_colors",
"os.path.isfile",
"os.path.isdir",
"mindboggle.mio.colors.label_adjacency_matrix",
"numpy.load",
"numpy.save"
] | [((356, 404), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'description'}), '(description=description)\n', (379, 404), False, 'import argparse\n'), ((863, 910), 'os.path.join', 'os.path.join', (['args.output_dirname', '"""matrix.npy"""'], {}), "(args.output_dirname, 'matrix.npy')\n", (875,... |
import sys
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from railrl.visualization import visualization_util as vu
from railrl.torch.vae.skew.common import prob_to_weight
def visualize_vae_samples(
epoch, training_data, vae,
report, d... | [
"railrl.visualization.visualization_util.plot_heatmap",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.plot",
"railrl.torch.vae.skew.common.prob_to_weight",
"numpy.array2string",
"numpy.swapaxes",
"matplotlib.pyplot.figu... | [((407, 419), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (417, 419), True, 'from matplotlib import pyplot as plt\n'), ((759, 779), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (770, 779), True, 'from matplotlib import pyplot as plt\n'), ((784, 847), 'matplotli... |
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torch.optim import lr_scheduler
from torchvision import datasets, transforms, models
import copy
import time
import argparse
from sys import argv
import os
import json
import numpy as np
def process_image(image):
''' Sca... | [
"torch.nn.ReLU",
"PIL.Image.open",
"torch.nn.Dropout",
"argparse.ArgumentParser",
"torchvision.models.vgg19",
"torch.load",
"torchvision.models.alexnet",
"torch.from_numpy",
"numpy.array",
"torch.cuda.is_available",
"torch.nn.Linear",
"torch.nn.LogSoftmax",
"json.load",
"torchvision.models... | [((455, 472), 'PIL.Image.open', 'Image.open', (['image'], {}), '(image)\n', (465, 472), False, 'from PIL import Image\n'), ((877, 908), 'numpy.array', 'np.array', (['[0.485, 0.456, 0.406]'], {}), '([0.485, 0.456, 0.406])\n', (885, 908), True, 'import numpy as np\n'), ((919, 950), 'numpy.array', 'np.array', (['[0.229, 0... |
import numpy as np
import paddle
from math import sqrt
from sklearn.linear_model import LinearRegression
def cos_formula(a, b, c):
''' formula to calculate the angle between two edges
a and b are the edge lengths, c is the angle length.
'''
res = (a**2 + b**2 - c**2) / (2 * a * b)
# sanity chec... | [
"numpy.abs",
"paddle.ones_like",
"numpy.arccos",
"numpy.corrcoef",
"paddle.cumsum",
"paddle.zeros",
"sklearn.linear_model.LinearRegression"
] | [((403, 417), 'numpy.arccos', 'np.arccos', (['res'], {}), '(res)\n', (412, 417), True, 'import numpy as np\n'), ((1107, 1125), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (1123, 1125), False, 'from sklearn.linear_model import LinearRegression\n'), ((1344, 1386), 'paddle.zeros', 'paddl... |
#!/usr/bin/env python
# coding: utf-8
import rospy
import geometry_msgs.msg
from sensor_msgs.msg import JointState
import numpy as np
class Arm_ik:
def __init__(self):
self._sub_pos = rospy.Subscriber("/arm_pos", geometry_msgs.msg.Point, self.pos_callback)
self.pub = rospy.Publisher("vv_kuwamai/ma... | [
"numpy.abs",
"rospy.Subscriber",
"rospy.is_shutdown",
"numpy.hstack",
"rospy.init_node",
"sensor_msgs.msg.JointState",
"numpy.array",
"rospy.Rate",
"rospy.spin",
"numpy.cos",
"numpy.linalg.norm",
"numpy.sin",
"rospy.Publisher",
"rospy.loginfo"
] | [((198, 270), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/arm_pos"""', 'geometry_msgs.msg.Point', 'self.pos_callback'], {}), "('/arm_pos', geometry_msgs.msg.Point, self.pos_callback)\n", (214, 270), False, 'import rospy\n'), ((290, 365), 'rospy.Publisher', 'rospy.Publisher', (['"""vv_kuwamai/master_joint_state"""', ... |
import numpy as np
import torch as th
class EpidemicModel(th.nn.Module):
"""Score driven epidemic model."""
def __init__(self):
super(EpidemicModel, self).__init__()
self.alpha = th.nn.Parameter(th.tensor(0.0, requires_grad=True))
self.beta = th.nn.Parameter(th.tensor(0.0, requires_gr... | [
"torch.log",
"torch.mean",
"torch.stack",
"torch.exp",
"torch.full_like",
"numpy.exp",
"torch.tensor",
"numpy.array",
"torch.isnan",
"torch.arange"
] | [((1808, 1829), 'torch.arange', 'th.arange', (['(0)', 'horizon'], {}), '(0, horizon)\n', (1817, 1829), True, 'import torch as th\n'), ((3787, 3808), 'torch.arange', 'th.arange', (['(0)', 'horizon'], {}), '(0, horizon)\n', (3796, 3808), True, 'import torch as th\n'), ((4800, 4818), 'torch.mean', 'th.mean', (['objective'... |
from data import *
from utilities import *
from networks import *
import matplotlib.pyplot as plt
import numpy as np
num_known_classes = 65 #25
num_all_classes = 65
def skip(data, label, is_train):
return False
batch_size = 32
def transform(data, label, is_train):
label = one_hot(num_all_classes,label)
d... | [
"numpy.savez_compressed",
"numpy.transpose",
"numpy.asarray",
"numpy.vstack"
] | [((2438, 2670), 'numpy.savez_compressed', 'np.savez_compressed', (['filename'], {'product_score': 'score_pr', 'product_label': 'label_pr', 'real_world_score': 'score_rw', 'real_world_label': 'label_rw', 'art_score': 'score_ar', 'art_label': 'label_ar', 'clipart_score': 'score_cl', 'clipart_label': 'label_cl'}), '(filen... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 31 15:40:31 2021
@author: jessm
this is comparing the teporal cube slices to their impainted counterparts
"""
import os
import matplotlib.pyplot as plt
import numpy as np
from astropy.table import QTable, Table, Column
from astropy import units as u
... | [
"astropy.table.Table",
"numpy.hstack",
"matplotlib.pyplot.colorbar",
"numpy.array",
"numpy.load",
"matplotlib.pyplot.subplots",
"numpy.round",
"matplotlib.pyplot.show"
] | [((329, 354), 'numpy.load', 'np.load', (['"""np_align30.npy"""'], {}), "('np_align30.npy')\n", (336, 354), True, 'import numpy as np\n'), ((364, 389), 'numpy.load', 'np.load', (['"""thresh_a30.npy"""'], {}), "('thresh_a30.npy')\n", (371, 389), True, 'import numpy as np\n'), ((398, 422), 'numpy.load', 'np.load', (['"""t... |
import numpy as np
import matplotlib.pyplot as plt
def evolution_strategy(
f,
population_size,
sigma,
lr,
initial_params,
num_iters):
# assume initial params is a 1-D array
num_params = len(initial_params)
reward_per_iteration = np.zeros(num_iters)
# Initalise parameters
pa... | [
"numpy.mean",
"matplotlib.pyplot.plot",
"numpy.zeros",
"numpy.random.randn",
"matplotlib.pyplot.show"
] | [((1739, 1756), 'matplotlib.pyplot.plot', 'plt.plot', (['rewards'], {}), '(rewards)\n', (1747, 1756), True, 'import matplotlib.pyplot as plt\n'), ((1757, 1767), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1765, 1767), True, 'import matplotlib.pyplot as plt\n'), ((267, 286), 'numpy.zeros', 'np.zeros', (['nu... |
import torch
import numpy as np
import pandas as pd
from analysis import generate_model_specs, load_data_as_table
from pathlib import Path
import matplotlib.pyplot as plt
LOGS_DIR = Path('logs')
DATA_DIR = Path('data')
FIG_SIZE = (6, 4)
def plot_by_hyper(df: pd.DataFrame, x_name, y_name, **kwargs):
fig = plt.fi... | [
"numpy.logspace",
"analysis.load_data_as_table",
"matplotlib.pyplot.show",
"pathlib.Path"
] | [((184, 196), 'pathlib.Path', 'Path', (['"""logs"""'], {}), "('logs')\n", (188, 196), False, 'from pathlib import Path\n'), ((208, 220), 'pathlib.Path', 'Path', (['"""data"""'], {}), "('data')\n", (212, 220), False, 'from pathlib import Path\n'), ((1098, 1146), 'analysis.load_data_as_table', 'load_data_as_table', (['l2... |
# Copyright (c) 2016, the Cap authors.
#
# This file is subject to the Modified BSD License and may not be distributed
# without copyright and license information. Please refer to the file LICENSE
# for the text and further information on this license.
from matplotlib import pyplot
from numpy import array, append
from... | [
"h5py.File",
"numpy.append",
"numpy.array",
"sys.exit",
"matplotlib.pyplot.subplots",
"sys.stdout.write"
] | [((717, 743), 'numpy.append', 'append', (["data['time']", 'time'], {}), "(data['time'], time)\n", (723, 743), False, 'from numpy import array, append\n'), ((1239, 1288), 'matplotlib.pyplot.subplots', 'pyplot.subplots', (['(2)'], {'sharex': '(True)', 'figsize': '(16, 12)'}), '(2, sharex=True, figsize=(16, 12))\n', (1254... |
from typing import Dict, List, Any
import numpy as np
from overrides import overrides
from .instance import TextInstance, IndexedInstance
from ..data_indexer import DataIndexer
class QuestionPassageInstance(TextInstance):
"""
A QuestionPassageInstance is a base class for datasets that consist primarily of a... | [
"numpy.asarray"
] | [((4624, 4672), 'numpy.asarray', 'np.asarray', (['self.question_indices'], {'dtype': '"""int32"""'}), "(self.question_indices, dtype='int32')\n", (4634, 4672), True, 'import numpy as np\n'), ((4697, 4744), 'numpy.asarray', 'np.asarray', (['self.passage_indices'], {'dtype': '"""int32"""'}), "(self.passage_indices, dtype... |
# %%
"""
Tests of the encoder classes
"""
import numpy as np
import pytest
import gym
from gym_physx.envs.shaping import PlanBasedShaping
from gym_physx.encoders.config_encoder import ConfigEncoder
from gym_physx.wrappers import DesiredGoalEncoder
@pytest.mark.parametrize("n_trials", [20])
@pytest.mark.parametrize("f... | [
"numpy.abs",
"gym_physx.wrappers.DesiredGoalEncoder",
"pytest.mark.parametrize",
"numpy.array",
"gym_physx.encoders.config_encoder.ConfigEncoder",
"gym_physx.envs.shaping.PlanBasedShaping"
] | [((251, 292), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""n_trials"""', '[20]'], {}), "('n_trials', [20])\n", (274, 292), False, 'import pytest\n'), ((294, 365), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""fixed_finger_initial_position"""', '[True, False]'], {}), "('fixed_finger_initial_... |
import os
import wget
import glob
import shutil
import zipfile
import tempfile
import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow import keras
from keras.models import Model, load_model
from keras.layers import Dense, GlobalAveragePooling2D, Dropout
from keras.preprocessing.image ... | [
"wget.download",
"zipfile.ZipFile",
"keras.layers.Dense",
"os.remove",
"os.path.exists",
"shutil.move",
"keras.models.Model",
"os.mkdir",
"keras.layers.GlobalAveragePooling2D",
"tensorflow.keras.applications.MobileNetV2",
"glob.glob",
"tensorflow.keras.applications.InceptionV3",
"sklearn.mod... | [((491, 512), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (510, 512), False, 'import tempfile\n'), ((549, 570), 'os.path.basename', 'os.path.basename', (['url'], {}), '(url)\n', (565, 570), False, 'import os\n'), ((582, 613), 'os.path.join', 'os.path.join', (['tempdir', 'basename'], {}), '(tempdir, ... |
"""
Defines some useful utilities for plotting the evolution of a Resonator Network
"""
import copy
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.lines import Line2D
from utils.encoding_decoding import cosine_sim
class LiveResonatorP... | [
"numpy.sqrt",
"numpy.array",
"utils.encoding_decoding.cosine_sim",
"copy.deepcopy",
"matplotlib.lines.Line2D",
"numpy.arange",
"numpy.reshape",
"numpy.max",
"matplotlib._pylab_helpers.Gcf.get_active",
"matplotlib.pyplot.close",
"matplotlib.gridspec.GridSpec",
"numpy.rint",
"numpy.min",
"ma... | [((2053, 2062), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (2060, 2062), True, 'from matplotlib import pyplot as plt\n'), ((7627, 7648), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (7635, 7648), True, 'from matplotlib import pyplot as plt\n'), ((7653, 7663), 'matplotl... |
#! /usr/bin/env python
'''
Produce a blackbody curve *** AB *** color look-up table, going from
[475-814] to [475-X], where X are the J_H_7_1 filters
'''
import numpy as np
from astropy.io import ascii
from astropy.table import Table
from astropy import constants as const
c = const.c.cgs.value
h = const.h.cgs.value
k ... | [
"numpy.log10",
"astropy.io.ascii.write",
"astropy.table.Table",
"numpy.exp",
"numpy.array",
"numpy.linspace"
] | [((408, 512), 'numpy.array', 'np.array', (['[0.476873, 0.782072, 0.590979, 0.817739, 1.02207, 1.240151, 1.535107, \n 1.830465, 1.326561]'], {}), '([0.476873, 0.782072, 0.590979, 0.817739, 1.02207, 1.240151, \n 1.535107, 1.830465, 1.326561])\n', (416, 512), True, 'import numpy as np\n'), ((904, 925), 'astropy.tabl... |
import numpy as np
from itertools import product
from deep_rlsp.envs.gridworlds.env import Env, Direction, get_grid_representation
class BasicRoomEnv(Env):
"""
Basic empty room with stochastic transitions. Used for debugging.
"""
def __init__(self, prob, use_pixels_as_observations=True):
sel... | [
"deep_rlsp.envs.gridworlds.env.get_grid_representation",
"deep_rlsp.envs.gridworlds.env.Direction.move_in_direction_number",
"numpy.ravel_multi_index",
"gym.utils.play.play",
"numpy.array",
"numpy.unravel_index",
"deep_rlsp.envs.gridworlds.env.Direction.get_number_from_direction"
] | [((3222, 3238), 'gym.utils.play.play', 'play', (['env'], {'fps': '(5)'}), '(env, fps=5)\n', (3226, 3238), False, 'from gym.utils.play import play\n'), ((622, 673), 'deep_rlsp.envs.gridworlds.env.Direction.get_number_from_direction', 'Direction.get_number_from_direction', (['Direction.STAY'], {}), '(Direction.STAY)\n', ... |
# Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# 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 app... | [
"functools.reduce",
"numpy.log2",
"numpy.sort",
"numpy.ix_",
"scipy.sparse.linalg.eigsh",
"scipy.sparse.csr_matrix",
"numpy.linalg.eigvalsh",
"numpy.linalg.eigvals",
"fermilib.utils._jellium.grid_indices",
"numpy.exp",
"fermilib.utils.count_qubits",
"numpy.concatenate",
"scipy.sparse.coo_mat... | [((1272, 1325), 'scipy.sparse.identity', 'scipy.sparse.identity', (['(2)'], {'format': '"""csr"""', 'dtype': 'complex'}), "(2, format='csr', dtype=complex)\n", (1293, 1325), False, 'import scipy\n'), ((1340, 1404), 'scipy.sparse.csc_matrix', 'scipy.sparse.csc_matrix', (['[[0.0, 1.0], [1.0, 0.0]]'], {'dtype': 'complex'}... |
#!/usr/bin/env python
# encoding: utf-8
"""
@Author: yangwenhao
@Contact: <EMAIL>
@Software: PyCharm
@File: vad_test.py
@Time: 2019/11/16 下午6:52
@Overview:
"""
import pdb
from scipy import signal
import numpy as np
from scipy.io import wavfile
import torch
import torch.nn as nn
import torch.optim as optim
from Proces... | [
"torch.nn.ReLU",
"Process_Data.Compute_Feat.compute_vad.ComputeVadEnergy",
"torch.nn.L1Loss",
"numpy.log",
"torch.from_numpy",
"numpy.array",
"torch.nn.MSELoss",
"matplotlib.pyplot.plot",
"torch.sign",
"python_speech_features.fbank",
"scipy.io.wavfile.read",
"torch.cat",
"matplotlib.pyplot.s... | [((450, 470), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (467, 470), False, 'import torch\n'), ((2957, 2979), 'scipy.io.wavfile.read', 'wavfile.read', (['filename'], {}), '(filename)\n', (2969, 2979), False, 'from scipy.io import wavfile\n'), ((2996, 3053), 'python_speech_features.fbank', 'fbank'... |
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import time
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
import matplotlib.cm as cmx
import os
np.random.seed(0)
def do_tsne(feats, labs, cls, show_unlabeled=False, sec='', savefig=True):... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"sklearn.decomposition.PCA",
"numpy.where",
"sklearn.manifold.TSNE",
"matplotlib.pyplot.close",
"numpy.array",
"os.path.dirname",
"matplotlib.cm.ScalarMappable",
"numpy.random.seed",
"matplotlib.colors.Normalize"... | [((227, 244), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (241, 244), True, 'import numpy as np\n'), ((687, 728), 'numpy.array', 'np.array', (['[cls[labs[i]] for i in cls_ind]'], {}), '([cls[labs[i]] for i in cls_ind])\n', (695, 728), True, 'import numpy as np\n'), ((800, 823), 'sklearn.decomposition... |
from collections import OrderedDict
import sys
import numpy as np
import onnx
from array import array
from pprint import pprint
def onnx2darknet(onnxfile):
# Load the ONNX model
model = onnx.load(onnxfile)
# Check that the IR is well formed
onnx.checker.check_model(model)
# Print a huma... | [
"collections.OrderedDict",
"numpy.fromfile",
"array.array",
"onnx.helper.printable_graph",
"numpy.array",
"numpy.zeros",
"onnx.load",
"onnx.checker.check_model"
] | [((203, 222), 'onnx.load', 'onnx.load', (['onnxfile'], {}), '(onnxfile)\n', (212, 222), False, 'import onnx\n'), ((267, 298), 'onnx.checker.check_model', 'onnx.checker.check_model', (['model'], {}), '(model)\n', (291, 298), False, 'import onnx\n'), ((546, 559), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n'... |
import os
import json
import warnings
import time
import random
import numpy as np
from gym_unity.envs import UnityEnv
from stable_baselines.common.vec_env import SubprocVecEnv
from supervisors.supervisor import Supervisor
def create_vec_env(visibility=2.5, safe_info=True, safe_states=True, supervisor=None, safety_di... | [
"os.makedirs",
"stable_baselines.common.vec_env.SubprocVecEnv",
"supervisors.supervisor.Supervisor",
"random.seed",
"time.sleep",
"numpy.array",
"gym_unity.envs.UnityEnv",
"numpy.random.seed",
"json.load",
"warnings.filterwarnings",
"json.dump"
] | [((625, 658), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (648, 658), False, 'import warnings\n'), ((8982, 9026), 'stable_baselines.common.vec_env.SubprocVecEnv', 'SubprocVecEnv', (['env_list'], {'start_method': '"""fork"""'}), "(env_list, start_method='fork')\n", (8995... |
#!/usr/bin/env python
# ------------------------------------------------------------------------------------------------------%
# Created by "Thieu" at 11:35, 11/07/2021 %
# ... | [
"numpy.sum",
"mealpy.evolutionary_based.GA.BaseGA",
"numpy.mean"
] | [((1393, 1489), 'mealpy.evolutionary_based.GA.BaseGA', 'BaseGA', (['obj_function', 'lb1', 'ub1', '"""min"""', 'verbose', 'epoch', 'pop_size'], {'obj_weight': '[0.2, 0.5, 0.3]'}), "(obj_function, lb1, ub1, 'min', verbose, epoch, pop_size, obj_weight=\n [0.2, 0.5, 0.3])\n", (1399, 1489), False, 'from mealpy.evolutiona... |
#!/usr/bin/env python
"""
This module does some of the math for doing ADMM.
All the 3D ADMM math is a Python version of the ideas and code in the
following references:
1. "High density 3D localization microscopy using sparse support recovery",
Ovesny et al., Optics Express, 2014.
2. "Computational methods in si... | [
"numpy.copy",
"numpy.ones",
"numpy.fft.ifft2",
"numpy.conj",
"numpy.fft.fft",
"numpy.fft.fft2",
"numpy.zeros",
"numpy.fft.ifft",
"numpy.zeros_like"
] | [((2841, 2872), 'numpy.zeros', 'numpy.zeros', (['(nc * mx, nr * my)'], {}), '((nc * mx, nr * my))\n', (2852, 2872), False, 'import numpy\n'), ((4757, 4796), 'numpy.ones', 'numpy.ones', (['mshape'], {'dtype': 'numpy.complex'}), '(mshape, dtype=numpy.complex)\n', (4767, 4796), False, 'import numpy\n'), ((7764, 7786), 'nu... |
from sys import platform as sys_pf
if sys_pf == 'darwin':
import matplotlib
matplotlib.use("TkAgg")
import unittest
import numpy.testing as np_test
from scripts.algorithms.polynomial_predictor import PolynomialPredictor
class PolynomialPredictorTests(unittest.TestCase):
def test_static_sequence(self):... | [
"matplotlib.use",
"numpy.testing.assert_almost_equal",
"scripts.algorithms.polynomial_predictor.PolynomialPredictor"
] | [((86, 109), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (100, 109), False, 'import matplotlib\n'), ((481, 536), 'scripts.algorithms.polynomial_predictor.PolynomialPredictor', 'PolynomialPredictor', (['time_series', 'num_predicted_periods'], {}), '(time_series, num_predicted_periods)\n', (... |
"""Tests data processing functionality in src/aposteriori/create_frame_dataset.py"""
from pathlib import Path
import copy
import tempfile
from hypothesis import given, settings
from hypothesis.strategies import integers
import ampal
import ampal.geometry as g
import aposteriori.data_prep.create_frame_data_set as cfds
... | [
"numpy.sqrt",
"aposteriori.data_prep.create_frame_data_set.Codec.CNOCBCA",
"aposteriori.data_prep.create_frame_data_set.encode_cb_to_ampal_residue",
"copy.deepcopy",
"numpy.testing.assert_array_less",
"numpy.testing.assert_array_almost_equal",
"pathlib.Path",
"hypothesis.settings",
"ampal.geometry.d... | [((410, 448), 'pathlib.Path', 'Path', (['"""tests/testing_files/pdb_files/"""'], {}), "('tests/testing_files/pdb_files/')\n", (414, 448), False, 'from pathlib import Path\n'), ((452, 475), 'hypothesis.settings', 'settings', ([], {'deadline': '(1500)'}), '(deadline=1500)\n', (460, 475), False, 'from hypothesis import gi... |
import time
import numpy
def getNotes():
return {
"id1": {
"noteId": "id1",
"userId": "user1",
"content": str(numpy.array([1,2,3,4])),
"createdAt": int(time.time()),
},
"id2": {
"noteId": "id2",
"userId": "user2",
"... | [
"numpy.array",
"time.time"
] | [((157, 182), 'numpy.array', 'numpy.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (168, 182), False, 'import numpy\n'), ((209, 220), 'time.time', 'time.time', ([], {}), '()\n', (218, 220), False, 'import time\n'), ((336, 361), 'numpy.array', 'numpy.array', (['[5, 6, 7, 8]'], {}), '([5, 6, 7, 8])\n', (347, 361), F... |
import os
import shutil
import numpy as np
import pandas as pd
import scipy.integrate, scipy.stats, scipy.optimize, scipy.signal
from scipy.stats import mannwhitneyu
import statsmodels.formula.api as smf
import pystan
def clean_folder(folder):
"""Create a new folder, or if the folder already exists,
delete a... | [
"pandas.Series",
"numpy.sqrt",
"os.makedirs",
"os.path.isdir",
"numpy.isnan",
"statsmodels.formula.api.ols",
"shutil.rmtree",
"pandas.DataFrame",
"numpy.percentile",
"numpy.random.randn"
] | [((410, 431), 'os.path.isdir', 'os.path.isdir', (['folder'], {}), '(folder)\n', (423, 431), False, 'import os\n'), ((4128, 4164), 'pandas.DataFrame', 'pd.DataFrame', (["fit_summary['summary']"], {}), "(fit_summary['summary'])\n", (4140, 4164), True, 'import pandas as pd\n'), ((5015, 5030), 'pandas.DataFrame', 'pd.DataF... |
import os.path
import numpy as np
cancer_type_pairs = [
["lung squamous cell carcinoma", "head & neck squamous cell carcinoma"],
["bladder urothelial carcinoma", "cervical & endocervical cancer"],
["colon adenocarcinoma", "rectum adenocarcinoma"],
["stomach adenocarcinoma", "esophageal carcinoma"],
["kidney ... | [
"numpy.loadtxt",
"numpy.load",
"numpy.argmax"
] | [((1435, 1455), 'numpy.loadtxt', 'np.loadtxt', (['filename'], {}), '(filename)\n', (1445, 1455), True, 'import numpy as np\n'), ((2130, 2154), 'numpy.load', 'np.load', (['params_filename'], {}), '(params_filename)\n', (2137, 2154), True, 'import numpy as np\n'), ((2171, 2196), 'numpy.load', 'np.load', (['results_filena... |
# -*- coding: utf-8 -*-
import numpy as np
import torch
import pytrol.util.argsparser as parser
from pytrol.control.agent.HPAgent import HPAgent
from pytrol.control.agent.MAPTrainerModelAgent import MAPTrainerModelAgent
from pytrol.model.knowledge.EnvironmentKnowledge import EnvironmentKnowledge
from pytrol.util.net.... | [
"numpy.minimum",
"pytrol.control.agent.HPAgent.HPAgent.__init__",
"numpy.array",
"pytrol.control.agent.MAPTrainerModelAgent.MAPTrainerModelAgent.__init__",
"pytrol.util.argsparser.parse_args"
] | [((1456, 1639), 'pytrol.control.agent.HPAgent.HPAgent.__init__', 'HPAgent.__init__', (['self'], {'id_': 'id_', 'original_id': 'original_id', 'env_knl': 'env_knl', 'connection': 'connection', 'agts_addrs': 'agts_addrs', 'variant': 'variant', 'depth': 'depth', 'interaction': 'interaction'}), '(self, id_=id_, original_id=... |
import numpy as np
from optimization.basic_neuralnet_lib import neuralnet
from optimization.basic_neuralnet_lib import tensors
from optimization.basic_neuralnet_lib import loss
from typing import Iterator, NamedTuple
DEFAULT_BATCH_SIZE = 32
def train(
network: neuralnet.NeuralNet,
inputs: tensors.Tensor,
... | [
"optimization.basic_neuralnet_lib.loss.loss",
"optimization.basic_neuralnet_lib.neuralnet.StochasticGradientDescent",
"optimization.basic_neuralnet_lib.loss.gradient",
"optimization.basic_neuralnet_lib.loss.TotalSquaredError",
"numpy.random.shuffle"
] | [((391, 415), 'optimization.basic_neuralnet_lib.loss.TotalSquaredError', 'loss.TotalSquaredError', ([], {}), '()\n', (413, 415), False, 'from optimization.basic_neuralnet_lib import loss\n'), ((454, 491), 'optimization.basic_neuralnet_lib.neuralnet.StochasticGradientDescent', 'neuralnet.StochasticGradientDescent', ([],... |
#import cv2
import pickle
import numpy as np
import PIL
from PIL import Image
import os.path
import sys
# import cv2
def get_train_data(chunk, img_row, img_col):
# print(" \n get train data - running")
X_train = []
Y_train = []
with open("/home/amit/Desktop/vignesh/allmerge2.pickle",'rb') as f1:
... | [
"numpy.asarray",
"PIL.Image.open",
"pickle.load"
] | [((342, 357), 'pickle.load', 'pickle.load', (['f1'], {}), '(f1)\n', (353, 357), False, 'import pickle\n'), ((1352, 1371), 'numpy.asarray', 'np.asarray', (['X_train'], {}), '(X_train)\n', (1362, 1371), True, 'import numpy as np\n'), ((1390, 1409), 'numpy.asarray', 'np.asarray', (['Y_train'], {}), '(Y_train)\n', (1400, 1... |
import numpy as np
def braille():
return {
'a' : np.array([[1, 0], [0, 0], [0, 0]], dtype=bool),
'b' : np.array([[1, 0], [1, 0], [0, 0]], dtype=bool),
'c' : np.array([[1, 1], [0, 0], [0, 0]], dtype=bool),
'd' : np.array([[1, 1], [0, 1], [0, 0]], dtype=bool),
'e' : np.array([[1, 0], [0, ... | [
"numpy.array"
] | [((58, 104), 'numpy.array', 'np.array', (['[[1, 0], [0, 0], [0, 0]]'], {'dtype': 'bool'}), '([[1, 0], [0, 0], [0, 0]], dtype=bool)\n', (66, 104), True, 'import numpy as np\n'), ((118, 164), 'numpy.array', 'np.array', (['[[1, 0], [1, 0], [0, 0]]'], {'dtype': 'bool'}), '([[1, 0], [1, 0], [0, 0]], dtype=bool)\n', (126, 16... |
"""
Plotly - Sparklines
===================
"""
# -------------------
# Main
# -------------------
# https://chart-studio.plotly.com/~empet/13748/sparklines/#/code
# https://omnipotent.net/jquery.sparkline/#s-about
# https://chart-studio.plotly.com/create/?fid=Dreamshot:8025#/
# Libraries
import numpy as np
import pan... | [
"pandas.to_timedelta",
"plotly.subplots.make_subplots",
"numpy.arange",
"numpy.random.randint",
"pandas.DataFrame",
"pandas.to_datetime"
] | [((575, 587), 'numpy.arange', 'np.arange', (['S'], {}), '(S)\n', (584, 587), True, 'import numpy as np\n'), ((592, 639), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(100)', 'size': '(S, N)'}), '(low=1, high=100, size=(S, N))\n', (609, 639), True, 'import numpy as np\n'), ((667, 682), 'pand... |
import os.path
import re
from numpy.distutils.core import setup, Extension
from numpy.distutils.system_info import get_info
def find_version(*paths):
fname = os.path.join(os.path.dirname(__file__), *paths)
with open(fname) as fp:
code = fp.read()
match = re.search(r"^__version__ = ['\"]([^'\"]*)['\... | [
"numpy.distutils.core.Extension",
"re.search"
] | [((926, 1018), 'numpy.distutils.core.Extension', 'Extension', ([], {'name': '"""plateflex.cpwt"""', 'sources': "['src/cpwt/cpwt.f90', 'src/cpwt/cpwt_sub.f90']"}), "(name='plateflex.cpwt', sources=['src/cpwt/cpwt.f90',\n 'src/cpwt/cpwt_sub.f90'])\n", (935, 1018), False, 'from numpy.distutils.core import setup, Extens... |
import numpy as np
from PIL import Image
import tensorflow as tf
import re
#ref: https://github.com/tensorflow/models/blob/1af55e018eebce03fb61bba9959a04672536107d/tutorials/image/imagenet/classify_image.py
class NodeLookup(object):
"""Converts integer node ID's to human readable labels."""
def __init__(self,
... | [
"PIL.Image.open",
"tensorflow.gfile.Exists",
"tensorflow.get_variable",
"re.compile",
"tensorflow.placeholder",
"tensorflow.Session",
"numpy.argmax",
"tensorflow.gfile.FastGFile",
"numpy.squeeze",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.global_variables_initializer"... | [((2500, 2512), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2510, 2512), True, 'import tensorflow as tf\n'), ((2521, 2628), 'tensorflow.get_variable', 'tf.get_variable', ([], {'name': '"""adv"""', 'shape': '[1, 100, 100, 3]', 'dtype': 'tf.float32', 'initializer': 'tf.zeros_initializer'}), "(name='adv', shape... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: wtte-dev
# language: python
# name: wtte-dev
# ---
# %% [markdown]
# # WTTE-RNN in PyTorch
#
# <NAME>
... | [
"torch_wtte.losses.WeibullCensoredNLLLoss",
"torch.nn.Tanh",
"matplotlib.pyplot.ylabel",
"torch_wtte.losses.WeibullActivation",
"numpy.log",
"numpy.nanmean",
"torch.cuda.is_available",
"sys.path.append",
"numpy.random.binomial",
"torch.nn.GRU",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.xl... | [((799, 820), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (814, 820), False, 'import sys\n'), ((852, 870), 'numpy.random.seed', 'np.random.seed', (['(11)'], {}), '(11)\n', (866, 870), True, 'import numpy as np\n'), ((871, 892), 'torch.manual_seed', 'torch.manual_seed', (['(11)'], {}), '(11)\n'... |
import numpy as np
from points import Points
from dataloader import loader
def distance(p1, p2):
return np.sum((p1 - p2) ** 2)
def initial_cluster(data, k):
'''
initialized the centers for K-means++
inputs:
data - numpy array
k - number of clusters
'''
centers = []
centers... | [
"numpy.random.choice",
"numpy.take",
"numpy.array",
"numpy.sum",
"numpy.zeros",
"dataloader.loader",
"numpy.argmin",
"points.Points",
"numpy.arange"
] | [((109, 131), 'numpy.sum', 'np.sum', (['((p1 - p2) ** 2)'], {}), '((p1 - p2) ** 2)\n', (115, 131), True, 'import numpy as np\n'), ((370, 384), 'numpy.zeros', 'np.zeros', (['size'], {}), '(size)\n', (378, 384), True, 'import numpy as np\n'), ((399, 414), 'numpy.arange', 'np.arange', (['size'], {}), '(size)\n', (408, 414... |
import itertools
import pytest
import numpy as np
import mmu
from mmu.commons._testing import generate_test_labels
from mmu.commons._testing import compute_reference_metrics
Y_DTYPES = [
bool,
np.bool_,
int,
np.int32,
np.int64,
float,
np.float32,
np.float64,
]
YHAT_DTYPES = [
bool... | [
"numpy.tile",
"numpy.allclose",
"mmu.commons._testing.compute_reference_metrics",
"itertools.product",
"numpy.random.uniform",
"numpy.array_equal",
"pytest.raises",
"mmu.binary_metrics",
"mmu.commons._testing.generate_test_labels"
] | [((584, 624), 'itertools.product', 'itertools.product', (['Y_DTYPES', 'YHAT_DTYPES'], {}), '(Y_DTYPES, YHAT_DTYPES)\n', (601, 624), False, 'import itertools\n'), ((1262, 1288), 'mmu.commons._testing.generate_test_labels', 'generate_test_labels', (['(1000)'], {}), '(1000)\n', (1282, 1288), False, 'from mmu.commons._test... |
# import libraries
import os
import numpy as np
import pandas as pd
import xarray as xray
import ftplib, wget, urllib
import dask as da
from dask.diagnostics import ProgressBar
from multiprocessing.pool import ThreadPool
import matplotlib.pyplot as plt
import shapely.ops
from shapely.geometry import box, Polygon
from m... | [
"wget.download",
"shapely.geometry.box",
"numpy.array",
"pandas.MultiIndex.from_tuples",
"pandas.notnull",
"xarray.open_mfdataset",
"pandas.date_range",
"os.remove",
"ogh.ensure_dir",
"ftplib.FTP",
"os.listdir",
"multiprocessing.pool.ThreadPool",
"geopandas.GeoDataFrame",
"urllib.request.u... | [((2690, 2715), 'os.path.basename', 'os.path.basename', (['fileurl'], {}), '(fileurl)\n', (2706, 2715), False, 'import os\n'), ((2723, 2747), 'os.path.isfile', 'os.path.isfile', (['basename'], {}), '(basename)\n', (2737, 2747), False, 'import os\n'), ((5215, 5240), 'os.path.basename', 'os.path.basename', (['fileurl'], ... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | [
"numpy.hstack",
"mleap.sklearn.preprocessing.data.LabelEncoder",
"mleap.sklearn.preprocessing.data.OneHotEncoder",
"tempfile.mkdtemp",
"shutil.rmtree",
"json.load",
"numpy.testing.assert_array_equal"
] | [((1114, 1188), 'mleap.sklearn.preprocessing.data.LabelEncoder', 'LabelEncoder', ([], {'input_features': "['label']", 'output_features': '"""label_le_encoded"""'}), "(input_features=['label'], output_features='label_le_encoded')\n", (1126, 1188), False, 'from mleap.sklearn.preprocessing.data import LabelEncoder\n'), ((... |
import glob
import torch
import random
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
from src.models.utils import FragmentDataset, ScratchGAN, loss_fn_scaled_mse
def retrain(scratchgan, dataset, N, batch_size=1):
scratchgan.train()
# for n, (x, y) in enumerate(dataset.take(N, batc... | [
"src.models.utils.ScratchGAN",
"numpy.max",
"torch.nn.MSELoss",
"src.models.utils.FragmentDataset",
"numpy.min",
"torch.no_grad",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((1249, 1261), 'src.models.utils.ScratchGAN', 'ScratchGAN', ([], {}), '()\n', (1259, 1261), False, 'from src.models.utils import FragmentDataset, ScratchGAN, loss_fn_scaled_mse\n'), ((1304, 1321), 'src.models.utils.FragmentDataset', 'FragmentDataset', ([], {}), '()\n', (1319, 1321), False, 'from src.models.utils impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.