code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... | [
"numpy.sum",
"numpy.abs",
"quantization.kernels.kernel_base.qrec_type",
"numpy.seterr",
"numpy.log2",
"numpy.iinfo",
"numpy.clip",
"quantization.kernels.kernel_base.params_type",
"numpy.max",
"numpy.array",
"numpy.exp"
] | [((1211, 1241), 'quantization.kernels.kernel_base.params_type', 'params_type', (['SoftMaxParameters'], {}), '(SoftMaxParameters)\n', (1222, 1241), False, 'from quantization.kernels.kernel_base import KernelBase, params_type, qrec_type\n'), ((1243, 1265), 'quantization.kernels.kernel_base.qrec_type', 'qrec_type', (['"""... |
"""
Implementation of the Determinant-based Mutual Information (DMI) Mechanism (Kong 2019).
@author: <NAME> <<EMAIL>>
"""
from itertools import combinations
from random import shuffle
import numpy as np
def dmi_mechanism(grader_dict, assignment_num, cluster_size):
"""
Computes payments for students ... | [
"itertools.combinations",
"random.shuffle",
"numpy.linalg.det",
"numpy.zeros"
] | [((1530, 1544), 'random.shuffle', 'shuffle', (['tasks'], {}), '(tasks)\n', (1537, 1544), False, 'from random import shuffle\n'), ((1576, 1600), 'itertools.combinations', 'combinations', (['graders', '(2)'], {}), '(graders, 2)\n', (1588, 1600), False, 'from itertools import combinations\n'), ((1620, 1652), 'numpy.zeros'... |
"""Contains tests for the private _solvers module"""
from numpy import insert, loadtxt, allclose
import pytest
from qmpy.solvers import schroedinger
from qmpy._fileio import _read_schrodinger
PROBLEMS = ['inf_potwell', 'fin_potwell', 'double_well', 'asym_potwell',
'harm_osci']
@pytest.mark.parametrize('... | [
"numpy.allclose",
"qmpy.solvers.schroedinger",
"numpy.insert",
"qmpy._fileio._read_schrodinger",
"pytest.mark.parametrize"
] | [((295, 339), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""problem"""', 'PROBLEMS'], {}), "('problem', PROBLEMS)\n", (318, 339), False, 'import pytest\n'), ((538, 561), 'qmpy._fileio._read_schrodinger', '_read_schrodinger', (['path'], {}), '(path)\n', (555, 561), False, 'from qmpy._fileio import _read_sc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import logging
import time
import multiprocessing
import cflib.crtp
from cflib.crazyflie import Crazyflie
from cflib.crazyflie.log import LogConfig
from cflib.crazyflie.syncCrazyflie import SyncCrazyflie
from cfli... | [
"cflib.crazyflie.syncLogger.SyncLogger",
"cflog.CFLog",
"matplotlib.pyplot.show",
"cflib.crazyflie.log.LogConfig",
"matplotlib.style.use",
"numpy.subtract",
"time.strftime",
"time.sleep",
"time.time",
"matplotlib.animation.FuncAnimation",
"matplotlib.pyplot.figure",
"cftune.PositionTuner",
"... | [((795, 825), 'matplotlib.style.use', 'style.use', (['"""seaborn-whitegrid"""'], {}), "('seaborn-whitegrid')\n", (804, 825), False, 'from matplotlib import style\n'), ((1031, 1066), 'numpy.array', 'np.array', (['[0.5, 0.5, alt_target, 0]'], {}), '([0.5, 0.5, alt_target, 0])\n', (1039, 1066), True, 'import numpy as np\n... |
import argparse
import numpy as np
import healpy
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--weight-paths", nargs="+", required=True)
parser.add_argument("--jk-def", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
... | [
"numpy.load",
"numpy.sum",
"argparse.ArgumentParser",
"numpy.zeros",
"healpy.read_map",
"numpy.savez"
] | [((91, 116), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (114, 116), False, 'import argparse\n'), ((333, 353), 'numpy.load', 'np.load', (['args.jk_def'], {}), '(args.jk_def)\n', (340, 353), True, 'import numpy as np\n'), ((407, 462), 'healpy.read_map', 'healpy.read_map', (['args.weight_paths... |
# multithread demo
# https://nrsyed.com/2018/07/05/multithreading-with-opencv-python-to-improve-video-processing-performance/
# object-oriented programming + multithread
#
# 1 thread - acquire image from camera
# 1 thread - to disply raw image
# 1 thread - to calculate Laplacian of Guassian image of the ra... | [
"threading.Thread",
"cv2.filter2D",
"cv2.waitKey",
"cv2.VideoCapture",
"numpy.finfo",
"numpy.array",
"cv2.imshow",
"datetime.datetime.now"
] | [((3835, 3859), 'cv2.VideoCapture', 'cv2.VideoCapture', (['source'], {}), '(source)\n', (3851, 3859), False, 'import cv2\n'), ((858, 872), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (870, 872), False, 'from datetime import datetime\n'), ((1344, 1365), 'cv2.VideoCapture', 'cv2.VideoCapture', (['src'], {}... |
# coding: utf-8
import numpy as np
from kerasy.ML.sampling import GibbsMsphereSampler
def test_gibbs_msphere_sampling(target=0.15):
radius = 10
num_samples = 10000
dimension = 6
sampler = GibbsMsphereSampler(dimension=dimension, radius=radius)
sample = sampler.sample(num_samples, verbose=-1)
... | [
"kerasy.ML.sampling.GibbsMsphereSampler",
"numpy.square",
"numpy.count_nonzero",
"numpy.all"
] | [((206, 261), 'kerasy.ML.sampling.GibbsMsphereSampler', 'GibbsMsphereSampler', ([], {'dimension': 'dimension', 'radius': 'radius'}), '(dimension=dimension, radius=radius)\n', (225, 261), False, 'from kerasy.ML.sampling import GibbsMsphereSampler\n'), ((374, 417), 'numpy.count_nonzero', 'np.count_nonzero', (['(norm <= (... |
import torch
import numpy as np
from .event_representation import EventRepresentation
from evrepr.thirdparty.matrixlstm.classification.layers.MatrixLSTM import MatrixLSTM
from evrepr.thirdparty.matrixlstm.classification.layers.SELayer import SELayer
class MatrixLSTMRepresentation(EventRepresentation):
def __i... | [
"numpy.pad",
"torch.as_tensor",
"evrepr.thirdparty.matrixlstm.classification.layers.SELayer.SELayer",
"numpy.stack"
] | [((2072, 2120), 'torch.as_tensor', 'torch.as_tensor', (['events_lens'], {'device': 'self.device'}), '(events_lens, device=self.device)\n', (2087, 2120), False, 'import torch\n'), ((1298, 1348), 'evrepr.thirdparty.matrixlstm.classification.layers.SELayer.SELayer', 'SELayer', (['self.matrixlstm.out_channels'], {'reductio... |
"""
:Authors: - <NAME>
"""
from setuptools import setup, find_packages
try:
import numpy as np
except ImportError:
raise ImportError("First you need to run: pip install numpy")
"""
try:
from Cython.Build import cythonize
except ImportError:
raise ImportError('First you need to run: pip install cython... | [
"numpy.get_include",
"setuptools.find_packages"
] | [((585, 600), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (598, 600), False, 'from setuptools import setup, find_packages\n'), ((659, 675), 'numpy.get_include', 'np.get_include', ([], {}), '()\n', (673, 675), True, 'import numpy as np\n')] |
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import to_categorical
from keras.preprocessing import image
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection... | [
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"keras.layers.Dropout",
"keras.layers.Flatten",
"keras.preprocessing.image.img_to_array",
"keras.preprocessing.image.load_img",
"keras.layers.Dense",
"numpy.array",
"keras.layers.Conv2D",
"keras.models.Sequential",
"keras.layers.MaxP... | [((376, 402), 'pandas.read_csv', 'pd.read_csv', (['"""dataset.csv"""'], {}), "('dataset.csv')\n", (387, 402), True, 'import pandas as pd\n'), ((714, 735), 'numpy.array', 'np.array', (['train_image'], {}), '(train_image)\n', (722, 735), True, 'import numpy as np\n'), ((871, 925), 'sklearn.model_selection.train_test_spli... |
import numpy as np
import pandas as pd
import datetime
date = datetime.datetime.now().strftime('%Y%m%d')
from time import perf_counter
start = perf_counter()
path = '/home/users/aslee/CaCO3_NWP/'
from sklearn.model_selection import train_test_split
data_df = pd.read_csv('{}data/spe+bulk_dataset_20201215.csv'.form... | [
"pandas.DataFrame",
"sklearn.model_selection.GridSearchCV",
"sklearn.decomposition.NMF",
"sklearn.svm.SVR",
"numpy.log",
"sklearn.model_selection.train_test_split",
"numpy.logspace",
"time.perf_counter",
"datetime.datetime.now"
] | [((146, 160), 'time.perf_counter', 'perf_counter', ([], {}), '()\n', (158, 160), False, 'from time import perf_counter\n'), ((659, 727), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'shuffle': '(True)', 'random_state': '(24)'}), '(X, y, test_size=0.2, shuffle=True,... |
from numpy import random
x = random.rand()
print(x)
| [
"numpy.random.rand"
] | [((30, 43), 'numpy.random.rand', 'random.rand', ([], {}), '()\n', (41, 43), False, 'from numpy import random\n')] |
"""Module for analysing station data"""
from ast import Import
import matplotlib.dates as dt
import numpy as np
import datetime
from floodsystem.station import MonitoringStation
def polyfit(dates, levels, p):
"""From a list of dates and levels returns a best fit numpy polynomial of order p,
and the shift ... | [
"numpy.array",
"datetime.timedelta"
] | [((915, 936), 'numpy.array', 'np.array', (['float_dates'], {}), '(float_dates)\n', (923, 936), True, 'import numpy as np\n'), ((937, 953), 'numpy.array', 'np.array', (['levels'], {}), '(levels)\n', (945, 953), True, 'import numpy as np\n'), ((766, 800), 'datetime.timedelta', 'datetime.timedelta', ([], {'microseconds': ... |
import cv2
import numpy as np
from mmcv.utils import Config
from mmseg.datasets import build_dataset, build_dataloader
def transform(im):
mean = [123.675, 116.28, 103.53]
mean = np.array(mean).reshape((1, 1, 3))
std = [58.395, 57.12, 57.375]
std = np.array(std).reshape((1, 1, 3))
im = im.permute... | [
"numpy.array",
"mmseg.datasets.build_dataset",
"mmcv.utils.Config.fromfile",
"mmseg.datasets.build_dataloader"
] | [((520, 543), 'mmcv.utils.Config.fromfile', 'Config.fromfile', (['config'], {}), '(config)\n', (535, 543), False, 'from mmcv.utils import Config\n'), ((1404, 1422), 'mmseg.datasets.build_dataset', 'build_dataset', (['cfg'], {}), '(cfg)\n', (1417, 1422), False, 'from mmseg.datasets import build_dataset, build_dataloader... |
"""
This script contains code for useful data transformations and data checks
used in the other modules of squidward.
"""
import sys
import warnings
import functools
import numpy as np
import scipy.linalg as la
try:
# python 2
numeric_types = (int, float, long, complex)
except:
# python 3
numeric_type... | [
"numpy.maximum",
"numpy.linalg.cond",
"numpy.linalg.svd",
"numpy.exp",
"numpy.diag",
"numpy.linalg.solve",
"numpy.unique",
"warnings.simplefilter",
"numpy.eye",
"numpy.identity",
"numpy.linalg.matrix_rank",
"numpy.linalg.det",
"numpy.linalg.cholesky",
"numpy.minimum",
"numpy.asarray",
... | [((347, 370), 'numpy.seterr', 'np.seterr', ([], {'over': '"""raise"""'}), "(over='raise')\n", (356, 370), True, 'import numpy as np\n'), ((947, 974), 'numpy.array_equal', 'np.array_equal', (['alpha', 'beta'], {}), '(alpha, beta)\n', (961, 974), True, 'import numpy as np\n'), ((1765, 1780), 'numpy.asarray', 'np.asarray'... |
###################### INFORMATION #############################
# akf-mocrin is a "Multiple OCR Interface"
# Program: **akf-mocrin**
# Info: **Python 3.6**
# Author: **<NAME>**
# Date: **12.01.2018**
########## IMPORT ##########
import configparser
import numpy as np
import argparse
import subpro... | [
"os.remove",
"mocrinlib.tessapi.tess_pprocess",
"argparse.ArgumentParser",
"mocrinlib.imgproc.safe_imread",
"mocrinlib.common.create_dir",
"os.path.isfile",
"numpy.arange",
"mocrinlib.common.get_filenames",
"mocrinlib.common.get_iopath",
"mocrinlib.abbyyrunner.start_abbyy",
"os.path.dirname",
... | [((878, 903), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (901, 903), False, 'import argparse\n'), ((7876, 7896), 'mocrinlib.common.create_dir', 'create_dir', (['path_out'], {}), '(path_out)\n', (7886, 7896), False, 'from mocrinlib.common import create_dir, get_iopath, get_filenames\n'), ((8... |
# This script opens a 2206B driver device, sets up both channels and a trigger then collects a block of data.
# This data is then plotted as mV against time in us.
import ctypes
import numpy as np
from picosdk.ps2000a import ps2000a as ps
import matplotlib.pyplot as plt
from picosdk.functions import adc2mV, assert_pic... | [
"ctypes.c_int16",
"picosdk.ps2000a.ps2000a.ps2000aSetChannel",
"ctypes.c_int32",
"ctypes.byref",
"picosdk.functions.assert_pico_ok",
"ctypes.c_float",
"numpy.linspace",
"math.log",
"datetime.datetime.now",
"matplotlib.pyplot.show",
"csv.writer",
"picosdk.ps2000a.ps2000a.ps2000aRunBlock",
"pi... | [((1189, 1205), 'ctypes.c_int16', 'ctypes.c_int16', ([], {}), '()\n', (1203, 1205), False, 'import ctypes\n'), ((1599, 1633), 'picosdk.functions.assert_pico_ok', 'assert_pico_ok', (["status['openunit']"], {}), "(status['openunit'])\n", (1613, 1633), False, 'from picosdk.functions import adc2mV, assert_pico_ok\n'), ((18... |
#https://www.youtube.com/watch?v=ZGU5kIG7b2I
#dependencies
import json #files
import numpy as np #vectorization
import random #generating random text
import tensorflow as tf #ML
import datetime #clock training time
text = open('issa_haikus_english').read()
#sort characters
chars = sorted(list(set(text)))
char_size =... | [
"tensorflow.train.Saver",
"random.uniform",
"tensorflow.global_variables_initializer",
"numpy.argmax",
"numpy.zeros",
"tensorflow.Session",
"tensorflow.concat",
"tensorflow.nn.softmax_cross_entropy_with_logits_v2",
"tensorflow.placeholder",
"tensorflow.matmul",
"tensorflow.Variable",
"tensorfl... | [((2041, 2051), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2049, 2051), True, 'import tensorflow as tf\n'), ((512, 532), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (526, 532), False, 'import random\n'), ((824, 851), 'numpy.zeros', 'np.zeros', ([], {'shape': '[char_size]'}), '(shape=[c... |
#!/usr/bin/env python3
import shelve
from glob import glob
import numpy as np
import matplotlib.pyplot as plt
import plot_helpers
import argparse
parser = argparse.ArgumentParser(description="produce boxplots for sojourn "
"time vs. d/n")
parser.add_argument('dataset', help="name ... | [
"matplotlib.pyplot.show",
"argparse.ArgumentParser",
"matplotlib.pyplot.legend",
"plot_helpers.cycle_styles",
"shelve.open",
"plot_helpers.config_paper",
"matplotlib.pyplot.figure",
"numpy.array",
"glob.glob",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.semilogy",
"matplotlib.pyplot.xlabel"... | [((161, 246), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""produce boxplots for sojourn time vs. d/n"""'}), "(description='produce boxplots for sojourn time vs. d/n'\n )\n", (184, 246), False, 'import argparse\n'), ((933, 960), 'plot_helpers.config_paper', 'plot_helpers.config_paper... |
from math import *
import sys, argparse, time
import numpy as np
import mdtraj as md
import general_scripts as gs
try:
import psutil
bPsutil = True
except:
print( "= = = NOTE: Module psutil isnot available, cannot respect memory usage on this run.." )
bPsutil = False
def print_selection_help():
pr... | [
"psutil.virtual_memory",
"numpy.sum",
"argparse.ArgumentParser",
"numpy.einsum",
"mdtraj.load",
"numpy.mean",
"numpy.linalg.norm",
"numpy.exp",
"sys.getsizeof",
"general_scripts.print_xylist",
"numpy.std",
"numpy.equal",
"mdtraj.iterload",
"numpy.stack",
"sys.exit",
"numpy.concatenate"... | [((20925, 20935), 'sys.exit', 'sys.exit', ([], {}), '()\n', (20933, 20935), False, 'import sys, argparse, time\n'), ((8465, 8492), 'numpy.zeros', 'np.zeros', (['nFiles'], {'dtype': 'int'}), '(nFiles, dtype=int)\n', (8473, 8492), True, 'import numpy as np\n'), ((8510, 8537), 'numpy.zeros', 'np.zeros', (['nFiles'], {'dty... |
from collections import defaultdict
import numpy as np
import io
from PDFStructureObjects import XrefEntry, XRefTable
# https://www.w3.org/TR/PNG/#9Filters
def png_algorithmPipeline(decoded_stream: bytes, number_of_columns: int, algorithm_id: int) -> bytes:
"""
Takes a png image to decompress its contents
... | [
"io.BytesIO",
"PDFStructureObjects.XRefTable",
"PDFStructureObjects.XrefEntry",
"numpy.frombuffer",
"numpy.dtype",
"collections.defaultdict",
"numpy.delete"
] | [((1437, 1468), 'numpy.frombuffer', 'np.frombuffer', (['data', 'big_endian'], {}), '(data, big_endian)\n', (1450, 1468), True, 'import numpy as np\n'), ((2153, 2179), 'numpy.delete', 'np.delete', (['png_array', '(0)', '(1)'], {}), '(png_array, 0, 1)\n', (2162, 2179), True, 'import numpy as np\n'), ((2508, 2530), 'io.By... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2016 <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 require... | [
"tensorflow.reduce_sum",
"codecs.open",
"numpy.argmax",
"tensorflow.variable_scope",
"tensorflow.shape",
"nparser.misc.colors.color_pattern",
"tensorflow.greater",
"nparser.misc.colors.ctext"
] | [((1673, 1707), 'tensorflow.greater', 'tf.greater', (['placeholder', 'self.ROOT'], {}), '(placeholder, self.ROOT)\n', (1683, 1707), True, 'import tensorflow as tf\n'), ((1732, 1753), 'tensorflow.shape', 'tf.shape', (['placeholder'], {}), '(placeholder)\n', (1740, 1753), True, 'import tensorflow as tf\n'), ((1781, 1802)... |
from builtins import zip
import numpy as np
from lsst.sims.utils import m5_flat_sed
from lsst.sims.photUtils import LSSTdefaults
def restore_files():
roots = ['61390_61603', '61573_61786', '61756_61969']
dicts = []
sbs = []
for root in roots:
restore_file = 'healpix/'+root+'.npz'
disk_... | [
"numpy.load",
"lsst.sims.photUtils.LSSTdefaults",
"numpy.power",
"numpy.isfinite",
"numpy.sort",
"numpy.arange",
"pdb.set_trace",
"builtins.zip",
"numpy.linspace",
"numpy.savez",
"lsst.sims.utils.m5_flat_sed",
"numpy.concatenate",
"numpy.in1d"
] | [((3085, 3178), 'numpy.savez', 'np.savez', (['"""percentile_m5_maps.npz"""'], {'histograms': 'histograms', 'histogram_npts': 'histogram_npts'}), "('percentile_m5_maps.npz', histograms=histograms, histogram_npts=\n histogram_npts)\n", (3093, 3178), True, 'import numpy as np\n'), ((327, 348), 'numpy.load', 'np.load', ... |
# Written by <NAME>
import PGM_h
from numpy.linalg import norm
from scipy import optimize as optimize
from math import exp
from math import log
k_features = 6
landa_init = [0.30303594, 0.30279514, 0.25452369, 0.30318327, 0.28723748, 0.27421734] # [1, 1, 1, 1, 1, 1]
# landa for 1000 train query [ 0.21909945 ... | [
"math.log",
"math.exp",
"PGM_h.h",
"numpy.linalg.norm"
] | [((6506, 6517), 'math.exp', 'exp', (['result'], {}), '(result)\n', (6509, 6517), False, 'from math import exp\n'), ((14239, 14255), 'math.log', 'log', (['best_pr', '(10)'], {}), '(best_pr, 10)\n', (14242, 14255), False, 'from math import log\n'), ((4711, 4723), 'math.log', 'log', (['pri', '(10)'], {}), '(pri, 10)\n', (... |
# -*- coding:utf-8 -*-
import random
from collections import OrderedDict
from contextlib import contextmanager
import torch
import numpy as np
def _set_seed(seed):
""" Set seed for system, numpy and pytorch. """
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
@contextmanager
def nul... | [
"torch.manual_seed",
"random.seed",
"numpy.random.seed"
] | [((224, 244), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (238, 244), True, 'import numpy as np\n'), ((249, 266), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (260, 266), False, 'import random\n'), ((271, 294), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (28... |
from __future__ import annotations
import numpy as np
import pandas as pd
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from psyke.schema import DiscreteFeature
from psyke.utils import get_default_random_seed
from tuprolog.theory import Theory
from typing import Iterable
import logging... | [
"psyke.classification.real.REAL",
"psyke.cart.Cart",
"logging.basicConfig",
"sklearn.metrics.r2_score",
"psyke.classification.trepan.Trepan",
"sklearn.metrics.mean_absolute_error",
"psyke.regression.iter.ITER",
"psyke.regression.gridrex.GridREx",
"numpy.isnan",
"psyke.regression.gridex.GridEx",
... | [((322, 362), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (341, 362), False, 'import logging\n'), ((372, 398), 'logging.getLogger', 'logging.getLogger', (['"""psyke"""'], {}), "('psyke')\n", (389, 398), False, 'import logging\n'), ((2026, 2088), 'sklearn.me... |
import random
import time
import numbers
import numpy as np
from collections import deque
def append_angle(Rover, new_angle):
'''append the latest angle to the list, and drop the oldest from the list to max length'''
Rover.last_nav_angles.append(new_angle)
while len(Rover.last_nav_angles) > Rover.use_las... | [
"numpy.mean",
"random.randrange",
"numpy.clip",
"time.time"
] | [((1857, 1868), 'time.time', 'time.time', ([], {}), '()\n', (1866, 1868), False, 'import time\n'), ((3721, 3732), 'time.time', 'time.time', ([], {}), '()\n', (3730, 3732), False, 'import time\n'), ((1094, 1105), 'time.time', 'time.time', ([], {}), '()\n', (1103, 1105), False, 'import time\n'), ((3022, 3033), 'time.time... |
import matplotlib.pyplot as plt
import numpy as np
from config import *
def get_name_dict():
with open('config/data_names.json') as ifs:
return eval(''.join(ifs.readlines()))
def get_algorithm_name_dict():
with open('config/algorithm_info.json') as ifs:
return json.load(ifs)["algorithm_abbr... | [
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.yticks",
"numpy.arange",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots"
] | [((2409, 2423), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2421, 2423), True, 'import matplotlib.pyplot as plt\n'), ((3449, 3479), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': 'TICK_SIZE'}), '(fontsize=TICK_SIZE)\n', (3459, 3479), True, 'import matplotlib.pyplot as plt\n'), ((3548, ... |
# https://medium.com/@thomascountz/19-line-line-by-line-python-perceptron-b6f113b161f3
"""
MIT License
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction... | [
"numpy.array",
"numpy.dot",
"numpy.zeros"
] | [((1491, 1517), 'numpy.zeros', 'np.zeros', (['(no_of_inputs + 1)'], {}), '(no_of_inputs + 1)\n', (1499, 1517), True, 'import numpy as np\n'), ((2847, 2867), 'numpy.array', 'np.array', (['[-1, 1, 1]'], {}), '([-1, 1, 1])\n', (2855, 2867), True, 'import numpy as np\n'), ((2914, 2930), 'numpy.array', 'np.array', (['[a, b]... |
import os
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn.functional as F
from torch import nn
import random
import scipy.io
from sklearn.decomposition import non_negative_factorization
random.seed(3)
torch.manual_seed(4)
def pre_processed_DTnet_1():
dataset_dir =... | [
"numpy.set_printoptions",
"torch.eye",
"torch.utils.data.DataLoader",
"torch.manual_seed",
"torch.Tensor",
"random.seed",
"os.path.sep.join"
] | [((233, 247), 'random.seed', 'random.seed', (['(3)'], {}), '(3)\n', (244, 247), False, 'import random\n'), ((249, 269), 'torch.manual_seed', 'torch.manual_seed', (['(4)'], {}), '(4)\n', (266, 269), False, 'import torch\n'), ((321, 352), 'os.path.sep.join', 'os.path.sep.join', (["['deepDTnet']"], {}), "(['deepDTnet'])\n... |
#! /usr/bin/env python
##########################################################################
# NSAp - Copyright (C) CEA, 2013 - 2017
# 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.... | [
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.colorbar",
"numpy.where",
"SimpleITK.WriteImage",
"SimpleITK.GetImageFromArray",
"collections.OrderedDict",
"six.iteritems",
"os.path.join",
"matplotlib.pyplot.savefig"
] | [((981, 1006), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (1004, 1006), False, 'import collections\n'), ((1093, 1128), 'six.iteritems', 'six.iteritems', (['self.enabledFeatures'], {}), '(self.enabledFeatures)\n', (1106, 1128), False, 'import six\n'), ((1980, 2021), 'six.iteritems', 'six.ite... |
import numpy as np
import xgboost as xgb
import re
from pitci.xgboost import XGBoosterAbsoluteErrorConformalPredictor
import pitci
import pytest
class TestInit:
"""Tests for the XGBoosterAbsoluteErrorConformalPredictor._init__ method."""
def test_inheritance(self):
"""Test that XGBoosterAbsoluteErr... | [
"pitci.get_absolute_error_conformal_predictor",
"pitci.helpers.check_interval_width",
"numpy.testing.assert_array_equal",
"re.escape",
"numpy.array",
"pitci.xgboost.XGBoosterAbsoluteErrorConformalPredictor",
"pytest.mark.parametrize"
] | [((9811, 9888), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""alpha"""', '[0.1, 0.25, 0.5, 0.7, 0.8, 0.9, 0.95, 0.99]'], {}), "('alpha', [0.1, 0.25, 0.5, 0.7, 0.8, 0.9, 0.95, 0.99])\n", (9834, 9888), False, 'import pytest\n'), ((1237, 1301), 'pitci.xgboost.XGBoosterAbsoluteErrorConformalPredictor', 'XGBoo... |
from optparse import OptionParser
import numpy as np
# This version is adapted for mem
__VERSION__ = 0.2
class percentile:
""" Calculated 10th, 50th and 90th percentiles of an array
Properties:
tenth - returns the tenth percentile
median - returns the median (or 50th percenti... | [
"numpy.percentile",
"numpy.genfromtxt",
"optparse.OptionParser"
] | [((1020, 1062), 'optparse.OptionParser', 'OptionParser', ([], {'usage': 'usage', 'version': 'version'}), '(usage=usage, version=version)\n', (1032, 1062), False, 'from optparse import OptionParser\n'), ((1263, 1285), 'numpy.genfromtxt', 'np.genfromtxt', (['args[0]'], {}), '(args[0])\n', (1276, 1285), True, 'import nump... |
"""
We are going to solve a nonlinear static system using the FETI nonlinear
static solver in this example. We decided to use an aluminium rectangular
2D structure, which is going to be fixed on the north edge and a force
of 15kN is going to beapplied on the south edge.
We start by importing the libraries needed for t... | [
"amfe.solver.translators.MulticomponentMechanicalSystem",
"amfeti.NonlinearStaticFetiSolver",
"amfe.ui.write_results_to_paraview",
"numpy.zeros_like",
"logging.basicConfig",
"amfe.component.StructuralComponent",
"amfe.component.component_composite.MeshComponentComposite",
"amfe.solver.AmfeSolution",
... | [((1079, 1118), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (1098, 1118), False, 'import logging\n'), ((1290, 1344), 'amfe.material.KirchhoffMaterial', 'KirchhoffMaterial', (['E_alu', 'nu_alu', 'rho_alu'], {'thickness': '(1)'}), '(E_alu, nu_alu, rho_alu, thic... |
import numpy as n, pylab as p, matplotlib
from scipy import stats
class NetworkPCA:
"""PCA cases of interest for observing stability in interaction networks.
1) Primacy of centrality measures for dispersion; and
2) precedence of symmetry over clustering;
3) average of all basic centrality... | [
"numpy.abs",
"numpy.argsort",
"pylab.figure",
"pylab.subplots_adjust",
"pylab.title",
"numpy.copy",
"pylab.ylabel",
"numpy.linalg.eig",
"pylab.xticks",
"pylab.suptitle",
"pylab.xlabel",
"numpy.cov",
"pylab.legend",
"pylab.subplot",
"numpy.dot",
"numpy.vstack",
"numpy.array",
"pylab... | [((621, 750), 'numpy.array', 'n.array', (['(network_measures.weighted_clusterings_, network_measures.degrees_,\n network_measures.weighted_directed_betweenness_)'], {}), '((network_measures.weighted_clusterings_, network_measures.degrees_,\n network_measures.weighted_directed_betweenness_))\n', (628, 750), True, ... |
from sys import path
path.append('./sunxspex')
from sunxspex import thermal_spectrum
from astropy import units as u
from astropy import constants as const
import numpy as np
from sunxspex.io import chianti_kev_cont_common_load, load_xray_abundances
from scipy.stats.mstats import gmean
from scipy.interpolate import inte... | [
"numpy.ones",
"numpy.clip",
"numpy.arange",
"numpy.exp",
"scipy.interpolate.interp1d",
"sys.path.append",
"numpy.isfinite",
"sunxspex.io.chianti_kev_cont_common_load",
"sunpy.coordinates.get_sunearth_distance",
"numpy.log10",
"sunxspex.io.load_xray_abundances",
"scipy.stats.mstats.gmean",
"n... | [((21, 46), 'sys.path.append', 'path.append', (['"""./sunxspex"""'], {}), "('./sunxspex')\n", (32, 46), False, 'from sys import path\n'), ((1560, 1648), 'sunxspex.thermal_spectrum.ChiantiThermalSpectrum', 'thermal_spectrum.ChiantiThermalSpectrum', (['energies'], {'abundance_type': '"""sun_coronal_ext"""'}), "(energies,... |
import numpy
import tarfile
import zipfile
import os
import shutil
from urllib.error import URLError, HTTPError
from urllib.request import urlretrieve
import tqdm
def get_file(fname, origin, untar=False, unzip=False, cache_subdir="datasets"):
"""Downloads a file from a URL if it not already in the cache."""
#... | [
"tqdm.tqdm",
"os.remove",
"zipfile.ZipFile",
"os.makedirs",
"numpy.asarray",
"numpy.zeros",
"os.path.exists",
"urllib.request.urlretrieve",
"numpy.max",
"os.path.isfile",
"numpy.array",
"numpy.arange",
"tarfile.open",
"shutil.rmtree",
"os.path.join",
"os.access",
"numpy.random.shuffl... | [((653, 693), 'os.path.join', 'os.path.join', (['datadir_base', 'cache_subdir'], {}), '(datadir_base, cache_subdir)\n', (665, 693), False, 'import os\n'), ((3023, 3053), 'numpy.random.shuffle', 'numpy.random.shuffle', (['examples'], {}), '(examples)\n', (3043, 3053), False, 'import numpy\n'), ((3449, 3493), 'numpy.zero... |
# ---------------------------
# <NAME>, <NAME>, <NAME> -- 2019
# The University of Oxford, The Alan Turing Institute
# contact: <EMAIL>, <EMAIL>, <EMAIL>
# ---------------------------
import tensorflow_probability as tfp
import functools
import itertools
import tensorflow as tf
import numpy as np
from tensorflow.ker... | [
"tensorflow.reduce_sum",
"tensorflow.keras.layers.Reshape",
"tensorflow.reshape",
"tensorflow.linalg.inv",
"numpy.prod",
"tensorflow.keras.layers.Flatten",
"tensorflow.python.ops.parallel_for.gradients.batch_jacobian",
"tensorflow.nn.softmax",
"tensorflow.random.uniform",
"tensorflow.keras.models.... | [((770, 821), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(0.5 * (labels - preds) ** 2)'], {'axis': '(-1)'}), '(0.5 * (labels - preds) ** 2, axis=-1)\n', (783, 821), True, 'import tensorflow as tf\n'), ((1096, 1223), 'functools.partial', 'functools.partial', (['Dense'], {'kernel_initializer': '"""glorot_normal"""', 'a... |
"""Classes and functions for operations with fmesh tallies.
Classes
-------
FMesh - class for storing individual fmesh tally data.
Functions
---------
read_meshtal(file) - reads all tallies from MCNP meshtal file.
read_meshtally(file) - reads individual fmesh tally from binary file (*.npy)
merge_tallies(*tally_weight... | [
"numpy.load",
"numpy.sum",
"mckit_meshes.mesh.geometry_spec.CartesianGeometrySpec",
"mckit_meshes.utils.rebin.rebin_spec_composer",
"pathlib.Path",
"numpy.isclose",
"mckit_meshes.mesh.geometry_spec.as_float_array",
"numpy.zeros_like",
"mckit_meshes.utils.rebin.trim_spec_composer",
"mckit_meshes.ut... | [((1724, 1751), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1741, 1751), False, 'import logging\n'), ((1788, 1809), 'mckit_meshes.utils.rebin.rebin_nd', 'rebin.rebin_nd', (['*args'], {}), '(*args)\n', (1802, 1809), True, 'import mckit_meshes.utils.rebin as rebin\n'), ((2569, 2583), 'n... |
import fnmatch
import os
import matplotlib.pyplot as plt
import numpy as np
import librosa
import tensorflow as tf
def files_within(directory_path, pattern="*"):
for dirpath, _, filenames in os.walk(directory_path):
for file_name in fnmatch.filter(filenames, pattern):
yield os.path.join(dirp... | [
"numpy.load",
"numpy.abs",
"numpy.sum",
"numpy.angle",
"numpy.floor",
"os.walk",
"numpy.empty",
"librosa.core.load",
"numpy.exp",
"os.path.join",
"numpy.expm1",
"numpy.random.choice",
"numpy.hanning",
"numpy.log10",
"numpy.random.shuffle",
"numpy.log1p",
"numpy.stack",
"numpy.conca... | [((199, 222), 'os.walk', 'os.walk', (['directory_path'], {}), '(directory_path)\n', (206, 222), False, 'import os\n'), ((610, 673), 'numpy.zeros', 'np.zeros', ([], {'shape': '(1, array.shape[0], slice_size, array.shape[2])'}), '(shape=(1, array.shape[0], slice_size, array.shape[2]))\n', (618, 673), True, 'import numpy ... |
import numpy as np
def datagen(x, m=5, c=10, seed=42):
np.random.seed(seed)
subset = np.random.choice(x, int(x.shape[0] * 0.8))
noise = np.random.normal(0, 1, subset.shape)
return np.reshape(subset, (-1,1)), np.reshape((subset + noise) * m + c, (-1,1)) | [
"numpy.random.seed",
"numpy.reshape",
"numpy.random.normal"
] | [((60, 80), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (74, 80), True, 'import numpy as np\n'), ((149, 185), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', 'subset.shape'], {}), '(0, 1, subset.shape)\n', (165, 185), True, 'import numpy as np\n'), ((197, 224), 'numpy.reshape', 'np.res... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 0.8.6
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Usage of modeling
#
# Pleas... | [
"matplotlib.pyplot.title",
"seaborn.heatmap",
"adhoc.modeling.show_feature_importance",
"sklearn.tree.DecisionTreeClassifier",
"matplotlib.pyplot.style.use",
"numpy.arange",
"pandas.DataFrame",
"sys.path.append",
"adhoc.modeling.ROCCurve",
"adhoc.utilities.facet_grid_scatter_plot",
"adhoc.modeli... | [((892, 924), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (905, 924), True, 'import matplotlib.pyplot as plt\n'), ((1077, 1110), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (1100, 1110), False, 'import warnin... |
from numpy.random import rand
from tensorboardX import SummaryWriter
import time
num_layers_options = [2, 3, 4]
hidden_size_options = [128, 256]
for num_layers in num_layers_options:
for hidden_size in hidden_size_options:
with SummaryWriter() as writer:
writer.add_hparams_start(dict(num_laye... | [
"numpy.random.rand",
"tensorboardX.SummaryWriter",
"time.sleep"
] | [((626, 639), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (636, 639), False, 'import time\n'), ((243, 258), 'tensorboardX.SummaryWriter', 'SummaryWriter', ([], {}), '()\n', (256, 258), False, 'from tensorboardX import SummaryWriter\n'), ((377, 383), 'numpy.random.rand', 'rand', ([], {}), '()\n', (381, 383), Fal... |
import pandas as pd
from sklearn.ensemble.forest import RandomForestClassifier
import numpy as np
features = {
"0":"Paralysis ", # partial body paralysis
"1":"Voice ",
"2":"Feeding_Tube " ,
"3": "Vision ",
"4": "Cognitive " ,
"5": "Perception " ,
"6": "Dressing " ,
"7":"Incontinence " ,
"8": "Emotions ",
"9" : "Sex " ... | [
"numpy.matrix",
"sklearn.ensemble.forest.RandomForestClassifier"
] | [((598, 638), 'sklearn.ensemble.forest.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(300)'}), '(n_estimators=300)\n', (620, 638), False, 'from sklearn.ensemble.forest import RandomForestClassifier\n'), ((673, 711), 'numpy.matrix', 'np.matrix', (['forest.feature_importances_'], {}), '(forest... |
import pytest
from scipy.stats.distributions import poisson
import statsmodels.api as sm
import numpy as np
@pytest.fixture
def scotland_data():
data = sm.datasets.scotland.load(as_pandas=False)
return data.exog, data.endog
@pytest.fixture
def poisson_data():
n_samples = 1000
int_coef, age_coef, weigh... | [
"numpy.random.uniform",
"scipy.stats.distributions.poisson.rvs",
"numpy.exp",
"numpy.random.normal",
"statsmodels.api.datasets.scotland.load",
"numpy.vstack"
] | [((157, 199), 'statsmodels.api.datasets.scotland.load', 'sm.datasets.scotland.load', ([], {'as_pandas': '(False)'}), '(as_pandas=False)\n', (182, 199), True, 'import statsmodels.api as sm\n'), ((355, 391), 'numpy.random.uniform', 'np.random.uniform', (['(30)', '(70)', 'n_samples'], {}), '(30, 70, n_samples)\n', (372, 3... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 15:45:49 2020
@author: peter
"""
import numpy as np
from pathlib import Path
import pandas as pd
import tifffile
from joblib import Parallel, delayed
from vsd_cancer.functions import cancer_functions as canf
def make_all_raw_tc(df_file, save_... | [
"vsd_cancer.functions.cancer_functions.t_course_from_roi",
"pandas.read_csv",
"vsd_cancer.functions.cancer_functions.lab2masks",
"pathlib.Path",
"numpy.array",
"joblib.Parallel",
"tifffile.imread",
"joblib.delayed"
] | [((370, 390), 'pandas.read_csv', 'pd.read_csv', (['df_file'], {}), '(df_file)\n', (381, 390), True, 'import pandas as pd\n'), ((1028, 1072), 'pathlib.Path', 'Path', (['save_dir', '"""ratio_stacks"""', 'trial_string'], {}), "(save_dir, 'ratio_stacks', trial_string)\n", (1032, 1072), False, 'from pathlib import Path\n'),... |
'''
Created on May 20, 2016
@author: josephbakarji
'''
import numpy as np
from notemidi import TrigNote, TrigNote_midinum, signswitch2note, TriggerChordTest, make_C2midi
from __init__ import settingsDir
from learning import Learn
from threading import Thread
from collections import deque
##########################... | [
"learning.Learn",
"threading.Thread.__init__",
"numpy.asarray",
"numpy.logical_not",
"numpy.zeros",
"notemidi.TrigNote_midinum",
"numpy.nonzero",
"notemidi.make_C2midi",
"notemidi.TrigNote",
"numpy.random.choice",
"notemidi.signswitch2note",
"notemidi.TriggerChordTest"
] | [((741, 762), 'numpy.asarray', 'np.asarray', (['sensvalue'], {}), '(sensvalue)\n', (751, 762), True, 'import numpy as np\n'), ((1021, 1047), 'numpy.logical_not', 'np.logical_not', (['turn_state'], {}), '(turn_state)\n', (1035, 1047), True, 'import numpy as np\n'), ((1723, 1744), 'threading.Thread.__init__', 'Thread.__i... |
"""Solvers take a mesh and return elementwise error estimate."""
import numpy as np
from skfem import (
CellBasis,
ElementTriP1,
Functional,
InteriorFacetBasis,
condense,
solve,
)
from skfem.helpers import grad
from skfem.models.poisson import laplace as laplacian
from skfem.models.poisson imp... | [
"numpy.sum",
"skfem.InteriorFacetBasis",
"numpy.zeros",
"skfem.ElementTriP1",
"skfem.models.poisson.unit_load.assemble",
"skfem.CellBasis",
"skfem.models.poisson.laplace.assemble",
"skfem.helpers.grad",
"numpy.add.at"
] | [((488, 502), 'skfem.ElementTriP1', 'ElementTriP1', ([], {}), '()\n', (500, 502), False, 'from skfem import CellBasis, ElementTriP1, Functional, InteriorFacetBasis, condense, solve\n'), ((515, 530), 'skfem.CellBasis', 'CellBasis', (['m', 'e'], {}), '(m, e)\n', (524, 530), False, 'from skfem import CellBasis, ElementTri... |
"""
Provides a base test class for other test classes to inherit from.
Includes the numpy testing functions as methods.
"""
import contextlib
import os.path
import sys
import unittest
from inspect import getsourcefile
import numpy as np
from numpy.testing import (
assert_allclose,
assert_almost_equal,
as... | [
"numpy.testing.assert_raises",
"numpy.testing.assert_almost_equal",
"numpy.testing.assert_array_almost_equal_nulp",
"numpy.testing.assert_array_equal",
"numpy.testing.assert_approx_equal",
"numpy.testing.assert_string_equal",
"numpy.testing.assert_equal",
"numpy.testing.assert_allclose",
"numpy.test... | [((2165, 2201), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['*args'], {}), '(*args, **kwargs)\n', (2184, 2201), False, 'from numpy.testing import assert_allclose, assert_almost_equal, assert_approx_equal, assert_array_almost_equal, assert_array_almost_equal_nulp, assert_array_equal, assert_array_less,... |
import h5py, time
import numpy as np
from utility import randomData
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.layers.wrappers import TimeDistributed
def buildModel(trainXShape, trainYShape, numLayers, neuonPerLayer):
... | [
"h5py.File",
"numpy.save",
"keras.layers.core.Dense",
"keras.layers.core.Activation",
"time.time",
"numpy.append",
"numpy.array",
"utility.randomData",
"keras.layers.recurrent.LSTM",
"keras.models.Sequential",
"numpy.concatenate"
] | [((399, 411), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (409, 411), False, 'from keras.models import Sequential\n'), ((895, 919), 'utility.randomData', 'randomData', (['f', 'numSample'], {}), '(f, numSample)\n', (905, 919), False, 'from utility import randomData\n'), ((932, 944), 'numpy.array', 'np.arr... |
"""
2.8 numpy copy & deep copy
"""
import numpy as np
a = np.arange(4)
print('array a:\n',a)
b = a
c = a
d = b
# 更改a[0]
a[0] = 11
print('更改a[0]的值为11\n',a[0])
print('b is a?\n', b is a)
print('b的值也会改变\n',b)
print('c is a?\n', c is a)
print('d is a?\n', d is a)
# 如果不想关联这些变量,则需要使用深拷贝(deep copy)
b = a.copy()
print(... | [
"numpy.arange"
] | [((62, 74), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (71, 74), True, 'import numpy as np\n')] |
import functools
import numpy as np
import pytest
import tensorflow as tf
from mock import mock
from tests.layers.convolutional.helper import (input_maybe_to_channels_last,
strides_tuple_to_channels_last,
output_maybe_to_cha... | [
"functools.partial",
"mock.mock.patch",
"tests.layers.convolutional.helper.strides_tuple_to_channels_last",
"numpy.zeros",
"numpy.transpose",
"pytest.raises",
"numpy.random.normal",
"tfsnippet.layers.shifted_conv2d",
"tfsnippet.layers.conv2d",
"tensorflow.Graph",
"tests.layers.convolutional.help... | [((591, 651), 'tests.layers.convolutional.helper.input_maybe_to_channels_last', 'input_maybe_to_channels_last', (['input'], {'data_format': 'data_format'}), '(input, data_format=data_format)\n', (619, 651), False, 'from tests.layers.convolutional.helper import input_maybe_to_channels_last, strides_tuple_to_channels_las... |
import math
import torch
import numpy as np
from sklearn.decomposition import PCA
import logging
logger = logging.getLogger('nmtpytorch')
def center_emb(x):
logger.info(f'Apply centering')
zero_rows = np.all(x == 0, axis=1)
# transform embedding to make the average to zero vector
# excluding zero vect... | [
"torch.cat",
"logging.getLogger",
"numpy.append",
"numpy.linalg.norm",
"sklearn.decomposition.PCA",
"torch.torch.from_numpy",
"numpy.all"
] | [((107, 138), 'logging.getLogger', 'logging.getLogger', (['"""nmtpytorch"""'], {}), "('nmtpytorch')\n", (124, 138), False, 'import logging\n'), ((211, 233), 'numpy.all', 'np.all', (['(x == 0)'], {'axis': '(1)'}), '(x == 0, axis=1)\n', (217, 233), True, 'import numpy as np\n'), ((459, 499), 'numpy.linalg.norm', 'np.lina... |
import numpy as np
import rospy
import cv2
from ..assignment.linear_assignment import LinearAssignment
from .monitor import Monitor
from ...utils.bbox_metrics import overlap
from ...utils.allocentric_spatial_relations import is_on_top, is_in, is_close
from ...utils.egocentric_spatial_relations import is_right_of, is_le... | [
"numpy.argmax"
] | [((7134, 7158), 'numpy.argmax', 'np.argmax', (['overlap_score'], {}), '(overlap_score)\n', (7143, 7158), True, 'import numpy as np\n')] |
import random
import numpy as np
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
class KimCNN(nn.Module):
def __init__(self, word_model, **config):
super().__init__()
n_fmaps = config.get("n_feature_maps", 100)
weight_lengths... | [
"torch.dot",
"torch.autograd.grad",
"numpy.empty",
"torch.nn.Embedding",
"torch.nn.Conv2d",
"random.sample",
"torch.cat",
"torch.max",
"torch.sum",
"torch.from_numpy"
] | [((1039, 1079), 'torch.autograd.grad', 'autograd.grad', (['output', 'self.sent_weights'], {}), '(output, self.sent_weights)\n', (1052, 1079), True, 'import torch.autograd as autograd\n'), ((1242, 1260), 'numpy.empty', 'np.empty', (['(sz, sz)'], {}), '((sz, sz))\n', (1250, 1260), True, 'import numpy as np\n'), ((1508, 1... |
import numpy as np
import matplotlib.pyplot as plt
identity = lambda x: x
class DenoisingAutoencoder(object):
"""
Denoising autoencoder.
"""
def sigmoid(self, x):
pos_mask = (x >= 0)
neg_mask = (x < 0)
z = np.zeros_like(x)
z[pos_mask] = np.exp(-x[pos_mask])
z[neg_mask] = ... | [
"numpy.zeros_like",
"numpy.random.seed",
"numpy.ones_like",
"numpy.sum",
"numpy.tanh",
"numpy.square",
"numpy.zeros",
"numpy.random.random",
"numpy.exp",
"numpy.random.choice",
"numpy.dot",
"numpy.sqrt"
] | [((242, 258), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (255, 258), True, 'import numpy as np\n'), ((279, 299), 'numpy.exp', 'np.exp', (['(-x[pos_mask])'], {}), '(-x[pos_mask])\n', (285, 299), True, 'import numpy as np\n'), ((320, 339), 'numpy.exp', 'np.exp', (['x[neg_mask]'], {}), '(x[neg_mask])\n', (... |
# Write the benchmarking functions here.
# See "Writing benchmarks" in the asv docs for more information.
import numpy as np
from tardis.tests import montecarlo_test_wrappers as montecarlo
LINE_SIZE = 10000000
class TimeSuite:
"""
An example benchmark that times the performance of various kinds
of itera... | [
"tardis.tests.montecarlo_test_wrappers.compute_distance2line_wrapper",
"tardis.tests.montecarlo_test_wrappers.compute_distance2electron_wrapper",
"numpy.random.random",
"numpy.arange",
"tardis.tests.montecarlo_test_wrappers.compute_distance2outer_wrapper",
"tardis.tests.montecarlo_test_wrappers.compute_di... | [((745, 801), 'tardis.tests.montecarlo_test_wrappers.compute_distance2outer_wrapper', 'montecarlo.compute_distance2outer_wrapper', (['(0.0)', '(0.5)', '(1.0)'], {}), '(0.0, 0.5, 1.0)\n', (786, 801), True, 'from tardis.tests import montecarlo_test_wrappers as montecarlo\n'), ((814, 870), 'tardis.tests.montecarlo_test_wr... |
import torch, os
from torch import nn
import numpy as np
from tqdm import tqdm
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from losses import SSIMLoss, generator_loss, discriminator_loss, generator_loss_separately, adversarial_loss, NRMSELoss, VGGPerceptualLoss
from plotter import plotter_GA... | [
"torch.optim.lr_scheduler.StepLR",
"numpy.sum",
"torch.ones",
"torch.nn.MSELoss",
"losses.SSIMLoss",
"plotter.plotter_UNET",
"plotter.plotter_GAN",
"losses.adversarial_loss",
"torch.sum",
"losses.discriminator_loss",
"torch.nn.Sigmoid",
"os.makedirs",
"torch.nn.L1Loss",
"os.path.isdir",
... | [((435, 447), 'torch.nn.Sigmoid', 'nn.Sigmoid', ([], {}), '()\n', (445, 447), False, 'from torch import nn\n'), ((1641, 1706), 'torch.optim.lr_scheduler.StepLR', 'StepLR', (['G_optimizer', 'hparams.step_size'], {'gamma': 'hparams.decay_gamma'}), '(G_optimizer, hparams.step_size, gamma=hparams.decay_gamma)\n', (1647, 17... |
#-*- coding:utf-8 -*-
import cv2
import numpy as np
###################################################
# O USO DE UM FILTRO PROS 'GOOD MATCHES' FAZ COM QUE HAJA UM DELAY DE ADAPTACAO
# (ao omitir a raposa, o programa ainda vai printar 'raposa encontrada' por alguns segundos)
# ISSO NAO É UM ERRO, É UMA CARACTERISTICA... | [
"numpy.dstack",
"cv2.Canny",
"cv2.HoughCircles",
"cv2.circle",
"numpy.median",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.FlannBasedMatcher",
"cv2.imshow",
"cv2.VideoCapture",
"cv2.imread",
"numpy.around",
"numpy.array",
"cv2.xfeatures2d.SIFT_create",
"cv2.destroyAllWindows",
"cv2.resize"
] | [((543, 562), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (559, 562), False, 'import cv2\n'), ((2746, 2775), 'cv2.xfeatures2d.SIFT_create', 'cv2.xfeatures2d.SIFT_create', ([], {}), '()\n', (2773, 2775), False, 'import cv2\n'), ((2952, 3002), 'cv2.FlannBasedMatcher', 'cv2.FlannBasedMatcher', (['index... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import random
import numpy as np
import matplotlib
from matplotlib.colors import LogNorm
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import mea... | [
"matplotlib.pyplot.title",
"numpy.absolute",
"numpy.sum",
"numpy.nan_to_num",
"matplotlib.pyplot.clf",
"numpy.argmax",
"random.sample",
"matplotlib.pyplot.bar",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.classification_report",
"numpy.isnan",
"matplotlib.pyplot.figure",
"numpy.mean",... | [((212, 233), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (226, 233), False, 'import matplotlib\n'), ((504, 531), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 9)'}), '(figsize=(16, 9))\n', (514, 531), True, 'import matplotlib.pyplot as plt\n'), ((595, 615), 'matplotlib.pypl... |
# 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 Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,... | [
"sklearn.utils.check_array",
"numpy.logical_not",
"numpy.zeros",
"numpy.argsort",
"sklearn.utils.check_consistent_length",
"numpy.issubdtype"
] | [((2803, 2865), 'sklearn.utils.check_consistent_length', 'check_consistent_length', (['event_indicator', 'event_time', 'estimate'], {}), '(event_indicator, event_time, estimate)\n', (2826, 2865), False, 'from sklearn.utils import check_consistent_length, check_array\n'), ((2889, 2934), 'sklearn.utils.check_array', 'che... |
import numpy as np
from stereosim.compute_coordinates import compute_coordinates
def compute_CAHVOR(pinhole_model):
"""
Computation of CAHVOR from photogrammetric parameters.
Parameters
----------
dict: dict
Takes dictionary containing photogrammetric camera Parameters
such as 'ca... | [
"numpy.array",
"stereosim.compute_coordinates.compute_coordinates"
] | [((1481, 1545), 'stereosim.compute_coordinates.compute_coordinates', 'compute_coordinates', (['A', "pinhole_model['az']", "pinhole_model['el']"], {}), "(A, pinhole_model['az'], pinhole_model['el'])\n", (1500, 1545), False, 'from stereosim.compute_coordinates import compute_coordinates\n'), ((1554, 1618), 'stereosim.com... |
import numpy as np
import pycpp_examples
from pytest import approx
import time
def test_pycpp_pose():
print(pycpp_examples)
print(dir(pycpp_examples))
Pose = pycpp_examples.Pose
pa = Pose(0, 0.2, 0.1)
pb = Pose(x=0.0, y=0.2, yaw=0.2)
odom = Pose.get_odom(pa, pb)
assert odom.x == approx(0.... | [
"time.time",
"pycpp_examples.sqrt_sum_vec",
"numpy.random.random",
"pytest.approx",
"numpy.sqrt"
] | [((578, 602), 'numpy.random.random', 'np.random.random', (['(500000)'], {}), '(500000)\n', (594, 602), True, 'import numpy as np\n'), ((616, 627), 'time.time', 'time.time', ([], {}), '()\n', (625, 627), False, 'import time\n'), ((725, 736), 'time.time', 'time.time', ([], {}), '()\n', (734, 736), False, 'import time\n')... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 28 13:27:32 2018
@author: <NAME>
"""
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import calinski_harabaz_score
from sklearn.cluster import AgglomerativeClustering
import numpy as np
import pca
import seaborn as sns
import matp... | [
"seaborn.lmplot",
"numpy.random.seed",
"pandas.DataFrame.from_dict",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.ylim",
"pandas.concat",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.Figure",
"os.path.dirname",
"pandas.merge",
"sklearn.metrics.calinski_harabaz_score",
"matplotl... | [((566, 583), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (580, 583), True, 'import numpy as np\n'), ((601, 663), 'sklearn.cluster.AgglomerativeClustering', 'AgglomerativeClustering', ([], {'n_clusters': 'num_groups', 'linkage': '"""ward"""'}), "(n_clusters=num_groups, linkage='ward')\n", (624, 663),... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# utils.py
"""
Utility functions for deconvolution
Copyright (c) 2016, <NAME>
"""
import numpy as np
from dphutils import radial_profile
def set_pyfftw_threads(threads=1):
"""A utility to set the number of threads to use in pyfftw"""
raise NotImplementedError
... | [
"numpy.fmax",
"numpy.sum",
"dphutils.radial_profile",
"numpy.empty",
"numpy.indices",
"numpy.finfo",
"numpy.arange",
"numpy.array",
"numpy.interp"
] | [((396, 412), 'numpy.fmax', 'np.fmax', (['data', '(0)'], {}), '(data, 0)\n', (403, 412), True, 'import numpy as np\n'), ((2541, 2562), 'numpy.indices', 'np.indices', (['datashape'], {}), '(datashape)\n', (2551, 2562), True, 'import numpy as np\n'), ((2710, 2732), 'numpy.arange', 'np.arange', (['half_yxsize'], {}), '(ha... |
import numpy as np
import matplotlib.pyplot as plt
import pickle
import matplotlib as mpl
mpl.rcParams['figure.dpi'] = 160
mpl.rc('text', usetex=True)
f1 = "coef_uc.dat"
f2 = "coef_ol.dat"
f3 = "coef_cl.dat"
cases = ['uncontrolled', 'open-loop controlled', 'closed-loop controlled']
data = {cases[0]: np.loadtxt(f1, u... | [
"matplotlib.rc",
"matplotlib.pyplot.subplots",
"numpy.loadtxt",
"matplotlib.pyplot.savefig"
] | [((123, 150), 'matplotlib.rc', 'mpl.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (129, 150), True, 'import matplotlib as mpl\n'), ((1356, 1384), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (1368, 1384), True, 'import matplotlib.pyplot as pl... |
"""Tests the functions to identify points in cycles work."""
import os
import numpy as np
from scipy.signal import argrelextrema
import pytest
from bycycle.cyclepoints import find_extrema, find_zerox, extrema_interpolated_phase
# Set data path
DATA_PATH = os.getcwd() + '/tutorials/data/'
###########################... | [
"numpy.load",
"bycycle.cyclepoints.find_extrema",
"bycycle.cyclepoints.extrema_interpolated_phase",
"os.getcwd",
"scipy.signal.argrelextrema",
"bycycle.cyclepoints.find_zerox",
"numpy.isclose",
"numpy.testing.assert_allclose",
"pytest.mark.xfail"
] | [((259, 270), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (268, 270), False, 'import os\n'), ((788, 829), 'numpy.load', 'np.load', (["(DATA_PATH + 'sim_stationary.npy')"], {}), "(DATA_PATH + 'sim_stationary.npy')\n", (795, 829), True, 'import numpy as np\n'), ((928, 958), 'scipy.signal.argrelextrema', 'argrelextrema', ... |
import unittest
import numpy as np
from bcipy.signal.evaluate.rules import Rule, HighVoltage, LowVoltage
from bcipy.signal.generator.generator import gen_random_data
class TestRules(unittest.TestCase):
"""Test Rules init and class methods """
def setUp(self):
"""Create rule objects to test """
... | [
"unittest.main",
"bcipy.signal.evaluate.rules.LowVoltage",
"numpy.random.randint",
"bcipy.signal.evaluate.rules.HighVoltage",
"bcipy.signal.generator.generator.gen_random_data"
] | [((2399, 2414), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2412, 2414), False, 'import unittest\n'), ((455, 490), 'bcipy.signal.evaluate.rules.HighVoltage', 'HighVoltage', (['self.highvoltage_value'], {}), '(self.highvoltage_value)\n', (466, 490), False, 'from bcipy.signal.evaluate.rules import Rule, HighVolt... |
""" Functions to generate the set of endpoints for the time series
benchmark on the HiRID database"""
import glob
import logging
import math
import os
import os.path
import pickle
import random
import sys
import lightgbm as lgbm
import numpy as np
import pandas as pd
import skfda.preprocessing.smoothing.kernel_sm... | [
"os.mkdir",
"numpy.absolute",
"sklearn.preprocessing.StandardScaler",
"numpy.sum",
"random.sample",
"sklearn.metrics.mean_absolute_error",
"numpy.isnan",
"pickle.load",
"os.path.join",
"pandas.DataFrame",
"numpy.zeros_like",
"numpy.copy",
"os.path.exists",
"numpy.isfinite",
"pandas.conca... | [((1061, 1082), 'numpy.copy', 'np.copy', (['pao2_est_arr'], {}), '(pao2_est_arr)\n', (1068, 1082), True, 'import numpy as np\n'), ((2304, 2356), 'logging.info', 'logging.info', (['"""Testing regression model for PaO2..."""'], {}), "('Testing regression model for PaO2...')\n", (2316, 2356), False, 'import logging\n'), (... |
import argparse
import numpy as np
import numpy.random as npr
import os
import scipy.misc
import torch
import torch.nn as nn
from colourization import (get_torch_vars, get_cat_rgb, get_rgb_cat,
process, UNet, CNN, DilatedUNet)
from load_data import load_cifar10
if __name__ == '__main__':
... | [
"numpy.pad",
"os.mkdir",
"numpy.load",
"colourization.DilatedUNet",
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.load",
"numpy.transpose",
"numpy.expand_dims",
"colourization.process",
"colourization.CNN",
"numpy.shape",
"colourization.get_rgb_cat",
"torch.max",
"colourization.... | [((332, 390), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train colourization"""'}), "(description='Train colourization')\n", (355, 390), False, 'import argparse\n'), ((1493, 1504), 'numpy.random.seed', 'npr.seed', (['(0)'], {}), '(0)\n', (1501, 1504), True, 'import numpy.random as np... |
from intersim.viz import Rasta
import numpy as np
def test_world_to_raster():
rasta = Rasta(
m_per_px = 0.5,
raster_fixpoint = (0.5, 0.5),
world_fixpoint = (100, 100),
camera_rotation = 0
)
coords = rasta._world_to_raster(
raster_shape=(50, 50),
points=np.arr... | [
"intersim.viz.Rasta",
"numpy.allclose",
"numpy.zeros",
"numpy.ones",
"numpy.array",
"numpy.tile"
] | [((91, 188), 'intersim.viz.Rasta', 'Rasta', ([], {'m_per_px': '(0.5)', 'raster_fixpoint': '(0.5, 0.5)', 'world_fixpoint': '(100, 100)', 'camera_rotation': '(0)'}), '(m_per_px=0.5, raster_fixpoint=(0.5, 0.5), world_fixpoint=(100, 100),\n camera_rotation=0)\n', (96, 188), False, 'from intersim.viz import Rasta\n'), ((... |
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import matplotlib.ticker as ticker
import matplotlib.animation as animation
import matplotlib.gridspec as gridspec
import pandas as pd
import numpy as np
import talib as ta
from matplotlib.dates import date2num
from matplotlib import sty... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"matplotlib.style.use",
"market_maker.utils.log.setup_custom_logger",
"matplotlib.animation.FuncAnimation",
"market_maker.plot.analysis.get_analysis",
"matplotlib.dates.DateFormatter",
"numpy.where",
"time.sleep",
"market_maker.utils.singleton.singleto... | [((534, 565), 'market_maker.utils.log.setup_custom_logger', 'log.setup_custom_logger', (['"""root"""'], {}), "('root')\n", (557, 565), False, 'from market_maker.utils import log\n'), ((587, 615), 'matplotlib.style.use', 'style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (596, 615), False, 'from matp... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from models.DCASE_baseline import AutoPool
from models.Time2vec import Time2Vec
from activation.mish import Mish
from torchlibrosa.augmentation import SpecAugmentation
class ConvBlock(nn.Module):
... | [
"torch.nn.Dropout",
"torch.bmm",
"torch.nn.functional.dropout",
"torch.nn.GroupNorm",
"torch.nn.init.constant_",
"torch.nn.Softmax",
"torchlibrosa.augmentation.SpecAugmentation",
"torch.no_grad",
"numpy.sqrt",
"numpy.power",
"torch.nn.LayerNorm",
"models.DCASE_baseline.AutoPool",
"torch.nn.L... | [((991, 1032), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['self.conv.weight'], {}), '(self.conv.weight)\n', (1014, 1032), True, 'import torch.nn as nn\n'), ((1140, 1149), 'torch.nn.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (1146, 1149), True, 'import torch.nn.functional as F\n'), ((2508, 2556... |
import numpy as np
from numpy.testing import (assert_almost_equal, assert_equal, assert_raises)
from statsmodels.base.transform import (BoxCox)
from statsmodels.datasets import macrodata
class TestTransform:
@classmethod
def setup_class(cls):
data = macrodata.load_pandas()
cls.x = data.data['... | [
"numpy.log",
"numpy.testing.assert_raises",
"numpy.testing.assert_almost_equal",
"statsmodels.base.transform.BoxCox",
"numpy.arange",
"numpy.testing.assert_equal",
"statsmodels.datasets.macrodata.load_pandas"
] | [((269, 292), 'statsmodels.datasets.macrodata.load_pandas', 'macrodata.load_pandas', ([], {}), '()\n', (290, 292), False, 'from statsmodels.datasets import macrodata\n'), ((354, 362), 'statsmodels.base.transform.BoxCox', 'BoxCox', ([], {}), '()\n', (360, 362), False, 'from statsmodels.base.transform import BoxCox\n'), ... |
# -*- coding: utf-8 -*-
import scipy.linalg as la
import numpy as np
from pyyeti import expmint
from ._base_ode_class import _BaseODE
# FIXME: We need the str/repr formatting used in Numpy < 1.14.
try:
np.set_printoptions(legacy="1.13")
except TypeError:
pass
class SolveExp2(_BaseODE):
r"""
2nd orde... | [
"numpy.set_printoptions",
"numpy.eye",
"scipy.linalg.lu_solve",
"pyyeti.expmint.getEPQ",
"numpy.atleast_2d"
] | [((208, 242), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'legacy': '"""1.13"""'}), "(legacy='1.13')\n", (227, 242), True, 'import numpy as np\n'), ((13456, 13476), 'numpy.atleast_2d', 'np.atleast_2d', (['force'], {}), '(force)\n', (13469, 13476), True, 'import numpy as np\n'), ((10929, 10967), 'pyyeti.expmi... |
import numpy as np
class Objeto(object):
def __init__(self):
super(Objeto, self).__init__()
self.x = 0
self.y = 0
self.velocidade = [0,0]
class Circulo(Objeto) :
def __init__(self, massa, x, y, raio, cor = (255,0,0)):
super(Circulo, self).__init__()
self.massa... | [
"numpy.dot",
"numpy.sin",
"numpy.array",
"numpy.cos"
] | [((884, 1164), 'numpy.array', 'np.array', (['[[self.x - self.largura / 2, self.y - self.comprimento / 2], [self.x + self\n .largura / 2, self.y - self.comprimento / 2], [self.x + self.largura / \n 2, self.y + self.comprimento / 2], [self.x - self.largura / 2, self.y +\n self.comprimento / 2]]'], {'dtype': 'np.... |
import os
import json
from glob import glob
import numpy as np
import pandas as pd
MAPPINGS = {
"mappings": {
"Cruise ID": "cruise",
"Unnamed: 1": "date",
"Latitude": "latitude",
"Longitude": "longitude",
"Sampling Depth (meters)": "depth",
"Station": "cast",
... | [
"os.path.exists",
"pandas.read_excel",
"numpy.where",
"pandas.to_datetime",
"os.path.join",
"pandas.concat"
] | [((3262, 3289), 'os.path.exists', 'os.path.exists', (['report_path'], {}), '(report_path)\n', (3276, 3289), False, 'import os\n'), ((3388, 3466), 'pandas.read_excel', 'pd.read_excel', (['report_path'], {'skiprows': '(8)', 'dtype': '{Y: str, M: str, D: str, T: str}'}), '(report_path, skiprows=8, dtype={Y: str, M: str, D... |
# -*- coding: utf-8 -*-
"""
Shunt Architectures.
Copyright 2021 Christian Doppler Laboratory for Embedded Machine Learning
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... | [
"keras_applications.correct_pad",
"tensorflow.keras.layers.BatchNormalization",
"numpy.log2",
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.Model",
"tensorflow.keras.layers.Input",
"tensorflow.keras.regularizers.l2"
] | [((1482, 1506), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (1487, 1506), False, 'from tensorflow.keras.layers import Input, Conv2D, DepthwiseConv2D, BatchNormalization, ReLU, Add, Concatenate, Activation, ZeroPadding2D\n'), ((4299, 4347), 'tensorflow.keras.Model',... |
#!/usr/bin/env python3
"""
@author: <NAME>
@email: <EMAIL>
* FORCE MODULE *
Contains force calculations (and potential energies) using known potentials:
- Gravitational
- Lennard-Jones
Latest update: May 7th 2021
"""
import numpy as np
import system
from numba import jit, njit, vectorize
epsilon = None
sigm... | [
"numpy.stack",
"numpy.divide",
"numpy.sum",
"numpy.triu",
"numpy.power",
"numpy.asarray",
"numpy.transpose",
"numpy.ones",
"numpy.reciprocal",
"numpy.cumsum",
"numpy.linspace",
"numpy.sign",
"numpy.eye",
"numpy.sqrt"
] | [((1931, 1965), 'numpy.linspace', 'np.linspace', (['(0.0)', 'max_dist', 'n_bins'], {}), '(0.0, max_dist, n_bins)\n', (1942, 1965), True, 'import numpy as np\n'), ((4507, 4526), 'numpy.sum', 'np.sum', (['f_x'], {'axis': '(0)'}), '(f_x, axis=0)\n', (4513, 4526), True, 'import numpy as np\n'), ((4539, 4558), 'numpy.sum', ... |
import os, argparse
import numpy as np
import torch
import cv2
from torchvision.utils import save_image, make_grid
from model import FactorVAE
from dataset import return_data
from gradcam import GradCAM
def load_checkpoint(model, ckpt_dir, ckptname, device, verbose=True):
filepath = os.path.join(ckpt_dir, ckptna... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.argmax",
"torch.cat",
"os.path.isfile",
"numpy.arange",
"model.FactorVAE",
"cv2.imshow",
"gradcam.GradCAM",
"os.path.join",
"torch.load",
"numpy.max",
"dataset.return_data",
"numpy.uint8",
"cv2.waitKey",
"numpy.asarray",
"torch.m... | [((291, 323), 'os.path.join', 'os.path.join', (['ckpt_dir', 'ckptname'], {}), '(ckpt_dir, ckptname)\n', (303, 323), False, 'import os, argparse\n'), ((331, 355), 'os.path.isfile', 'os.path.isfile', (['filepath'], {}), '(filepath)\n', (345, 355), False, 'import os, argparse\n'), ((1737, 1751), 'numpy.uint8', 'np.uint8',... |
from picket.globalvar import *
from picket.preprocessor.embeddings import load_embedding
from collections import OrderedDict
from tqdm import tqdm
import pandas as pd
import numpy as np
import json, logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class Dataset(object)... | [
"logging.basicConfig",
"pandas.read_csv",
"logging.getLogger",
"picket.preprocessor.embeddings.load_embedding",
"collections.OrderedDict",
"pandas.to_numeric",
"pandas.concat",
"numpy.issubdtype"
] | [((208, 229), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (227, 229), False, 'import json, logging\n'), ((239, 266), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (256, 266), False, 'import json, logging\n'), ((580, 595), 'collections.OrderedDict', 'OrderedDict', (['{... |
#######################################################################
# Copyright (C) 2016 <NAME>(<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
##############################################################... | [
"functools.partial",
"matplotlib.pyplot.show",
"numpy.sum",
"numpy.copy",
"numpy.abs",
"matplotlib.pyplot.plot",
"numpy.power",
"numpy.asarray",
"matplotlib.pyplot.legend",
"numpy.zeros",
"numpy.random.seed",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.random.choice",
"matplotlib.... | [((516, 538), 'numpy.zeros', 'np.zeros', (['(N_STATES + 2)'], {}), '(N_STATES + 2)\n', (524, 538), True, 'import numpy as np\n'), ((589, 615), 'numpy.arange', 'np.arange', (['(1)', '(N_STATES + 1)'], {}), '(1, N_STATES + 1)\n', (598, 615), True, 'import numpy as np\n'), ((820, 849), 'numpy.asarray', 'np.asarray', (['[0... |
import torch.nn as nn
import torch
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn import Parameter
import math
USE_CUDA = torch.cuda.is_available()
class CNN(nn.Module):
"""
input: [batch_size, 3, 64, 128]
output: [batch_size, 32, 256]
"""
d... | [
"torch.nn.Dropout",
"torch.bmm",
"torch.nn.Embedding",
"torch.cat",
"torch.nn.LayerNorm",
"torch.Tensor",
"torch.nn.Linear",
"torch.zeros",
"torch.matmul",
"torch.nn.Parameter",
"torch.nn.GRU",
"torch.nn.Tanh",
"torch.nn.Conv2d",
"torch.nn.BatchNorm2d",
"torch.cuda.is_available",
"torc... | [((178, 203), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (201, 203), False, 'import torch\n'), ((414, 429), 'torch.nn.Sequential', 'nn.Sequential', ([], {}), '()\n', (427, 429), True, 'import torch.nn as nn\n'), ((1527, 1606), 'torch.nn.GRU', 'nn.GRU', (['(256)', 'rnn_hidden_size', 'num_rnn... |
"""Get an input to cmdstanpy.CmdStanModel.sample from a pd.DataFrame."""
import itertools
import logging
import re
import time
from dataclasses import dataclass
from typing import Dict, List
import numpy as np
import pandas as pd
from scipy.linalg import null_space
from .util import codify, rref, get_free_fluxes
logg... | [
"pandas.DataFrame",
"numpy.identity",
"re.escape",
"numpy.linalg.matrix_rank",
"pandas.Series",
"pandas.concat",
"logging.getLogger"
] | [((325, 352), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (342, 352), False, 'import logging\n'), ((7037, 7092), 'pandas.DataFrame', 'pd.DataFrame', (['(0)'], {'columns': 'base_ordering', 'index': 'S.columns'}), '(0, columns=base_ordering, index=S.columns)\n', (7049, 7092), True, 'impo... |
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from scipy import signal
from . import exp_decay, exp_decay_sin, get_calibration_dict, get_title, \
save_fig, smooth_data_butter, smooth_data_SG, plot_cf_data, \
get_sample_name, g_from_qubi... | [
"numpy.multiply",
"numpy.amin",
"numpy.argmax",
"matplotlib.pyplot.subplots",
"scipy.optimize.curve_fit",
"numpy.argmin",
"numpy.amax",
"matplotlib.ticker.FormatStrFormatter",
"numpy.linspace",
"numpy.diag",
"matplotlib.pyplot.tight_layout"
] | [((786, 806), 'numpy.linspace', 'np.linspace', (['(50)', '(150)'], {}), '(50, 150)\n', (797, 806), True, 'import numpy as np\n'), ((5418, 5433), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (5430, 5433), True, 'import matplotlib.pyplot as plt\n'), ((6469, 6487), 'matplotlib.pyplot.tight_layout'... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 11 09:56:39 2017
@author: <NAME>
"""
"""
This script visualizes data using matplotlib
``Execute``
$ python matplotlib_viz.py
"""
import numpy as np
import matplotlib.pyplot as plt
if __name__=='__main__':
# sample plot
x = np.linspace(-10, 10... | [
"matplotlib.pyplot.title",
"numpy.abs",
"matplotlib.pyplot.subplot2grid",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.arange",
"matplotlib.pyplot.gca",
"numpy.tan",
"matplotlib.pyplot.rcParams.update",
"numpy.linspace",
"numpy.log10",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show... | [((301, 325), 'numpy.linspace', 'np.linspace', (['(-10)', '(10)', '(50)'], {}), '(-10, 10, 50)\n', (312, 325), True, 'import numpy as np\n'), ((332, 341), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (338, 341), True, 'import numpy as np\n'), ((351, 365), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\... |
import os
from os.path import join
from ...Functions.FEMM.draw_FEMM import draw_FEMM
from ...Functions.Electrical.coordinate_transformation import n2dq
from ...Classes._FEMMHandler import _FEMMHandler
from ...Classes.OutMagFEMM import OutMagFEMM
from numpy import linspace, pi, split
from SciDataTool.Classes.Data1D imp... | [
"SciDataTool.Classes.Data1D.Data1D",
"os.makedirs",
"os.path.exists",
"numpy.linspace",
"os.path.join"
] | [((1057, 1079), 'os.path.join', 'join', (['path_res', '"""Femm"""'], {}), "(path_res, 'Femm')\n", (1061, 1079), False, 'from os.path import join\n'), ((1466, 1491), 'os.path.join', 'join', (['save_dir', 'file_name'], {}), '(save_dir, file_name)\n', (1470, 1491), False, 'from os.path import join\n'), ((2248, 2353), 'Sci... |
import torch
import numpy as np
from sklearn.model_selection import train_test_split
from hpbandster.core.worker import Worker
import ConfigSpace.hyperparameters as CSH
import ConfigSpace as CS
from src.probability import pMOM_loglike, diag_w_Gauss_loglike, depth_categorical_VI
from src.utils import Datafeed
from src.... | [
"src.DUN.stochastic_fc_models.arq_uncert_fc_MLP",
"sklearn.model_selection.train_test_split",
"src.utils.Datafeed",
"numpy.argmin",
"src.datasets.load_flight",
"numpy.isnan",
"ConfigSpace.EqualsCondition",
"ConfigSpace.hyperparameters.UniformFloatHyperparameter",
"ConfigSpace.ConfigurationSpace",
... | [((25852, 25873), 'numpy.argmin', 'np.argmin', (['valid_NLLs'], {}), '(valid_NLLs)\n', (25861, 25873), True, 'import numpy as np\n'), ((1040, 1134), 'ConfigSpace.hyperparameters.UniformFloatHyperparameter', 'CSH.UniformFloatHyperparameter', (['"""lr"""'], {'lower': '(0.0001)', 'upper': '(1)', 'default_value': '(0.01)',... |
#!/usr/bin/env python
import argparse
import os
def main():
last = sorted(args.snapshots, key=os.path.getmtime)
last = last[-args.num:]
print("average over", last)
avg = None
if args.backend == 'pytorch':
import torch
# sum
for path in last:
states = torch.load... | [
"numpy.load",
"argparse.ArgumentParser",
"torch.save",
"numpy.savez_compressed",
"torch.device"
] | [((1521, 1546), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1544, 1546), False, 'import argparse\n'), ((649, 674), 'torch.save', 'torch.save', (['avg', 'args.out'], {}), '(avg, args.out)\n', (659, 674), False, 'import torch\n'), ((1289, 1325), 'numpy.savez_compressed', 'np.savez_compressed'... |
import cv2
import numpy as np
def apply_merge_transformations(
image, kernels, transformations=(cv2.MORPH_OPEN, 1), plot=False):
"""
Process image by applying morphological transformations using OpenCV.
It takes in a list of kernels as an input and itterates through that list applying each transor... | [
"numpy.zeros_like",
"numpy.count_nonzero",
"cv2.waitKey",
"cv2.morphologyEx",
"cv2.threshold",
"numpy.zeros",
"numpy.ones",
"cv2.imread",
"numpy.mean",
"cv2.rectangle",
"cv2.imshow"
] | [((1185, 1205), 'numpy.zeros_like', 'np.zeros_like', (['image'], {}), '(image)\n', (1198, 1205), True, 'import numpy as np\n'), ((8412, 8433), 'numpy.count_nonzero', 'np.count_nonzero', (['img'], {}), '(img)\n', (8428, 8433), True, 'import numpy as np\n'), ((1478, 1525), 'cv2.threshold', 'cv2.threshold', (['image', '(0... |
import albumentations as A
import mmcv
import numpy as np
from mmcv.runner import obj_from_dict
from numpy import random
from . import transforms
class PhotoMetricDistortion(object):
def __init__(self,
brightness_delta=32,
contrast_range=(0.5, 1.5),
saturation_r... | [
"numpy.random.uniform",
"mmcv.runner.obj_from_dict",
"mmcv.bgr2hsv",
"numpy.random.randint",
"numpy.array",
"numpy.tile",
"numpy.random.permutation",
"mmcv.hsv2bgr"
] | [((675, 692), 'numpy.random.randint', 'random.randint', (['(2)'], {}), '(2)\n', (689, 692), False, 'from numpy import random\n'), ((949, 966), 'numpy.random.randint', 'random.randint', (['(2)'], {}), '(2)\n', (963, 966), False, 'from numpy import random\n'), ((1227, 1244), 'mmcv.bgr2hsv', 'mmcv.bgr2hsv', (['img'], {}),... |
import os
import logging
import datetime
import numpy as np
import pandas as pd
from collections import OrderedDict
from .utils import (calc_num_na, load_data, inverse_logit,
choose_from_binary_probs, choose_from_multinomial_probs)
from .config import DATA_DIR, MODEL_FILES
log = logging.getLogger... | [
"pandas.DataFrame",
"numpy.random.uniform",
"os.path.exists",
"numpy.ones",
"pandas.notnull",
"collections.OrderedDict",
"os.path.join",
"logging.getLogger"
] | [((303, 330), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (320, 330), False, 'import logging\n'), ((346, 374), 'os.path.join', 'os.path.join', (['DATA_DIR', 'item'], {}), '(DATA_DIR, item)\n', (358, 374), False, 'import os\n'), ((443, 476), 'os.path.join', 'os.path.join', (['DATA_DIR',... |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from bld.project_paths import project_paths_join as ppj
from src.simulation_study.data_generating_process import data_generating_process
from src.simulation_study.sim_study import fix_simulation_params
np.random.seed(123)
data_dict = {}
for mo... | [
"matplotlib.pyplot.title",
"seaborn.set_style",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.axvline",
"numpy.random.seed",
"bld.project_paths.project_paths_join",
"numpy.floor",
"src.simulation_study.sim_study.fix_simulation_params",
"seaborn.regplot",
"matplotlib.pyplot.subplots_adjust",
"m... | [((278, 297), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (292, 297), True, 'import numpy as np\n'), ((1494, 1520), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (1507, 1520), True, 'import seaborn as sns\n'), ((1532, 1574), 'matplotlib.pyplot.subplots', 'plt... |
"""
pip to do :
pip install QtAwesome
pip install pygmsh
pip install gmsh
"""
import sys
import os
from PyQt5.QtWidgets import *
#QMainWindow,QApplication,QRadioButton,QWidget,QPushButton,QAction,QLineEdit,QGridLayout,QGroupBox,QMessageBox,QHBoxLayout,QComboBox,QVBoxLayout,QLabel,QStatusBar,QCheckBox,QSlider,QFileDi... | [
"os.getcwd",
"qtawesome.icon",
"os.system",
"numpy.sin",
"numpy.arange",
"matplotlib.pyplot.subplots",
"os.chdir"
] | [((708, 745), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 4)', 'dpi': '(200)'}), '(figsize=(5, 4), dpi=200)\n', (720, 745), True, 'import matplotlib.pyplot as plt\n'), ((817, 837), 'numpy.arange', 'np.arange', (['(0)', '(2)', '(0.1)'], {}), '(0, 2, 0.1)\n', (826, 837), True, 'import numpy as np\... |
import numpy as np
def point_cross_cnt_arr(x_arr: np.array, y_arr: np.array, c: int) -> np.array:
base_arr = (x_arr == c)
compare_arr = (y_arr == c)
# row
sum_i = base_arr.sum(axis=1, keepdims=True)
row_loss = (sum_i != compare_arr).astype(int).sum()
# col
sum_j = base_arr.sum(axis=0, kee... | [
"numpy.zeros",
"numpy.minimum",
"numpy.array",
"numpy.ones"
] | [((416, 444), 'numpy.minimum', 'np.minimum', (['(sum_i + sum_j)', '(1)'], {}), '(sum_i + sum_j, 1)\n', (426, 444), True, 'import numpy as np\n'), ((648, 711), 'numpy.array', 'np.array', (['[del_loss, keep_loss, row_loss, col_loss, cross_loss]'], {}), '([del_loss, keep_loss, row_loss, col_loss, cross_loss])\n', (656, 71... |
"""
Test a trained autoencoder
"""
import argparse
import os
import random
import time
import cv2 # pytype: disable=import-error
import imgaug
import numpy as np
import torch as th
from ae.autoencoder import load_ae, preprocess_image
from ae.data_loader import CheckFliplrPostProcessor, get_image_augmenter
parser = ... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"numpy.random.randint",
"numpy.mean",
"ae.data_loader.CheckFliplrPostProcessor",
"cv2.imshow",
"numpy.std",
"numpy.max",
"random.seed",
"ae.autoencoder.preprocess_image",
"cv2.waitKey",
"torch.manual_seed",
"numpy.median",
"numpy.min",
"tor... | [((320, 345), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (343, 345), False, 'import argparse\n'), ((1151, 1172), 'ae.autoencoder.load_ae', 'load_ae', (['args.ae_path'], {}), '(args.ae_path)\n', (1158, 1172), False, 'from ae.autoencoder import load_ae, preprocess_image\n'), ((1254, 1270), 'n... |
import numpy as np
from scipy.fftpack import fft2,ifft2
from cqt_toolbox.icqt import icqt
def inv_mcft(mcft_in, cqt_params, fbank_sr_domain):
"""
This function reconstructs a time-doman signal given its
Multi-resolution Common Fate Transform (MCFT).
The intermediary time-frequency domain representation... | [
"numpy.conj",
"cqt_toolbox.icqt.icqt",
"numpy.zeros",
"numpy.shape",
"scipy.fftpack.ifft2",
"scipy.fftpack.fft2"
] | [((1979, 1998), 'cqt_toolbox.icqt.icqt', 'icqt', (['cqt_dict_full'], {}), '(cqt_dict_full)\n', (1983, 1998), False, 'from cqt_toolbox.icqt import icqt\n'), ((2695, 2712), 'numpy.shape', 'np.shape', (['mcft_in'], {}), '(mcft_in)\n', (2703, 2712), True, 'import numpy as np\n'), ((2778, 2831), 'numpy.zeros', 'np.zeros', (... |
import numpy as np
import utils.make_coordinates as make_coordinates
def averaged_slope_intercept(image, lines, left, right):
left_fit=[]
right_fit=[]
global left_avg
global right_avg
try:
for line in lines:
x1, y1, x2, y2 = line.reshape(4)
parameters = np.polyfit((... | [
"numpy.array",
"utils.make_coordinates.make_coordinates",
"numpy.average",
"numpy.polyfit"
] | [((751, 779), 'numpy.average', 'np.average', (['left_fit'], {'axis': '(0)'}), '(left_fit, axis=0)\n', (761, 779), True, 'import numpy as np\n'), ((804, 833), 'numpy.average', 'np.average', (['right_fit'], {'axis': '(0)'}), '(right_fit, axis=0)\n', (814, 833), True, 'import numpy as np\n'), ((1009, 1059), 'utils.make_co... |
from bimt.query.cfg import config
import xml.etree.ElementTree as ET
import pandas as pd
import numpy as np
class ProcessQuery:
def __init__(self, xml_file):
self.xml_file = xml_file
def transform(self, raw_query):
query = raw_query.strip(";,?!()\{\}\\/'")
query = query.upper()
... | [
"pandas.DataFrame",
"xml.etree.ElementTree.parse",
"numpy.mean",
"numpy.ravel"
] | [((856, 883), 'pandas.DataFrame', 'pd.DataFrame', (['consulta_data'], {}), '(consulta_data)\n', (868, 883), True, 'import pandas as pd\n'), ((1076, 1097), 'numpy.mean', 'np.mean', (['score_values'], {}), '(score_values)\n', (1083, 1097), True, 'import numpy as np\n'), ((1728, 1752), 'numpy.ravel', 'np.ravel', (['espera... |
#%% import different modules
import matplotlib
import matplotlib.pyplot as plt
from one_step_kmeans_method import *
import numpy as np
import numpy.linalg as li
from generate_data import *
from measure_error import *
from ADMM_sidel_method import *
from cvx_siedel_method import *
from ADMM_siedel_tv_method import *
fr... | [
"numpy.size",
"matplotlib.pyplot.show",
"numpy.multiply",
"matplotlib.pyplot.plot",
"numpy.power",
"matplotlib.pyplot.legend",
"numpy.ones",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.vstack"
] | [((3118, 3136), 'numpy.size', 'np.size', (['verbose_a'], {}), '(verbose_a)\n', (3125, 3136), True, 'import numpy as np\n'), ((3144, 3174), 'numpy.linspace', 'np.linspace', (['(0)', '(size - 1)', 'size'], {}), '(0, size - 1, size)\n', (3155, 3174), True, 'import numpy as np\n'), ((3181, 3195), 'matplotlib.pyplot.subplot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.