code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 25 12:48:20 2018
@author: <EMAIL>
"""
def swap_matrix_element (A, P):
import random as r
S1 = len(A)
S2 = len(A[0])
for i in range(P):
row1 = r.randint(0, S1-1)
row2 = r.randint(0, S1-1)
col1 = r.randint(0, S2-1)
col2 = r.r... | [
"random.randint",
"numpy.isnan"
] | [((215, 235), 'random.randint', 'r.randint', (['(0)', '(S1 - 1)'], {}), '(0, S1 - 1)\n', (224, 235), True, 'import random as r\n'), ((249, 269), 'random.randint', 'r.randint', (['(0)', '(S1 - 1)'], {}), '(0, S1 - 1)\n', (258, 269), True, 'import random as r\n'), ((283, 303), 'random.randint', 'r.randint', (['(0)', '(S2... |
import numpy as np
import keras,gc,nltk
import pandas as pd
from keras.utils import to_categorical
from sklearn import preprocessing
from supervised_BAE import *
from utils import *
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from sklearn import preprocessing
from utils ... | [
"numpy.load",
"numpy.random.seed",
"keras.datasets.cifar10.load_data",
"sklearn.preprocessing.StandardScaler",
"numpy.random.shuffle",
"numpy.asarray",
"utils.sample_test_mask",
"time.perf_counter",
"sklearn.preprocessing.LabelEncoder",
"numpy.zeros",
"gc.collect",
"numpy.concatenate",
"kera... | [((451, 483), 'numpy.random.seed', 'np.random.seed', (['__random_state__'], {}), '(__random_state__)\n', (465, 483), True, 'import numpy as np\n'), ((597, 631), 'keras.datasets.cifar10.load_data', 'keras.datasets.cifar10.load_data', ([], {}), '()\n', (629, 631), False, 'import keras, gc, nltk\n'), ((745, 794), 'numpy.a... |
from __future__ import division, print_function, absolute_import
from shutil import copyfile
from src.TensorFlowModels import ModelConfig
from src.Miscellaneous import bcolors
import os
import glob
import tflearn
import numpy as np
import pandas as pd
import tensorflow as tf
import src.TensorFlowModels as TFModels
i... | [
"os.remove",
"pandas.read_csv",
"tensorflow.reset_default_graph",
"numpy.shape",
"glob.glob",
"os.path.exists",
"tensorflow.variable_scope",
"numpy.reshape",
"shutil.copyfile",
"numpy.ceil",
"matplotlib.use",
"src.TensorFlowModels.ModelConfig",
"os.makedirs",
"numpy.isscalar",
"os.path.i... | [((337, 358), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (351, 358), False, 'import matplotlib\n'), ((778, 791), 'src.TensorFlowModels.ModelConfig', 'ModelConfig', ([], {}), '()\n', (789, 791), False, 'from src.TensorFlowModels import ModelConfig\n'), ((3483, 3507), 'tensorflow.reset_default_... |
# ------------------------------------------------------------------------------
# Program: The LDAR Simulator (LDAR-Sim)
# File: methods.deployment.OGI_Camera
# Purpose: OGI company specific deployment classes and methods based on RK (2018)
#
# Copyright (C) 2018-2021 Intelligent Methane Monitoring and... | [
"math.exp",
"numpy.random.binomial",
"methods.funcs.measured_rate",
"math.log10",
"numpy.random.normal",
"utils.attribution.update_tag"
] | [((1428, 1454), 'numpy.random.normal', 'np.random.normal', (['(4.9)', '(0.3)'], {}), '(4.9, 0.3)\n', (1444, 1454), True, 'import numpy as np\n'), ((1468, 1555), 'numpy.random.normal', 'np.random.normal', (["self.config['sensor']['MDL'][0]", "self.config['sensor']['MDL'][1]"], {}), "(self.config['sensor']['MDL'][0], sel... |
import numpy as np
from tilitools.svdd_dual_qp import SvddDualQP
class LatentSVDD:
""" Latent variable support vector data description.
Written by <NAME>, TU Berlin, 2014
For more information see:
'Learning and Evaluation with non-i.i.d Label Noise'
Goernitz et al., AISTATS & JML... | [
"numpy.array",
"tilitools.svdd_dual_qp.SvddDualQP",
"numpy.zeros",
"numpy.random.randn"
] | [((1386, 1405), 'numpy.zeros', 'np.zeros', (['(DIMS, N)'], {}), '((DIMS, N))\n', (1394, 1405), True, 'import numpy as np\n'), ((1439, 1458), 'numpy.zeros', 'np.zeros', (['(DIMS, N)'], {}), '((DIMS, N))\n', (1447, 1458), True, 'import numpy as np\n'), ((2933, 2944), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2941... |
#!/usr/bin/env python
# coding: utf-8
# # ml lab5
# In[7]:
import os
import numpy as np
import scipy.optimize as opt
import scipy.io
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# ### 1. read `ex5data1.mat`
# In[4]:
data = scipy.io.loadmat('data/ex5data1.mat')
X = data['X']
y = np.squeez... | [
"sklearn.feature_extraction.text.CountVectorizer",
"numpy.sum",
"nltk.stem.PorterStemmer",
"matplotlib.pyplot.gca",
"sklearn.model_selection.train_test_split",
"numpy.zeros",
"numpy.argmin",
"re.sub",
"numpy.mean",
"numpy.array",
"numpy.arange",
"sklearn.svm.SVC",
"numpy.squeeze",
"sklearn... | [((311, 332), 'numpy.squeeze', 'np.squeeze', (["data['y']"], {}), "(data['y'])\n", (321, 332), True, 'import numpy as np\n'), ((839, 854), 'sklearn.svm.LinearSVC', 'svm.LinearSVC', ([], {}), '()\n', (852, 854), False, 'from sklearn import svm\n'), ((962, 1010), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2... |
import numpy as np
class simulated_parameter:
def __init__(self, parameter_name, parameter_mean, parameter_stddev, start_year, end_year):
self._parameter_name = parameter_name
self._parameter_mean = parameter_mean
self._parameter_stddev = parameter_stddev
self._start_year = start_... | [
"numpy.random.normal"
] | [((410, 495), 'numpy.random.normal', 'np.random.normal', ([], {'loc': 'self._parameter_mean', 'scale': 'self._parameter_stddev', 'size': '(1)'}), '(loc=self._parameter_mean, scale=self._parameter_stddev, size=1\n )\n', (426, 495), True, 'import numpy as np\n')] |
import numpy as np
import keras.backend as K
from keras.layers import Layer
class LinearLayer(Layer):
""" linear regression score by using ids of user/item """
def __init__(self, num_user, num_item, **kwargs):
super(LinearLayer, self).__init__(**kwargs)
self.b_u = K.variable(np.zeros((num_user... | [
"keras.backend.reshape",
"numpy.zeros",
"keras.backend.gather"
] | [((887, 917), 'keras.backend.reshape', 'K.reshape', (['regression', '(-1, 1)'], {}), '(regression, (-1, 1))\n', (896, 917), True, 'import keras.backend as K\n'), ((302, 325), 'numpy.zeros', 'np.zeros', (['(num_user, 1)'], {}), '((num_user, 1))\n', (310, 325), True, 'import numpy as np\n'), ((390, 413), 'numpy.zeros', '... |
# Copyright 2020 Amazon Technologies, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | [
"numpy.uint32",
"numpy.abs",
"numpy.floor",
"numpy.random.randint",
"unittest.main",
"gluoncv.model_zoo.get_model",
"numpy.finfo",
"numpy.max",
"mxnet.gpu",
"copy.deepcopy",
"mxnet.autograd.record",
"numpy.ceil",
"mxnet.gluon.loss.SoftmaxCrossEntropyLoss",
"mxnet.init.Xavier",
"utils.ber... | [((1062, 1080), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (1065, 1080), False, 'from numba import jit\n'), ((1114, 1126), 'numpy.uint32', 'np.uint32', (['(1)'], {}), '(1)\n', (1123, 1126), True, 'import numpy as np\n'), ((1272, 1284), 'numpy.uint32', 'np.uint32', (['(1)'], {}), '(1)\n', (12... |
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd
import sklearn
from sklearn import datasets
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from skle... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"pandas.merge",
"sklearn.cluster.KMeans",
"sklearn.datasets.load_breast_cancer",
"matplotlib.pyplot.figure",
"sklearn.dec... | [((1256, 1271), 'pandas.DataFrame', 'pd.DataFrame', (['X'], {}), '(X)\n', (1268, 1271), True, 'import pandas as pd\n'), ((1429, 1459), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'n_components'}), '(n_components=n_components)\n', (1432, 1459), False, 'from sklearn.decomposition import PCA\n'), ((1586, 161... |
import numpy as np
import pytz
from pandas._libs.tslibs import (
Resolution,
get_resolution,
)
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
def test_get_resolution_nano():
# don't return the fallback RESO_DAY
arr = np.array([1], dtype=np.int64)
res = get_resolution(arr)
assert res =... | [
"pandas._libs.tslibs.get_resolution",
"numpy.array"
] | [((244, 273), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'np.int64'}), '([1], dtype=np.int64)\n', (252, 273), True, 'import numpy as np\n'), ((284, 303), 'pandas._libs.tslibs.get_resolution', 'get_resolution', (['arr'], {}), '(arr)\n', (298, 303), False, 'from pandas._libs.tslibs import Resolution, get_resolution\n... |
import sys
import argparse
from yolo import YOLO, detect_video
from PIL import Image
from keras.utils.generic_utils import Progbar
import os
import numpy as np
import matplotlib.pyplot as plt
from PIL import ImageDraw, ImageFont
def detect_sequence_imgs(yolo, list_images, output_dir, save_img=False):
... | [
"os.mkdir",
"PIL.Image.new",
"keras.utils.generic_utils.Progbar",
"matplotlib.pyplot.show",
"os.makedirs",
"argparse.ArgumentParser",
"numpy.floor",
"os.path.exists",
"PIL.Image.open",
"PIL.Image.alpha_composite",
"numpy.array",
"yolo.YOLO.get_defaults",
"PIL.ImageDraw.Draw",
"argparse.Arg... | [((626, 647), 'keras.utils.generic_utils.Progbar', 'Progbar', ([], {'target': 'steps'}), '(target=steps)\n', (633, 647), False, 'from keras.utils.generic_utils import Progbar\n'), ((7588, 7647), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'argument_default': 'argparse.SUPPRESS'}), '(argument_default=arg... |
# -*- coding: utf-8 -*-
import os, sys
import numpy as np
import matplotlib.pylab as plt
from sklearn.manifold import TSNE
import json, pickle
def load_json_data(json_path):
fea_dict = json.load(open(json_path))
fea_category_dict = {}
for key in fea_dict.keys():
cat = key[:key.find('_')]
if cat not in fea_cat... | [
"matplotlib.pylab.colorbar",
"sklearn.manifold.TSNE",
"numpy.array",
"numpy.matmul",
"matplotlib.pylab.cm.get_cmap",
"numpy.squeeze",
"matplotlib.pylab.subplots",
"numpy.unique",
"matplotlib.pylab.show"
] | [((1006, 1020), 'numpy.array', 'np.array', (['Data'], {}), '(Data)\n', (1014, 1020), True, 'import numpy as np\n'), ((1030, 1047), 'numpy.squeeze', 'np.squeeze', (['Label'], {}), '(Label)\n', (1040, 1047), True, 'import numpy as np\n'), ((1583, 1623), 'numpy.matmul', 'np.matmul', (['feas', "lda_paras['ProjectMat']"], {... |
import cv2 as cv
import numpy as np
def const_accel(dt = 1.0/30):
kf = cv.KalmanFilter(18, 6, 0)
state = np.zeros((18, 1), np.float32)
# Transition matrix position/orientation
tmp = np.eye(9, dtype=np.float32)
tmp[0:3, 3:6] = np.eye(3, dtype=np.float32) * dt
tmp[3:6, 6:9] = np.eye(3, dtyp... | [
"cv2.KalmanFilter",
"numpy.eye",
"numpy.zeros"
] | [((77, 102), 'cv2.KalmanFilter', 'cv.KalmanFilter', (['(18)', '(6)', '(0)'], {}), '(18, 6, 0)\n', (92, 102), True, 'import cv2 as cv\n'), ((115, 144), 'numpy.zeros', 'np.zeros', (['(18, 1)', 'np.float32'], {}), '((18, 1), np.float32)\n', (123, 144), True, 'import numpy as np\n'), ((205, 232), 'numpy.eye', 'np.eye', (['... |
import numpy as np
import numpy.linalg as la
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
import sys
import SBW_util as util
from matplotlib.animation import FuncAnimation
eps_u = 0.001 # 0.01
eps_v = 0.001 # 0.001
gamma_u = 0.005# 0.05
zeta = 0.0
alpha_v = 0... | [
"matplotlib.pyplot.plot",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.linalg.norm",
"numpy.exp",
"numpy.linalg.solve"
] | [((5835, 5847), 'numpy.zeros', 'np.zeros', (['(20)'], {}), '(20)\n', (5843, 5847), True, 'import numpy as np\n'), ((6402, 6415), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (6412, 6415), True, 'from matplotlib import pyplot as plt\n'), ((6416, 6431), 'matplotlib.pyplot.plot', 'plt.plot', (['xx', '... |
import numpy as np
def read_pairs(pairs_filename):
pairs = []
with open(pairs_filename, 'r') as f:
for line in f.readlines()[1:]:
print(line)
pair = line.strip().split()
print('--',pair)
pairs.append(pair)
return np.array(pairs)
read_pair... | [
"numpy.array"
] | [((292, 307), 'numpy.array', 'np.array', (['pairs'], {}), '(pairs)\n', (300, 307), True, 'import numpy as np\n')] |
'''
data parameters
data: cora / dblp / arXiv / acm
split: train-test split used for the dataset
'''
data = "dblp"
split = 2
'''
model parameters
h: number of hidden dimensions
drop: hidden droput
relu: flag for relu non-linearity
'''
h = 1024
drop = 0.0
relu = False
'''
miscellaneous parameters
lr: learning rate... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"logging.basicConfig",
"os.makedirs",
"torch.manual_seed",
"os.path.exists",
"torch.cuda.is_available",
"torch.device",
"inspect.currentframe",
"os.path.split",
"os.path.join",
"os.listdir",
"logging.getLogger"
] | [((704, 729), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (727, 729), False, 'import argparse\n'), ((738, 848), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Inductive Vertex Embedding on Multi-Relational Ordered Hypergraphs"""'}), "(description=\n 'Induct... |
''' Demonstrates linear regression with TensorFlow '''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
# Set constants
N = 1000
learning_rate = 0.1
batch_size = 40 # the size of the part of the entire dataset, we... | [
"tensorflow.global_variables_initializer",
"numpy.empty",
"tensorflow.Session",
"tensorflow.pow",
"tensorflow.placeholder",
"numpy.random.randint",
"tensorflow.random_normal",
"numpy.random.normal",
"tensorflow.train.GradientDescentOptimizer"
] | [((443, 467), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'N'}), '(size=N)\n', (459, 467), True, 'import numpy as np\n'), ((477, 521), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.5)', 'scale': '(0.2)', 'size': 'N'}), '(loc=0.5, scale=0.2, size=N)\n', (493, 521), True, 'import numpy as np\n'... |
#
from typing import List
import sys
import json
import numpy as np
from fairseq import pybleu
def process_bpe_symbol(sentence: str, bpe_symbol: str):
if bpe_symbol is not None:
sentence = (sentence + ' ').replace(bpe_symbol, '').rstrip()
return sentence
# =====
# algorithm helper
... | [
"numpy.abs",
"json.loads",
"numpy.zeros",
"numpy.random.randint",
"fairseq.pybleu.PyBleuScorer",
"numpy.arange",
"numpy.all"
] | [((745, 775), 'numpy.all', 'np.all', (['(match_score_arr >= 0.0)'], {}), '(match_score_arr >= 0.0)\n', (751, 775), True, 'import numpy as np\n'), ((857, 905), 'numpy.zeros', 'np.zeros', (['(1 + len1, 1 + len2)'], {'dtype': 'np.float32'}), '((1 + len1, 1 + len2), dtype=np.float32)\n', (865, 905), True, 'import numpy as ... |
import time
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split, KFold
from dogFunctions import genData, genBatch
def convBlock( X, trn, nFilters, kernelSize, bnm ):
'''A block consisting of a convolution, a poolingi, and a batch normalization layer.'''
heInit = t... | [
"tensorflow.get_collection",
"tensorflow.reset_default_graph",
"tensorflow.layers.max_pooling2d",
"tensorflow.layers.batch_normalization",
"tensorflow.nn.softmax",
"tensorflow.nn.elu",
"tensorflow.placeholder_with_default",
"tensorflow.concat",
"tensorflow.placeholder",
"tensorflow.cast",
"dogFu... | [((319, 352), 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', ([], {}), '()\n', (350, 352), True, 'import tensorflow as tf\n'), ((1017, 1050), 'tensorflow.variance_scaling_initializer', 'tf.variance_scaling_initializer', ([], {}), '()\n', (1048, 1050), True, 'import tensorflow as tf\n'), (... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__all__ = ["Summary"]
import fitsio
import numpy as np
try:
import matplotlib.pyplot as pl
except ImportError:
pl = None
else:
from matplotlib.ticker import MaxNLocator
from matplotlib.backends.backend_pdf impo... | [
"matplotlib.backends.backend_pdf.PdfPages",
"numpy.random.uniform",
"numpy.zeros_like",
"numpy.abs",
"numpy.log",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.close",
"matplotlib.ticker.MaxNLocator",
"numpy.isfinite",
"fitsio.read",
"matplotlib.pyplot.figure",
"numpy.all"
] | [((967, 1013), 'fitsio.read', 'fitsio.read', (['parent_response.target_pixel_file'], {}), '(parent_response.target_pixel_file)\n', (978, 1013), False, 'import fitsio\n'), ((1032, 1070), 'fitsio.read', 'fitsio.read', (["query['light_curve_file']"], {}), "(query['light_curve_file'])\n", (1043, 1070), False, 'import fitsi... |
from typing import Dict, List, Tuple
from black import main
import matplotlib.pyplot as plt
import numpy as np
def _make_histogram(
reshaped_image: np.ndarray, threshold: float, bins: int = 5
) -> Tuple[List[int], np.ndarray]:
"""Fetch top colors from the histogram
Args:
reshaped_image (np.ndarr... | [
"numpy.histogramdd",
"numpy.unravel_index",
"numpy.argmin",
"numpy.min",
"numpy.where",
"numpy.array",
"numpy.max",
"numpy.mean",
"numpy.var",
"numpy.concatenate"
] | [((851, 906), 'numpy.histogramdd', 'np.histogramdd', (['reshaped_image'], {'bins': 'bins', 'range': 'ranges'}), '(reshaped_image, bins=bins, range=ranges)\n', (865, 906), True, 'import numpy as np\n'), ((2284, 2305), 'numpy.array', 'np.array', (['main_colors'], {}), '(main_colors)\n', (2292, 2305), True, 'import numpy ... |
import cv2
import numpy as np
img = cv2.imread("imori.jpg").astype(np.float32)
H,W,C=img.shape
#gray scale
b = img[:,:,0].copy()
g = img[:,:,1].copy()
r = img[:,:,2].copy()
gray = 0.2126 * r + 0.7152 * g + 0.0722 * b #0.2126+0.7152+0.0722 = 1
gray = gray.astype(np.uint8)
#filtersize
filtersize=3
pad=filtersize//2
o... | [
"cv2.waitKey",
"cv2.imwrite",
"cv2.destroyAllWindows",
"numpy.zeros",
"cv2.imread",
"numpy.max",
"numpy.min",
"cv2.imshow"
] | [((323, 378), 'numpy.zeros', 'np.zeros', (['(H + pad * 2, W + pad * 2, C)'], {'dtype': 'np.float'}), '((H + pad * 2, W + pad * 2, C), dtype=np.float)\n', (331, 378), True, 'import numpy as np\n'), ((695, 729), 'cv2.imwrite', 'cv2.imwrite', (['"""question13.jpg"""', 'out'], {}), "('question13.jpg', out)\n", (706, 729), ... |
'''
interactive plot/ graphical user interface to select an area for segmentation, and appropriate thresholds.
'''
from matplotlib.widgets import PolygonSelector, Button,Slider
from matplotlib import path
from matplotlib.image import AxesImage
from matplotlib.backend_bases import MouseEvent
from matplotlib.colors imp... | [
"numpy.load",
"matplotlib.pyplot.axes",
"matplotlib.widgets.Slider",
"numpy.mean",
"numpy.arange",
"matplotlib.widgets.PolygonSelector",
"matplotlib.pyplot.imread",
"numpy.round",
"matplotlib.colors.LinearSegmentedColormap.from_list",
"numpy.meshgrid",
"os.path.exists",
"tkinter.filedialog.ask... | [((12274, 12335), 'matplotlib.colors.LinearSegmentedColormap.from_list', 'LinearSegmentedColormap.from_list', (['"""mycmap"""', "['red', 'white']"], {}), "('mycmap', ['red', 'white'])\n", (12307, 12335), False, 'from matplotlib.colors import LinearSegmentedColormap\n'), ((12384, 12398), 'matplotlib.pyplot.subplots', 'p... |
from __future__ import division
import time
from Model import Road
from Model import Lane
import numpy as np
import cv2 as cv
from types import NoneType
import numpy as np
import moviepy.editor as mpy
import matplotlib.pyplot as plt
from ImageProcessing.PerspectiveWrapper import PerspectiveWrapper
import tensorflow a... | [
"numpy.sum",
"matplotlib.pyplot.clf",
"numpy.ravel",
"matplotlib.pyplot.figure",
"cv2.line",
"get_model.get_model",
"numpy.copy",
"matplotlib.pyplot.imshow",
"ImageProcessing.PerspectiveWrapper.PerspectiveWrapper",
"Model.Road",
"tensorflow.compat.v1.Session",
"matplotlib.pyplot.pause",
"cv2... | [((608, 631), 'keras.backend.set_learning_phase', 'K.set_learning_phase', (['(0)'], {}), '(0)\n', (628, 631), True, 'from keras import backend as K\n'), ((688, 714), 'tensorflow.compat.v1.ConfigProto', 'tf.compat.v1.ConfigProto', ([], {}), '()\n', (712, 714), True, 'import tensorflow as tf\n'), ((959, 994), 'tensorflow... |
from easyhmm import sparsehmm, hmm
import numpy as np
obsProbList = np.array(((1.0, 0.0, 0.0), (0.0, 0.51, 0.5), (0.0, 0.0, 1.0), (0.5, 0.51, 0.0), (1/3, 1/3, 1/3), (0.75, 0.25, 0.0)), dtype = np.float32)
obsProbList = np.concatenate((obsProbList, obsProbList[::-1], obsProbList))
obsProbList += 1e-5
obsProbList ... | [
"numpy.sum",
"easyhmm.hmm.ViterbiDecoder",
"numpy.ones",
"numpy.array",
"numpy.concatenate"
] | [((72, 217), 'numpy.array', 'np.array', (['((1.0, 0.0, 0.0), (0.0, 0.51, 0.5), (0.0, 0.0, 1.0), (0.5, 0.51, 0.0), (1 /\n 3, 1 / 3, 1 / 3), (0.75, 0.25, 0.0))'], {'dtype': 'np.float32'}), '(((1.0, 0.0, 0.0), (0.0, 0.51, 0.5), (0.0, 0.0, 1.0), (0.5, 0.51, \n 0.0), (1 / 3, 1 / 3, 1 / 3), (0.75, 0.25, 0.0)), dtype=np... |
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from magnebot import Arm
from magnebot.paths import IK_ORIENTATIONS_RIGHT_PATH, IK_ORIENTATIONS_LEFT_PATH, IK_POSITIONS_PATH
from magnebot.ik.orientation import ORIENTATIONS
"""
Visualize the pre-calculated IK orientation solutions... | [
"PIL.Image.new",
"numpy.abs",
"PIL.ImageFont.truetype",
"pathlib.Path",
"numpy.arange",
"magnebot.paths.IK_POSITIONS_PATH.resolve",
"PIL.ImageDraw.Draw"
] | [((627, 651), 'pathlib.Path', 'Path', (['"""../doc/images/ik"""'], {}), "('../doc/images/ik')\n", (631, 651), False, 'from pathlib import Path\n'), ((1153, 1186), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['font_path', '(14)'], {}), '(font_path, 14)\n', (1171, 1186), False, 'from PIL import Image, ImageDraw, Ima... |
import os
from searcher.es_search import SearchResults_ES
from searcher.corpus_manager import CorpusManager
#from searcher.models import QueryRequest, VisRequest
#from searcher.query_handler import QueryHandler
from searcher.corpus_manager import CorpusManager
from searcher.nlp_model_manager import NLPModelManager
from... | [
"pandas.DataFrame",
"tqdm.tqdm",
"numpy.errstate",
"searcher.es_search.SearchResults_ES",
"gensim.models.LdaModel",
"numpy.arange",
"searcher.corpus_manager.CorpusManager",
"gensim.models.CoherenceModel"
] | [((637, 666), 'searcher.corpus_manager.CorpusManager', 'CorpusManager', (['self.query_obj'], {}), '(self.query_obj)\n', (650, 666), False, 'from searcher.corpus_manager import CorpusManager\n'), ((752, 868), 'searcher.es_search.SearchResults_ES', 'SearchResults_ES', (["self.query_obj['database']"], {'qry_obj': 'self.qu... |
import numpy as np
from PulseGenerator import Pulse
# physical constants
planck = 4.13566751691e-15 # ev s
hbarfs = planck * 1e15 / (2 * np.pi) #ev fs
ev_nm = 1239.842
opt_t = np.linspace(900,1100,10)/hbarfs
def build_fitness_function(
nbins=30,
tl_duration=19.0,
e_carrier=2.22,
e_shap... | [
"numpy.load",
"numpy.sum",
"PulseGenerator.Pulse",
"numpy.array",
"numpy.exp",
"numpy.linspace",
"numpy.random.rand",
"numpy.sqrt"
] | [((177, 203), 'numpy.linspace', 'np.linspace', (['(900)', '(1100)', '(10)'], {}), '(900, 1100, 10)\n', (188, 203), True, 'import numpy as np\n'), ((429, 456), 'numpy.load', 'np.load', (['"""operators/es.npy"""'], {}), "('operators/es.npy')\n", (436, 456), True, 'import numpy as np\n'), ((469, 499), 'numpy.load', 'np.lo... |
import os, sys
import argparse
import numpy as np
import gzip
# image processing
from PIL import Image
import cv2
from ipfml import utils
from ipfml.processing import transform, segmentation
import matplotlib.pyplot as plt
from estimators import estimate, estimators_list
data_output = 'data/generated'
def write_pr... | [
"sys.stdout.write",
"os.makedirs",
"argparse.ArgumentParser",
"estimators.estimate",
"os.path.exists",
"ipfml.processing.segmentation.divide_in_blocks",
"PIL.Image.open",
"numpy.arange",
"os.path.join",
"os.listdir"
] | [((720, 746), 'sys.stdout.write', 'sys.stdout.write', (['"""\x1b[F"""'], {}), "('\\x1b[F')\n", (736, 746), False, 'import os, sys\n'), ((775, 890), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Check complexity of each zone of scene using estimator during rendering"""'}), "(description=... |
import csv
import json
import multiprocessing as mp
import os
import random
import signal
import string
import sys
import traceback
from datetime import datetime, timedelta
from itertools import repeat
import nest_asyncio
import numpy as np
from cate.core import DATA_STORE_REGISTRY, ds
from cate.core.ds import DataAcc... | [
"os.mkdir",
"os.remove",
"numpy.sum",
"random.choices",
"os.path.isfile",
"sys.exc_info",
"csv.DictWriter",
"multiprocessing.cpu_count",
"cate.core.ds.open_dataset",
"os.path.exists",
"datetime.timedelta",
"traceback.format_exc",
"cate.core.DATA_STORE_REGISTRY.get_data_store",
"signal.alar... | [((330, 350), 'nest_asyncio.apply', 'nest_asyncio.apply', ([], {}), '()\n', (348, 350), False, 'import nest_asyncio\n'), ((3313, 3357), 'signal.signal', 'signal.signal', (['signal.SIGALRM', 'alarm_handler'], {}), '(signal.SIGALRM, alarm_handler)\n', (3326, 3357), False, 'import signal\n'), ((3362, 3388), 'signal.alarm'... |
import numpy as np
import pandas as pd
from perceptron import MLP
import seaborn as sns
import matplotlib.pyplot as plt
if __name__ == "__main__":
# create a dataset to train and test a network
x_train = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
y_train = np.array([[1, 0, 0, ... | [
"pandas.DataFrame",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.legend",
"numpy.array",
"pandas.melt",
"perceptron.MLP",
"pandas.concat",
"matplotlib.pyplot.savefig"
] | [((219, 285), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n', (227, 285), True, 'import numpy as np\n'), ((300, 366), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]'], {... |
from __future__ import print_function, absolute_import, division # makes these scripts backward compatible with python 2.6 and 2.7
# Importing the base class
from co_simulation_base_io import CoSimulationBaseIO
# Other imports
import numpy as np
import co_simulation_tools as cs_tools
def Create(solvers, solver_name... | [
"co_simulation_tools.ImportArrayFromSolver",
"numpy.array"
] | [((586, 598), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (594, 598), True, 'import numpy as np\n'), ((607, 673), 'co_simulation_tools.ImportArrayFromSolver', 'cs_tools.ImportArrayFromSolver', (['from_client', 'data_name', 'data_array'], {}), '(from_client, data_name, data_array)\n', (637, 673), True, 'import co... |
import copy
import itertools
import seaborn as sns
import glob
import os
import math
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import imutils
import numpy as np
from pre_processing import Pre_Processing
import cv2
import scipy.special
import time
import matplotlib
vehicle_info = "vehicle_info"
... | [
"numpy.arctan2",
"cv2.bitwise_and",
"math.atan2",
"cv2.arcLength",
"cv2.boxPoints",
"cv2.minAreaRect",
"cv2.imshow",
"os.path.join",
"cv2.contourArea",
"numpy.zeros_like",
"cv2.cvtColor",
"os.path.exists",
"math.cos",
"pre_processing.Pre_Processing",
"cv2.destroyAllWindows",
"cv2.bound... | [((592, 608), 'pre_processing.Pre_Processing', 'Pre_Processing', ([], {}), '()\n', (606, 608), False, 'from pre_processing import Pre_Processing\n'), ((4137, 4148), 'time.time', 'time.time', ([], {}), '()\n', (4146, 4148), False, 'import time\n'), ((11776, 11787), 'time.time', 'time.time', ([], {}), '()\n', (11785, 117... |
import numpy as np
import math
class Aligner:
def __init__(self,coordFile):
self.coordFile=coordFile
self._natoms=0
self._symbols=[]
self._resids = []
self._atomids = []
self._resnames = []
self._x=[]
self._y=[]
self._z=[]
... | [
"numpy.argmax",
"numpy.cross",
"numpy.zeros",
"math.cosine",
"math.sine",
"numpy.linalg.norm",
"numpy.matmul",
"numpy.dot"
] | [((4770, 4799), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': 'float'}), '((3, 3), dtype=float)\n', (4778, 4799), True, 'import numpy as np\n'), ((4807, 4836), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': 'float'}), '((3, 3), dtype=float)\n', (4815, 4836), True, 'import numpy as np\n'), ((4842, 4871), 'numpy.z... |
import logging
from pathlib import Path
from typing import BinaryIO, Callable, Dict, Iterable, NewType, Union, IO
import numpy
from absl import flags
from cv2.cv2 import IMREAD_COLOR, imdecode, cvtColor, COLOR_RGB2BGR
from injector import Binder, Module, inject, singleton
import ffmpeg
import subprocess
from rep0st.db... | [
"numpy.fromfile",
"numpy.frombuffer",
"absl.flags.DEFINE_string",
"pathlib.Path",
"cv2.cv2.imdecode",
"ffmpeg.input",
"typing.NewType",
"cv2.cv2.cvtColor",
"logging.getLogger"
] | [((351, 378), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (368, 378), False, 'import logging\n'), ((399, 504), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""rep0st_media_path"""', '""""""', '"""Path to media directory used by rep0st to save media."""'], {}), "('rep0st_media_... |
# MIT License
# xlr8
# Copyright (c) 2022 Ethereal AI
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, me... | [
"sklearn.utils.check_random_state",
"sklearn.utils.extmath.randomized_range_finder",
"scipy.linalg.svd",
"sklearn.utils.extmath.svd_flip",
"sklearn.utils.extmath.safe_sparse_dot",
"numpy.dot"
] | [((11843, 11875), 'sklearn.utils.check_random_state', 'check_random_state', (['random_state'], {}), '(random_state)\n', (11861, 11875), False, 'from sklearn.utils import check_array, check_random_state\n'), ((12171, 12318), 'sklearn.utils.extmath.randomized_range_finder', 'randomized_range_finder', (['M'], {'size': 'n_... |
#!/usr/bin/env python
# _*_coding:utf-8_*_
"""
@Project: Project4
@File : app.py
@Author : <NAME>
@Time : 2021/12/3
"""
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output, State
import pandas as pd
import numpy as np
from surprise import KNNBasic, Reader, Dataset
i... | [
"pandas.DataFrame",
"dash.html.H2",
"dash.Dash",
"numpy.average",
"surprise.Dataset.load_from_df",
"pandas.read_csv",
"surprise.Reader",
"warnings.filterwarnings",
"dash.html.Div",
"pandas.merge",
"dash.dependencies.State",
"dash.html.Button",
"dash.dcc.Tab",
"dash.dependencies.Input",
"... | [((335, 368), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (358, 368), False, 'import warnings\n'), ((5181, 5270), 'pandas.read_csv', 'pd.read_csv', (["(myurl + 'movies.dat?raw=true')"], {'header': 'None', 'sep': '"""::"""', 'encoding': '"""latin1"""'}), "(myurl + 'movie... |
from OSIM.Simulation.NetToComp import NetToComp
from OSIM.Modeling.CircuitSystemEquations import CircuitSystemEquations
from OSIM.Simulation.CircuitAnalysis.CircuitAnalyser import CircuitAnalyser
import numpy as np
seq = CircuitSystemEquations(NetToComp('GilberMixerEasy.net').getComponents())
ca = CircuitAnalyser(seq)... | [
"numpy.zeros",
"OSIM.Simulation.NetToComp.NetToComp",
"OSIM.Simulation.CircuitAnalysis.CircuitAnalyser.CircuitAnalyser",
"numpy.amax"
] | [((300, 320), 'OSIM.Simulation.CircuitAnalysis.CircuitAnalyser.CircuitAnalyser', 'CircuitAnalyser', (['seq'], {}), '(seq)\n', (315, 320), False, 'from OSIM.Simulation.CircuitAnalysis.CircuitAnalyser import CircuitAnalyser\n'), ((1206, 1254), 'numpy.zeros', 'np.zeros', (['(2, res[0].shape[1])'], {'dtype': 'np.float64'})... |
import numpy as np
def get_fuel_v1(mass):
return int(np.floor(mass / 3) - 2)
def get_fuel_v2(mass):
fuel = int(np.floor(mass / 3) - 2)
if fuel <= 0:
return 0
else:
return fuel + get_fuel_v2(fuel)
def load_inputs(filename):
with open(filename) as f:
return [int(line.strip()... | [
"numpy.floor"
] | [((58, 76), 'numpy.floor', 'np.floor', (['(mass / 3)'], {}), '(mass / 3)\n', (66, 76), True, 'import numpy as np\n'), ((121, 139), 'numpy.floor', 'np.floor', (['(mass / 3)'], {}), '(mass / 3)\n', (129, 139), True, 'import numpy as np\n')] |
import os
import sys
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import optotrak.calibrationcore as cc
from utils.logger import *
#import analysis.delayedfeedback.database as db
#import analysis.delayedfeedback.datalayer as dtl
import analysis.delayedfeedback.analyze_delayedfeedback as a... | [
"matplotlib.pyplot.title",
"numpy.load",
"numpy.abs",
"numpy.sum",
"numpy.argmax",
"os.walk",
"numpy.ones",
"numpy.isnan",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.interp",
"os.path.join",
"numpy.linalg.pinv",
"numpy.nanmean",
"matplotlib.pyplot.imshow",
"os.path.dirname",
... | [((1394, 1441), 'numpy.arange', 'np.arange', (['framenumbers[0]', 'framenumbers[-1]', '(1)'], {}), '(framenumbers[0], framenumbers[-1], 1)\n', (1403, 1441), True, 'import numpy as np\n'), ((1659, 1688), 'numpy.interp', 'np.interp', (['x', 'framenumbers', 't'], {}), '(x, framenumbers, t)\n', (1668, 1688), True, 'import ... |
import numpy as np
import time
from keras.callbacks import TensorBoard, ModelCheckpoint
from keras.models import Model, Input, load_model
from keras.layers.core import Activation
from keras.layers.core import Dense, Dropout
from keras.layers import concatenate
from keras.initializers import he_normal
from DataGenerato... | [
"keras.models.load_model",
"keras.layers.core.Dense",
"numpy.load",
"numpy.random.seed",
"keras.callbacks.ModelCheckpoint",
"keras.layers.core.Activation",
"keras.models.Input",
"keras.models.Model",
"time.time",
"DataGenerator.DataGenerator",
"keras.layers.core.Dropout"
] | [((844, 862), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (858, 862), True, 'import numpy as np\n'), ((1429, 1466), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['epoch_path'], {'period': '(4)'}), '(epoch_path, period=4)\n', (1444, 1466), False, 'from keras.callbacks import TensorBoard, M... |
""" Testing driver LatinHypercubeDriver."""
import unittest
from random import seed
from types import GeneratorType
import numpy as np
from openmdao.api import IndepVarComp, Group, Problem, Component
from openmdao.test.paraboloid import Paraboloid
from openmdao.test.util import assert_rel_error
from openmdao.driver... | [
"unittest.main",
"openmdao.api.IndepVarComp",
"numpy.random.seed",
"openmdao.api.Problem",
"openmdao.drivers.latinhypercube_driver.LatinHypercubeDriver",
"numpy.floor",
"openmdao.drivers.latinhypercube_driver._rand_latin_hypercube",
"random.seed",
"openmdao.drivers.latinhypercube_driver._mmlhs",
"... | [((7420, 7435), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7433, 7435), False, 'import unittest\n'), ((753, 771), 'random.seed', 'seed', (['self.seedval'], {}), '(self.seedval)\n', (757, 771), False, 'from random import seed\n'), ((780, 808), 'numpy.random.seed', 'np.random.seed', (['self.seedval'], {}), '(se... |
from matplotlib import pyplot as plt
from matplotlib import rcParams
import numpy as np
import pickle
import copy as cp
import gs2_plotting as gplot
from plot_phi2_vs_time import plot_phi2_ky_vs_t
def my_single_task(ifile,run,myin,myout,mygrids,mytime,myfields,stitching=False):
# Compute and save to dat file
... | [
"matplotlib.pyplot.title",
"numpy.absolute",
"pickle.dump",
"numpy.empty",
"matplotlib.pyplot.figure",
"pickle.load",
"numpy.arange",
"gs2_plotting.plot_1d",
"numpy.copy",
"numpy.transpose",
"numpy.max",
"numpy.linspace",
"numpy.divide",
"copy.deepcopy",
"numpy.ceil",
"matplotlib.pyplo... | [((9739, 9785), 'gs2_plotting.merge_pdfs', 'gplot.merge_pdfs', (['pdflist', 'merged_pdfname', 'run'], {}), '(pdflist, merged_pdfname, run)\n', (9755, 9785), True, 'import gs2_plotting as gplot\n'), ((11442, 11467), 'copy.deepcopy', 'cp.deepcopy', (['full_time[0]'], {}), '(full_time[0])\n', (11453, 11467), True, 'import... |
# code for a local TFlite (Tensor Flow Lite) test, assuming an env where tflite is installed, see instructions below
"""
sample zipped test env should be available here:
https://github.com/lineality/tensorflow_lite_in_aws_lambda_function
to use pre-made-zipped tflite env for python 3.8:
$ unzip env.zip
$ source env/... | [
"numpy.asarray",
"tflite_runtime.interpreter.Interpreter"
] | [((2302, 2329), 'tflite_runtime.interpreter.Interpreter', 'Interpreter', (['"""model.tflite"""'], {}), "('model.tflite')\n", (2313, 2329), False, 'from tflite_runtime.interpreter import Interpreter\n'), ((2876, 2917), 'numpy.asarray', 'np.asarray', (['X_raw_input'], {'dtype': 'np.float32'}), '(X_raw_input, dtype=np.flo... |
# this is the python implementation for the credit risk project
import os
import numpy as np
import pandas as pd
import re
from math import sqrt
import time
import string
import matplotlib
import matplotlib.pyplot as plt
import nltk
import sklearn
from sklearn import preprocessing
from sklearn.feature_extraction.text... | [
"sklearn.ensemble.RandomForestClassifier",
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"pandas.DataFrame",
"matplotlib.pyplot.show",
"sklearn.preprocessing.scale",
"os.getcwd",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"sklearn.model_selection.cross_val_score",
"num... | [((1085, 1192), 'os.chdir', 'os.chdir', (['"""C:\\\\Users\\\\wmwms\\\\OneDrive - George Mason University\\\\Academics\\\\2020Fall\\\\CS584\\\\HW2"""'], {}), "(\n 'C:\\\\Users\\\\wmwms\\\\OneDrive - George Mason University\\\\Academics\\\\2020Fall\\\\CS584\\\\HW2'\n )\n", (1093, 1192), False, 'import os\n'), ((117... |
from ._functions import pdist
import numpy as np
def smote(minority_data_points, k=1):
'''
SMOTE (Synthetic Minority Oversampling TEchnique).
Used to generate more data points for minority class or imbalanced learning.
Parameters
----------
minority_data_points : numpy.array
Inputs or ... | [
"numpy.argsort",
"numpy.random.uniform",
"numpy.arange"
] | [((1508, 1544), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', '(npoints * k)'], {}), '(0, 1, npoints * k)\n', (1525, 1544), True, 'import numpy as np\n'), ((950, 979), 'numpy.argsort', 'np.argsort', (['distances'], {'axis': '(1)'}), '(distances, axis=1)\n', (960, 979), True, 'import numpy as np\n'), ((12... |
import numpy as np
import argparse
import glob
import amrex_plot_tools as amrex
if __name__ == "__main__":
import pylab as plt
rkey, ikey = amrex.get_particle_keys()
t = []
fee = []
fexR = []
fexI = []
fxx = []
pupt = []
files = sorted(glob.glob("plt[0-9][0-9][0-9][0-9][0-9]"))
... | [
"pylab.grid",
"pylab.savefig",
"numpy.array",
"amrex_plot_tools.get_particle_keys",
"glob.glob",
"pylab.gcf",
"pylab.gca",
"amrex_plot_tools.read_particle_data",
"pylab.legend",
"pylab.plot",
"numpy.sqrt"
] | [((150, 175), 'amrex_plot_tools.get_particle_keys', 'amrex.get_particle_keys', ([], {}), '()\n', (173, 175), True, 'import amrex_plot_tools as amrex\n'), ((762, 775), 'numpy.array', 'np.array', (['fee'], {}), '(fee)\n', (770, 775), True, 'import numpy as np\n'), ((787, 801), 'numpy.array', 'np.array', (['fexR'], {}), '... |
import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
import numpy as np
def hill_slopes(rule, transactions):
"""Visualize rule as hill slopes.
**Reference:** <NAME>. et al. (2020). Visualization of Numerical Association Rules by Hill Slopes.
In:... | [
"numpy.concatenate",
"numpy.empty",
"numpy.zeros",
"numpy.argsort",
"numpy.reshape",
"numpy.linspace",
"numpy.column_stack",
"numpy.interp",
"matplotlib.pyplot.subplots",
"numpy.all",
"numpy.sqrt"
] | [((893, 915), 'numpy.empty', 'np.empty', (['num_features'], {}), '(num_features)\n', (901, 915), True, 'import numpy as np\n'), ((1499, 1521), 'numpy.empty', 'np.empty', (['num_features'], {}), '(num_features)\n', (1507, 1521), True, 'import numpy as np\n'), ((2088, 2127), 'numpy.sqrt', 'np.sqrt', (['(support ** 2 + co... |
# -*- coding: utf-8 -*-
# @Time : 2020/12/12
# @Author : <NAME>
# @GitHub : https://github.com/lartpang
from functools import wraps
import numpy as np
import torch
def reduce_score(score: torch.Tensor, mean_on_loss: bool = True):
if mean_on_loss:
loss = (1 - score).mean()
else:
loss = 1... | [
"numpy.cos",
"functools.wraps"
] | [((835, 846), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (840, 846), False, 'from functools import wraps\n'), ((2511, 2547), 'numpy.cos', 'np.cos', (['(curr_iter / num_iter * np.pi)'], {}), '(curr_iter / num_iter * np.pi)\n', (2517, 2547), True, 'import numpy as np\n')] |
# import unittest
from pandas import DataFrame
from pandas.tools.describe import value_range
import numpy as np
def test_value_range():
df = DataFrame(np.random.randn(5, 5))
df.ix[0, 2] = -5
df.ix[2, 0] = 5
res = value_range(df)
assert(res['Minimum'] == -5)
assert(res['Maximum'] == 5)
... | [
"numpy.random.randn",
"pandas.tools.describe.value_range"
] | [((234, 249), 'pandas.tools.describe.value_range', 'value_range', (['df'], {}), '(df)\n', (245, 249), False, 'from pandas.tools.describe import value_range\n'), ((159, 180), 'numpy.random.randn', 'np.random.randn', (['(5)', '(5)'], {}), '(5, 5)\n', (174, 180), True, 'import numpy as np\n')] |
# Training to a set of multiple objects (e.g. ShapeNet or DTU)
# tensorboard logs available in logs/<expname>
import imp
import sys
import os
from unittest.mock import patch
sys.path.insert(
0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
)
sys.path.insert(
0, os.path.abspath(os.path.join(os... | [
"torch.empty",
"numpy.random.randint",
"util.get_cuda",
"util.decompose_to_subpatches",
"torch.no_grad",
"util.gen_rays",
"data.get_split_dataset",
"random.randint",
"os.path.dirname",
"render.NeRFRenderer.from_conf",
"os.path.exists",
"torch.load",
"util.args.parse_args",
"model.loss.item... | [((3595, 3670), 'util.args.parse_args', 'util.args.parse_args', (['extra_args'], {'training': '(True)', 'default_ray_batch_size': '(128)'}), '(extra_args, training=True, default_ray_batch_size=128)\n', (3615, 3670), False, 'import util\n'), ((3680, 3709), 'util.get_cuda', 'util.get_cuda', (['args.gpu_id[0]'], {}), '(ar... |
"""The example:
- creates waveform file from two i_data and q_data vectors
- sends the file to the SGT100A instrument
- activates the waveform
You have the option of auto-scaling the samples to the full range with the parameter 'auto_scale'
"""
import numpy as np
from RsSgt import *
RsSgt.assert_minimum_version('... | [
"numpy.sin",
"numpy.arange",
"numpy.cos"
] | [((803, 847), 'numpy.arange', 'np.arange', (['(0)', '(50 / wave_freq)', '(1 / clock_freq)'], {}), '(0, 50 / wave_freq, 1 / clock_freq)\n', (812, 847), True, 'import numpy as np\n'), ((891, 934), 'numpy.cos', 'np.cos', (['(2 * np.pi * wave_freq * time_vector)'], {}), '(2 * np.pi * wave_freq * time_vector)\n', (897, 934)... |
# Copyright (c) 2020, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root
# or https://opensource.org/licenses/BSD-3-Clause
import random
import numpy as np
from ai_economist.foundation.base.registrar import Registry
cla... | [
"numpy.minimum",
"ai_economist.foundation.base.registrar.Registry",
"numpy.ones",
"random.choice",
"numpy.random.randint",
"numpy.array",
"numpy.random.rand",
"numpy.concatenate"
] | [((18196, 18215), 'ai_economist.foundation.base.registrar.Registry', 'Registry', (['BaseAgent'], {}), '(BaseAgent)\n', (18204, 18215), False, 'from ai_economist.foundation.base.registrar import Registry\n'), ((13972, 14005), 'random.choice', 'random.choice', (['self._action_names'], {}), '(self._action_names)\n', (1398... |
from modeldata import from_downloaded as modeldata_from_downloaded
import log
from utilities import get_ncfiles_in_dir,get_variable_name,get_variable_name_reverse
from utilities import convert_time_to_datetime,get_n_months,get_l_time_range,add_month_to_timestamp
from netCDF4 import Dataset
from datetime import datetime... | [
"netCDF4.Dataset",
"utilities.get_variable_name",
"utilities.get_variable_name_reverse",
"utilities.add_month_to_timestamp",
"utilities.get_ncfiles_in_dir",
"utilities.convert_time_to_datetime",
"utilities.get_l_time_range",
"os.path.exists",
"datetime.datetime",
"modeldata.from_downloaded",
"lo... | [((653, 682), 'utilities.get_ncfiles_in_dir', 'get_ncfiles_in_dir', (['input_dir'], {}), '(input_dir)\n', (671, 682), False, 'from utilities import get_ncfiles_in_dir, get_variable_name, get_variable_name_reverse\n'), ((1438, 1457), 'netCDF4.Dataset', 'Dataset', (['input_path'], {}), '(input_path)\n', (1445, 1457), Fal... |
import math
from pandas import DataFrame
import numpy as np
from __init__fuzzy import *
def experiment(sliding_number=3, hidden_node=15):
dat_nn = np.asarray(scaler.fit_transform(dat))
X_train_size = int(len(dat_nn)*0.7)
sliding = np.array(list(SlidingWindow(dat_nn, sliding_number)))
X_train_nn = sl... | [
"numpy.array",
"numpy.savez",
"numpy.arange"
] | [((948, 1055), 'numpy.savez', 'np.savez', (["('model_saved/BPNN_%s_%s' % (sliding_number, score_mape))"], {'y_pred': 'y_pred', 'y_true': 'y_actual_test'}), "('model_saved/BPNN_%s_%s' % (sliding_number, score_mape), y_pred=\n y_pred, y_true=y_actual_test)\n", (956, 1055), True, 'import numpy as np\n'), ((1176, 1189),... |
# -*- encoding:utf-8 -*-
from __future__ import print_function
import os, codecs, re
import random
import numpy as np
from datetime import datetime
from collections import defaultdict, Counter
from nltk.stem.porter import PorterStemmer
import reader
from utils import AGENT_FIRST_THRESHOLD, AGENT_SECOND_THRES... | [
"numpy.random.seed",
"codecs.open",
"re.split",
"random.sample",
"nltk.stem.porter.PorterStemmer",
"numpy.zeros",
"collections.defaultdict",
"datetime.datetime.strptime",
"numpy.random.random",
"random.seed",
"collections.Counter",
"os.path.join",
"re.sub"
] | [((414, 458), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""chat_sequences.txt"""'], {}), "(BASE_DIR, 'chat_sequences.txt')\n", (426, 458), False, 'import os, codecs, re\n'), ((483, 523), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""utt_length.txt"""'], {}), "(BASE_DIR, 'utt_length.txt')\n", (495, 523), False,... |
"""
Script to get all the tiles from available scenes, aoi and date range for Planetscope or Skysat
Author: @developmentseed
Run:
python3 get_planet_tiles.py --geojson=supersites.geojson \
--api_key=xxxxx \
--collections=PSScene3Band \
--start_date=2020,1,1 \
--end_... | [
"json.load",
"argparse.ArgumentParser",
"numpy.asarray",
"planet.api.filters.geom_filter",
"planet.api.filters.date_range",
"planet.api.filters.range_filter",
"requests.auth.HTTPBasicAuth",
"planet.api.filters.build_search_request",
"mercantile.tile",
"planet.api.ClientV1"
] | [((666, 680), 'planet.api.ClientV1', 'api.ClientV1', ([], {}), '()\n', (678, 680), False, 'from planet import api\n'), ((2330, 2381), 'planet.api.filters.build_search_request', 'api.filters.build_search_request', (['query', 'item_types'], {}), '(query, item_types)\n', (2362, 2381), False, 'from planet import api\n'), (... |
import numpy as np
# transfer functions
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# derivative of sigmoid
def dsigmoid(y):
return np.multiply(y, (1.0 - y))
def tanh(x):
return np.tanh(x)
# derivative for tanh sigmoid
def dtanh(y):
return 1 - np.multiply(y, y)
| [
"numpy.exp",
"numpy.multiply",
"numpy.tanh"
] | [((144, 167), 'numpy.multiply', 'np.multiply', (['y', '(1.0 - y)'], {}), '(y, 1.0 - y)\n', (155, 167), True, 'import numpy as np\n'), ((196, 206), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (203, 206), True, 'import numpy as np\n'), ((268, 285), 'numpy.multiply', 'np.multiply', (['y', 'y'], {}), '(y, y)\n', (279, 2... |
#!/usr/local/bin/python3
# solver2021.py : 2021 Sliding tile puzzle solver
#
# Code by: <NAME> (hatha), <NAME> (aagond)
#
# Based on skeleton code by D. Crandall & B551 Staff, September 2021
#
#References used are as follows:
#1. https://www.quora.com/How-do-I-create-a-nested-list-from-a-flat-one-in-Python to creat... | [
"queue.PriorityQueue",
"copy.deepcopy",
"numpy.array"
] | [((2976, 2996), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (2989, 2996), False, 'import copy\n'), ((3220, 3240), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (3233, 3240), False, 'import copy\n'), ((3738, 3758), 'copy.deepcopy', 'copy.deepcopy', (['board'], {}), '(board)\n', (375... |
#!/usr/bin/env python3
import LinearResponseVariationalBayes as vb
import LinearResponseVariationalBayes.SparseObjectives as obj_lib
import LinearResponseVariationalBayes.OptimizationUtils as opt_lib
import autograd.numpy as np
import numpy.testing as np_test
import unittest
class QuadraticModel(object):
def __in... | [
"unittest.main",
"LinearResponseVariationalBayes.OptimizationUtils.minimize_objective_trust_ncg",
"LinearResponseVariationalBayes.OptimizationUtils.get_sym_matrix_inv_sqrt",
"LinearResponseVariationalBayes.OptimizationUtils.repeatedly_optimize",
"LinearResponseVariationalBayes.SparseObjectives.Objective",
... | [((5354, 5369), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5367, 5369), False, 'import unittest\n'), ((381, 414), 'LinearResponseVariationalBayes.VectorParam', 'vb.VectorParam', (['"""theta"""'], {'size': 'dim'}), "('theta', size=dim)\n", (395, 414), True, 'import LinearResponseVariationalBayes as vb\n'), ((4... |
from MyAIGuide.data import GoogleFitDataTCX, DATA_DIR, get_google_fit_steps, collect_activities_from_dir, get_google_fit_activities
import pandas as pd
import numpy as np
TEST_PARTICIPANT = DATA_DIR / 'Participant2Anonymized'
TCX_FILE = "2018-11-05T16_46_19-05_00_PT17M6S_Marche à pied.tcx"
TCX_DIR = DATA_DIR / "Parti... | [
"pandas.DataFrame",
"MyAIGuide.data.GoogleFitDataTCX",
"pandas.date_range",
"numpy.zeros",
"MyAIGuide.data.get_google_fit_steps",
"MyAIGuide.data.collect_activities_from_dir",
"MyAIGuide.data.get_google_fit_activities"
] | [((412, 464), 'pandas.date_range', 'pd.date_range', (['"""2015-11-19"""'], {'periods': '(1550)', 'freq': '"""1D"""'}), "('2015-11-19', periods=1550, freq='1D')\n", (425, 464), True, 'import pandas as pd\n'), ((904, 933), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd', 'index': 'i'}), '(data=d, index=i)\n', (916,... |
#!/usr/bin/env python3
import numpy as np
from functools import partial
class TailBoost:
def __init__(self, urm):
self.weights = list()
self.urm = urm
self.__create_weights()
self.update_scores = partial(np.vectorize(lambda weight, score: score * weight), self.weights)
def _... | [
"numpy.array",
"numpy.log",
"numpy.vectorize"
] | [((726, 748), 'numpy.array', 'np.array', (['self.weights'], {}), '(self.weights)\n', (734, 748), True, 'import numpy as np\n'), ((244, 294), 'numpy.vectorize', 'np.vectorize', (['(lambda weight, score: score * weight)'], {}), '(lambda weight, score: score * weight)\n', (256, 294), True, 'import numpy as np\n'), ((678, ... |
import numpy as np
import matplotlib.pyplot as plt
from signals.fourier import fourier
from signals.analysis import ClimbingAgent
def test_fourier():
fs = 100
length = 100.0
n = fs * length
x = np.linspace(0., length, n)
y = np.sin(10. * 2. * np.pi * x)
y += 0.75 * np.sin(20. * 2. * np.pi * ... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"signals.analysis.ClimbingAgent",
"numpy.sin",
"signals.fourier.fourier",
"numpy.linspace"
] | [((214, 241), 'numpy.linspace', 'np.linspace', (['(0.0)', 'length', 'n'], {}), '(0.0, length, n)\n', (225, 241), True, 'import numpy as np\n'), ((249, 279), 'numpy.sin', 'np.sin', (['(10.0 * 2.0 * np.pi * x)'], {}), '(10.0 * 2.0 * np.pi * x)\n', (255, 279), True, 'import numpy as np\n'), ((425, 439), 'signals.fourier.f... |
import numpy as np
'''
Label any new implementation of von-Zeipel cylinders in another spacetime
by prefixing VZC, followed by the id of the spacetime.
'''
class VZCBase():
def __init__(self, l, r0, r_range=(2, 18),
num=10000, verbose=True):
self.r_in, self.r_out = r_range
self.nu... | [
"numpy.linspace"
] | [((345, 408), 'numpy.linspace', 'np.linspace', (['self.r_in', 'self.r_out'], {'num': 'self.num', 'endpoint': '(True)'}), '(self.r_in, self.r_out, num=self.num, endpoint=True)\n', (356, 408), True, 'import numpy as np\n')] |
# Copyright (c) 2016-present, Facebook, Inc.
#
# 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... | [
"unittest.main",
"caffe2.python.core.CreateOperator",
"hypothesis.strategies.text",
"numpy.array"
] | [((4080, 4095), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4093, 4095), False, 'import unittest\n'), ((1833, 1910), 'caffe2.python.core.CreateOperator', 'core.CreateOperator', (['"""StringPrefix"""', "['strings']", "['stripped']"], {'length': 'length'}), "('StringPrefix', ['strings'], ['stripped'], length=len... |
import numpy as np
from . import compute_max_angle
def gensk97(N):
# See http://dx.doi.org/10.1016/j.jsb.2006.06.002 and references therein
N = int(N)
h = -1.0 + (2.0/(N-1))*np.arange(0,N)
theta = np.arccos(h)
phi_base = np.zeros_like(theta)
phi_base[1:(N-1)] = ((3.6/np.sqrt(N))/np.sqrt(1 - h[1... | [
"numpy.zeros_like",
"numpy.sum",
"numpy.ceil",
"numpy.cumsum",
"numpy.sin",
"numpy.array",
"numpy.arange",
"numpy.cos",
"numpy.arccos",
"numpy.sqrt"
] | [((214, 226), 'numpy.arccos', 'np.arccos', (['h'], {}), '(h)\n', (223, 226), True, 'import numpy as np\n'), ((242, 262), 'numpy.zeros_like', 'np.zeros_like', (['theta'], {}), '(theta)\n', (255, 262), True, 'import numpy as np\n'), ((343, 362), 'numpy.cumsum', 'np.cumsum', (['phi_base'], {}), '(phi_base)\n', (352, 362),... |
# Python Script to initialize a Peripheral Architecture:
# Developed by <NAME> as part of the Piranhas Toolkit
# Questions & bugs: <EMAIL>
import numpy as np
from piranhas import *
import math
# Run Intialization Parameters:
param = param_init_all()
scale = param.scale
fovea = param.fovea
e0_in_deg = param.e0_in_deg... | [
"numpy.empty",
"numpy.floor",
"numpy.zeros",
"numpy.mod",
"numpy.shape",
"numpy.where",
"numpy.mean",
"numpy.linalg.norm",
"numpy.squeeze",
"numpy.round"
] | [((1329, 1365), 'numpy.shape', 'np.shape', (['peripheral_filters.regions'], {}), '(peripheral_filters.regions)\n', (1337, 1365), True, 'import numpy as np\n'), ((1492, 1556), 'numpy.empty', 'np.empty', (['(N_theta * N_e, peri_height, peri_width)'], {'dtype': 'object'}), '((N_theta * N_e, peri_height, peri_width), dtype... |
#!/usr/bin/python
import os
import sys
import numpy
import datetime
import re
# Probability of correctness
fq_prob_list = [0.725,
0.9134,
0.936204542,
0.949544344,
0.959009084,
0.966350507,
0.972348887,
0.97... | [
"numpy.copy",
"numpy.searchsorted",
"re.findall",
"numpy.array",
"numpy.math.log10",
"datetime.datetime.now",
"sys.exit"
] | [((4481, 4504), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4502, 4504), False, 'import datetime\n'), ((3719, 3730), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3727, 3730), False, 'import sys\n'), ((13758, 13817), 'numpy.searchsorted', 'numpy.searchsorted', (['crt_pt_sorted_array', '[star... |
import os
import json
import argparse
import sys
import numpy as np
from logger import Logger
from pathlib import Path
from joblib import Parallel, delayed
from modeling.model import KuramotoSystem, plot_interaction
from plotting.animate import Animator
from plotting.plot_solution import PlotSetup
CONFIG_NAME = 'co... | [
"json.dump",
"json.load",
"argparse.ArgumentParser",
"json.loads",
"subprocess.check_output",
"plotting.animate.Animator",
"json.dumps",
"modeling.model.KuramotoSystem",
"pathlib.Path",
"numpy.linspace",
"joblib.Parallel",
"plotting.plot_solution.PlotSetup",
"joblib.delayed",
"modeling.mod... | [((788, 873), 'modeling.model.KuramotoSystem', 'KuramotoSystem', (['(nodes_side, nodes_side)', "config['system']", 'gain'], {'boundary': 'torus'}), "((nodes_side, nodes_side), config['system'], gain, boundary=torus\n )\n", (802, 873), False, 'from modeling.model import KuramotoSystem, plot_interaction\n'), ((940, 97... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
:Description: Larva segmentation
:Authors: (c) <NAME> <<EMAIL>>
:Date: 2020-08-120
"""
import os
import cv2 as cv
import numpy as np
# from scipy.io import loadmat
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from glob import iglob
# import json
... | [
"argparse.ArgumentParser",
"cv2.VideoWriter_fourcc",
"numpy.ones",
"glob.iglob",
"cv2.imshow",
"os.path.join",
"cv2.subtract",
"cv2.dilate",
"cv2.cvtColor",
"os.path.exists",
"cv2.connectedComponents",
"cv2.destroyAllWindows",
"numpy.uint8",
"cv2.waitKey",
"cv2.morphologyEx",
"cv2.crea... | [((698, 827), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Larva segmentation."""', 'formatter_class': 'ArgumentDefaultsHelpFormatter', 'conflict_handler': '"""resolve"""'}), "(description='Larva segmentation.', formatter_class=\n ArgumentDefaultsHelpFormatter, conflict_handler='resolve')\n"... |
"""
Adapted from https://github.com/leoxiaobin/deep-high-resolution-net.pytorch
Original licence: Copyright (c) Microsoft, under the MIT License.
"""
from abc import ABC, abstractmethod
import copy
import random
import cv2
import numpy as np
from albumentations import (
Compose,
Normalize,
)
import tensorflow... | [
"copy.deepcopy",
"numpy.sum",
"numpy.random.randn",
"cv2.cvtColor",
"random.shuffle",
"numpy.random.rand",
"numpy.zeros",
"numpy.ones",
"cv2.imread",
"cv2.warpAffine",
"random.random",
"numpy.arange",
"numpy.exp",
"albumentations.Normalize"
] | [((2316, 2343), 'copy.deepcopy', 'copy.deepcopy', (['self.db[idx]'], {}), '(self.db[idx])\n', (2329, 2343), False, 'import copy\n'), ((2470, 2542), 'cv2.imread', 'cv2.imread', (['image_file', '(cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)'], {}), '(image_file, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)\n', ... |
# <NAME>, 18/04/2018
# Project 2018, Iris Dataset Analysis
# https://web.microsoftstream.com/video/74b18405-5ee1-47f0-a42d-e8831a453a91
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.amin.html
# https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.amax.html
# https://web.microsoftstream.com/v... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"numpy.amin",
"numpy.std",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.legend",
"numpy.genfromtxt",
"numpy.amax",
"numpy.mean",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((598, 646), 'numpy.genfromtxt', 'numpy.genfromtxt', (['"""data/iris.csv"""'], {'delimiter': '""","""'}), "('data/iris.csv', delimiter=',')\n", (614, 646), False, 'import numpy\n'), ((1124, 1146), 'numpy.amax', 'numpy.amax', (['data[:, 2]'], {}), '(data[:, 2])\n', (1134, 1146), False, 'import numpy\n'), ((1158, 1180),... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/3/20 16:25
# @Author : <NAME>
# @Site :
# @File : memnet.py
# @Software: PyCharm
# @Github : https://github.com/stevehamwu
import pickle
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def position_encoding(... | [
"torch.nn.Dropout",
"torch.nn.utils.clip_grad_norm_",
"torch.nn.Embedding",
"numpy.transpose",
"numpy.ones",
"torch.nn.functional.softmax",
"torch.nn.Linear",
"torch.sum"
] | [((367, 425), 'numpy.ones', 'np.ones', (['(embedding_size, sentence_size)'], {'dtype': 'np.float32'}), '((embedding_size, sentence_size), dtype=np.float32)\n', (374, 425), True, 'import numpy as np\n'), ((692, 714), 'numpy.transpose', 'np.transpose', (['encoding'], {}), '(encoding)\n', (704, 714), True, 'import numpy a... |
#encoding:UTF-8
import gym
import matplotlib
import numpy as np
import sys
from collections import defaultdict
if "../" not in sys.path:
sys.path.append("../")
from lib.envs.blackjack import BlackjackEnv
from lib import plotting
matplotlib.style.use('ggplot')
env = BlackjackEnv()
def make_epsilon_greedy_polic... | [
"sys.path.append",
"lib.plotting.plot_value_function",
"matplotlib.style.use",
"numpy.argmax",
"numpy.zeros",
"numpy.ones",
"collections.defaultdict",
"numpy.max",
"sys.stdout.flush",
"lib.envs.blackjack.BlackjackEnv"
] | [((237, 267), 'matplotlib.style.use', 'matplotlib.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (257, 267), False, 'import matplotlib\n'), ((275, 289), 'lib.envs.blackjack.BlackjackEnv', 'BlackjackEnv', ([], {}), '()\n', (287, 289), False, 'from lib.envs.blackjack import BlackjackEnv\n'), ((3649, 3667), 'collecti... |
import sys
import getopt
import numpy as np
import matplotlib.pyplot as plt
import scipy
def usage():
print("""Usage:
-o, --output [output_file_name] Output file name (Required)
-h, --help Print this message (Optional)
""")
def init_params():
'''
Initializes ... | [
"numpy.abs",
"getopt.getopt",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"numpy.fromfile",
"sys.exit"
] | [((2385, 2407), 'numpy.abs', 'np.abs', (['complex_output'], {}), '(complex_output)\n', (2391, 2407), True, 'import numpy as np\n'), ((2411, 2429), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'power'], {}), '(t, power)\n', (2419, 2429), True, 'import matplotlib.pyplot as plt\n'), ((2432, 2442), 'matplotlib.pyplot.show'... |
import pandas as pd
import talib
import numpy as np
import os
path = os.getcwd()+'\\'
# 读取数据
Data = pd.read_table(path+'res\\999999.txt', delim_whitespace=True, encoding='gbk')
Data = Data[:-1]
Data.columns = ['time', 'openp', 'highp', 'lowp', 'closep', 'volume', 'amount']
# 计算指标,汇总到indicators里
def myMACD(price, fa... | [
"talib.MACD",
"talib.EMA",
"os.getcwd",
"pandas.ewma",
"numpy.savetxt",
"talib.STOCH",
"numpy.diff",
"talib.RSI",
"numpy.column_stack",
"pandas.read_table"
] | [((102, 180), 'pandas.read_table', 'pd.read_table', (["(path + 'res\\\\999999.txt')"], {'delim_whitespace': '(True)', 'encoding': '"""gbk"""'}), "(path + 'res\\\\999999.txt', delim_whitespace=True, encoding='gbk')\n", (115, 180), True, 'import pandas as pd\n'), ((820, 899), 'talib.MACD', 'talib.MACD', (["Data['closep']... |
# torch
import hydra.utils
import torch
# built-in
import copy
import os
import datetime
import time
import numpy as np
import math
# logging
import wandb
# project
import probspec_routines as ps_routines
from tester import test
import ckconv
from torchmetrics import Accuracy
import antialiasing
from optim import co... | [
"wandb.log",
"numpy.load",
"numpy.sum",
"numpy.allclose",
"torch.randn",
"optim.construct_optimizer",
"tester.test",
"torch.dropout",
"os.path.join",
"antialiasing.get_gabornet_summaries",
"antialiasing.regularize_gabornet",
"datetime.datetime.now",
"ckconv.nn.LnLoss",
"ckconv.nn.LimitLnLo... | [((715, 752), 'os.path.join', 'os.path.join', (['wandb.run.dir', 'filename'], {}), '(wandb.run.dir, filename)\n', (727, 752), False, 'import os\n'), ((1052, 1068), 'wandb.save', 'wandb.save', (['path'], {}), '(path)\n', (1062, 1068), False, 'import wandb\n'), ((2831, 2862), 'optim.construct_optimizer', 'construct_optim... |
#%%
import torch
from torch import optim, nn
from torchvision import models, transforms
model = models.vgg16(pretrained=True)
#%%
class FeatureExtractor(nn.Module):
def __init__(self, model):
super(FeatureExtractor, self).__init__()
# Extract VGG-16 Feature Layers
self.features = list(model.features)
... | [
"lshash.LSHash",
"torch.nn.Sequential",
"torchvision.transforms.Resize",
"torchvision.transforms.ToPILImage",
"torchvision.transforms.ToTensor",
"cv2.imread",
"numpy.array",
"torch.cuda.is_available",
"torchvision.transforms.CenterCrop",
"torchvision.models.vgg16",
"torch.no_grad",
"torch.nn.F... | [((97, 126), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (109, 126), False, 'from torchvision import models, transforms\n'), ((881, 910), 'torchvision.models.vgg16', 'models.vgg16', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (893, 910), False, 'from tor... |
import pandas as pd
import csv
import numpy as np
from datetime import datetime
import json
import os
from shapely.geometry import shape, Point
from fuzzywuzzy import process
## TODO implement string similarity for crime categories
## TODO reiterate through this data set once a week for discrepancies
## Aggregating L... | [
"pandas.DataFrame",
"shapely.geometry.Point",
"json.load",
"pandas.read_csv",
"fuzzywuzzy.process.extractOne",
"datetime.datetime.strptime",
"shapely.geometry.shape",
"numpy.concatenate"
] | [((366, 530), 'pandas.read_csv', 'pd.read_csv', (['"""https://data.boston.gov/dataset/6220d948-eae2-4e4b-8723-2dc8e67722a3/resource/12cb3883-56f5-47de-afa5-3b1cf61b257b/download/tmp3bg1m024.csv"""'], {}), "(\n 'https://data.boston.gov/dataset/6220d948-eae2-4e4b-8723-2dc8e67722a3/resource/12cb3883-56f5-47de-afa5-3b1c... |
import torch
from collections import OrderedDict
from torch.nn import utils, functional as F
from torch.optim import Adam
from torch.backends import cudnn
from model import build_model, weights_init
import scipy.misc as sm
import numpy as np
import os
import cv2
from loss import bce_iou_loss
# normalize the predicted... | [
"model.build_model",
"torch.load",
"numpy.asarray",
"torch.sigmoid",
"torch.max",
"torch.no_grad",
"os.path.join",
"torch.min",
"cv2.resize"
] | [((367, 379), 'torch.max', 'torch.max', (['d'], {}), '(d)\n', (376, 379), False, 'import torch\n'), ((389, 401), 'torch.min', 'torch.min', (['d'], {}), '(d)\n', (398, 401), False, 'import torch\n'), ((1659, 1688), 'model.build_model', 'build_model', (['self.config.arch'], {}), '(self.config.arch)\n', (1670, 1688), Fals... |
# --------------------------------------------------------
# P2ORM: Formulation, Inference & Application
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# --------------------------------------------------------
import numpy as np
import os
import ntpath
import torch
import scipy.io as s... | [
"lib.dataset.gen_label_methods.occ_order_pred_to_ori",
"scipy.io.loadmat",
"numpy.ones",
"matplotlib.pyplot.figure",
"lib.dataset.gen_label_methods.occ_order_pred_to_edge_prob",
"os.path.join",
"lib.dataset.gen_label_methods.order8_to_order_pixwise_np",
"sys.path.append",
"lib.dataset.gen_label_meth... | [((399, 424), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""agg"""'], {}), "('agg')\n", (417, 424), True, 'import matplotlib.pyplot as plt\n'), ((463, 487), 'sys.path.append', 'sys.path.append', (['"""../.."""'], {}), "('../..')\n", (478, 487), False, 'import sys\n'), ((741, 766), 'os.path.dirname', '... |
import numpy
from chainer import cuda
from chainer import optimizer
class RMSpropGraves(optimizer.Optimizer):
"""<NAME> RMSprop.
See http://arxiv.org/abs/1308.0850
"""
def __init__(self, lr=1e-4, alpha=0.95, momentum=0.9, eps=1e-4):
# Default parameter values are the ones in the original p... | [
"chainer.cuda.elementwise",
"numpy.zeros_like",
"chainer.cuda.zeros_like",
"numpy.sqrt"
] | [((486, 509), 'numpy.zeros_like', 'numpy.zeros_like', (['param'], {}), '(param)\n', (502, 509), False, 'import numpy\n'), ((522, 545), 'numpy.zeros_like', 'numpy.zeros_like', (['param'], {}), '(param)\n', (538, 545), False, 'import numpy\n'), ((562, 585), 'numpy.zeros_like', 'numpy.zeros_like', (['param'], {}), '(param... |
import csv
import tqdm
import logging
import numpy as np
from os import path
from collections import deque
import chainer
import chainerrl
from chainer import serializers
from chainer.backends import cuda
from src.abstract.agent import Agent
from src.finger.model import QFunction
from src.utilities.behaviour import A... | [
"src.utilities.behaviour.AgentBehaviour",
"chainerrl.replay_buffers.prioritized.PrioritizedReplayBuffer",
"numpy.random.choice",
"chainer.optimizers.Adam",
"tqdm.tqdm",
"csv.writer",
"chainer.optimizers.MomentumSGD",
"collections.deque",
"numpy.amax",
"numpy.max",
"chainerrl.agents.DoubleDQN",
... | [((582, 609), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (599, 609), False, 'import logging\n'), ((630, 688), 'src.finger.finger_agent_environment.FingerAgentEnv', 'FingerAgentEnv', (['layout_config', 'agent_params', 'finger', 'train'], {}), '(layout_config, agent_params, finger, trai... |
import os
import sys
import cv2
import numpy as np
from tqdm import tqdm
def eval_phys_data_single_pendulum(data_filepath, num_vids, num_frms, save_path):
from eval_phys_single_pendulum import eval_physics, phys_vars_list
phys = {p_var:[] for p_var in phys_vars_list}
for n in tqdm(range(num_vids)):
... | [
"numpy.save",
"numpy.abs",
"numpy.isnan",
"numpy.array",
"eval_phys_elastic_pendulum.eval_physics",
"os.path.join"
] | [((746, 770), 'numpy.save', 'np.save', (['save_path', 'phys'], {}), '(save_path, phys)\n', (753, 770), True, 'import numpy as np\n'), ((2086, 2110), 'numpy.save', 'np.save', (['save_path', 'phys'], {}), '(save_path, phys)\n', (2093, 2110), True, 'import numpy as np\n'), ((3629, 3653), 'numpy.save', 'np.save', (['save_p... |
import pickle
import numpy as np
import librosa
import pandas as pd
from raw_audio_create_dict import split_data
dict_path = '/scratch/speech/raw_audio_dataset/raw_audio_full.pkl'
file = open(dict_path, 'rb')
data = pickle.load(file)
audio_path = '/scratch/speech/raw_audio_dataset/audio_paths_labels_updated.csv'
df =... | [
"pickle.dump",
"pandas.read_csv",
"pickle.load",
"numpy.array",
"raw_audio_create_dict.split_data"
] | [((217, 234), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (228, 234), False, 'import pickle\n'), ((321, 344), 'pandas.read_csv', 'pd.read_csv', (['audio_path'], {}), '(audio_path)\n', (332, 344), True, 'import pandas as pd\n'), ((1455, 1482), 'raw_audio_create_dict.split_data', 'split_data', (['dataset_up... |
#!/usr/bin/env python
import roslib; roslib.load_manifest('numpy_eigen'); roslib.load_manifest('rostest');
import numpy_eigen
import numpy_eigen.test as npe
import numpy
import sys
# http://docs.python.org/library/unittest.html#test-cases
import unittest
import generator_config
typeTag2NumpyTypeObjectMap = dict()
t... | [
"numpy.abs",
"roslib.load_manifest",
"rostest.rosrun",
"numpy.random.random"
] | [((37, 72), 'roslib.load_manifest', 'roslib.load_manifest', (['"""numpy_eigen"""'], {}), "('numpy_eigen')\n", (57, 72), False, 'import roslib\n'), ((74, 105), 'roslib.load_manifest', 'roslib.load_manifest', (['"""rostest"""'], {}), "('rostest')\n", (94, 105), False, 'import roslib\n'), ((5047, 5101), 'rostest.rosrun', ... |
"""
This script is for thermodynamic model for sortseq data for the paper
MAVE-NN: learning genotype-phenotype maps from multiplex assays of variant effect
<NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, <NAME>
"""
# Standard imports
import numpy as np
from numpy.core.fromnumeric import sort
import pandas as pd
import warnin... | [
"json.load",
"tensorflow.keras.backend.sum",
"argparse.ArgumentParser",
"warnings.filterwarnings",
"pandas.read_csv",
"numpy.random.randn",
"tensorflow.reshape",
"mavenn.Model",
"tensorflow.keras.initializers.Constant",
"tensorflow.keras.backend.exp",
"mavenn.split_dataset",
"mavenn.src.utils.... | [((500, 533), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (523, 533), False, 'import warnings\n'), ((859, 886), 'mavenn.src.utils.set_seed', 'mavenn.src.utils.set_seed', ([], {}), '()\n', (884, 886), False, 'import mavenn\n'), ((945, 959), 'datetime.datetime.now', 'date... |
############################################################################
# This Python file is part of PyFEM, the code that accompanies the book: #
# #
# 'Non-Linear Finite Element Analysis of Solids and Structures' #
# <NA... | [
"pyfem.fem.Assembly.assembleTangentStiffness",
"numpy.zeros",
"pyfem.fem.Assembly.assembleInternalForce"
] | [((2668, 2683), 'numpy.zeros', 'zeros', (['dofCount'], {}), '(dofCount)\n', (2673, 2683), False, 'from numpy import zeros, array\n'), ((2699, 2714), 'numpy.zeros', 'zeros', (['dofCount'], {}), '(dofCount)\n', (2704, 2714), False, 'from numpy import zeros, array\n'), ((2731, 2746), 'numpy.zeros', 'zeros', (['dofCount'],... |
# -*- encoding: utf-8 -*-
'''
@File : kdTree.py
@Contact : <EMAIL>
@Modify Time @Author @Version @Desciption
------------ ----------- -------- -----------
2020/1/4 21:27 guzhouweihu 1.0 None
'''
import math
from collections import namedtuple
import time
from random impo... | [
"heapq.heappushpop",
"heapq.nlargest",
"priority_queue.MaxHeap",
"random.random",
"numpy.array"
] | [((2013, 2044), 'priority_queue.MaxHeap', 'MaxHeap', (['near_k', '(lambda x: x[0])'], {}), '(near_k, lambda x: x[0])\n', (2020, 2044), False, 'from priority_queue import MaxHeap\n'), ((3428, 3445), 'numpy.array', 'np.array', (['result3'], {}), '(result3)\n', (3436, 3445), True, 'import numpy as np\n'), ((3059, 3067), '... |
'''
'''
__debug = False
from collections import namedtuple , Counter
import copy, sys
import numpy as np
try:
from src import core,file
from src.TWL06 import twl
except:
import core,file
from TWL06 import twl
def pattern(word,utf8=False):
pattern = np.zeros(len(word),dtype="int")
index = 0
if utf8: seen = ""
... | [
"copy.deepcopy",
"TWL06.twl.add",
"numpy.empty",
"numpy.zeros",
"collections.namedtuple",
"collections.Counter"
] | [((767, 779), 'numpy.empty', 'np.empty', (['[]'], {}), '([])\n', (775, 779), True, 'import numpy as np\n'), ((2282, 2304), 'collections.Counter', 'Counter', (['possibilities'], {}), '(possibilities)\n', (2289, 2304), False, 'from collections import namedtuple, Counter\n'), ((2535, 2563), 'numpy.zeros', 'np.zeros', (['(... |
import math
from abc import ABC
from typing import Optional, Callable
import numpy as np
from .. import distances
from .part_reward import PartReward
class PartVelocityReward(PartReward, ABC):
"""
A reward that punishes (linear and angular) movement of parts.
"""
def __init__(self, name_prefix: str... | [
"numpy.mean",
"numpy.linalg.norm"
] | [((3156, 3197), 'numpy.linalg.norm', 'np.linalg.norm', (['velocities[:, 0]'], {'axis': '(-1)'}), '(velocities[:, 0], axis=-1)\n', (3170, 3197), True, 'import numpy as np\n'), ((3227, 3268), 'numpy.linalg.norm', 'np.linalg.norm', (['velocities[:, 1]'], {'axis': '(-1)'}), '(velocities[:, 1], axis=-1)\n', (3241, 3268), Tr... |
import platform
import cv2
import timeit
import argparse
import os
import sys
import multiprocessing as mp
import geopandas
mp.set_start_method('spawn', force=True)
import utils.dataframe
import numpy as np
from utils import raster_processing, to_agol, features, dataframe
import rasterio.warp
import rasterio.crs
impo... | [
"utils.features.create_aoi_poly",
"numpy.sum",
"argparse.ArgumentParser",
"models.XViewFirstPlaceClsModel",
"multiprocessing.set_start_method",
"utils.to_agol.agol_arg_check",
"torch.cuda.device_count",
"collections.defaultdict",
"pathlib.Path",
"utils.dataframe.make_aoi_df",
"loguru.logger.remo... | [((126, 166), 'multiprocessing.set_start_method', 'mp.set_start_method', (['"""spawn"""'], {'force': '(True)'}), "('spawn', force=True)\n", (145, 166), True, 'import multiprocessing as mp\n'), ((13038, 13052), 'loguru.logger.catch', 'logger.catch', ([], {}), '()\n', (13050, 13052), False, 'from loguru import logger\n')... |
# -*- encoding=utf-8 -*-
# Took and modified the BaseCamera class, and changed the Camera Class
# Original Source: https://blog.miguelgrinberg.com/post/flask-video-streaming-revisited
# Original Code Repository: https://github.com/miguelgrinberg/flask-video-streaming
# Modified a little bit in inference method from fac... | [
"model.utils.decode_bbox",
"threading.Timer",
"numpy.argmax",
"email.mime.text.MIMEText",
"model.utils.single_class_non_max_suppression",
"cv2.rectangle",
"cv2.imencode",
"smtplib.SMTP",
"email.mime.multipart.MIMEMultipart",
"numpy.max",
"uuid.UUID",
"datetime.datetime.now",
"cv2.resize",
... | [((4487, 4518), 'cv2.resize', 'cv2.resize', (['image', 'target_shape'], {}), '(image, target_shape)\n', (4497, 4518), False, 'import cv2\n'), ((4572, 4604), 'numpy.expand_dims', 'np.expand_dims', (['image_np'], {'axis': '(0)'}), '(image_np, axis=0)\n', (4586, 4604), True, 'import numpy as np\n'), ((4641, 4691), 'model.... |
from pathlib import Path
from typing import Iterable
from os.path import basename, splitext
import sys
from difflib import context_diff
import click
import numpy as np
from sadedegel.dataset._core import safe_json_load
from sadedegel.dataset import load_sentence_corpus, file_paths
def file_diff(i1: Iterable, i2: Iter... | [
"sadedegel.dataset._core.safe_json_load",
"os.path.basename",
"sadedegel.dataset.load_sentence_corpus",
"click.command",
"difflib.context_diff",
"sadedegel.dataset.file_paths",
"pathlib.Path",
"numpy.array",
"click.secho",
"sys.exit"
] | [((802, 817), 'click.command', 'click.command', ([], {}), '()\n', (815, 817), False, 'import click\n'), ((841, 868), 'sadedegel.dataset.load_sentence_corpus', 'load_sentence_corpus', (['(False)'], {}), '(False)\n', (861, 868), False, 'from sadedegel.dataset import load_sentence_corpus, file_paths\n'), ((655, 695), 'cli... |
import slidingwindow as sw
import numpy as np
import cv2
def splitAlphaMask(image):
"""
Splits the last channel of an image from the rest of the channels.
Useful for splitting away the alpha channel of an image and treating
it as the image mask.
The input image should be a NumPy array of shape [h,w,c].
The r... | [
"slidingwindow.SlidingWindow",
"numpy.unique",
"numpy.nonzero",
"cv2.connectedComponentsWithStats",
"cv2.minAreaRect",
"cv2.findContours"
] | [((689, 718), 'numpy.nonzero', 'np.nonzero', (['(mask != maskValue)'], {}), '(mask != maskValue)\n', (699, 718), True, 'import numpy as np\n'), ((1646, 1661), 'numpy.unique', 'np.unique', (['mask'], {}), '(mask)\n', (1655, 1661), True, 'import numpy as np\n'), ((2085, 2133), 'cv2.connectedComponentsWithStats', 'cv2.con... |
# Copyright 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 ... | [
"torch.mean",
"numpy.maximum",
"numpy.sum",
"torch.nn.init.xavier_normal_",
"numpy.zeros",
"torch.softmax",
"numpy.mean",
"torch.nn.ParameterList",
"torch.zeros",
"sklearn.metrics.confusion_matrix",
"torch.sum",
"torch.log",
"numpy.diag"
] | [((3934, 3966), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['y_real', 'y_pred'], {}), '(y_real, y_pred)\n', (3950, 3966), False, 'from sklearn.metrics import confusion_matrix\n'), ((3981, 3992), 'numpy.diag', 'np.diag', (['cm'], {}), '(cm)\n', (3988, 3992), True, 'import numpy as np\n'), ((4063, 4085), 'n... |
'''
Copyright 2022 Airbus SAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... | [
"copy.deepcopy",
"math.exp",
"numpy.maximum",
"pandas.DataFrame.from_dict",
"numpy.array"
] | [((3565, 3622), 'copy.deepcopy', 'deepcopy', (['self.resource_demand[self.resource_name].values'], {}), '(self.resource_demand[self.resource_name].values)\n', (3573, 3622), False, 'from copy import deepcopy\n'), ((3757, 3845), 'numpy.maximum', 'np.maximum', (['(self.use_stock[self.sub_resource_list[0]].values / demand_... |
"""
Collection of utility functions
"""
from numpy.random import RandomState
import pandas as pd
import numpy as np
import os
import functools
from networkx.algorithms import bipartite
import logging
def make_random_bipartite_data(group1, group2, p, seed):
"""
:type group1: list
:param group1: Ids of fi... | [
"pandas.DataFrame",
"os.listdir",
"os.remove",
"numpy.sum",
"os.makedirs",
"logging.basicConfig",
"pandas.read_csv",
"os.path.exists",
"numpy.random.RandomState",
"logging.info",
"os.path.isfile",
"numpy.arange",
"os.rmdir",
"os.path.join",
"pandas.concat"
] | [((1027, 1097), 'logging.info', 'logging.info', (['""" (bipartite index created, now resolving item values)"""'], {}), "(' (bipartite index created, now resolving item values)')\n", (1039, 1097), False, 'import logging\n'), ((1442, 1503), 'logging.info', 'logging.info', (['""" (resolution done, now converting to tup... |
import sys
path = '../../../'
sys.path.append(path)
from pdeopt.tools import get_data
import numpy as np
directories = [ 'Starter10/',
'Starter11/',
'Starter111/',
'Starter2/',
'Starter439/',
'Starter66/',
'Starter744/',
... | [
"sys.path.append",
"tabulate.tabulate",
"numpy.linalg.norm",
"pdeopt.tools.get_data"
] | [((30, 51), 'sys.path.append', 'sys.path.append', (['path'], {}), '(path)\n', (45, 51), False, 'import sys\n'), ((1265, 1287), 'numpy.linalg.norm', 'np.linalg.norm', (['mu_opt'], {}), '(mu_opt)\n', (1279, 1287), True, 'import numpy as np\n'), ((1440, 1505), 'pdeopt.tools.get_data', 'get_data', (['directory', 'method_tu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.