code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import unittest
import os, shutil
import subprocess
import sys
import rpy2.robjects as robjects
import glob
import pyreadr
import torch
import pickle
import re
import matplotlib.pyplot as plt
import random
import numpy as np
import warnings
import torch.optim as optim
prepath=os.getcwd()
test_input=prepath+"/test_dat... | [
"os.unlink",
"os.path.isfile",
"pickle.load",
"os.path.islink",
"unittest.TestLoader",
"torch.device",
"shutil.rmtree",
"os.path.join",
"os.chdir",
"torch.load",
"train_mlp_full_modified.get_lr",
"shutil.copyfile",
"re.search",
"train_mlp_full_modified.batch_sampler_block",
"torch.manual... | [((279, 290), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (288, 290), False, 'import os, shutil\n'), ((652, 700), 'sys.path.insert', 'sys.path.insert', (['(0)', "(prepath + '/output/project/')"], {}), "(0, prepath + '/output/project/')\n", (667, 700), False, 'import sys\n'), ((15583, 15600), 'os.chdir', 'os.chdir', (['... |
import numpy as np
from scipy.stats import norm, nbinom
def sirp(storeTab, motion_panel_t, para):
# importing the pervious states
S = storeTab[:, 0]
E = storeTab[:, 1]
I = storeTab[:, 2]
R = storeTab[:, 3]
D = storeTab[:, 4]
case_report = storeTab[:, 5]
case_test = storeTab[:, 6]
p... | [
"scipy.stats.norm.logpdf",
"numpy.exp",
"numpy.clip",
"scipy.stats.nbinom.logpmf"
] | [((568, 611), 'numpy.clip', 'np.clip', (['(motion_panel_t[:, 0] * I / N)', '(0)', '(1)'], {}), '(motion_panel_t[:, 0] * I / N, 0, 1)\n', (575, 611), True, 'import numpy as np\n'), ((638, 673), 'numpy.clip', 'np.clip', (['motion_panel_t[:, 1]', '(0)', '(1)'], {}), '(motion_panel_t[:, 1], 0, 1)\n', (645, 673), True, 'imp... |
import random
import sys
from datetime import datetime
import torch
import numpy as np
import os
import logging
import torch.utils.data as data
import json
def seed_all_rng(seed=None):
"""
Set the random seed for the RNG in torch, numpy and python.
Args:
seed (int): if None, will use a strong ran... | [
"json.load",
"numpy.random.seed",
"os.getpid",
"torch.manual_seed",
"numpy.asarray",
"os.path.dirname",
"numpy.zeros",
"json.dumps",
"numpy.random.randint",
"random.seed",
"os.urandom",
"datetime.datetime.now",
"json.JSONEncoder.default",
"logging.getLogger"
] | [((630, 650), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (644, 650), True, 'import numpy as np\n'), ((716, 733), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (727, 733), False, 'import random\n'), ((529, 556), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)... |
import cv2 as cv
import numpy as np
import os
from typing import Final
#rock = 0, scissor = 1, paper = 2
ROCK: Final = 0
SCISSOR: Final = 1
PAPER: Final = 2
def ModeSelect():
return 0
def DistanceCheck():
return True
def GetRcp():
while True :
if DistanceCheck() == True : break
return... | [
"numpy.random.randint"
] | [((772, 792), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (789, 792), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet')
from numpy import random
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.model_selection import train... | [
"app.http.api.dbquery.doInsertRequest",
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.naive_bayes.MultinomialNB",
"nltk.stem.WordNetLemmatizer",
"sklearn.linear_model.SGDClassifier",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.tree.DecisionTreeClassifier",
"... | [((51, 77), 'nltk.download', 'nltk.download', (['"""stopwords"""'], {}), "('stopwords')\n", (64, 77), False, 'import nltk\n'), ((78, 100), 'nltk.download', 'nltk.download', (['"""punkt"""'], {}), "('punkt')\n", (91, 100), False, 'import nltk\n'), ((101, 144), 'nltk.download', 'nltk.download', (['"""averaged_perceptron_... |
from ortools.linear_solver import pywraplp
import numpy as np
def solve_with_ip(grid: np.ndarray) -> (np.ndarray, float):
'''Solve Sudoku instance (np.matrix) with IP modeling. Returns a tuple with the resulting matrix and the execution time in seconds.'''
assert grid.shape == (9,9)
grid_size = 9
... | [
"ortools.linear_solver.pywraplp.Solver",
"numpy.zeros"
] | [((382, 461), 'ortools.linear_solver.pywraplp.Solver', 'pywraplp.Solver', (['"""Sudoku Solver"""', 'pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING'], {}), "('Sudoku Solver', pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n", (397, 461), False, 'from ortools.linear_solver import pywraplp\n'), ((2309, 2341), 'numpy.zeros'... |
import unittest
import numpy as np
import numpy.random as ra
from srlife import helpers
class TestRandom(unittest.TestCase):
def test_ms2ts(self):
C = ra.random((6,6))
C1 = helpers.ms2ts(C)
C2 = helpers.ms2ts_faster(C)
self.assertTrue(np.allclose(C1,C2))
def test_usym(self):
M = ra.random((... | [
"srlife.helpers.ms2ts",
"srlife.helpers.ms2ts_faster",
"srlife.helpers.usym_faster",
"numpy.allclose",
"srlife.helpers.sym_faster",
"numpy.random.random",
"srlife.helpers.sym",
"srlife.helpers.usym"
] | [((160, 177), 'numpy.random.random', 'ra.random', (['(6, 6)'], {}), '((6, 6))\n', (169, 177), True, 'import numpy.random as ra\n'), ((186, 202), 'srlife.helpers.ms2ts', 'helpers.ms2ts', (['C'], {}), '(C)\n', (199, 202), False, 'from srlife import helpers\n'), ((212, 235), 'srlife.helpers.ms2ts_faster', 'helpers.ms2ts_f... |
import numpy as np
from scipy.optimize import minimize
from lrCostFunction import lrCostFunction
def oneVsAll(X, y, num_labels, lambda_):
""" trains multiple logistic regression classifiers and returns all
the classifiers in a matrix all_theta, where the i-th row of all_theta
corresponds to the c... | [
"lrCostFunction.lrCostFunction",
"numpy.zeros",
"numpy.ones"
] | [((523, 552), 'numpy.zeros', 'np.zeros', (['(num_labels, n + 1)'], {}), '((num_labels, n + 1))\n', (531, 552), True, 'import numpy as np\n'), ((1337, 1352), 'numpy.zeros', 'np.zeros', (['(n + 1)'], {}), '(n + 1)\n', (1345, 1352), True, 'import numpy as np\n'), ((604, 614), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n',... |
import numpy as np
from hci import *
def pupil_sin_phase(pupil, wavsx=1, wavsy=0, amplitude=0.1):
size=int(np.sqrt(pupil.size))
x=np.arange(size)
y=np.arange(size)
sin = np.zeros((size,size))
if wavsx==0 and wavsy==0:
return pupil
elif wavsy==0:
yfreq=0
xfreq = 2*np.pi/... | [
"numpy.fromfile",
"numpy.asarray",
"numpy.zeros",
"numpy.sin",
"numpy.arange",
"numpy.sqrt"
] | [((677, 714), 'numpy.fromfile', 'np.fromfile', (['"""indices.dat"""'], {'dtype': 'int'}), "('indices.dat', dtype=int)\n", (688, 714), True, 'import numpy as np\n'), ((944, 970), 'numpy.asarray', 'np.asarray', (['modal_ab_basis'], {}), '(modal_ab_basis)\n', (954, 970), True, 'import numpy as np\n'), ((139, 154), 'numpy.... |
import os
import pickle as pk
from collections import defaultdict, namedtuple
from copy import deepcopy
from time import time
import matplotlib.pyplot as plt
import numpy as np
import torch
from tqdm import tqdm
from base_options import BASE_OPTIONS, RES_FOLDER, State
from basics import evaluate_steps
from networks i... | [
"visualisation.plot_convergence",
"os.mkdir",
"pickle.dump",
"copy.deepcopy",
"numpy.random.seed",
"os.makedirs",
"os.path.join",
"torch.manual_seed",
"train_distilled_image.distill",
"time.time",
"collections.defaultdict",
"base_options.State",
"pickle.load",
"collections.namedtuple",
"... | [((434, 491), 'collections.namedtuple', 'namedtuple', (['"""ResEl"""', "['state', 'steps', 'losses', 'time']"], {}), "('ResEl', ['state', 'steps', 'losses', 'time'])\n", (444, 491), False, 'from collections import defaultdict, namedtuple\n'), ((1584, 1605), 'torch.manual_seed', 'torch.manual_seed', (['(42)'], {}), '(42... |
# -*- coding: utf-8 -*-
"""
Scikit-learn predictor implementation\n
Models are expected to be implementations of a scikit-learn linear model and must support calling predict(X=example)\n
http://scikit-learn.org/stable/modules/classes.html#module-sklearn.linear_model
"""
from predict.predictors.base_predictor import Ba... | [
"numpy.fromstring"
] | [((2433, 2463), 'numpy.fromstring', 'np.fromstring', (['x'], {'sep': 'self.sep'}), '(x, sep=self.sep)\n', (2446, 2463), True, 'import numpy as np\n')] |
import optuna
import numpy as np
import pandas as pd
from functools import partial
from . import model_bank
import mlflow
from .AAMPreprocessor import AAMPreprocessor
import joblib
from .FastAIutils import *
from .metrics import model_metrics, pretty_scores, get_scores
from loguru import logger
from pathlib import Path... | [
"pandas.DataFrame",
"functools.partial",
"mlflow.start_run",
"pprint.pformat",
"random.randint",
"mlflow.set_experiment",
"joblib.dump",
"pandas.isnull",
"pathlib.Path",
"loguru.logger.bind",
"tabulate.tabulate",
"mlflow.log_params",
"mlflow.set_tags",
"joblib.load",
"mlflow.log_metrics"... | [((1303, 1332), 'loguru.logger.bind', 'logger.bind', ([], {'name': 'logger_name'}), '(name=logger_name)\n', (1314, 1332), False, 'from loguru import logger\n'), ((2506, 2610), 'optuna.create_study', 'optuna.create_study', ([], {'direction': '"""maximize"""', 'study_name': 'self.config.PROJECT_NAME', 'load_if_exists': '... |
## APPLICATION OF COP ON COVID19 DATA
# pylint: disable=no-self-argument, no-member
from core import some, no, value, struct
from cop import load_data, translation, patient, model
import datetime as dt
from matplotlib import pylab as lab
from scipy.signal import savgol_filter as smooth
from scipy import stats
import ... | [
"scipy.signal.savgol_filter",
"numpy.average",
"scipy.stats.iqr",
"cop.translation",
"scipy.stats.shapiro",
"numpy.median",
"numpy.std",
"scipy.stats.normaltest",
"core.struct",
"datetime.date",
"datetime.date.today",
"matplotlib.pylab.plot",
"cop.model",
"cop.patient",
"numpy.random.ran... | [((844, 864), 'cop.translation', 'translation', (['by_vars'], {}), '(by_vars)\n', (855, 864), False, 'from cop import load_data, translation, patient, model\n'), ((878, 894), 'cop.patient', 'patient', (['by_vars'], {}), '(by_vars)\n', (885, 894), False, 'from cop import load_data, translation, patient, model\n'), ((931... |
import numpy as np
import sys
sys.path.append('..')
from utils import model_init, optimizer_init, client_update, diffuse_params, average_models, evaluate
def run_failures_no_recovery(train_loader, test_loader, comm_matrix, num_rounds, epochs, num_clients,
failure_round, num_failures, corr='global', net='net',... | [
"sys.path.append",
"utils.evaluate",
"utils.diffuse_params",
"utils.average_models",
"numpy.nonzero",
"utils.client_update",
"numpy.random.choice",
"utils.model_init",
"utils.optimizer_init"
] | [((30, 51), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (45, 51), False, 'import sys\n'), ((3666, 3694), 'utils.model_init', 'model_init', (['num_clients', 'net'], {}), '(num_clients, net)\n', (3676, 3694), False, 'from utils import model_init, optimizer_init, client_update, diffuse_params, av... |
import math
import numpy as np
from scrtbp.system import coeffs, sections
from scrtbp.taylor import integrators
def test_poincare_periodic_orbit():
mu = 0.01215
coeff_func, state_dim, extra_dim = coeffs.generate_taylor_coeffs(mu)
step = 0.05
order = 20
solve = integrators.generate_dense_integr... | [
"scrtbp.taylor.integrators.generate_dense_integrator",
"numpy.array",
"numpy.linspace",
"scrtbp.system.coeffs.generate_taylor_coeffs"
] | [((209, 242), 'scrtbp.system.coeffs.generate_taylor_coeffs', 'coeffs.generate_taylor_coeffs', (['mu'], {}), '(mu)\n', (238, 242), False, 'from scrtbp.system import coeffs, sections\n'), ((287, 375), 'scrtbp.taylor.integrators.generate_dense_integrator', 'integrators.generate_dense_integrator', (['coeff_func', 'state_di... |
try:
import tensorflow as tf
from latte.metrics.keras import interpolatability as K
has_tf = True
except:
has_tf = False
import numpy as np
import pytest
from latte.metrics.core import interpolatability as C
@pytest.mark.skipif(not has_tf, reason="requires tensorflow")
class TestSmoothness:
de... | [
"numpy.random.randn",
"tensorflow.convert_to_tensor",
"latte.metrics.core.interpolatability.Smoothness",
"pytest.mark.skipif",
"numpy.arange",
"numpy.testing.assert_allclose",
"latte.metrics.keras.interpolatability.Smoothness",
"tensorflow.assert_equal"
] | [((231, 291), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(not has_tf)'], {'reason': '"""requires tensorflow"""'}), "(not has_tf, reason='requires tensorflow')\n", (249, 291), False, 'import pytest\n'), ((365, 379), 'latte.metrics.core.interpolatability.Smoothness', 'C.Smoothness', ([], {}), '()\n', (377, 379), True... |
"""Tests the surveytools.footprint module."""
import numpy as np
from surveytools.footprint import VphasFootprint, VphasOffset
def test_vphas_offset_coordinates():
"""Test the offset pattern, which is expected to equal
ra -0, dec +0 arcsec for the "a" pointing;
ra -588, dec +660 arcsec for the "b" pointin... | [
"numpy.radians",
"numpy.testing.assert_almost_equal",
"surveytools.footprint.VphasOffset",
"surveytools.footprint.VphasFootprint"
] | [((391, 407), 'surveytools.footprint.VphasFootprint', 'VphasFootprint', ([], {}), '()\n', (405, 407), False, 'from surveytools.footprint import VphasFootprint, VphasOffset\n'), ((412, 484), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (["vf.offsets['0001a']['ra']", '(97.2192513369)'], {}), "(v... |
import numpy as np
from gym_collision_avoidance.envs.sensors.Sensor import Sensor
from gym_collision_avoidance.envs import Config
import matplotlib.pyplot as plt
import time
class LaserScanSensor(Sensor):
""" 2D LaserScan based on map of the environment (containing static objects and other agents)
Currently ... | [
"numpy.dstack",
"numpy.meshgrid",
"numpy.ones_like",
"numpy.invert",
"numpy.roll",
"matplotlib.pyplot.imshow",
"numpy.zeros",
"numpy.cumsum",
"matplotlib.pyplot.figure",
"numpy.where",
"numpy.arange",
"numpy.sin",
"numpy.linspace",
"numpy.cos",
"matplotlib.pyplot.pause",
"gym_collision... | [((1369, 1390), 'gym_collision_avoidance.envs.sensors.Sensor.Sensor.__init__', 'Sensor.__init__', (['self'], {}), '(self)\n', (1384, 1390), False, 'from gym_collision_avoidance.envs.sensors.Sensor import Sensor\n'), ((1724, 1783), 'numpy.linspace', 'np.linspace', (['self.min_angle', 'self.max_angle', 'self.num_beams'],... |
import numpy
import pandas
import os.path
from scipy import sparse
from sklearn.externals import joblib
import scipy.sparse as scipy
from sklearn.model_selection import KFold
def calc_ERROR(X, Y, w, b):
return Y - (numpy.dot(X, w) + b)
def calc_MSE(error):
return (numpy.power(error, 2)).sum(axis=0) / error.s... | [
"numpy.power",
"sklearn.model_selection.KFold",
"scipy.sparse.csr_matrix",
"numpy.arange",
"numpy.exp",
"numpy.random.normal",
"numpy.dot",
"numpy.vstack",
"numpy.random.shuffle",
"numpy.sqrt"
] | [((384, 399), 'numpy.sqrt', 'numpy.sqrt', (['mse'], {}), '(mse)\n', (394, 399), False, 'import numpy\n'), ((2748, 2794), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['target'], {'dtype': 'numpy.float32'}), '(target, dtype=numpy.float32)\n', (2765, 2794), False, 'from scipy import sparse\n'), ((749, 789), 'numpy.ra... |
import cv2
import numpy as np
import stackedImages
cap = cv2.VideoCapture('./lane-detection/solidWhiteRight.mp4')
carCascade = cv2.CascadeClassifier('./objectDetection/files/car.xml')
fps = cap.get(cv2.CAP_PROP_FPS)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 100)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 40)
def drawLanes(image, lane... | [
"cv2.line",
"cv2.Canny",
"numpy.zeros_like",
"cv2.bitwise_and",
"cv2.cvtColor",
"cv2.destroyAllWindows",
"numpy.zeros",
"cv2.fillPoly",
"cv2.VideoCapture",
"cv2.rectangle",
"cv2.imread",
"cv2.bitwise_or",
"numpy.array",
"cv2.CascadeClassifier",
"stackedImages.stackImages",
"cv2.imshow"... | [((58, 114), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""./lane-detection/solidWhiteRight.mp4"""'], {}), "('./lane-detection/solidWhiteRight.mp4')\n", (74, 114), False, 'import cv2\n'), ((128, 184), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""./objectDetection/files/car.xml"""'], {}), "('./objectDetection... |
import warnings
warnings.filterwarnings("ignore")
import os
import sys
import env
import tensorflow as tf
import numpy as np
import pickle
import random
from bm.dbm import DBM
from bm.rbm.rbm import BernoulliRBM, logit_mean
from bm.init_BMs import * # helper functions to initialize, fit and load RBMs and 2 layer DBM
f... | [
"sklearn.externals.joblib.dump",
"numpy.random.seed",
"numpy.argmax",
"numpy.logspace",
"tensorflow.ConfigProto",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.pyplot.style.use",
"os.path.join",
"numpy.unique",
"os.path.exists",
"random.seed",
"numpy.reshape",
"numpy.random.choice"... | [((16, 49), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (39, 49), False, 'import warnings\n'), ((779, 797), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (793, 797), True, 'import numpy as np\n'), ((798, 813), 'random.seed', 'random.seed', (['(42)'], ... |
import pandas as pd
import numpy as np
from sklearn import model_selection,preprocessing
import RN_Perceptron as rn
datos = pd.read_csv('../Datos/Drug5.csv')
#-- ordinales a numericos ---
mapeo = {'Sex': {'F':1, 'M':0},
'BP':{'HIGH':2, 'NORMAL':1, 'LOW':0},
'Cholesterol':{'NORMAL':... | [
"numpy.sum",
"RN_Perceptron.entrena_Perceptron",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.MinMaxScaler",
"numpy.array",
"RN_Perceptron.aplica_Perceptron"
] | [((136, 169), 'pandas.read_csv', 'pd.read_csv', (['"""../Datos/Drug5.csv"""'], {}), "('../Datos/Drug5.csv')\n", (147, 169), True, 'import pandas as pd\n'), ((384, 412), 'numpy.array', 'np.array', (['datos.iloc[:, :-1]'], {}), '(datos.iloc[:, :-1])\n', (392, 412), True, 'import numpy as np\n'), ((858, 945), 'sklearn.mod... |
from numpy.core.numeric import roll
from rosidl_parser.definition import Include
from scipy.spatial.transform import Rotation
import quaternion
import math
import numpy as np
from rclpy.node import Node
from rclpy.parameter import Parameter
from std_srvs.srv import Trigger
from sensor_msgs.msg import Imu
from nav_msg... | [
"brov2_interfaces.msg.DVLOdom",
"nav_msgs.msg.Odometry",
"math.asin",
"brov2_interfaces.msg.Barometer",
"math.atan2",
"scipy.spatial.transform.Rotation.from_euler",
"numpy.cross",
"sensor_msgs.msg.Imu",
"numpy.array",
"rclpy.parameter.Parameter",
"quaternion.as_float_array",
"numpy.sqrt",
"n... | [((2335, 2340), 'brov2_interfaces.msg.DVL', 'DVL', ([], {}), '()\n', (2338, 2340), False, 'from brov2_interfaces.msg import DVL, DVLOdom, Barometer\n'), ((2369, 2378), 'brov2_interfaces.msg.DVLOdom', 'DVLOdom', ([], {}), '()\n', (2376, 2378), False, 'from brov2_interfaces.msg import DVL, DVLOdom, Barometer\n'), ((2406,... |
"""Class to handle all the book-keeping of an HST observation"""
import numpy as np
from numpy import ma
from glob import glob
from datetime import datetime
import warnings
from tqdm.notebook import tqdm
from copy import deepcopy
import matplotlib.pyplot as plt
import os
import logging
from astropy.io import fits
fro... | [
"os.mkdir",
"numpy.sum",
"numpy.abs",
"numpy.nanmedian",
"matplotlib.pyplot.subplot2grid",
"numpy.ones",
"numpy.argsort",
"matplotlib.pyplot.figure",
"numpy.mean",
"os.path.isfile",
"numpy.ma.masked_array",
"numpy.random.normal",
"numpy.arange",
"glob.glob",
"numpy.unique",
"astropy.st... | [((706, 732), 'logging.getLogger', 'logging.getLogger', (['"""ombre"""'], {}), "('ombre')\n", (723, 732), False, 'import logging\n'), ((3110, 3158), 'numpy.asarray', 'np.asarray', (["[hdr['FILTER'] for hdr in self.hdrs]"], {}), "([hdr['FILTER'] for hdr in self.hdrs])\n", (3120, 3158), True, 'import numpy as np\n'), ((3... |
import numpy as np
import requests as req
from requests.exceptions import HTTPError
import time
from geopy import distance
import osmnx as ox
def calc_gradient_angle(point1, point2):
""" Calculate the gradient angle between two points on the earth's surface
Parameters
----------
point1: tuple (latitu... | [
"osmnx.get_nearest_edge",
"geopy.distance.geodesic",
"geopy.distance.great_circle",
"time.sleep",
"numpy.min",
"numpy.max",
"numpy.array",
"requests.get",
"numpy.arctan",
"osmnx.utils_graph.get_route_edge_attributes",
"osmnx.graph_from_bbox"
] | [((6456, 6468), 'numpy.min', 'np.min', (['lats'], {}), '(lats)\n', (6462, 6468), True, 'import numpy as np\n'), ((6481, 6493), 'numpy.max', 'np.max', (['lats'], {}), '(lats)\n', (6487, 6493), True, 'import numpy as np\n'), ((6506, 6518), 'numpy.min', 'np.min', (['lngs'], {}), '(lngs)\n', (6512, 6518), True, 'import num... |
"""Tests for structure_exporter."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
from absl.testing import parameterized
from morph_net.network_regularizers import flop_regularizer
from morph_net.tools import structure_exporter as se
import n... | [
"tensorflow.test.main",
"morph_net.network_regularizers.flop_regularizer.GammaFlopsRegularizer",
"numpy.random.seed",
"tensorflow.trainable_variables",
"tensorflow.global_variables_initializer",
"morph_net.tools.structure_exporter.StructureExporter",
"morph_net.tools.structure_exporter.get_remove_common... | [((1337, 1375), 'tensorflow.constant', 'tf.constant', (['(0.0)'], {'shape': '[1, 17, 19, 3]'}), '(0.0, shape=[1, 17, 19, 3])\n', (1348, 1375), True, 'import tensorflow as tf\n'), ((1537, 1565), 'tensorflow.concat', 'tf.concat', (['[conv1, conv2]', '(3)'], {}), '([conv1, conv2], 3)\n', (1546, 1565), True, 'import tensor... |
import simplejson as json
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
def load_dataset(path):
with open(path) as f:
dataset = json.load(f)
return dataset['images'], dataset['annotations'], dataset
def main():
images, anns, dataset = load_dataset('datasets/t... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.plot",
"numpy.std",
"numpy.asarray",
"matplotlib.mlab.normpdf",
"simplejson.load",
"numpy.mean"
] | [((505, 523), 'numpy.asarray', 'np.asarray', (['ratios'], {}), '(ratios)\n', (515, 523), True, 'import numpy as np\n'), ((533, 548), 'numpy.mean', 'np.mean', (['ratios'], {}), '(ratios)\n', (540, 548), True, 'import numpy as np\n'), ((561, 575), 'numpy.std', 'np.std', (['ratios'], {}), '(ratios)\n', (567, 575), True, '... |
import os
from glob import glob
import matplotlib.pyplot as plt
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from ncp.tools.plotting import plot_prediction
def get_latest_epoch(dir: str) -> int:
paths = glob(os.path.join(dir, "model_*.ckpt.meta"))
n_epochs = [int(p.replace(... | [
"os.path.join",
"tensorflow.compat.v1.train.Saver",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.ConfigProto",
"numpy.linspace",
"tensorflow.compat.v1.disable_v2_behavior",
"numpy.concatenate",
"numpy.sqrt"
] | [((119, 143), 'tensorflow.compat.v1.disable_v2_behavior', 'tf.disable_v2_behavior', ([], {}), '()\n', (141, 143), True, 'import tensorflow.compat.v1 as tf\n'), ((593, 609), 'tensorflow.compat.v1.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (607, 609), True, 'import tensorflow.compat.v1 as tf\n'), ((665, 681), 'ten... |
import numpy as np
methods = ['sqp']
class npnlp_result(dict):
def __new__(cls, *args, **kwargs):
obj = super(npnlp_result, cls).__new__(cls, *args, **kwargs)
obj2 = {'x':None,
'fval':None,
'exitflag':None,
'message':None,
'kkt':None,... | [
"numpy.array"
] | [((948, 960), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (956, 960), True, 'import numpy as np\n'), ((994, 1006), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1002, 1006), True, 'import numpy as np\n'), ((1039, 1051), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1047, 1051), True, 'import numpy as... |
"""
Main module - set of functions that simulate or correct colorblindness for images
as described in
https://www.researchgate.net/publication/326626897_Smartphone_Based_Image_Color_Correction_for_Color_Blindness
"""
import numpy as np
import cv2
## LMS Daltonization
def rgb_to_lms(img):
"""
lms_matrix = np.ar... | [
"numpy.zeros_like",
"numpy.abs",
"numpy.tensordot",
"cv2.cvtColor",
"numpy.empty_like",
"numpy.clip",
"numpy.max",
"numpy.where",
"numpy.array",
"numpy.reshape",
"numpy.min",
"numpy.arange",
"numpy.select"
] | [((484, 612), 'numpy.array', 'np.array', (['[[0.3904725, 0.54990437, 0.00890159], [0.07092586, 0.96310739, 0.00135809],\n [0.02314268, 0.12801221, 0.93605194]]'], {}), '([[0.3904725, 0.54990437, 0.00890159], [0.07092586, 0.96310739, \n 0.00135809], [0.02314268, 0.12801221, 0.93605194]])\n', (492, 612), True, 'imp... |
import numpy as np
import torch
def q2r(q):
# Rotation matrix from Hamiltonian quaternion
# Source: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
w, x, y, z = tuple(q)
n = 1.0/np.sqrt(x*x+y*y+z*z+w*w)
x *= n
y *= n
z *= n
w *= n
r = np.array([[1.0 -... | [
"numpy.abs",
"numpy.arctan2",
"numpy.sin",
"numpy.linalg.inv",
"numpy.array",
"numpy.cos",
"numpy.sqrt"
] | [((304, 595), 'numpy.array', 'np.array', (['[[1.0 - 2.0 * y * y - 2.0 * z * z, 2.0 * x * y - 2.0 * z * w, 2.0 * x * z +\n 2.0 * y * w], [2.0 * x * y + 2.0 * z * w, 1.0 - 2.0 * x * x - 2.0 * z *\n z, 2.0 * y * z - 2.0 * x * w], [2.0 * x * z - 2.0 * y * w, 2.0 * y * z +\n 2.0 * x * w, 1.0 - 2.0 * x * x - 2.0 * y... |
from math import exp, log
import numpy as np
def train_sigmoid(out, target, prior1, prior0=None):
# calculate A and B for the sigmoid
# p_i = 1 / (1 + exp(A * f_i + B))
#
# INPUT:
# out = array of outputs (SVM) or mu for LVQ
# target = array of booleans: is i-th example a positive example?
... | [
"math.log",
"numpy.zeros",
"numpy.sum",
"math.exp"
] | [((954, 965), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (962, 965), True, 'import numpy as np\n'), ((1144, 1176), 'math.log', 'log', (['((prior0 + 1) / (prior1 + 1))'], {}), '((prior0 + 1) / (prior1 + 1))\n', (1147, 1176), False, 'from math import exp, log\n'), ((535, 561), 'numpy.sum', 'np.sum', (['(target == p... |
import torch.nn as nn
import torch
import numpy as np
from warnings import warn
from ...utils import fitted_zig_mean, fitted_zig_variance
class ZIGEncoder(nn.Module):
def __init__(
self,
core,
readout,
zero_thresholds=None,
init_ks=None,
theta_image_dependent=True,
... | [
"torch.ones",
"numpy.log",
"torch.any",
"torch.exp",
"torch.sigmoid",
"torch.rand",
"torch.zeros",
"warnings.warn"
] | [((3780, 3797), 'torch.exp', 'torch.exp', (['logloc'], {}), '(logloc)\n', (3789, 3797), False, 'import torch\n'), ((3511, 3530), 'torch.exp', 'torch.exp', (['logtheta'], {}), '(logtheta)\n', (3520, 3530), False, 'import torch\n'), ((3817, 3838), 'torch.any', 'torch.any', (['(loc == 0.0)'], {}), '(loc == 0.0)\n', (3826,... |
import numpy as np
import os
import pickle
def read_and_process(filename):
i = 72 - 12
j = 0
image = []
with open(filename, 'rb') as logfile:
data = logfile.read()
while i < 46536 - 12:
image.append(data[i] + data[i + 1] * 256)
j = j + 1
i = i + 2
return image
# Relies on Hough transform results
# ... | [
"pickle.dump",
"numpy.linalg.norm",
"numpy.array",
"numpy.reshape",
"os.listdir"
] | [((615, 641), 'os.listdir', 'os.listdir', (["('../' + folder)"], {}), "('../' + folder)\n", (625, 641), False, 'import os\n'), ((1339, 1363), 'pickle.dump', 'pickle.dump', (['features', 'f'], {}), '(features, f)\n', (1350, 1363), False, 'import pickle\n'), ((1407, 1429), 'pickle.dump', 'pickle.dump', (['labels', 'f'], ... |
import torch.nn as nn
import torch
import numpy as np
import torch.nn.functional as F
class SineLayer(nn.Module):
# See paper sec. 3.2, final paragraph, and supplement Sec. 1.5 for discussion of omega_0.
# If is_first=True, omega_0 is a frequency factor which simply multiplies the activations before the
... | [
"torch.nn.Sequential",
"torch.nn.Linear",
"torch.no_grad",
"torch.sin",
"numpy.sqrt"
] | [((895, 942), 'torch.nn.Linear', 'nn.Linear', (['in_features', 'out_features'], {'bias': 'bias'}), '(in_features, out_features, bias=bias)\n', (904, 942), True, 'import torch.nn as nn\n'), ((2889, 2913), 'torch.nn.Sequential', 'nn.Sequential', (['*self.net'], {}), '(*self.net)\n', (2902, 2913), True, 'import torch.nn a... |
"""
Support for cftime axis in matplotlib.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
from collections import namedtuple
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.transforms as mt... | [
"numpy.abs",
"cftime.utime",
"matplotlib.ticker.MaxNLocator",
"cftime.datetime",
"numpy.floor",
"numpy.all",
"matplotlib.units.AxisInfo",
"numpy.array",
"collections.namedtuple",
"matplotlib.units.ConversionInterface.is_numlike",
"matplotlib.transforms.nonsingular"
] | [((607, 670), 'collections.namedtuple', 'namedtuple', (['"""FormatOption"""', "['lower', 'upper', 'format_string']"], {}), "('FormatOption', ['lower', 'upper', 'format_string'])\n", (617, 670), False, 'from collections import namedtuple\n'), ((3078, 3124), 'matplotlib.ticker.MaxNLocator', 'mticker.MaxNLocator', (['max_... |
import numpy as np
from collections import OrderedDict
from concurrent import futures as futures
from os import path as osp
from pathlib import Path
from skimage import io
import mmcv
#from mmdet3d.core.bbox import box_np_ops
import box_np_ops
def get_image_index_str(img_idx, use_prefix_id=False):
if use_prefix_id... | [
"numpy.copy",
"concurrent.futures.ThreadPoolExecutor",
"numpy.fromfile",
"skimage.io.imread",
"numpy.zeros",
"os.path.exists",
"box_np_ops.points_in_rbbox",
"numpy.ones",
"box_np_ops.remove_outside_points",
"pathlib.Path",
"numpy.logical_xor",
"numpy.array",
"numpy.arange",
"numpy.loadtxt"... | [((838, 854), 'pathlib.Path', 'Path', (['prefixpath'], {}), '(prefixpath)\n', (842, 854), False, 'from pathlib import Path\n'), ((2532, 2565), 'numpy.array', 'np.array', (['[x[0] for x in content]'], {}), '([x[0] for x in content])\n', (2540, 2565), True, 'import numpy as np\n'), ((3830, 3861), 'numpy.array', 'np.array... |
import os.path
import numpy as np
import torchvision
import torchvision.transforms as transforms
import torch
import h5py
from data.base_dataset import *
from PIL import Image
import math, random
import time
def make_dataset_fromlst(listfilename):
"""
NYUlist format:
imagepath seglabelpath depthpath HHApat... | [
"time.time",
"numpy.random.seed",
"PIL.Image.open"
] | [((2333, 2353), 'numpy.random.seed', 'np.random.seed', (['(8964)'], {}), '(8964)\n', (2347, 2353), True, 'import numpy as np\n'), ((1101, 1145), 'PIL.Image.open', 'Image.open', (["self.paths_dict['images'][index]"], {}), "(self.paths_dict['images'][index])\n", (1111, 1145), False, 'from PIL import Image\n'), ((2525, 25... |
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import os
import sys
from scipy.interpolate import interp1d
from scipy.signal import savgol_filter
import matplotlib.pyplot as plt
# arguments for image file extension and r value
try:
r = float(sys.argv[1])
imgfile = sys.argv[2]
dpi = int(sys.ar... | [
"scipy.signal.savgol_filter",
"matplotlib.pyplot.close",
"matplotlib.pyplot.ylabel",
"numpy.amax",
"matplotlib.use",
"numpy.diff",
"numpy.linspace",
"scipy.interpolate.interp1d",
"matplotlib.pyplot.xlabel",
"os.listdir",
"matplotlib.pyplot.savefig"
] | [((18, 41), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (32, 41), False, 'import matplotlib\n'), ((861, 880), 'os.listdir', 'os.listdir', (['dirname'], {}), '(dirname)\n', (871, 880), False, 'import os\n'), ((1441, 1502), 'numpy.linspace', 'np.linspace', (['tauc_spectrum[0, 0]', 'tauc_spec... |
import random
import numpy as np
import torch
import learn2learn as l2l
from torch import nn, optim
def accuracy(predictions, targets):
predictions = predictions.argmax(dim=1).view(targets.shape)
return (predictions == targets).sum().float() / targets.size(0)
def fast_adapt(batch, learner, loss, adaptatio... | [
"learn2learn.vision.models.OmniglotCNN",
"numpy.random.seed",
"learn2learn.algorithms.MAML",
"torch.manual_seed",
"timeit.default_timer",
"torch.nn.CrossEntropyLoss",
"torch.cuda.manual_seed",
"numpy.mean",
"random.seed",
"numpy.arange",
"torch.device",
"learn2learn.vision.benchmarks.get_tasks... | [((1454, 1476), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (1474, 1476), False, 'import timeit\n'), ((1667, 1684), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1678, 1684), False, 'import random\n'), ((1685, 1705), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (... |
#Dependencies
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#################################################
# Database Setup
######################################... | [
"sqlalchemy.func.avg",
"numpy.ravel",
"flask.Flask",
"sqlalchemy.orm.Session",
"flask.jsonify",
"sqlalchemy.func.min",
"sqlalchemy.create_engine",
"sqlalchemy.ext.automap.automap_base",
"sqlalchemy.func.max"
] | [((341, 391), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///Resources/hawaii.sqlite"""'], {}), "('sqlite:///Resources/hawaii.sqlite')\n", (354, 391), False, 'from sqlalchemy import create_engine, func\n'), ((449, 463), 'sqlalchemy.ext.automap.automap_base', 'automap_base', ([], {}), '()\n', (461, 463), F... |
# main imports
import numpy as np
import pandas as pd
import sys, os, argparse
# image processing
from PIL import Image
from ipfml import utils
from ipfml.processing import transform, segmentation
import matplotlib.pyplot as plt
# model imports
import joblib
from keras.models import load_model
# modules and config ... | [
"sys.stdout.write",
"keras.models.load_model",
"modules.utils.data.get_scene_image_quality",
"argparse.ArgumentParser",
"processing.features_extractions.extract_data",
"sys.path.insert",
"numpy.expand_dims",
"PIL.Image.open",
"numpy.arange",
"numpy.array",
"ipfml.utils.normalize_arr_with_range",... | [((328, 350), 'sys.path.insert', 'sys.path.insert', (['(0)', '""""""'], {}), "(0, '')\n", (343, 350), False, 'import sys, os, argparse\n'), ((1076, 1102), 'sys.stdout.write', 'sys.stdout.write', (['"""\x1b[F"""'], {}), "('\\x1b[F')\n", (1092, 1102), False, 'import sys, os, argparse\n'), ((1130, 1203), 'argparse.Argumen... |
#!/usr/bin/env python
# license removed for brevity
import numpy as np
import rospy
from sensor_msgs.msg import Joy
from std_msgs.msg import Float64, Float32MultiArray
from geometry_msgs.msg import Twist
from math import pi, sqrt
import numpy as np
import scipy.interpolate as sc # interp1d, CubicSpline, splprep, splev... | [
"numpy.math.atan2",
"rospy.Subscriber",
"numpy.ones",
"std_msgs.msg.Float64",
"numpy.sin",
"rospy.Rate",
"rospy.is_shutdown",
"rospy.init_node",
"numpy.linspace",
"math.sqrt",
"numpy.asarray",
"numpy.cross",
"numpy.cos",
"numpy.dot",
"numpy.concatenate",
"numpy.vstack",
"numpy.deg2ra... | [((457, 471), 'numpy.deg2rad', 'np.deg2rad', (['(40)'], {}), '(40)\n', (467, 471), True, 'import numpy as np\n'), ((489, 532), 'rospy.init_node', 'rospy.init_node', (['_node_name'], {'anonymous': '(True)'}), '(_node_name, anonymous=True)\n', (504, 532), False, 'import rospy\n'), ((544, 559), 'rospy.Rate', 'rospy.Rate',... |
import numpy as np
import math
def calculate_expectation(length):
expect = np.zeros(length + 1)
expect[1] = 2
for n in range(2, length + 1):
expect[n] = (sum(choose(n, k) * expect[k] for k in range(1, n)) + 2 ** n)/((2 ** n) - 1)
print(expect[length])
def choose(n, k):
return mat... | [
"numpy.zeros",
"math.factorial"
] | [((80, 100), 'numpy.zeros', 'np.zeros', (['(length + 1)'], {}), '(length + 1)\n', (88, 100), True, 'import numpy as np\n'), ((317, 334), 'math.factorial', 'math.factorial', (['n'], {}), '(n)\n', (331, 334), False, 'import math\n'), ((336, 353), 'math.factorial', 'math.factorial', (['k'], {}), '(k)\n', (350, 353), False... |
# Copyright 2019-2020 <NAME>
#
# 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 wri... | [
"littlemcmc.NUTS",
"numpy.random.seed",
"numpy.random.randn",
"littlemcmc.sample",
"littlemcmc.HamiltonianMC",
"numpy.random.rand",
"numpy.testing.assert_allclose"
] | [((773, 791), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (787, 791), True, 'import numpy as np\n'), ((825, 851), 'numpy.random.rand', 'np.random.rand', (['model_ndim'], {}), '(model_ndim)\n', (839, 851), True, 'import numpy as np\n'), ((863, 953), 'littlemcmc.HamiltonianMC', 'HamiltonianMC', ([], ... |
""" resonance graph library
"""
import itertools
import functools
import numpy
from automol import dict_
from automol.graph._graph import frozen as _frozen
from automol.graph._graph import atom_keys as _atom_keys
from automol.graph._graph import atoms as _atoms
from automol.graph._graph import bond_keys as _bond_keys
f... | [
"automol.graph._graph.set_bond_orders",
"automol.graph._graph.maximum_spin_multiplicity",
"automol.graph._graph.without_bond_orders",
"automol.graph._graph.atom_neighbor_keys",
"automol.graph._graph.atom_explicit_hydrogen_valences",
"automol.graph._graph.atom_lone_pair_counts",
"numpy.less",
"automol.... | [((1539, 1587), 'automol.graph._graph.atom_unsaturated_valences', '_atom_unsaturated_valences', (['rgr'], {'bond_order': '(True)'}), '(rgr, bond_order=True)\n', (1565, 1587), True, 'from automol.graph._graph import atom_unsaturated_valences as _atom_unsaturated_valences\n'), ((1610, 1652), 'automol.graph._graph.atom_bo... |
import keras, sys, cv2, os
from keras.models import Model, load_model
import numpy as np
import pandas as pd
from math import atan2, degrees
img_size = 224
base_path = 'samples'
file_list = sorted(os.listdir(base_path))
# this is most important thing
glasses = cv2.imread('images/glasses.png', cv2.IMREAD_UNCHANGED)
b... | [
"keras.models.load_model",
"numpy.abs",
"cv2.bitwise_and",
"cv2.medianBlur",
"math.atan2",
"numpy.clip",
"cv2.warpAffine",
"numpy.mean",
"numpy.linalg.norm",
"cv2.imshow",
"os.path.join",
"cv2.getRotationMatrix2D",
"cv2.cvtColor",
"cv2.imwrite",
"cv2.copyMakeBorder",
"cv2.split",
"cv... | [((263, 317), 'cv2.imread', 'cv2.imread', (['"""images/glasses.png"""', 'cv2.IMREAD_UNCHANGED'], {}), "('images/glasses.png', cv2.IMREAD_UNCHANGED)\n", (273, 317), False, 'import keras, sys, cv2, os\n'), ((390, 416), 'keras.models.load_model', 'load_model', (['bbs_model_name'], {}), '(bbs_model_name)\n', (400, 416), Fa... |
#!/usr/bin/env python
"""
twist_to_motors - converts a twist message to motor commands. Needed for navigation stack
Copyright (C) 2012 <NAME>.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software F... | [
"rospy.Subscriber",
"rospy.Time.now",
"rospy.Publisher",
"rospy.Rate",
"rospy.loginfo",
"rospy.get_param",
"rospy.is_shutdown",
"std_msgs.msg.Int32MultiArray",
"rospy.init_node",
"numpy.interp",
"rospy.get_name"
] | [((1403, 1437), 'rospy.init_node', 'rospy.init_node', (['"""twist_to_motors"""'], {}), "('twist_to_motors')\n", (1418, 1437), False, 'import rospy\n'), ((1451, 1467), 'rospy.get_name', 'rospy.get_name', ([], {}), '()\n', (1465, 1467), False, 'import rospy\n'), ((1470, 1508), 'rospy.loginfo', 'rospy.loginfo', (["('%s st... |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import random, sys
import os, os.path
from argparse import ArgumentParser
ALPHA = 5
def file_extension(path):
pathes=os.path.splitext(path)
if len(pathes) > 1:
return pathes[1]
return "txt"
def build_parser():
parser = ArgumentParser()
... | [
"argparse.ArgumentParser",
"cv2.medianBlur",
"random.shuffle",
"cv2.fillPoly",
"os.path.isfile",
"cv2.minMaxLoc",
"cv2.imshow",
"cv2.matchTemplate",
"cv2.seamlessClone",
"random.seed",
"numpy.real",
"cv2.destroyAllWindows",
"cv2.waitKey",
"numpy.fft.fft2",
"eencode.encode",
"numpy.zero... | [((179, 201), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (195, 201), False, 'import os, os.path\n'), ((302, 318), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (316, 318), False, 'from argparse import ArgumentParser\n'), ((1281, 1305), 'cv2.medianBlur', 'cv2.medianBlur', (['ima... |
"""Test wrappers."""
import numpy as np
import gym
import sys
# from gym import spaces
# from gym.core import Wrapper
import matplotlib.pyplot as plt
import neurogym as ngym
from neurogym.wrappers import TrialHistory
from neurogym.wrappers import SideBias
from neurogym.wrappers import PassAction
from neurogym.wrappers... | [
"matplotlib.pyplot.title",
"neurogym.wrappers.PassReward",
"numpy.sum",
"numpy.abs",
"numpy.ones",
"neurogym.wrappers.Variable_nch",
"matplotlib.pyplot.figure",
"numpy.mean",
"neurogym.wrappers.Noise",
"neurogym.wrappers.TTLPulse",
"neurogym.wrappers.VariableMapping",
"numpy.unique",
"neurog... | [((2200, 2230), 'gym.make', 'gym.make', (['env_name'], {}), '(env_name, **env_args)\n', (2208, 2230), False, 'import gym\n'), ((2241, 2286), 'neurogym.wrappers.SideBias', 'SideBias', (['env'], {'probs': 'probs', 'block_dur': 'blk_dur'}), '(env, probs=probs, block_dur=blk_dur)\n', (2249, 2286), False, 'from neurogym.wra... |
'''
<NAME> 2015
PSRFITS specification: www.atnf.csiro.au/people/pulsar/index.html?n=Main.Psrfits
EXAMPLE USAGE:
ar = Archive(filename)
ar.tscrunch()
ar.pavplot()
TODO:
Check POL_TYPE in the above to figure out how to pscrunch
Add emulate_psrchive mode?
Allow for chopping of subints, frequencies, etc?
Flip order ... | [
"astropy.coordinates.SkyCoord",
"numpy.sum",
"numpy.abs",
"numpy.argmax",
"pypulse.singlepulse.SinglePulse",
"numpy.empty",
"numpy.floor",
"numpy.ones",
"numpy.isnan",
"numpy.shape",
"gc.collect",
"inspect.getargvalues",
"numpy.mean",
"numpy.arange",
"matplotlib.pyplot.figure",
"os.pat... | [((1129, 1173), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (1138, 1173), True, 'import numpy as np\n'), ((7423, 7449), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['DATA'], {}), '(DATA)\n', (7443, 7449), True, 'import numpy ... |
import setuptools
from distutils.core import setup, Extension
import numpy as np
#, "wm_dist-4.0.c"
long_description="wm_dist calculates distances from points on a mesh through a volume. Distances are calculated by solving the Eikonal equation.\nThe primary use case for wm_dist is brain imaging for calculating distanc... | [
"numpy.get_include",
"setuptools.find_packages"
] | [((988, 1014), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (1012, 1014), False, 'import setuptools\n'), ((663, 679), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (677, 679), True, 'import numpy as np\n')] |
import torch
import torch.nn as nn
import torch.nn.functional as F
import pandas as pd
import numpy as np
import tqdm
from rec.model.pinsage import PinSage
from rec.datasets.movielens import MovieLens
from rec.utils import cuda
from dgl import DGLGraph
import argparse
import pickle
import os
parser = argparse.Argumen... | [
"pickle.dump",
"tqdm.tqdm",
"argparse.ArgumentParser",
"torch.zeros_like",
"torch.LongTensor",
"tqdm.trange",
"rec.datasets.movielens.MovieLens",
"os.path.exists",
"torch.cat",
"numpy.setdiff1d",
"torch.sigmoid",
"pickle.load",
"numpy.array",
"torch.randperm",
"pandas.Series",
"torch.n... | [((304, 329), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (327, 329), False, 'import argparse\n'), ((900, 926), 'os.path.exists', 'os.path.exists', (['cache_file'], {}), '(cache_file)\n', (914, 926), False, 'import os\n'), ((1009, 1029), 'rec.datasets.movielens.MovieLens', 'MovieLens', (['""... |
#!/usr/bin/env python3
# coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
data = [(1, 0), (2, 0), (10, 1)]
var_x = np.array([x for x, y in data])
var_y = np.array([y for x, y in data])
print(var_x)
print(var_y)
def sigmoid(z):
exp = np_exp(-z)
return 1.0 / (1 + exp)
def np_exp(array):
... | [
"numpy.minimum",
"numpy.multiply",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.maximum",
"numpy.average",
"numpy.abs",
"numpy.square",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array",
"numpy.arange"
] | [((133, 163), 'numpy.array', 'np.array', (['[x for x, y in data]'], {}), '([x for x, y in data])\n', (141, 163), True, 'import numpy as np\n'), ((172, 202), 'numpy.array', 'np.array', (['[y for x, y in data]'], {}), '([y for x, y in data])\n', (180, 202), True, 'import numpy as np\n'), ((659, 682), 'numpy.multiply', 'n... |
# coding: utf-8
import pandas as pd
import numpy as np
def dsigmoid(x):
return np.exp(x)/ (1.0 + np.exp(x))**2
def sigmoid(x):
return 1.0/ (1.0 + np.exp(-x))
class MLP:
def __init__(self):
self.W = [None]
self.A = [None]
self.Z = [None]
self.b = [None]
sel... | [
"numpy.sum",
"numpy.random.randn",
"numpy.empty",
"numpy.zeros",
"numpy.exp",
"numpy.dot"
] | [((86, 95), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (92, 95), True, 'import numpy as np\n'), ((426, 457), 'numpy.empty', 'np.empty', (['n_nodes'], {'dtype': 'object'}), '(n_nodes, dtype=object)\n', (434, 457), True, 'import numpy as np\n'), ((158, 168), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (164, 168), ... |
"""
Misceallaneous functions.
@title: raijin_tools
@author: <NAME> <<EMAIL>>
@institutions: Monash University and the Australian Bureau of Meteorology
@date: 15/08/2017
.. autosummary::
:toctree: generated/
get_files
get_season
"""
# Python Standard Library
import os
import datetime
import numpy as np
... | [
"os.walk",
"os.path.join",
"numpy.in1d"
] | [((1143, 1158), 'os.walk', 'os.walk', (['inpath'], {}), '(inpath)\n', (1150, 1158), False, 'import os\n'), ((1663, 1707), 'numpy.in1d', 'np.in1d', (['supported_extension', 'file_extension'], {}), '(supported_extension, file_extension)\n', (1670, 1707), True, 'import numpy as np\n'), ((1812, 1850), 'os.path.join', 'os.p... |
import time
import sympy
from sympy.ntheory import factorint
from scipy.special import comb
import copy
from collections import OrderedDict
from itertools import combinations
import random
import numpy as np
import os
from fractions import Fraction
import math
import networkx
from networkx.algorithms.app... | [
"tvm.auto_scheduler.search_policy.SketchPolicy",
"tvm.auto_scheduler.RecordToFile",
"tvm.relay.optimize",
"tvm.auto_scheduler.measure_record.RecordReader",
"os.path.isfile",
"numpy.mean",
"tvm.auto_scheduler.measure_record.load_best_record",
"tvm.IRModule.from_expr",
"json.loads",
"tvm.auto_schedu... | [((905, 941), 'tvm.auto_scheduler.cost_model.XGBModel', 'auto_scheduler.cost_model.XGBModel', ([], {}), '()\n', (939, 941), False, 'from tvm import auto_scheduler\n'), ((960, 1037), 'tvm.auto_scheduler.search_policy.SketchPolicy', 'auto_scheduler.search_policy.SketchPolicy', (['search_task', 'cost_model'], {'verbose': ... |
# Author: <NAME>
#
# License: BSD 3 clause
import logging
import numpy as np
import pandas as pd
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from gensim.utils import simple_preprocess
from gensim.parsing.preprocessing import strip_tags
import umap
import hdbscan
from sklearn.metrics.pairwise import cosine... | [
"gensim.parsing.preprocessing.strip_tags",
"numpy.argmax",
"wordcloud.WordCloud",
"joblib.dump",
"logging.Formatter",
"numpy.argsort",
"matplotlib.pyplot.figure",
"sklearn.metrics.pairwise.cosine_similarity",
"numpy.append",
"numpy.max",
"logging.StreamHandler",
"sklearn.cluster.dbscan",
"um... | [((487, 515), 'logging.getLogger', 'logging.getLogger', (['"""top2vec"""'], {}), "('top2vec')\n", (504, 515), False, 'import logging\n'), ((554, 577), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (575, 577), False, 'import logging\n'), ((594, 667), 'logging.Formatter', 'logging.Formatter', (['"""... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# import logging
# logger = logging.getLogger(__name__)
# from __future__ import print_function
from loguru import logger
import pytest
import os.path
path_to_script = os.path.dirname(os.path.abspath(__file__))
# import funkcí z jiného adresáře
import sys
import unittest
i... | [
"unittest.main",
"numpy.random.rand",
"seededitorqt.plugin.SampleThresholdPlugin",
"seededitorqt.QTSeedEditor",
"PyQt5.QtWidgets.QApplication"
] | [((6060, 6075), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6073, 6075), False, 'import unittest\n'), ((982, 1004), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (994, 1004), False, 'from PyQt5.QtWidgets import QApplication\n'), ((1123, 1154), 'seededitorqt.QTSeedEditor', ... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import scipy.io as io
import tracklib.filter as ft
import tracklib.init as init
import tracklib.model as model
import tracklib.utils as utils
import matplotlib.pyplot as plt
def plot_ellipse(ax, x0, y0, C, N, *args, **kwargs):
x, y = utils.ellip_... | [
"tracklib.filter.KochEOFilter",
"tracklib.filter.LanEOFilter",
"tracklib.model.F_cv",
"tracklib.model.H_cv",
"matplotlib.pyplot.show",
"tracklib.utils.ellip_point",
"scipy.io.loadmat",
"tracklib.init.cv_init",
"numpy.empty",
"tracklib.model.R_cv",
"scipy.io.savemat",
"matplotlib.pyplot.figure"... | [((308, 339), 'tracklib.utils.ellip_point', 'utils.ellip_point', (['x0', 'y0', 'C', 'N'], {}), '(x0, y0, C, N)\n', (325, 339), True, 'import tracklib.utils as utils\n'), ((414, 440), 'scipy.io.loadmat', 'io.loadmat', (['"""gtt_data.mat"""'], {}), "('gtt_data.mat')\n", (424, 440), True, 'import scipy.io as io\n'), ((681... |
"""
motion_wiki = {
"walk": ForwardProfile("walk", 0.5, startup=True),
"trot": ForwardProfile("trot", 1.28, startup=True),
"jump": Profile("dynamic_jumping", stages=[0.1, 0.05], ops=[JMP, FWD], startup=True),
"turn": TurningProfile("turn", 0.01, startup=True),
"sit": Profile("sit", [1.0], [SIT], sta... | [
"os.makedirs",
"argparse.ArgumentParser",
"animation.animation.Animation",
"os.path.exists",
"numpy.zeros",
"numpy.linalg.norm",
"pybullet_data.getDataPath",
"os.path.join",
"numpy.concatenate"
] | [((875, 966), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate forwarding gaits at customized speeds."""'}), "(description=\n 'Generate forwarding gaits at customized speeds.')\n", (898, 966), False, 'import argparse\n'), ((1916, 1942), 'animation.animation.Animation', 'Animati... |
# Copyright (C) 2018 <NAME>
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
#from curses.ascii import NUL
import numpy as np
from .utils import sorted_by_key # noqa
from .station import MonitoringStation
def stations_by_distance(stations, p):
... | [
"numpy.array",
"numpy.deg2rad"
] | [((516, 565), 'numpy.array', 'np.array', (['[station.coord for station in stations]'], {}), '([station.coord for station in stations])\n', (524, 565), True, 'import numpy as np\n'), ((788, 822), 'numpy.deg2rad', 'np.deg2rad', (['(p[0] - locations[:, 0])'], {}), '(p[0] - locations[:, 0])\n', (798, 822), True, 'import nu... |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2019 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... | [
"numpy.iscomplexobj",
"numpy.std",
"numpy.isfinite",
"numpy.any",
"numpy.mean"
] | [((3020, 3040), 'numpy.isfinite', 'numpy.isfinite', (['data'], {}), '(data)\n', (3034, 3040), False, 'import numpy\n'), ((3123, 3139), 'numpy.mean', 'numpy.mean', (['data'], {}), '(data)\n', (3133, 3139), False, 'import numpy\n'), ((3142, 3157), 'numpy.std', 'numpy.std', (['data'], {}), '(data)\n', (3151, 3157), False,... |
import inquirer
import os
import pickle
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing import image
from random import sample
# Global settings
INPUT_DATA_DIR = 'data/raw_filtered/'
INPUT_SHAPE = (224, 224, 3)
TARGET = 'make'
# All available training ... | [
"tensorflow.keras.models.load_model",
"matplotlib.pyplot.show",
"inquirer.List",
"numpy.argmax",
"random.sample",
"matplotlib.pyplot.imshow",
"tensorflow.keras.preprocessing.image.img_to_array",
"inquirer.prompt",
"matplotlib.pyplot.axis",
"tensorflow.keras.preprocessing.image.load_img",
"matplo... | [((765, 782), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (776, 782), False, 'import pickle\n'), ((813, 881), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['"""models/resnet_unfreeze_all_filtered.tf"""'], {}), "('models/resnet_unfreeze_all_filtered.tf')\n", (839, 881), True, 'impor... |
#!/usr/bin/env python3
# coding: utf-8
import numpy as np
import pandas as pd
from IPython.display import display # TODO: is it needed?
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_sq... | [
"matplotlib.pyplot.title",
"seaborn.histplot",
"matplotlib.pyplot.show",
"sklearn.tree.DecisionTreeRegressor",
"sklearn.preprocessing.scale",
"pandas.read_csv",
"sklearn.ensemble.GradientBoostingRegressor",
"sklearn.metrics.r2_score",
"sklearn.model_selection.RandomizedSearchCV",
"sklearn.neural_n... | [((1149, 1166), 'pandas.read_csv', 'pd.read_csv', (['file'], {}), '(file)\n', (1160, 1166), True, 'import pandas as pd\n'), ((1651, 1678), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 5)'}), '(figsize=(12, 5))\n', (1661, 1678), True, 'import matplotlib.pyplot as plt\n'), ((1683, 1717), 'seaborn.hist... |
import os
import numpy as np
import pandas as pd
from pandas.core.common import array_equivalent
from plio.utils.utils import file_search
# This function reads the lookup tables used to expand metadata from the file names
# This is separated from parsing the filenames so that for large lists of files the
# lookup t... | [
"pandas.DataFrame",
"pandas.core.common.array_equivalent",
"plio.utils.utils.file_search",
"os.path.basename",
"pandas.read_csv",
"numpy.array",
"pandas.concat",
"numpy.unique",
"numpy.in1d"
] | [((538, 579), 'pandas.read_csv', 'pd.read_csv', (["LUT_files['ID']"], {'index_col': '(0)'}), "(LUT_files['ID'], index_col=0)\n", (549, 579), True, 'import pandas as pd\n'), ((604, 648), 'pandas.read_csv', 'pd.read_csv', (["LUT_files['spect']"], {'index_col': '(0)'}), "(LUT_files['spect'], index_col=0)\n", (615, 648), T... |
import json
import os
import socket
from datetime import datetime
import imageio
import numpy as np
from sklearn.metrics import accuracy_score, confusion_matrix, jaccard_score
from torchsummary import summary
class GIF:
def __init__(self, folder, filename="result.gif", w=400, h=300):
os.makedirs(folder, ... | [
"imageio.get_writer",
"os.remove",
"numpy.save",
"os.makedirs",
"sklearn.metrics.accuracy_score",
"imageio.imread",
"os.path.exists",
"json.dumps",
"datetime.datetime.now",
"sklearn.metrics.jaccard_score",
"socket.gethostname",
"torchsummary.summary",
"sklearn.metrics.confusion_matrix",
"i... | [((1563, 1595), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (1579, 1595), False, 'from sklearn.metrics import accuracy_score, confusion_matrix, jaccard_score\n'), ((1611, 1641), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['y_true', 'y_pred'], {}), ... |
import numpy as np
import pandas as pd
from scipy.spatial.distance import pdist, squareform
from sklearn.utils import check_random_state
def _make_initial_medoids(distances, n_clusters, random_state):
random_state = check_random_state(random_state)
m, n = distances.shape
distances_df = pd.DataFrame({'id... | [
"pandas.DataFrame",
"sklearn.utils.check_random_state",
"numpy.sum",
"numpy.argmin",
"numpy.array",
"scipy.spatial.distance.pdist",
"pandas.concat",
"numpy.unique"
] | [((222, 254), 'sklearn.utils.check_random_state', 'check_random_state', (['random_state'], {}), '(random_state)\n', (240, 254), False, 'from sklearn.utils import check_random_state\n'), ((1626, 1637), 'numpy.sum', 'np.sum', (['sse'], {}), '(sse)\n', (1632, 1637), True, 'import numpy as np\n'), ((1361, 1388), 'numpy.uni... |
import os
import sys
import math
import time
import multiprocessing as mp
from copy import deepcopy
import numpy as np
from agents.base_es import ESAgent, Network
from agents.misc.logger import CmdLineLogger
from agents.misc.success_evaluator import SuccessEvaluator
from agents.openai_es_backend.es_utils import job_w... | [
"copy.deepcopy",
"numpy.sum",
"multiprocessing.Lock",
"math.ceil",
"agents.base_es.Network",
"time.time",
"agents.misc.utils.query_yes_no",
"numpy.random.randint",
"numpy.array",
"numpy.mean",
"multiprocessing.Queue",
"agents.misc.logger.CmdLineLogger",
"multiprocessing.Process",
"os.path.... | [((726, 797), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2 ** 32 - 1)'], {'size': 'self.n_workers', 'dtype': 'np.uint32'}), '(0, 2 ** 32 - 1, size=self.n_workers, dtype=np.uint32)\n', (743, 797), True, 'import numpy as np\n'), ((851, 860), 'multiprocessing.Lock', 'mp.Lock', ([], {}), '()\n', (858, 860), Tr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import ot
def wasserstein_point1_fast(data1, data2, i, j, a, b, xs, xt):
"""
Computes the 1-pt Wasserstein distance for a single point in the spatain domain
"""
N = data1.shape[2]
xs[:] = (data1[i,j,:]).reshape((N,1))
... | [
"ot.dist",
"ot.emd2",
"numpy.zeros",
"numpy.ones"
] | [((368, 403), 'ot.dist', 'ot.dist', (['xs', 'xt'], {'metric': '"""euclidean"""'}), "(xs, xt, metric='euclidean')\n", (375, 403), False, 'import ot\n'), ((420, 436), 'ot.emd2', 'ot.emd2', (['a', 'b', 'M'], {}), '(a, b, M)\n', (427, 436), False, 'import ot\n'), ((716, 751), 'ot.dist', 'ot.dist', (['xs', 'xt'], {'metric':... |
import matplotlib.pyplot as plt
import numpy as np
import pygimli as pg
class FourPhaseModel():
def __init__(self, vw=1500., va=330., vi=3500., vr=5500, a=1., n=2., m=1.3,
phi=0.4, rhow=150.):
"""Four phase model (4PM) after Hauck et al. (2011). Estimates fraction
of ice, air an... | [
"pygimli.show",
"seaborn.set",
"numpy.meshgrid",
"pygimli.warn",
"numpy.logspace",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.colorbar",
"numpy.ma.array",
"matplotlib.pyplot.figure",
"numpy.isclose",
"numpy.array",
"numpy.min",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"matplot... | [((5829, 5857), 'numpy.linspace', 'np.linspace', (['(500)', '(6000)', '(1000)'], {}), '(500, 6000, 1000)\n', (5840, 5857), True, 'import numpy as np\n'), ((5868, 5891), 'numpy.logspace', 'np.logspace', (['(2)', '(7)', '(1000)'], {}), '(2, 7, 1000)\n', (5879, 5891), True, 'import numpy as np\n'), ((5903, 5922), 'numpy.m... |
import os
import time
# Limit TF logs:
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import tensorflow.python.compiler.tensorrt
from tensorflow.python.saved_model import tag_constants
from tensorflow.python.saved_model import signature_constants
from pkg_resources import resource_filename
from datacl... | [
"tensorflow.compat.v1.get_default_graph",
"tensorflow.convert_to_tensor",
"numpy.asarray",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.ConfigProto",
"tensorflow.import_graph_def",
"tensorflow.compat.v1.GraphDef",
"tensorflow.saved_model.load"
] | [((739, 765), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {}), '()\n', (763, 765), True, 'import tensorflow as tf\n'), ((836, 874), 'tensorflow.compat.v1.Session', 'tf.compat.v1.Session', ([], {'config': 'tf_config'}), '(config=tf_config)\n', (856, 874), True, 'import tensorflow as tf\n'), ((32... |
# crop.py
# <NAME>
K = 9 # Corner match kernel size (fast_corners will use
# max(3, K // 2 + 1).)
import cv2
import numpy as np
import sys
def corners(original, f=4):
gray = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
h, w = original.shape[:2]
k = np.ones((K, K), dtype=np.uint8)
# Make top le... | [
"cv2.warpPerspective",
"cv2.findHomography",
"cv2.cvtColor",
"cv2.imwrite",
"cv2.morphologyEx",
"numpy.ones",
"cv2.imread",
"numpy.array",
"cv2.rectangle",
"cv2.minMaxLoc",
"cv2.pyrDown",
"cv2.matchTemplate"
] | [((189, 231), 'cv2.cvtColor', 'cv2.cvtColor', (['original', 'cv2.COLOR_BGR2GRAY'], {}), '(original, cv2.COLOR_BGR2GRAY)\n', (201, 231), False, 'import cv2\n'), ((270, 301), 'numpy.ones', 'np.ones', (['(K, K)'], {'dtype': 'np.uint8'}), '((K, K), dtype=np.uint8)\n', (277, 301), True, 'import numpy as np\n'), ((1411, 1453... |
import numpy as np
class COCOKeypointLabel():
key_points = {
'nose': 0,
'left_eye': 1,
'right_eye': 2,
'left_ear': 3,
'right_ear': 4,
'left_shoulder': 5,
'right_shoulder': 6,
'left_elbow': 7,
'right_elbow': 8,
'left_wrist': 9,
... | [
"numpy.array"
] | [((516, 692), 'numpy.array', 'np.array', (['[[0, 1], [0, 2], [1, 3], [2, 4], [0, 5], [0, 6], [5, 7], [7, 9], [6, 8], [8,\n 10], [5, 6], [5, 11], [6, 12], [11, 12], [11, 13], [13, 15], [12, 14],\n [14, 16]]'], {}), '([[0, 1], [0, 2], [1, 3], [2, 4], [0, 5], [0, 6], [5, 7], [7, 9], [\n 6, 8], [8, 10], [5, 6], [5... |
# !/usr/bin/env python
"""Define the unit tests for the :mod:`colour.models.common` module."""
import numpy as np
import unittest
from itertools import product
from colour.models import Iab_to_XYZ, Jab_to_JCh, JCh_to_Jab, XYZ_to_Iab
from colour.utilities import domain_range_scale, ignore_numpy_errors
__author__ = "C... | [
"unittest.main",
"colour.models.Iab_to_XYZ",
"colour.utilities.domain_range_scale",
"colour.models.JCh_to_Jab",
"numpy.array",
"numpy.tile",
"colour.models.Jab_to_JCh",
"numpy.reshape",
"itertools.product",
"colour.models.XYZ_to_Iab"
] | [((13557, 13572), 'unittest.main', 'unittest.main', ([], {}), '()\n', (13570, 13572), False, 'import unittest\n'), ((1731, 1780), 'numpy.array', 'np.array', (['[41.52787529, 52.63858304, 26.92317922]'], {}), '([41.52787529, 52.63858304, 26.92317922])\n', (1739, 1780), True, 'import numpy as np\n'), ((1797, 1812), 'colo... |
import os
import pathlib
import numpy as np
from PIL import Image
from tqdm import tqdm
from data import convert_rgb_to_y, convert_rgb_to_ycbcr, convert_ycbcr_to_rgb
from fsrcnn import psnr
def upscale_large(fsrcnn, image_folder, output_folder, upscaling, rgb=True):
if not os.path.exists(output_fold... | [
"data.convert_rgb_to_ycbcr",
"os.makedirs",
"data.convert_rgb_to_y",
"os.path.exists",
"numpy.expand_dims",
"numpy.clip",
"numpy.hstack",
"PIL.Image.fromarray",
"PIL.Image.open",
"pathlib.Path",
"numpy.mean",
"numpy.array",
"numpy.squeeze",
"os.path.join",
"os.listdir"
] | [((372, 398), 'pathlib.Path', 'pathlib.Path', (['image_folder'], {}), '(image_folder)\n', (384, 398), False, 'import pathlib\n'), ((1602, 1628), 'pathlib.Path', 'pathlib.Path', (['image_folder'], {}), '(image_folder)\n', (1614, 1628), False, 'import pathlib\n'), ((3166, 3187), 'numpy.expand_dims', 'np.expand_dims', (['... |
import uptide
import pandas as pd
import numpy as np
# https://en.wikipedia.org/wiki/Theory_of_tides#Harmonic_analysis
default_tidal_constituents = [
'M2',
'S2',
'N2',
'K2', # Semi-diurnal
'K1',
'O1',
'P1',
'Q1', # Diurnal
'M4',
'M6',
'S4',
'MK3', # Short period
'... | [
"pandas.DataFrame",
"numpy.zeros_like",
"numpy.ones_like",
"uptide.Tides",
"numpy.cos"
] | [((493, 519), 'uptide.Tides', 'uptide.Tides', (['constituents'], {}), '(constituents)\n', (505, 519), False, 'import uptide\n'), ((669, 685), 'numpy.ones_like', 'np.ones_like', (['td'], {}), '(td)\n', (681, 685), True, 'import numpy as np\n'), ((699, 716), 'numpy.zeros_like', 'np.zeros_like', (['td'], {}), '(td)\n', (7... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import os
import numpy as np
from scipy.io import savemat
import image_funcs as imf
import nexstim2mri as n2m
import vis_funcs as vf
def main():
SHOW_WINDOW = True
SHOW_AXES = True
SHOW_EEG = True
SAVE_EEG = True
reorder = [0, 2, 1]
... | [
"numpy.set_printoptions",
"csv.reader",
"image_funcs.load_image",
"numpy.zeros",
"numpy.savetxt",
"scipy.io.savemat",
"vis_funcs.create_window",
"nexstim2mri.coord_change",
"vis_funcs.add_line",
"os.path.splitext",
"image_funcs.load_eeg_mat",
"vis_funcs.add_marker",
"os.path.join"
] | [((601, 656), 'os.path.join', 'os.path.join', (['data_dir', "(filenames['FILE_LIST'] + '.csv')"], {}), "(data_dir, filenames['FILE_LIST'] + '.csv')\n", (613, 656), False, 'import os\n'), ((2841, 2875), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (2860, 2875), True... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 12 10:00:50 2020
@author: <NAME>
This script:
To do:
Remove seasonal option? And new_seasonal
Remove all s3 and s4 stuff
Make a dataframe of total glacier runoff beforehand, takes too long to have the whole spatial nc
... | [
"matplotlib.cm.get_cmap",
"pandas.read_csv",
"os.path.isfile",
"mpl_toolkits.axes_grid1.inset_locator.inset_axes",
"numpy.mean",
"numpy.interp",
"os.path.join",
"os.chdir",
"pandas.DataFrame",
"matplotlib.pyplot.colorbar",
"pandas.datetime.datetime",
"numpy.append",
"numpy.cumsum",
"scipy.... | [((3252, 3269), 'os.chdir', 'os.chdir', (['RUN_DIR'], {}), '(RUN_DIR)\n', (3260, 3269), False, 'import os\n'), ((3359, 3383), 'os.path.join', 'join', (['RUN_DIR', '"""Figures"""'], {}), "(RUN_DIR, 'Figures')\n", (3363, 3383), False, 'from os.path import join\n'), ((18159, 18177), 'pandas.concat', 'pd.concat', (['OF_lis... |
import copy
import unittest
import numpy as np
from gnn import GraphNeuralNetwork
from optimizer import SGD, MomentumSGD, Adam
class TestSGD(unittest.TestCase):
def test_update(self):
sgd = SGD()
gnn = GraphNeuralNetwork(vector_size=2)
expected = gnn.params
sgd.update(gnn)
... | [
"unittest.main",
"copy.deepcopy",
"numpy.zeros_like",
"numpy.abs",
"optimizer.Adam",
"optimizer.SGD",
"gnn.GraphNeuralNetwork",
"numpy.array",
"optimizer.MomentumSGD",
"numpy.random.rand",
"numpy.sqrt"
] | [((4279, 4294), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4292, 4294), False, 'import unittest\n'), ((205, 210), 'optimizer.SGD', 'SGD', ([], {}), '()\n', (208, 210), False, 'from optimizer import SGD, MomentumSGD, Adam\n'), ((225, 258), 'gnn.GraphNeuralNetwork', 'GraphNeuralNetwork', ([], {'vector_size': '(... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
from electricitylci.globals import data_dir, output_dir
from electricitylci.eia923_generation import eia923_download
import os
from os.path import join
from electricitylci.utils import find_file_in_folder
import requests
import electricitylci.PhysicalQuantit... | [
"numpy.average",
"os.makedirs",
"pandas.read_csv",
"pandas.merge",
"electricitylci.eia923_generation.eia923_download",
"os.path.exists",
"pandas.read_excel",
"electricitylci.utils.find_file_in_folder",
"electricitylci.PhysicalQuantities.convert",
"requests.get",
"pandas.concat",
"os.path.join"... | [((5293, 5359), 'pandas.read_excel', 'pd.read_excel', (['eia7a_path'], {'sheet_name': '"""Hist_Coal_Prod"""', 'skiprows': '(3)'}), "(eia7a_path, sheet_name='Hist_Coal_Prod', skiprows=3)\n", (5306, 5359), True, 'import pandas as pd\n'), ((5959, 6009), 'pandas.read_csv', 'pd.read_csv', (["(data_dir + '/coal_state_to_basi... |
import matplotlib.pyplot as plt
import numpy as np
w_ii = 1.6
a = np.linspace(-1,1,200)
a = a[1:-1]
z = np.arctanh(a) - w_ii*a
plt.plot(a, np.zeros(z.shape),'--k')
plt.plot([0,0],z[[0,-1]],'--k')
plt.plot(a,z,'-k')
plt.xlim(a[[0,-1]])
plt.ylim(z[[0,-1]])
plt.show()
| [
"matplotlib.pyplot.xlim",
"numpy.arctanh",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"numpy.zeros",
"numpy.linspace"
] | [((67, 90), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(200)'], {}), '(-1, 1, 200)\n', (78, 90), True, 'import numpy as np\n'), ((165, 200), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 0]', 'z[[0, -1]]', '"""--k"""'], {}), "([0, 0], z[[0, -1]], '--k')\n", (173, 200), True, 'import matplotlib.pyplot as plt\n'),... |
import numpy as np
import pandas as pd
import math
from copy import deepcopy
from sklearn.metrics import davies_bouldin_score as dbindex
class Reward_Function:
def __init__(self, max_dist):
self.max_dist = max_dist
pass
def reward_function(self, df, k, total_data_size, obs, action, done):
... | [
"pandas.DataFrame",
"copy.deepcopy",
"math.log10",
"numpy.array",
"numpy.linalg.norm",
"numpy.prod"
] | [((1791, 1805), 'copy.deepcopy', 'deepcopy', (['data'], {}), '(data)\n', (1799, 1805), False, 'from copy import deepcopy\n'), ((1867, 1881), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1879, 1881), True, 'import pandas as pd\n'), ((1994, 2008), 'numpy.array', 'np.array', (['coor'], {}), '(coor)\n', (2002, 20... |
import os
import json
import re
import string
import argparse
import wikipedia
import requests
import json
from evaluate_prediction import check_present_and_duplicate_keyphrases, check_duplicate_keyphrases
from tqdm import tqdm
from stanfordcorenlp import StanfordCoreNLP
from utils import string_helper
import numpy as ... | [
"argparse.ArgumentParser",
"numpy.ones",
"numpy.argsort",
"os.path.join",
"evaluate_prediction.check_present_and_duplicate_keyphrases",
"json.loads",
"os.path.exists",
"re.findall",
"utils.string_helper.stem_word_list",
"requests.get",
"utils.string_helper.stem_str_list",
"re.sub",
"re.split... | [((884, 920), 'numpy.zeros', 'np.zeros', (['num_keyphrases'], {'dtype': 'bool'}), '(num_keyphrases, dtype=bool)\n', (892, 920), True, 'import numpy as np\n'), ((6244, 6293), 'utils.string_helper.stem_str_list', 'string_helper.stem_str_list', (['keyphrase_variations'], {}), '(keyphrase_variations)\n', (6271, 6293), Fals... |
# PyVot Python Variational Optimal Transportation
# Author: <NAME> <<EMAIL>>
# Date: April 28th 2020
# Licence: MIT
import numpy as np
from cycler import cycler
import matplotlib.pyplot as plt
from math import pi, cos, sin
import os
import sys
import time
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath... | [
"numpy.random.seed",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.random.normal",
"matplotlib.pyplot.gca",
"os.path.abspath",
"time.clock",
"numpy.append",
"math.cos",
"numpy.linspace",
"numpy.size",
"matplotlib.pyplot.show",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.ylim",
"ma... | [((486, 511), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * pi)', 'n'], {}), '(0, 2 * pi, n)\n', (497, 511), True, 'import numpy as np\n'), ((573, 591), 'numpy.random.seed', 'np.random.seed', (['(19)'], {}), '(19)\n', (587, 591), True, 'import numpy as np\n'), ((1467, 1498), 'numpy.random.uniform', 'np.random.uniform... |
import numpy as np
SPEED_LIGHT = 299_792_458.0
VACUUM_PERMEABILITY = 4e-7 * np.pi
VACUUM_PERMITTIVITY = 1/(VACUUM_PERMEABILITY * SPEED_LIGHT**2)
VACUUM_IMPEDANCE = VACUUM_PERMEABILITY * SPEED_LIGHT
def curl_E(E):
curl = np.zeros(E.shape)
curl[:, :-1, :, 0] += E[:, 1:, :, 2] - E[:, :-1, :, 2]
curl[:, :,... | [
"numpy.sum",
"numpy.cross",
"numpy.zeros",
"numpy.ones"
] | [((228, 245), 'numpy.zeros', 'np.zeros', (['E.shape'], {}), '(E.shape)\n', (236, 245), True, 'import numpy as np\n'), ((648, 665), 'numpy.zeros', 'np.zeros', (['H.shape'], {}), '(H.shape)\n', (656, 665), True, 'import numpy as np\n'), ((3319, 3343), 'numpy.cross', 'np.cross', (['self.E', 'self.H'], {}), '(self.E, self.... |
from numpy import genfromtxt, savetxt, flipud
# Read CSV file as two dimensional array.
data = genfromtxt('insolation_matrix.csv', delimiter=',', dtype=int)
# Reverse only even rows.
data[1::2, :] = data[1::2, ::-1]
# Transpose matrix.
data = data.transpose()
# Flip matrix because sun tracker starts from bottom pos... | [
"numpy.savetxt",
"numpy.flipud",
"numpy.genfromtxt"
] | [((96, 157), 'numpy.genfromtxt', 'genfromtxt', (['"""insolation_matrix.csv"""'], {'delimiter': '""","""', 'dtype': 'int'}), "('insolation_matrix.csv', delimiter=',', dtype=int)\n", (106, 157), False, 'from numpy import genfromtxt, savetxt, flipud\n'), ((334, 346), 'numpy.flipud', 'flipud', (['data'], {}), '(data)\n', (... |
import os
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import utils
from frdimg_help import add_y_in_input, resample_df_mean, resample_df_mean, get_EE_from_rad_in_pix
# ---------- Graphics ------------
import seaborn as sns; sns.set()
sns.set_context("poster",font_scale=1.2,rc={"font":"helvet... | [
"seaborn.set_style",
"utils.make_dir",
"os.path.join",
"matplotlib.pyplot.subplots",
"seaborn.color_palette",
"numpy.linspace",
"frdimg_help.resample_df_mean",
"seaborn.set",
"seaborn.set_context",
"utils.resample_df"
] | [((252, 261), 'seaborn.set', 'sns.set', ([], {}), '()\n', (259, 261), True, 'import seaborn as sns\n'), ((262, 329), 'seaborn.set_context', 'sns.set_context', (['"""poster"""'], {'font_scale': '(1.2)', 'rc': "{'font': 'helvetica'}"}), "('poster', font_scale=1.2, rc={'font': 'helvetica'})\n", (277, 329), True, 'import s... |
import dataclasses
import numpy as np
import typing
import datetime
import covid19sim.inference.message_utils as mu
class RiskLevelBoundsCheckedType(mu.RiskLevelType):
"""
Wrapper class aliasing RiskLevelType to bound check passed data to
RiskLevelType
"""
lo_bound = 0
hi_bound = mu.risk_leve... | [
"covid19sim.inference.message_utils.UpdateMessage",
"numpy.split",
"dataclasses.field",
"covid19sim.inference.message_utils.create_new_uid",
"numpy.random.randint",
"datetime.timedelta",
"numpy.arange",
"numpy.random.choice",
"covid19sim.inference.message_utils.EncounterMessage"
] | [((1285, 1311), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (1303, 1311), False, 'import datetime\n'), ((1989, 2040), 'dataclasses.field', 'dataclasses.field', ([], {'default_factory': 'list', 'init': '(False)'}), '(default_factory=list, init=False)\n', (2006, 2040), False, 'import ... |
__all__ = ["ExtremaCalculator"]
import pdb # noqa: F401
import pandas as pd
import matplotlib as mpl
import numpy as np
import solarwindpy as swp
class ExtremaCalculator(object):
r"""Calculate the minima and maxima for a activity index, defining an
Indicator Cycle starting at Minima N and ending at Minimu... | [
"numpy.asarray",
"matplotlib.dates.num2date",
"pandas.DatetimeIndex",
"pandas.cut",
"matplotlib.dates.DateFormatter",
"pandas.to_timedelta",
"numpy.arange",
"pandas.Series",
"pandas.to_datetime",
"matplotlib.dates.date2num",
"matplotlib.dates.YearLocator",
"pandas.concat",
"solarwindpy.pp.su... | [((4640, 4655), 'numpy.asarray', 'np.asarray', (['hdl'], {}), '(hdl)\n', (4650, 4655), True, 'import numpy as np\n'), ((4670, 4685), 'numpy.asarray', 'np.asarray', (['lbl'], {}), '(lbl)\n', (4680, 4685), True, 'import numpy as np\n'), ((4890, 4925), 'matplotlib.dates.date2num', 'mpl.dates.date2num', (['self.data.index'... |
from __future__ import absolute_import
from __future__ import unicode_literals
from osgeo import gdal, osr
import pyproj
import os, logging, json, sys, glob, re, traceback
import os.path as osp
import numpy as np
import netCDF4 as nc4
from vis.postprocessor import Postprocessor
from utils import load_sys_cfg, Dict, m... | [
"vis.var_wisdom.is_windvec",
"vis.var_wisdom.is_fire_var",
"numpy.isnan",
"numpy.ma.masked_array",
"osgeo.gdal.GetDriverByName",
"os.path.join",
"utils.make_clean_dir",
"netCDF4.Dataset",
"vis.var_wisdom.get_wisdom",
"logging.error",
"traceback.print_exc",
"six.moves.range",
"vis.var_wisdom.... | [((776, 792), 'vis.var_wisdom.is_fire_var', 'is_fire_var', (['var'], {}), '(var)\n', (787, 792), False, 'from vis.var_wisdom import get_wisdom, is_windvec, is_fire_var, strip_end\n'), ((990, 1002), 'six.moves.range', 'range', (['zsize'], {}), '(zsize)\n', (995, 1002), False, 'from six.moves import range\n'), ((2759, 27... |
# -*- coding: utf-8 -*-
"""Wrappers that provide agents an environment API.
This module contains wrappers that allow an agent to emulate the
interface of an environment object. With a similar API to environment
objects, agents can be stacked for hierarchical reinforcement learning
with good code incapsulation and mi... | [
"numpy.stack",
"numpy.sum",
"util.update_target_graph",
"agents.ac_rnn_ra_network.AC_rnn_ra_Network",
"tensorflow.Summary",
"numpy.zeros",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.ion",
"numpy.max",
"numpy.mean",
"numpy.array",
"util.process_frame",
"numpy.exp",
"numpy.linspace",
"nu... | [((2034, 2096), 'agents.ac_rnn_ra_network.AC_rnn_ra_Network', 'AC_rnn_ra_Network', (['s_shape', 'a_size', 'self.name', 'trainer'], {'hlvl': '(1)'}), '(s_shape, a_size, self.name, trainer, hlvl=1)\n', (2051, 2096), False, 'from agents.ac_rnn_ra_network import AC_rnn_ra_Network\n'), ((2198, 2240), 'util.update_target_gra... |
"""
This script trains DRA on the Huys task.
"""
import itertools
import numpy as np
import pandas as pd
from time import time
from task import HuysTask
env = HuysTask(depth=3)
n_trials = int(6e4)
# Hyper params
beta = 10
N_traj = 10
nRestarts = 5
# initializing params
lmda= 1
a1 = 0.1 # learning r... | [
"pandas.DataFrame",
"numpy.trace",
"numpy.multiply",
"numpy.square",
"numpy.mod",
"time.time",
"numpy.clip",
"numpy.ma.log",
"numpy.max",
"numpy.random.randint",
"numpy.linalg.inv",
"numpy.exp",
"numpy.arange",
"numpy.mean",
"numpy.around",
"numpy.dot",
"task.HuysTask",
"numpy.vsta... | [((161, 178), 'task.HuysTask', 'HuysTask', ([], {'depth': '(3)'}), '(depth=3)\n', (169, 178), False, 'from task import HuysTask\n'), ((669, 691), 'numpy.vstack', 'np.vstack', (['(t, t1, t1)'], {}), '((t, t1, t1))\n', (678, 691), True, 'import numpy as np\n'), ((1035, 1051), 'numpy.max', 'np.max', (['(beta * x)'], {}), ... |
import argparse
import os
import numpy as np
import pandas as pd
from skimage import io
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('input',
type=str,
help='original dataset directory')
parser.add_argument('output',
... | [
"pandas.DataFrame",
"argparse.ArgumentParser",
"skimage.io.imsave",
"os.path.basename",
"pandas.read_csv",
"os.path.dirname",
"numpy.arange",
"os.path.join",
"skimage.io.imread"
] | [((122, 147), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (145, 147), False, 'import argparse\n'), ((2104, 2144), 'os.path.join', 'os.path.join', (['args.input', '"""metadata.csv"""'], {}), "(args.input, 'metadata.csv')\n", (2116, 2144), False, 'import os\n'), ((2172, 2213), 'os.path.join', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from patterns import CORONAL_BACKING, R_WEAKENING, STOPPING, VELAR_FRONTING
from lexicon import Lexicon
from corpus import Corpus
from progress.bar import Bar
from collections import Counter
from itertools import repeat
import logging... | [
"lexicon.Lexicon",
"csv.writer",
"numpy.isnan",
"corpus.Corpus",
"collections.Counter",
"pandas.concat",
"itertools.repeat"
] | [((482, 508), 'lexicon.Lexicon', 'Lexicon', (['language', 'lexicon'], {}), '(language, lexicon)\n', (489, 508), False, 'from lexicon import Lexicon\n'), ((531, 546), 'corpus.Corpus', 'Corpus', (['corpora'], {}), '(corpora)\n', (537, 546), False, 'from corpus import Corpus\n'), ((889, 957), 'pandas.concat', 'pd.concat',... |
#!/usr/bin/env python3
import numpy as np
import torch
from torch import nn
from torch.utils.data import Sampler
from torch.utils.data import Dataset
from .Utils import TransformTensorDataset
from .Models import Ensemble, Model
import copy
class BootstrapSampler(Sampler):
""" Implements bootstrap sampling in P... | [
"numpy.random.seed",
"torch.stack",
"torch.nn.ModuleList"
] | [((1028, 1048), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1042, 1048), True, 'import numpy as np\n'), ((7399, 7425), 'torch.stack', 'torch.stack', (['losses'], {'dim': '(1)'}), '(losses, dim=1)\n', (7410, 7425), False, 'import torch\n'), ((7449, 7479), 'torch.stack', 'torch.stack', (['accuraci... |
#!/usr/bin/env python
from __future__ import (print_function, absolute_import, division)
import numpy as np
from astropy.convolution import convolve
from astropy.convolution import Gaussian1DKernel
from astropy.stats import gaussian_fwhm_to_sigma
from .interpolation import interpolate_profile
from .utils import get_... | [
"astropy.convolution.convolve",
"numpy.fabs",
"numpy.diff",
"astropy.convolution.Gaussian1DKernel",
"numpy.linspace",
"numpy.interp",
"numpy.sqrt"
] | [((1681, 1710), 'numpy.linspace', 'np.linspace', (['(-100)', '(100)', '(10000)'], {}), '(-100, 100, 10000)\n', (1692, 1710), True, 'import numpy as np\n'), ((1993, 2034), 'numpy.fabs', 'np.fabs', (['((wave - central_wavelength) / f0)'], {}), '((wave - central_wavelength) / f0)\n', (2000, 2034), True, 'import numpy as n... |
#!/usr/bin/env python
'''
Learning 2 x 3 bar and stripe using Born Machine.
'''
import numpy as np
import pdb, os, fire
import scipy.sparse as sps
from qcbm import train
from qcbm.testsuit import load_barstripe
np.random.seed(2)
try:
os.mkdir('data')
except:
pass
# the testcase used in this program.
depth = ... | [
"os.mkdir",
"numpy.random.seed",
"numpy.abs",
"qcbm.dataset.barstripe_pdf",
"matplotlib.pyplot.figure",
"numpy.prod",
"numpy.savetxt",
"qcbm.dataset.binary_basis",
"numpy.append",
"numpy.max",
"numpy.loadtxt",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel"... | [((213, 230), 'numpy.random.seed', 'np.random.seed', (['(2)'], {}), '(2)\n', (227, 230), True, 'import numpy as np\n'), ((344, 401), 'qcbm.testsuit.load_barstripe', 'load_barstripe', (['geometry', 'depth'], {'structure': '"""chowliu-tree"""'}), "(geometry, depth, structure='chowliu-tree')\n", (358, 401), False, 'from q... |
# -*- coding: utf-8 -*-
# @Author : PistonYang(<EMAIL>)
__all__ = ['Cutout_PIL']
import numpy as np
from PIL import Image
class Cutout_PIL(object):
"""Random erase the given PIL Image.
It has been proposed in
`Improved Regularization of Convolutional Neural Networks with Cutout`.
`https://arxiv.org... | [
"numpy.random.uniform",
"numpy.random.rand",
"numpy.ones",
"numpy.random.randint",
"PIL.Image.fromarray",
"numpy.sqrt"
] | [((1392, 1419), 'numpy.random.uniform', 'np.random.uniform', (['s_l', 's_h'], {}), '(s_l, s_h)\n', (1409, 1419), True, 'import numpy as np\n'), ((1569, 1596), 'numpy.random.uniform', 'np.random.uniform', (['r_1', 'r_2'], {}), '(r_1, r_2)\n', (1586, 1596), True, 'import numpy as np\n'), ((1706, 1737), 'numpy.random.rand... |
"""Implementation of Kalman Filter"""
import numpy as np
class KalmanFilter:
def __init__(self, A: np.array, B: np.array, H: np.array):
self.A = A
self.B = B
self.H = H
self.Q = None
self.R = None
self.x0 = None
self.p0 = None
# Kalman gain
... | [
"numpy.eye"
] | [((882, 905), 'numpy.eye', 'np.eye', (['self.H.shape[0]'], {}), '(self.H.shape[0])\n', (888, 905), True, 'import numpy as np\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.