code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import enum
import itertools
import math
import random
from typing import Any
import numpy as np
from numpy.typing import NDArray
from bot.lib.consts import SHAPES, SRS_KICKS
Pieces = enum.Enum('PIECES', 'I L J S Z T O')
class Piece:
def __init__(self, board: NDArray[np.int8], t: int, x: int = 10, y: int = 3, ... | [
"numpy.roll",
"random.shuffle",
"enum.Enum",
"numpy.zeros",
"math.copysign",
"numpy.array",
"itertools.islice",
"numpy.all"
] | [((187, 223), 'enum.Enum', 'enum.Enum', (['"""PIECES"""', '"""I L J S Z T O"""'], {}), "('PIECES', 'I L J S Z T O')\n", (196, 223), False, 'import enum\n'), ((1851, 1907), 'numpy.array', 'np.array', (['SHAPES[self.type - 1][self.rot]'], {'dtype': 'np.int8'}), '(SHAPES[self.type - 1][self.rot], dtype=np.int8)\n', (1859,... |
import numpy
from scipy import ndimage
with open("data.txt", "r") as fh:
lines = fh.readlines()
heightmap = []
for line in lines:
row = [ int(i) for i in line.strip() ]
heightmap.append(row)
heightmap = numpy.array(heightmap)
# I thiiiink we only really care about finding the 9-height lines and getting... | [
"scipy.ndimage.label",
"numpy.array"
] | [((219, 241), 'numpy.array', 'numpy.array', (['heightmap'], {}), '(heightmap)\n', (230, 241), False, 'import numpy\n'), ((376, 405), 'scipy.ndimage.label', 'ndimage.label', (['(heightmap != 9)'], {}), '(heightmap != 9)\n', (389, 405), False, 'from scipy import ndimage\n')] |
import os
import tensorflow as tf
import numpy as np
import pickle as pkl
import matplotlib.pyplot as plt
from deepcompton.utils import angular_separation
realdatadir = ["SetImageReal_theta_38_phi_303.pkl", "SetImageReal_theta_65_phi_210.pkl"]
models_dir = "./models"
model_scores = {}
model_separations = {}
mean_separ... | [
"matplotlib.pyplot.title",
"tensorflow.keras.models.load_model",
"os.path.join",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.legend",
"numpy.argsort",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"numpy.array",
"tensorflow.math.sin",
"matplotlib.pyplot.ylabel",
"tensorflow.math.... | [((389, 413), 'numpy.arange', 'np.arange', (['(100)', '(2000)', '(50)'], {}), '(100, 2000, 50)\n', (398, 413), True, 'import numpy as np\n'), ((799, 821), 'os.listdir', 'os.listdir', (['models_dir'], {}), '(models_dir)\n', (809, 821), False, 'import os\n'), ((2423, 2440), 'numpy.argsort', 'np.argsort', (['means'], {}),... |
# type: ignore
import numba
import numpy as np
from scipy.sparse import csr_matrix
from sklearn import linear_model
from maddness.util.hash_function_helper import create_codebook_start_end_idxs
@numba.njit(fastmath=True, cache=True)
def sparsify_and_int8_A_enc(A_enc, K=16):
"""
returns X_binary from an encod... | [
"numpy.linalg.lstsq",
"numpy.ceil",
"numpy.empty",
"numpy.asfarray",
"numba.njit",
"numpy.zeros",
"maddness.util.hash_function_helper.create_codebook_start_end_idxs",
"numpy.ones",
"numpy.argsort",
"numpy.where",
"numpy.linalg.norm",
"numpy.arange",
"numpy.linalg.solve",
"sklearn.linear_mo... | [((198, 235), 'numba.njit', 'numba.njit', ([], {'fastmath': '(True)', 'cache': '(True)'}), '(fastmath=True, cache=True)\n', (208, 235), False, 'import numba\n'), ((1449, 1486), 'numba.njit', 'numba.njit', ([], {'fastmath': '(True)', 'cache': '(True)'}), '(fastmath=True, cache=True)\n', (1459, 1486), False, 'import numb... |
import numpy as np
import math
import basis.robot_math as rm
import visualization.panda.world as wd
import robot_sim.robots.yumi.yumi as ym
import modeling.geometric_model as gm
import motion.optimization_based.incremental_nik as inik
if __name__ == "__main__":
base = wd.World(cam_pos=[3, -1, 1], lookat_pos=[0, 0,... | [
"motion.optimization_based.incremental_nik.IncrementalNIK",
"robot_sim.robots.yumi.yumi.Yumi",
"modeling.geometric_model.gen_frame",
"basis.robot_math.rotmat_from_axangle",
"numpy.array",
"visualization.panda.world.World"
] | [((274, 326), 'visualization.panda.world.World', 'wd.World', ([], {'cam_pos': '[3, -1, 1]', 'lookat_pos': '[0, 0, 0.5]'}), '(cam_pos=[3, -1, 1], lookat_pos=[0, 0, 0.5])\n', (282, 326), True, 'import visualization.panda.world as wd\n'), ((384, 407), 'robot_sim.robots.yumi.yumi.Yumi', 'ym.Yumi', ([], {'enable_cc': '(True... |
import numpy as np
from .base import BaseLR
from .value import LRvalue
class OnedimEigLR(BaseLR):
def __init__(self, d: int):
self.__d = d
self.__v = LRvalue(0, 1)
def __call__(self, t: int, grad_t: np.ndarray) -> LRvalue:
sum_eigen = np.sum(np.power(grad_t, 2))
## Based on the... | [
"numpy.power"
] | [((276, 295), 'numpy.power', 'np.power', (['grad_t', '(2)'], {}), '(grad_t, 2)\n', (284, 295), True, 'import numpy as np\n')] |
import sys
import os
sys.path.append("D:/work/牧原数字")
from data.cough_detection.denoise.audio_denoising import perform_spectral_subtraction
from 智能化部门.vad.vad.project_vad import segmentVoiceByZero
import librosa
import time
from praatio import tgio
import numpy as np
import tensorflow as tf
LENGTH = 9600... | [
"sys.path.append",
"智能化部门.vad.vad.project_vad.segmentVoiceByZero",
"time.time",
"praatio.tgio.Textgrid",
"praatio.tgio.IntervalTier",
"numpy.max",
"librosa.load",
"numpy.min",
"os.path.splitext",
"numpy.float64",
"data.cough_detection.denoise.audio_denoising.perform_spectral_subtraction"
] | [((25, 56), 'sys.path.append', 'sys.path.append', (['"""D:/work/牧原数字"""'], {}), "('D:/work/牧原数字')\n", (40, 56), False, 'import sys\n'), ((486, 517), 'numpy.float64', 'np.float64', (['(data / 2 ** (8 * 2))'], {}), '(data / 2 ** (8 * 2))\n', (496, 517), True, 'import numpy as np\n'), ((1008, 1040), 'librosa.load', 'libro... |
import os
import sys
from PIL import Image
from PIL import ImageFilter
import random
import torchvision.datasets as Datasets
import torchvision.transforms as Transforms
from torchvision.datasets import VisionDataset, ImageFolder
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms.functional ... | [
"torchvision.datasets.STL10",
"os.path.isfile",
"torchvision.transforms.Normalize",
"os.path.join",
"torchvision.datasets.utils.check_integrity",
"torchvision.datasets.utils.verify_str_arg",
"torchvision.datasets.utils.download_and_extract_archive",
"torch.utils.data.DataLoader",
"numpy.transpose",
... | [((13177, 13211), 'torchvision.transforms.Compose', 'Transforms.Compose', (['transform_list'], {}), '(transform_list)\n', (13195, 13211), True, 'import torchvision.transforms as Transforms\n'), ((13970, 14061), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'dset', 'batch_size': 'batch_size', 'shuffle': ... |
import numpy as np
import random
from pygments import highlight
import yaml
import aiida
from aiida import orm
from aiida.engine import WorkChain, while_
from aiida.engine.persistence import ObjectLoader
from functools import singledispatch
import math
from plumpy.utils import AttributesFrozendict
from aiida.orm.nod... | [
"random.gauss",
"aiida.orm.Dict",
"random.uniform",
"numpy.empty",
"aiida.orm.nodes.data.base.to_aiida_type",
"yaml.dump",
"numpy.hstack",
"aiida.engine.while_",
"random.random",
"random.seed",
"aiida.engine.persistence.ObjectLoader",
"operator.itemgetter",
"numpy.vstack"
] | [((12246, 12304), 'numpy.empty', 'np.empty', (['(num_elitism, population.shape[1])'], {'dtype': 'object'}), '((num_elitism, population.shape[1]), dtype=object)\n', (12254, 12304), True, 'import numpy as np\n'), ((12474, 12539), 'numpy.empty', 'np.empty', (['(num_mating_parents, population.shape[1])'], {'dtype': 'object... |
import proper
import matplotlib.pyplot as plt
import numpy as np
# from medis.Utils.plot_tools import view_datacube, quicklook_wf, quicklook_im
def coronagraph(wfo, f_lens, occulter_type, diam):
plt.figure(figsize=(12,8))
plt.subplot(2,2,1)
plt.imshow(proper.prop_get_phase(wfo), origin = "lower")
plt.t... | [
"proper.prop_circular_aperture",
"matplotlib.pyplot.suptitle",
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.exp",
"proper.prop_radius",
"numpy.sqrt",
"proper.prop_begin",
"proper.prop_circular_obscuration",
"numpy.linspace",
"proper.prop_get_sampling_radians",
"matplotlib.py... | [((3848, 3871), 'numpy.ones', 'np.ones', (['(width, width)'], {}), '((width, width))\n', (3855, 3871), True, 'import numpy as np\n'), ((3871, 3966), 'proper.prop_run', 'proper.prop_run', (['"""simple_coron"""', '(1.1)', 'width'], {'PHASE_OFFSET': '(1)', 'PASSVALUE': "{'input_map': flat}"}), "('simple_coron', 1.1, width... |
import numpy as np
def txt2arr(path: str, delimiter: str = ' ') -> np.array:
with open(path, 'r', encoding='utf-8') as f:
mat = f.read()
row_list = mat.splitlines()
data_list = [[float(i)
for i in row.strip().split(delimiter)]
for row in row_list]
return np.a... | [
"numpy.array",
"numpy.sum"
] | [((316, 335), 'numpy.array', 'np.array', (['data_list'], {}), '(data_list)\n', (324, 335), True, 'import numpy as np\n'), ((395, 415), 'numpy.sum', 'np.sum', (['((x - y) ** 2)'], {}), '((x - y) ** 2)\n', (401, 415), True, 'import numpy as np\n')] |
import numpy as np
import glfw
from OpenGL.GL import *
from OpenGL.GLU import *
gAzimuth = np.radians(45)
gElevation = np.radians(45)
gDistance = 5.
gMouseMode = 0 # 0 : no mode, 1 : Left click mode, 2 : Right click mode
gPrevPos = None
gAt = np.zeros(3)
gScrollBuf = 0.
gJoints = [] # name, offset, channels, channel v... | [
"glfw.poll_events",
"glfw.make_context_current",
"glfw.window_should_close",
"glfw.set_drop_callback",
"glfw.get_cursor_pos",
"numpy.sin",
"glfw.set_mouse_button_callback",
"glfw.swap_buffers",
"numpy.radians",
"glfw.set_key_callback",
"numpy.cross",
"glfw.init",
"numpy.cos",
"glfw.swap_in... | [((92, 106), 'numpy.radians', 'np.radians', (['(45)'], {}), '(45)\n', (102, 106), True, 'import numpy as np\n'), ((120, 134), 'numpy.radians', 'np.radians', (['(45)'], {}), '(45)\n', (130, 134), True, 'import numpy as np\n'), ((244, 255), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (252, 255), True, 'import nump... |
# Desc: test numpy serialization.
# Author: <NAME>
# Date: 16-02-19
# Reference:
# https://stackoverflow.com/questions/30698004/how-can-i-serialize-a-numpy-array-while-preserving-matrix-dimensions
# https://medium.com/datadriveninvestor/deploy-your-pytorch-model-to-production-f69460192217
import numpy as np
import... | [
"pickle.loads",
"base64.b64decode",
"cv2.imread",
"numpy.array",
"base64.b64encode",
"pickle.dumps"
] | [((677, 721), 'numpy.array', 'np.array', (['[[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]]'], {}), '([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0]])\n', (685, 721), True, 'import numpy as np\n'), ((1158, 1180), 'cv2.imread', 'cv2.imread', (['image_path'], {}), '(image_path)\n', (1168, 1180), False, 'import cv2\n'), ((1198, 1215), 'pickle.dump... |
# ----------------------------------------------------------------------------
# This software is in the public domain, furnished "as is", without technical
# support, and with no warranty, express or implied, as to its usefulness for
# any purpose.
#
# DiffNewTopo.py
#
# Creates the following temporary difference elem... | [
"SmartScript.SmartScript.__init__",
"numpy.nanmin",
"com.raytheon.viz.gfe.ui.runtimeui.DisplayMessageDialog.openError",
"TimeRange.allTimes",
"numpy.nanmax"
] | [((1239, 1283), 'SmartScript.SmartScript.__init__', 'SmartScript.SmartScript.__init__', (['self', 'dbss'], {}), '(self, dbss)\n', (1271, 1283), False, 'import SmartScript\n'), ((2494, 2513), 'numpy.nanmax', 'numpy.nanmax', (['delta'], {}), '(delta)\n', (2506, 2513), False, 'import numpy\n'), ((2531, 2550), 'numpy.nanmi... |
from sklearn.model_selection import train_test_split
import numba
from numba import njit
import pandas as pd
import numpy as np
@njit
def sample_winner(team_one, team_two, p_matrix):
if np.random.rand() < p_matrix[team_one, team_two]:
return int(team_one)
else:
return int(team_two)
@njit
def... | [
"numpy.sum",
"numpy.std",
"numpy.asarray",
"numpy.zeros",
"numpy.ones",
"numpy.mean",
"numpy.arange",
"numpy.random.rand",
"numpy.concatenate"
] | [((672, 689), 'numpy.zeros', 'np.zeros', (['(64, 6)'], {}), '((64, 6))\n', (680, 689), True, 'import numpy as np\n'), ((972, 1008), 'numpy.zeros', 'np.zeros', (['(32, 6)'], {'dtype': 'numba.int64'}), '((32, 6), dtype=numba.int64)\n', (980, 1008), True, 'import numpy as np\n'), ((1135, 1163), 'numpy.arange', 'np.arange'... |
# -*- coding: utf-8 -*-
r"""
This module reads in the following input files:
Files defining sets of nodes
----------------------------
min.A: single-column[int], (N_A + 1, )
First line contains the number of nodes in community A.
Subsequent lines contain the node ID (1-indexed) of the nodes belonging to A.
Example:... | [
"numpy.sum",
"numpy.log",
"numpy.abs",
"numpy.ix_",
"numpy.zeros",
"numpy.all",
"numpy.hstack",
"numpy.percentile",
"scipy.sparse.csr_matrix",
"numpy.arange",
"numpy.exp",
"scipy.sparse.csgraph.connected_components",
"numpy.loadtxt",
"os.path.join",
"numpy.unique"
] | [((6178, 6209), 'numpy.hstack', 'np.hstack', (["(TSD['I'], TSD['F'])"], {}), "((TSD['I'], TSD['F']))\n", (6187, 6209), True, 'import numpy as np\n'), ((6214, 6245), 'numpy.hstack', 'np.hstack', (["(TSD['F'], TSD['I'])"], {}), "((TSD['F'], TSD['I']))\n", (6223, 6245), True, 'import numpy as np\n'), ((6266, 6339), 'numpy... |
# A collection of useful functions
#
# NumpyUtility.py
#
# <NAME>, 2018
import numpy as np
def findNearestIdx(array, value):
'''Return the index of nearest value in an array to the given value'''
idx = (np.abs(array-value)).argmin()
return idx
def findNearest(array, value):
'''Return the nearest va... | [
"numpy.asscalar",
"numpy.abs"
] | [((215, 236), 'numpy.abs', 'np.abs', (['(array - value)'], {}), '(array - value)\n', (221, 236), True, 'import numpy as np\n'), ((462, 480), 'numpy.asscalar', 'np.asscalar', (['array'], {}), '(array)\n', (473, 480), True, 'import numpy as np\n')] |
import torch
import numpy as np
from rdkit import Chem
from torch import nn
from torch.nn import functional as F
import pandas as pd
import time
def Variable(tensor):
"""Wrapper for torch.autograd.Variable that also accepts
numpy arrays directly and automatically assigns it to
the GPU. Be aware in c... | [
"pandas.read_csv",
"os.walk",
"time.strftime",
"pandas.read_table",
"numpy.unique",
"pandas.DataFrame",
"torch.zeros_like",
"torch.where",
"torch.autograd.Variable",
"torch.nn.functional.mse_loss",
"pandas.read_excel",
"numpy.sort",
"torch.cuda.is_available",
"torch.from_numpy",
"torch.o... | [((466, 491), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (489, 491), False, 'import torch\n'), ((558, 589), 'torch.autograd.Variable', 'torch.autograd.Variable', (['tensor'], {}), '(tensor)\n', (581, 589), False, 'import torch\n'), ((1479, 1513), 'numpy.unique', 'np.unique', (['arr_'], {'re... |
import matplotlib
matplotlib.use('AGG')
import numpy as np
import cv2
import pycocotools.mask as cocomask
import opencv_mat as gm
from .single_image_process import get_transform, get_restriction
def __cocoseg_to_binary(seg, height, width):
"""
COCO style segmentation to binary mask
:param seg: coco-s... | [
"numpy.set_printoptions",
"pycocotools.mask.decode",
"numpy.uint8",
"numpy.asarray",
"numpy.zeros",
"opencv_mat.global_matting",
"cv2.merge",
"matplotlib.use",
"cv2.split",
"opencv_mat.guided_filter",
"pycocotools.mask.frPyObjects",
"pycocotools.mask.merge"
] | [((18, 39), 'matplotlib.use', 'matplotlib.use', (['"""AGG"""'], {}), "('AGG')\n", (32, 39), False, 'import matplotlib\n'), ((1255, 1296), 'numpy.zeros', 'np.zeros', (['(height, width)'], {'dtype': 'np.int32'}), '((height, width), dtype=np.int32)\n', (1263, 1296), True, 'import numpy as np\n'), ((1599, 1618), 'numpy.asa... |
"""
Mask R-CNN
Train on the toy Balloon dataset and implement color splash effect.
Copyright (c) 2018 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by <NAME>
------------------------------------------------------------
Usage: import the module (see Jupyter notebooks for examples),... | [
"numpy.sum",
"argparse.ArgumentParser",
"cv2.VideoWriter_fourcc",
"skimage.measure.find_contours",
"mrcnn.model.MaskRCNN",
"os.path.join",
"sys.path.append",
"mrcnn.utils.download_trained_weights",
"os.path.abspath",
"cv2.imwrite",
"os.path.exists",
"numpy.int32",
"datetime.datetime.now",
... | [((1324, 1343), 'os.path.abspath', 'os.path.abspath', (['""""""'], {}), "('')\n", (1339, 1343), False, 'import os\n'), ((1364, 1389), 'sys.path.append', 'sys.path.append', (['ROOT_DIR'], {}), '(ROOT_DIR)\n', (1379, 1389), False, 'import sys\n'), ((1568, 1611), 'os.path.join', 'os.path.join', (['ROOT_DIR', '"""mask_rcnn... |
import numpy as np
import matplotlib.pyplot as plt
# plot priors
def plot_priors(X_val, y_prior, n_ensembles):
fig = plt.figure(figsize=(10, 4))
ax = fig.add_subplot(111)
for ens in range(0, n_ensembles):
ax.plot(X_val, y_prior[ens], 'k')
ax.set_xlim(-2.5, 2.5)
plt.show()
# plot prediction... | [
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show",
"numpy.concatenate"
] | [((122, 149), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 4)'}), '(figsize=(10, 4))\n', (132, 149), True, 'import matplotlib.pyplot as plt\n'), ((291, 301), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (299, 301), True, 'import matplotlib.pyplot as plt\n'), ((393, 420), 'matplotlib.pyplo... |
"""特征标准化"""
import numpy as np
import random
from tqdm import tqdm
from data_utils.utility import read_manifest
from data_utils.audio import AudioSegment
class FeatureNormalizer(object):
"""音频特征归一化类
if mean_std_filepath is provided (not None), the normalizer will directly
initilize from the file. Otherw... | [
"tqdm.tqdm",
"numpy.load",
"numpy.std",
"random.Random",
"data_utils.utility.read_manifest",
"numpy.hstack",
"data_utils.audio.AudioSegment.from_file",
"numpy.mean",
"numpy.savez"
] | [((2017, 2067), 'numpy.savez', 'np.savez', (['filepath'], {'mean': 'self._mean', 'std': 'self._std'}), '(filepath, mean=self._mean, std=self._std)\n', (2025, 2067), True, 'import numpy as np\n'), ((2164, 2181), 'numpy.load', 'np.load', (['filepath'], {}), '(filepath)\n', (2171, 2181), True, 'import numpy as np\n'), ((2... |
from cv2 import getRotationMatrix2D, Canny, line, bitwise_and, FILLED, rectangle, warpAffine
from numpy import ones, float32, uint8
from numpy.ma import sqrt
# Extract only rhombus
def extract_gameboard(image, window_width, window_height):
m = float32([[1, 0, -(window_width - window_height) / 2], [0, 1, 0]])
... | [
"cv2.Canny",
"cv2.bitwise_and",
"numpy.float32",
"numpy.ones",
"cv2.warpAffine",
"numpy.ma.sqrt"
] | [((250, 315), 'numpy.float32', 'float32', (['[[1, 0, -(window_width - window_height) / 2], [0, 1, 0]]'], {}), '([[1, 0, -(window_width - window_height) / 2], [0, 1, 0]])\n', (257, 315), False, 'from numpy import ones, float32, uint8\n'), ((328, 380), 'cv2.warpAffine', 'warpAffine', (['image', 'm', '(window_height, wind... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 18 04:14:28 2015
@author: nebula
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import math
class SolvePDE():
LINESTYLE = ['-', ':', '--', '-.']
PRINT_RANGE = 10
X = 1.0
NX = 101
DT ... | [
"numpy.meshgrid",
"matplotlib.pyplot.show",
"mpl_toolkits.mplot3d.Axes3D",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.mat"
] | [((790, 802), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (800, 802), True, 'import matplotlib.pyplot as plt\n'), ((817, 828), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (823, 828), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((1087, 1102), 'matplotlib.pyplot.xlabel', 'p... |
from .optimizers import get_optimizer
from ..metrics import get_metrics
import numpy as np
class Sequential:
def __init__(self, layers =None):
if layers != None:
self.layers = layers
self.set_input_count_all()
else:
self.layers = []
def add(self, layer):
if len(self.layers) == 0:... | [
"numpy.mean",
"numpy.arange",
"numpy.random.shuffle"
] | [((2471, 2492), 'numpy.arange', 'np.arange', (['x.shape[0]'], {}), '(x.shape[0])\n', (2480, 2492), True, 'import numpy as np\n'), ((2518, 2544), 'numpy.random.shuffle', 'np.random.shuffle', (['shuffle'], {}), '(shuffle)\n', (2535, 2544), True, 'import numpy as np\n'), ((3019, 3046), 'numpy.arange', 'np.arange', (['x_tr... |
import networkx as nx
import scipy.linalg
import numpy as np
from sklearn import preprocessing
from sklearn.cluster import KMeans
from numpy import linalg
def asym_weight_matrix(G, nodelist = None, data = None):
"""Returns the affinity matrix (usually denoted as A, but denoted as W here)
of the DiGraph G. W i... | [
"numpy.full",
"sklearn.cluster.KMeans",
"numpy.asarray",
"networkx.get_edge_attributes",
"numpy.linalg.eig",
"numpy.isnan",
"sklearn.preprocessing.normalize",
"numpy.dot",
"numpy.diag"
] | [((1252, 1293), 'numpy.full', 'np.full', (['(nlen, nlen)', 'np.nan'], {'order': 'None'}), '((nlen, nlen), np.nan, order=None)\n', (1259, 1293), True, 'import numpy as np\n'), ((1487, 1512), 'numpy.asarray', 'np.asarray', (['W'], {'dtype': 'None'}), '(W, dtype=None)\n', (1497, 1512), True, 'import numpy as np\n'), ((305... |
# Under MIT License, see LICENSE.txt
import logging
from typing import List
import numpy as np
from Util.geometry import Line, angle_between_three_points, perpendicular, wrap_to_pi, closest_point_on_line, \
normalize, intersection_between_lines
from Util.position import Position
from Util.role import Role
from Ut... | [
"numpy.stack",
"numpy.divide",
"numpy.transpose",
"ai.Algorithm.path_partitionner.Obstacle",
"ai.states.game_state.GameState",
"numpy.cross",
"numpy.zeros",
"numpy.clip",
"Util.geometry.angle_between_three_points",
"Util.geometry.normalize",
"numpy.argmin",
"Util.geometry.wrap_to_pi",
"Util.... | [((2205, 2290), 'Util.geometry.angle_between_three_points', 'angle_between_three_points', (['their_goal_line.p1', 'ball_position', 'their_goal_line.p2'], {}), '(their_goal_line.p1, ball_position,\n their_goal_line.p2)\n', (2231, 2290), False, 'from Util.geometry import Line, angle_between_three_points, perpendicular... |
from common import data_provider
from common.trinary_data import TrinaryData
import common.constants as cn
from common_python.testing import helpers
from common_python.util.persister import Persister
import common_python.util.dataframe as dataframe
import copy
import numpy as np
import os
import pandas as pd
import un... | [
"unittest.main",
"common_python.util.persister.Persister",
"copy.deepcopy",
"common_python.testing.helpers.isValidDataFrame",
"numpy.dtype",
"common.data_provider.DataProvider",
"pdb.set_trace",
"common.trinary_data.TrinaryData"
] | [((10098, 10126), 'unittest.main', 'unittest.main', ([], {'failfast': '(True)'}), '(failfast=True)\n', (10111, 10126), False, 'import unittest\n'), ((459, 487), 'common.data_provider.DataProvider', 'data_provider.DataProvider', ([], {}), '()\n', (485, 487), False, 'from common import data_provider\n'), ((528, 570), 'co... |
import copy
import datetime
import os
import time
import numpy as np
import termcolor
import yaml
current_logger = None
class Logger:
'''Logger used to display and save logs, and save experiment configs.'''
def __init__(self, path=None, width=60, script_path=None, config=None):
self.path = path or... | [
"os.makedirs",
"numpy.std",
"yaml.dump",
"copy.copy",
"time.time",
"termcolor.colored",
"numpy.min",
"numpy.mean",
"datetime.timedelta",
"numpy.max",
"os.path.join"
] | [((1466, 1477), 'time.time', 'time.time', ([], {}), '()\n', (1475, 1477), False, 'import time\n'), ((4427, 4461), 'os.path.join', 'os.path.join', (['self.path', '"""log.csv"""'], {}), "(self.path, 'log.csv')\n", (4439, 4461), False, 'import os\n'), ((5245, 5256), 'time.time', 'time.time', ([], {}), '()\n', (5254, 5256)... |
"""
@brief PyTorch validation code for 3D segmentation.
@author <NAME> (<EMAIL>)
@date July 2021.
"""
import argparse
import os
import json
import numpy as np
import csv
from tqdm import tqdm
import torch
import torch.utils.data
import nibabel as nib
from run_train import get_loss
from src.dataset.dataset_evaluati... | [
"os.mkdir",
"argparse.ArgumentParser",
"numpy.argmax",
"json.dumps",
"numpy.mean",
"os.path.join",
"json.loads",
"numpy.std",
"torch.load",
"os.path.exists",
"nibabel.save",
"numpy.max",
"infer_seg.segment",
"run_train.get_loss",
"src.evaluation_metrics.segmentation_metrics.dice_score",
... | [((519, 589), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run validation for segmentation"""'}), "(description='Run validation for segmentation')\n", (542, 589), False, 'import argparse\n'), ((11110, 11143), 'os.path.join', 'os.path.join', (['opt.save', '"""log.txt"""'], {}), "(opt.sa... |
from dipy.segment.mask import median_otsu
from abc import (
ABC,
abstractmethod
)
from dependency_injector import providers, containers
import numpy as np
from dipy.segment.mask import median_otsu
class Preprocess(ABC):
"""
Base class for the preprocessing step
"""
@abstractmethod
def ... | [
"dipy.segment.mask.median_otsu",
"numpy.zeros"
] | [((487, 580), 'dipy.segment.mask.median_otsu', 'median_otsu', (['image'], {'vol_idx': '[0, 1]', 'median_radius': '(4)', 'numpass': '(2)', 'autocrop': '(False)', 'dilate': '(1)'}), '(image, vol_idx=[0, 1], median_radius=4, numpass=2, autocrop=\n False, dilate=1)\n', (498, 580), False, 'from dipy.segment.mask import m... |
# coding: utf-8
# In[106]:
from flask import Flask
from flask import request
from flask import jsonify
import pprint
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.neighbors import NearestNeighbors
app = Flask(__name__)
#... | [
"numpy.log",
"flask.request.args.get",
"pandas.read_csv",
"flask.Flask",
"sklearn.preprocessing.MinMaxScaler",
"flask.jsonify",
"pprint.pprint",
"pandas.concat"
] | [((302, 317), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (307, 317), False, 'from flask import Flask\n'), ((350, 364), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {}), '()\n', (362, 364), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((401, 449), 'pandas.read_csv', 'pd.read... |
from . import recog
import cv2
import numpy
from numpy import ndarray
from typing import Iterable
def handle_source(source: Iterable[ndarray], delay: int) -> None:
maskname = ""
show_green_chevrons = True
show_green_boxes = True
show_red_chevrons = True
show_red_boxes = True
for frame in source... | [
"cv2.waitKey",
"cv2.imshow",
"numpy.where",
"cv2.rectangle",
"cv2.destroyAllWindows"
] | [((1158, 1182), 'cv2.imshow', 'cv2.imshow', (['"""bzst"""', 'demo'], {}), "('bzst', demo)\n", (1168, 1182), False, 'import cv2\n'), ((1224, 1242), 'cv2.waitKey', 'cv2.waitKey', (['delay'], {}), '(delay)\n', (1235, 1242), False, 'import cv2\n'), ((1288, 1311), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), ... |
import random
import numpy as np
from src.data_arrays import DataArrays
import datetime
a = np.random.randint(1, 10000, 1000000)
dataArrays = DataArrays()
start_at = datetime.datetime.now()
b = dataArrays.sort(a)
ends_at = datetime.datetime.now()
print("Duration: {}".format(ends_at-start_at))
| [
"numpy.random.randint",
"datetime.datetime.now",
"src.data_arrays.DataArrays"
] | [((93, 129), 'numpy.random.randint', 'np.random.randint', (['(1)', '(10000)', '(1000000)'], {}), '(1, 10000, 1000000)\n', (110, 129), True, 'import numpy as np\n'), ((144, 156), 'src.data_arrays.DataArrays', 'DataArrays', ([], {}), '()\n', (154, 156), False, 'from src.data_arrays import DataArrays\n'), ((168, 191), 'da... |
from __future__ import print_function
import os
import argparse
import numpy as np
import cv2
from centerface_v3 import CenterFace
parser = argparse.ArgumentParser(description='Retinaface')
parser.add_argument('--dataset', default=r'F:\face_detection\centerface-master\centerface-master\FDDB', type=str, help='dataset'... | [
"centerface_v3.CenterFace",
"cv2.putText",
"argparse.ArgumentParser",
"os.makedirs",
"cv2.imwrite",
"numpy.float32",
"os.path.exists",
"cv2.imread",
"cv2.rectangle",
"os.path.join",
"cv2.resize"
] | [((141, 190), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Retinaface"""'}), "(description='Retinaface')\n", (164, 190), False, 'import argparse\n'), ((805, 848), 'os.path.join', 'os.path.join', (['args.dataset', '"""originalPics/"""'], {}), "(args.dataset, 'originalPics/')\n", (817, 8... |
import sys
sys.path.append('../')
sys.path.append('../../binary_classifier')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
import itertools
from tqdm import tqdm
import pickle
from sklearn.cluster import KMeans
import tensorflow as tf
from tensorflow.keras import models
reward_ta... | [
"numpy.load",
"numpy.amin",
"numpy.ones",
"numpy.shape",
"numpy.random.randint",
"numpy.mean",
"sys.path.append",
"numpy.zeros_like",
"numpy.copy",
"numpy.std",
"numpy.apply_along_axis",
"numpy.max",
"numpy.int",
"numpy.reshape",
"numpy.linspace",
"itertools.product",
"tensorflow.ker... | [((12, 34), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (27, 34), False, 'import sys\n'), ((35, 77), 'sys.path.append', 'sys.path.append', (['"""../../binary_classifier"""'], {}), "('../../binary_classifier')\n", (50, 77), False, 'import sys\n'), ((3148, 3173), 'numpy.copy', 'np.copy', (['se... |
#-*- coding:utf-8 -*-
import tensorflow as tf
import numpy as np
import pdb
from common.layers import get_initializer
from encoder import EncoderBase
import copy
#refer:https://github.com/galsang/ABCNN/blob/master/ABCNN.py
class ABCNN(EncoderBase):
def __init__(self, **kwargs):
"""
Implmenentaion ... | [
"tensorflow.einsum",
"tensorflow.reduce_sum",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.reshape",
"tensorflow.variable_scope",
"tensorflow.concat",
"tensorflow.transpose",
"tensorflow.layers.average_pooling2d",
"tensorflow.placeholder",
"tensorflow.cast",
"tensorflow.stack",
"num... | [((1250, 1296), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(v1 * v2)'], {'axis': '(1)', 'name': '"""cos_sim"""'}), "(v1 * v2, axis=1, name='cos_sim')\n", (1263, 1296), True, 'import tensorflow as tf\n'), ((7663, 7726), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None]', 'name': '"""x_quer... |
import multiprocessing
import os
import warnings
import xml.etree.ElementTree as et
from typing import Dict, Generator, Tuple, Union
import astropy.units as u
import fil_finder
import numpy as np
import pandas as pd
import skimage
import skimage.draw
import skimage.morphology
import tqdm
from ginjinn.utils.utils impo... | [
"pandas.DataFrame",
"xml.etree.ElementTree.parse",
"ginjinn.utils.utils.get_obj_anns",
"ginjinn.utils.utils.load_coco_ann",
"warnings.simplefilter",
"fil_finder.FilFinder2D",
"numpy.power",
"skimage.draw.polygon2mask",
"skimage.morphology.skeletonize",
"numpy.array",
"warnings.catch_warnings",
... | [((795, 850), 'skimage.draw.polygon2mask', 'skimage.draw.polygon2mask', (['(h, w)', 'seg_local[:, [1, 0]]'], {}), '((h, w), seg_local[:, [1, 0]])\n', (820, 850), False, 'import skimage\n'), ((1536, 1559), 'ginjinn.utils.utils.load_coco_ann', 'load_coco_ann', (['ann_file'], {}), '(ann_file)\n', (1549, 1559), False, 'fro... |
import tensorflow as tf
import numpy as np
def create_samples(n_clusters, n_samples_per_cluster, n_features, embiggen_factor, seed):
np.random.seed(seed)
slices = []
centroids = []
# Create samples for each cluster
for i in range(n_clusters):
samples = tf.random_normal((n_samples_per_clus... | [
"numpy.random.seed",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.scatter",
"tensorflow.concat",
"numpy.random.random"
] | [((140, 160), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (154, 160), True, 'import numpy as np\n'), ((713, 749), 'tensorflow.concat', 'tf.concat', (['(0)', 'slices'], {'name': '"""samples"""'}), "(0, slices, name='samples')\n", (722, 749), True, 'import tensorflow as tf\n'), ((766, 807), 'tensor... |
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score, confusion_matrix,accuracy_score, classification_report, roc_curve, auc
from ... | [
"matplotlib.pyplot.title",
"sklearn.externals.joblib.dump",
"seaborn.heatmap",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.figure",
"pandas.DataFrame",
"numpy.random.RandomState",
"nu... | [((477, 502), 'numpy.random.RandomState', 'np.random.RandomState', (['(42)'], {}), '(42)\n', (498, 502), True, 'import numpy as np\n'), ((1473, 1646), 'sklearn.ensemble.IsolationForest', 'IsolationForest', ([], {'n_estimators': '(100)', 'max_samples': '"""auto"""', 'contamination': '(0.01)', 'max_features': '(1.0)', 'b... |
# Copyright 2021 NVIDIA Corporation
#
# 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 wr... | [
"test_tools.generators.broadcasts_to",
"numpy.allclose",
"numpy.einsum",
"test_tools.generators.permutes_to",
"test_tools.generators.mk_0to1_array",
"functools.lru_cache",
"cunumeric.einsum"
] | [((4706, 4729), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (4715, 4729), False, 'from functools import lru_cache\n'), ((4807, 4830), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (4816, 4830), False, 'from functools import lru_cache\n'), ((492... |
#!/usr/bin/env python
# coding: utf-8
import pygame
import time
import random
import numpy as np
#DEFINIG 3 DISPLAY FUNCTIONS
def Your_score(score, yellow, score_font, dis):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])
def our_snake(dis,... | [
"pygame.quit",
"pygame.event.post",
"pygame.event.Event",
"pygame.font.SysFont",
"pygame.draw.rect",
"pygame.display.set_mode",
"pygame.event.get",
"numpy.zeros",
"pygame.init",
"pygame.display.update",
"numpy.array",
"random.randrange",
"pygame.display.set_caption",
"pygame.time.Clock",
... | [((757, 770), 'pygame.init', 'pygame.init', ([], {}), '()\n', (768, 770), False, 'import pygame\n'), ((989, 1037), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(dis_width, dis_height)'], {}), '((dis_width, dis_height))\n', (1012, 1037), False, 'import pygame\n'), ((1042, 1090), 'pygame.display.set_caption',... |
from abc import ABCMeta
from argparse import ArgumentParser
from warnings import warn
import numpy as np
import pydub
import pytorch_lightning as pl
import soundfile
import torch
import torch.nn as nn
import torch.nn.functional as f
import wandb
from pytorch_lightning.loggers import WandbLogger
import models.cunet_mod... | [
"os.mkdir",
"argparse.ArgumentParser",
"museval.eval_mus_track",
"torch.cat",
"models.fourier.multi_channeled_STFT",
"torch.nn.init.kaiming_normal_",
"os.path.exists",
"models.cunet_model.CUNET",
"torch.nn.functional.binary_cross_entropy_with_logits",
"soundfile.write",
"torch.zeros",
"models.... | [((598, 642), 'warnings.warn', 'warn', (['"""TODO: zero estimation, caused by ddp"""'], {}), "('TODO: zero estimation, caused by ddp')\n", (602, 642), False, 'from warnings import warn\n'), ((1065, 1084), 'torch.mean', 'torch.mean', (['ref_sig'], {}), '(ref_sig)\n', (1075, 1084), False, 'import torch\n'), ((1109, 1128)... |
import numpy as np
import scipy.ndimage as nd
import scipy.io as io
import os
LOCAL_PATH = "/home/ets/lixiang/tf-3dgan-master/sample-data/volumetric_data/"
def getVoxelFromMat(path, cube_len=64):
voxels = io.loadmat(path)['instance']
voxels = np.pad(voxels,(1,1),'constant',constant_values=(0,0))
if cube_len... | [
"numpy.pad",
"numpy.save",
"scipy.io.loadmat",
"scipy.ndimage.zoom",
"os.path.splitext",
"os.path.split",
"os.path.join",
"os.listdir"
] | [((251, 309), 'numpy.pad', 'np.pad', (['voxels', '(1, 1)', '"""constant"""'], {'constant_values': '(0, 0)'}), "(voxels, (1, 1), 'constant', constant_values=(0, 0))\n", (257, 309), True, 'import numpy as np\n'), ((1077, 1099), 'os.listdir', 'os.listdir', (['LOCAL_PATH'], {}), '(LOCAL_PATH)\n', (1087, 1099), False, 'impo... |
import numpy as np
from framework import Sentence
from ._fb_helper import forward, backward
from .PR_helper import null_b
from scipy.optimize import minimize
class PosteriorRegularization(object):
def __init__(self, m, null_mode, k, cfg):
self.cfg = cfg
self.m = m
self.M = 0
self.m... | [
"scipy.optimize.minimize",
"numpy.zeros",
"numpy.ones",
"numpy.array",
"numpy.exp",
"numpy.concatenate",
"numpy.sqrt"
] | [((593, 604), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (601, 604), True, 'import numpy as np\n'), ((1276, 1329), 'numpy.zeros', 'np.zeros', ([], {'shape': '(self.k, self.M, 1)', 'dtype': 'np.float64'}), '(shape=(self.k, self.M, 1), dtype=np.float64)\n', (1284, 1329), True, 'import numpy as np\n'), ((1660, 169... |
import dataclasses
import os
import re
from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
@dataclasses.dataclass
class EegSeries:
subject: int
series: int
data_df: pd.DataFrame
def __post__init__(self):
self.size = self.data_df.shape[0]
@dataclasses.dat... | [
"pandas.read_csv",
"numpy.pad",
"pathlib.Path",
"re.compile"
] | [((2975, 3023), 're.compile', 're.compile', (['"""subj(\\\\d+)_series(\\\\d+)_\\\\w+\\\\.csv"""'], {}), "('subj(\\\\d+)_series(\\\\d+)_\\\\w+\\\\.csv')\n", (2985, 3023), False, 'import re\n'), ((3164, 3180), 'pathlib.Path', 'Path', (['"""../input"""'], {}), "('../input')\n", (3168, 3180), False, 'from pathlib import Pa... |
import pymongo
from bson.objectid import ObjectId
import numpy as np
import datetime
import time
# crio uma conexão com o mongo passando o localhost, usuario e senha
clientMongo = pymongo.MongoClient('"mongodb://localhost:27017/"',username='root', password='<PASSWORD>') # fake
db = clientMongo["Banco"] # esp... | [
"pymongo.MongoClient",
"numpy.mean",
"datetime.timedelta",
"datetime.datetime.fromtimestamp",
"datetime.datetime.now"
] | [((188, 283), 'pymongo.MongoClient', 'pymongo.MongoClient', (['""""mongodb://localhost:27017/\\""""'], {'username': '"""root"""', 'password': '"""<PASSWORD>"""'}), '(\'"mongodb://localhost:27017/"\', username=\'root\',\n password=\'<PASSWORD>\')\n', (207, 283), False, 'import pymongo\n'), ((1138, 1174), 'datetime.da... |
## created by <NAME>
## Created: 2/14/2019
## Last Modified: 5/21/2019
## class to return Statistic Values/graphs/concepts/calculation
from StatisticLabSupport import statistic_lab_support
from StatisticLabVisualizer import statistic_lab_vizard
import warnings
from functools import partial
import functools
import panda... | [
"scipy.stats.norm.ppf",
"functools.partial",
"scipy.stats.chi2.sf",
"scipy.stats.norm.sf",
"scipy.integrate.quad",
"scipy.stats.chi2.isf",
"scipy.stats.ttest_1samp",
"StatisticLabSupport.statistic_lab_support",
"StatisticLabVisualizer.statistic_lab_vizard",
"numpy.exp",
"numpy.arange",
"functo... | [((588, 611), 'StatisticLabSupport.statistic_lab_support', 'statistic_lab_support', ([], {}), '()\n', (609, 611), False, 'from StatisticLabSupport import statistic_lab_support\n'), ((618, 640), 'StatisticLabVisualizer.statistic_lab_vizard', 'statistic_lab_vizard', ([], {}), '()\n', (638, 640), False, 'from StatisticLab... |
# UTILIZE GW P_3D LOCALIZATION MAP
# BASED ON https://github.com/lpsinger/gw-galaxies/blob/master/gw-galaxies.ipynb
# 2019.07.19 MADE BY <NAME>
# 2019.XX.XX UPDATED BY <NAME>
#============================================================
# MODULE
#------------------------------------------------------------
from ... | [
"matplotlib.pyplot.title",
"numpy.sum",
"numpy.argmax",
"healpy.nside2pixarea",
"numpy.argsort",
"numpy.arange",
"healpy.ang2pix",
"matplotlib.pyplot.tight_layout",
"scipy.stats.norm",
"ligo.skymap.postprocess.find_greedy_credible_levels",
"numpy.cumsum",
"matplotlib.pyplot.xticks",
"numpy.s... | [((965, 990), 'os.system', 'os.system', (['"""ls *.fits.gz"""'], {}), "('ls *.fits.gz')\n", (974, 990), False, 'import os, glob\n'), ((1263, 1306), 'healpy.read_map', 'hp.read_map', (['filename'], {'verbose': '(True)', 'h': '(True)'}), '(filename, verbose=True, h=True)\n', (1274, 1306), True, 'import healpy as hp\n'), ... |
import numpy as np
import cv2
from PIL import Image
from . import resources
from . import imgops
def match_template(img, resource):
scale = img.height / 720
img = imgops.scale_to_height(img.convert('RGB'), 720)
imgmat = np.asarray(img)
match_result = imgops.match_template(imgmat, resources.load_image... | [
"numpy.asarray"
] | [((235, 250), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (245, 250), True, 'import numpy as np\n'), ((357, 400), 'numpy.asarray', 'np.asarray', (['match_result[0]'], {'dtype': 'np.int32'}), '(match_result[0], dtype=np.int32)\n', (367, 400), True, 'import numpy as np\n')] |
# %%
'''----------------------------------------------------------------
This script is the (2 / 3) of MOT purpose, previous is MultiFrame.py, next is sort.py
Aims to combine Mask-RCNN and discrepancy results and pass to tracker
----------------------------------------------------------------'''
import sys
sys.path.app... | [
"sys.path.append",
"cv2.boundingRect",
"tqdm.tqdm",
"cv2.circle",
"cv2.putText",
"os.path.join",
"cv2.cvtColor",
"numpy.empty",
"cv2.waitKey",
"numpy.percentile",
"numpy.shape",
"objecttrack.sort.SortMot",
"numpy.array",
"cv2.rectangle",
"cv2.drawContours",
"cv2.destroyAllWindows",
"... | [((308, 329), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (323, 329), False, 'import sys\n'), ((1177, 1266), 'objecttrack.sort.SortMot', 'sort.SortMot', ([], {'max_age': 'maxDisappeared', 'min_hits': 'min_hits', 'iou_threshold': 'iou_threshold'}), '(max_age=maxDisappeared, min_hits=min_hits, i... |
import numpy as np
import scipy.io.wavfile as wav
from csv_loader import CSVLoader
from numpy.lib import stride_tricks
class Spectrogram2Loader(CSVLoader):
def stft(self, sig, frameSize, overlapFac=0.5, window=np.hanning):
win = window(frameSize)
hopSize = int(frameSize - np.floor(overlapFac * fr... | [
"numpy.divide",
"numpy.fft.rfft",
"numpy.abs",
"numpy.floor",
"numpy.transpose",
"numpy.expand_dims",
"numpy.zeros",
"scipy.io.wavfile.read",
"numpy.shape",
"numpy.fft.fftfreq",
"numpy.lib.stride_tricks.as_strided",
"numpy.linspace"
] | [((937, 956), 'numpy.fft.rfft', 'np.fft.rfft', (['frames'], {}), '(frames)\n', (948, 956), True, 'import numpy as np\n'), ((1104, 1118), 'numpy.shape', 'np.shape', (['spec'], {}), '(spec)\n', (1112, 1118), True, 'import numpy as np\n'), ((1135, 1163), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'freq_bins'], {}), ... |
import numpy as np
from collections import Counter
from sklearn import tree
from sklearn.datasets import load_iris
from copy import deepcopy
import matplotlib.pyplot as plt
def gini(y_train,train_no):
y_dict=Counter(y_train)
prob={key:y_dict[key]/train_no for key in y_dict.keys()}
gini=0
for... | [
"sklearn.datasets.load_iris",
"copy.deepcopy",
"numpy.average",
"numpy.sum",
"numpy.asarray",
"numpy.zeros",
"sklearn.tree.DecisionTreeClassifier",
"numpy.shape",
"numpy.array",
"collections.Counter",
"sklearn.tree.items"
] | [((221, 237), 'collections.Counter', 'Counter', (['y_train'], {}), '(y_train)\n', (228, 237), False, 'from collections import Counter\n'), ((434, 462), 'numpy.sum', 'np.sum', (['((y_train - avg) ** 2)'], {}), '((y_train - avg) ** 2)\n', (440, 462), True, 'import numpy as np\n'), ((550, 560), 'collections.Counter', 'Cou... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 29 15:26:26 2018
@author: <NAME>
@version: 0.1
"""
import numpy as np
from openpyxl import load_workbook
class Signal:
def __init__(self, time, values, sample_rate, nom_freq = 0):
self.time = time
self.values = values
sel... | [
"numpy.sin",
"numpy.arange",
"openpyxl.load_workbook",
"numpy.random.normal"
] | [((1011, 1041), 'numpy.arange', 'np.arange', (['(0)', '(spp * num_cycles)'], {}), '(0, spp * num_cycles)\n', (1020, 1041), True, 'import numpy as np\n'), ((3143, 3182), 'openpyxl.load_workbook', 'load_workbook', (['filename'], {'data_only': '(True)'}), '(filename, data_only=True)\n', (3156, 3182), False, 'from openpyxl... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 20 09:29:11 2021
@author: jakubicek
"""
import numpy as np
import numpy.matlib
import torch
import random
import h5py
import os
import glob
def CreateDataset(path_data, ind):
dictGen = dict(gapA=0 , infB=1 , mdh=2 , pgi=3 , phoE=4 , rpoB=5 , tonB=6, run=7)
... | [
"h5py.File",
"numpy.asarray",
"numpy.float32",
"numpy.zeros",
"numpy.expand_dims",
"random.randrange",
"os.path.normpath",
"numpy.linspace"
] | [((1260, 1284), 'h5py.File', 'h5py.File', (['sig_path', '"""r"""'], {}), "(sig_path, 'r')\n", (1269, 1284), False, 'import h5py\n'), ((1323, 1349), 'numpy.asarray', 'np.asarray', (["f[a]['signal']"], {}), "(f[a]['signal'])\n", (1333, 1349), True, 'import numpy as np\n'), ((1390, 1412), 'numpy.asarray', 'np.asarray', ([... |
import random
import numpy as np
import torch
digit_text_german = ['null', 'eins', 'zwei', 'drei', 'vier', 'fuenf', 'sechs', 'sieben', 'acht', 'neun']
digit_text_english = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
def char2Index(alphabet, character):
return alphabet.find(c... | [
"numpy.argmax"
] | [((1624, 1649), 'numpy.argmax', 'np.argmax', (['gen_t'], {'axis': '(-1)'}), '(gen_t, axis=-1)\n', (1633, 1649), True, 'import numpy as np\n')] |
import torch
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import pickle
import torch.utils.data as torchdata
import matplotlib.patches as mpatches
import colorcet
from pathlib import Path
from torch import nn
from torch.nn import functional as F
from alr.utils import savefig
from alr.da... | [
"numpy.stack",
"numpy.isin",
"numpy.argsort",
"numpy.nonzero",
"pathlib.Path",
"pickle.load",
"alr.utils.savefig",
"numpy.linspace",
"alr.data.datasets.Dataset.CIFAR10.get",
"matplotlib.pyplot.subplots",
"os.chdir"
] | [((358, 444), 'os.chdir', 'os.chdir', (['"""/Users/harry/Documents/workspace/thesis/reports/09_imbalanced_classes"""'], {}), "(\n '/Users/harry/Documents/workspace/thesis/reports/09_imbalanced_classes')\n", (366, 444), False, 'import os\n'), ((529, 550), 'alr.data.datasets.Dataset.CIFAR10.get', 'Dataset.CIFAR10.get'... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the 'license' file acc... | [
"sagemaker_inference.errors.UnsupportedFormatError",
"numpy.load",
"json.loads",
"six.BytesIO",
"numpy.genfromtxt",
"six.StringIO",
"numpy.array"
] | [((1387, 1410), 'json.loads', 'json.loads', (['string_like'], {}), '(string_like)\n', (1397, 1410), False, 'import json\n'), ((1422, 1449), 'numpy.array', 'np.array', (['data'], {'dtype': 'dtype'}), '(data, dtype=dtype)\n', (1430, 1449), True, 'import numpy as np\n'), ((2018, 2039), 'six.StringIO', 'StringIO', (['strin... |
import json, os, re, parmap
import multiprocessing as mp
from multiprocessing import Manager
import numpy as np
import codecs
import argparse
def matching(index, tgt_corpus, src_corpus, ngram_list, ngram, dictionary, unique, tag) :
for i in index :
sub1 = []
sub2 = []
rep_sentence = tg... | [
"json.load",
"argparse.ArgumentParser",
"multiprocessing.Manager",
"parmap.map",
"pdb.set_trace",
"numpy.array_split",
"multiprocessing.cpu_count"
] | [((1539, 1564), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1562, 1564), False, 'import argparse\n'), ((3565, 3579), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (3577, 3579), True, 'import multiprocessing as mp\n'), ((3647, 3679), 'numpy.array_split', 'np.array_split', ([... |
__all__ = ['COPYRIGHT','TITLE','SOURCE','DESCRSHORT','DESCRLONG','NOTE', 'load']
"""Taxation Powers Vote for the Scottish Parliament 1997 dataset."""
__docformat__ = 'restructuredtext'
COPYRIGHT = """Used with express permission from the original author,
who retains all rights."""
TITLE = "Taxation Powers Vo... | [
"os.path.abspath",
"numpy.array",
"scikits.statsmodels.datasets.Dataset",
"numpy.column_stack"
] | [((2645, 2679), 'numpy.array', 'array', (['data[names[0]]'], {'dtype': 'float'}), '(data[names[0]], dtype=float)\n', (2650, 2679), False, 'from numpy import recfromtxt, column_stack, array\n'), ((2812, 2916), 'scikits.statsmodels.datasets.Dataset', 'Dataset', ([], {'data': 'data', 'names': 'names', 'endog': 'endog', 'e... |
import numpy as np
"""
Utility functions to initialize a lattice .
image, random, random positive, random within range with a single 'maximum' ping site in center, center ping binary 0s except maximum 1 in center, binary 1 and 0 with density parameter
magic square and scaled primes are amusing seeds
"""
from PIL impo... | [
"numpy.zeros",
"PIL.Image.open",
"numpy.max",
"numpy.where",
"numpy.reshape",
"numpy.random.rand"
] | [((550, 572), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (560, 572), False, 'from PIL import Image\n'), ((813, 841), 'numpy.random.rand', 'np.random.rand', (['xside', 'yside'], {}), '(xside, yside)\n', (827, 841), True, 'import numpy as np\n'), ((1711, 1735), 'numpy.zeros', 'np.zeros', (['(... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module implements the DAOStarFinder class.
"""
import warnings
from astropy.table import Table
from astropy.utils import lazyproperty
import numpy as np
from .base import StarFinderBase
from ._utils import _StarCutout, _StarFinderKernel, _find_... | [
"numpy.meshgrid",
"astropy.table.Table",
"numpy.sum",
"numpy.abs",
"numpy.isscalar",
"numpy.transpose",
"numpy.isnan",
"numpy.argsort",
"numpy.arange",
"warnings.warn",
"numpy.log10"
] | [((10229, 10236), 'astropy.table.Table', 'Table', ([], {}), '()\n', (10234, 10236), False, 'from astropy.table import Table\n'), ((14683, 14700), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (14694, 14700), True, 'import numpy as np\n'), ((15307, 15317), 'numpy.sum', 'np.sum', (['wt'], {}), '(wt)\n', ... |
import numpy as np
def read_square_matrix():
d = [int(e) for e in input().split()]
m = [d]
for k in range(len(d)-1):
m.append([int(e) for e in input().split()])
return np.array(m)
def min_in_each_row(m): # หาวิธีเขียนแค่ค าสั่งเดียว
return np.array([min(r) for r in m])
def max_in_each_column... | [
"numpy.array"
] | [((192, 203), 'numpy.array', 'np.array', (['m'], {}), '(m)\n', (200, 203), True, 'import numpy as np\n'), ((873, 886), 'numpy.array', 'np.array', (['new'], {}), '(new)\n', (881, 886), True, 'import numpy as np\n')] |
# Necessary packages
#import tensorflow as tf
##IF USING TF 2 use following import to still use TF < 2.0 Functionalities
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np
from tqdm import tqdm
from gain_utils import *
from evaluations import *
def GAIN(miss_data_x, gain_parameters):
... | [
"tensorflow.compat.v1.zeros",
"numpy.nan_to_num",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.reduce_mean",
"tensorflow.compat.v1.concat",
"tensorflow.compat.v1.log",
"numpy.isnan",
"tensorflow.compat.v1.nn.sigmoid",
"tensorflow.compat.v1.matmul",
"tensorflow.compat.v1.Session",
"t... | [((155, 179), 'tensorflow.compat.v1.disable_v2_behavior', 'tf.disable_v2_behavior', ([], {}), '()\n', (177, 179), True, 'import tensorflow.compat.v1 as tf\n'), ((320, 344), 'tensorflow.compat.v1.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (342, 344), True, 'import tensorflow.compat.v1 as tf\n'), (... |
#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
import os
import numpy as np
import skimage.io as io
import tensorflow.keras as keras
import DeepMeta.models.utils_model as utils_model
import DeepMeta.postprocessing.post_process_and_count as postprocess
import DeepMeta.utils.data as data
import DeepMeta.utils.global_var... | [
"DeepMeta.postprocessing.post_process_and_count.remove_blobs",
"tensorflow.keras.models.load_model",
"DeepMeta.utils.utils.print_red",
"DeepMeta.utils.data.get_predict_dataset",
"DeepMeta.utils.utils.border_detected",
"numpy.array",
"DeepMeta.postprocessing.post_process_and_count.dilate_and_erode",
"o... | [((1811, 1824), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (1819, 1824), True, 'import numpy as np\n'), ((2040, 2053), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (2048, 2053), True, 'import numpy as np\n'), ((2118, 2172), 'os.path.join', 'os.path.join', (['gv.PATH_DATA', '"""Souris_Test/souris_8.tif... |
import imageio
import os
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from torchvision.utils import save_image
from src.evaluation.vis_helper import *
# To change name and type of the generated images
PLOT_NAMES = dict(
generate_samples="samples.png",
data_samples="d... | [
"numpy.concatenate",
"torch.randn",
"torch.zeros",
"torch.cat",
"torch.exp",
"torchvision.utils.save_image",
"PIL.Image.fromarray",
"torch.no_grad",
"os.path.join",
"imageio.mimsave"
] | [((6246, 6293), 'torch.randn', 'torch.randn', (['(size[0] * size[1])', 'self.latent_dim'], {}), '(size[0] * size[1], self.latent_dim)\n', (6257, 6293), False, 'import torch\n'), ((11546, 11599), 'numpy.concatenate', 'np.concatenate', (['(reconstructions, traversals)'], {'axis': '(0)'}), '((reconstructions, traversals),... |
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense
from keras.models import Sequential
# define the input and output of the XOR function
inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], "float32")
outputs = np.array([[0], [1], [1], [0]], "float32")
# Build a simple two-layer feed-... | [
"keras.models.Sequential",
"numpy.array",
"numpy.ones",
"tensorflow.keras.layers.Dense"
] | [((181, 234), 'numpy.array', 'np.array', (['[[0, 0], [0, 1], [1, 0], [1, 1]]', '"""float32"""'], {}), "([[0, 0], [0, 1], [1, 0], [1, 1]], 'float32')\n", (189, 234), True, 'import numpy as np\n'), ((245, 286), 'numpy.array', 'np.array', (['[[0], [1], [1], [0]]', '"""float32"""'], {}), "([[0], [1], [1], [0]], 'float32')\... |
import numpy as np
def cached(method):
def wrapped(self):
mname = '_'+method.__name__
if not hasattr(self, mname):
setattr(self, mname, method(self))
return getattr(self, mname)
return wrapped
def pbias(a, b):
"""Absolute percent bias between value a and b."""
ret... | [
"numpy.abs"
] | [((324, 349), 'numpy.abs', 'np.abs', (['((a / b - 1) * 100)'], {}), '((a / b - 1) * 100)\n', (330, 349), True, 'import numpy as np\n')] |
# Written by: <NAME>, @dataoutsider
# Viz: "Good Read", enjoy!
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os
from math import pi, cos, sin, exp, sqrt, atan2
import matplotlib.pyplot as plt
def feather(x, length, cutoff_0_to_2):
xt = x/length
xf = xt*cutoff_0_to_2
# x spa... | [
"numpy.interp",
"os.path.dirname",
"math.sin"
] | [((459, 480), 'numpy.interp', 'np.interp', (['xf', 'xr', 'xi'], {}), '(xf, xr, xi)\n', (468, 480), True, 'import numpy as np\n'), ((491, 511), 'numpy.interp', 'np.interp', (['xf', 'xr', 'a'], {}), '(xf, xr, a)\n', (500, 511), True, 'import numpy as np\n'), ((522, 542), 'numpy.interp', 'np.interp', (['xf', 'xr', 'f'], {... |
# mPyPl - Monadic Pipeline Library for Python
# http://github.com/shwars/mPyPl
# mPyPl pipe functions that are not yet implemented in the original repo
from pipe import Pipe
import numpy as np
import os
@Pipe
def cachecomputex(seq, orig_ext, new_ext, func_yes=None, func_no=None, filename_field='filename'):
"""
... | [
"os.path.isfile",
"numpy.zeros"
] | [((800, 819), 'os.path.isfile', 'os.path.isfile', (['nfn'], {}), '(nfn)\n', (814, 819), False, 'import os\n'), ((2813, 2872), 'numpy.zeros', 'np.zeros', (['((batchsize,) + lbls_shape)'], {'dtype': 'out_labels_dtype'}), '((batchsize,) + lbls_shape, dtype=out_labels_dtype)\n', (2821, 2872), True, 'import numpy as np\n'),... |
import cv2
import numpy as np
import poly as pl
import mask as mask
import contours as contours
import calibrate as calibrate
import mask as mk
##### rects_list is a 2d list (rects are (center point, rotation), box_list is 3d list
def getrectbox(blank_img, contours):
blank_img_copy = blank_img.copy()
rects_l... | [
"cv2.contourArea",
"numpy.int0",
"cv2.waitKey",
"poly.draw_points_yx",
"mask.blue_mask",
"cv2.VideoCapture",
"poly.draw_line_rot",
"contours.get_contour",
"cv2.boxPoints",
"calibrate.undistort_fisheye",
"cv2.minAreaRect",
"cv2.drawContours",
"cv2.imshow",
"mask.white_mask"
] | [((2878, 2938), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""http://localhost:8081/stream/video.mjpeg"""'], {}), "('http://localhost:8081/stream/video.mjpeg')\n", (2894, 2938), False, 'import cv2\n'), ((2617, 2634), 'mask.blue_mask', 'mk.blue_mask', (['pic'], {}), '(pic)\n', (2629, 2634), True, 'import mask as mk\n'),... |
"""
PROJECT: POLARIZATION OF THE CMB BY FOREGROUNDS
"""
import numpy as np
import pandas as pd
import healpy as hp
import itertools
from math import atan2, pi, acos
from matplotlib import pyplot as plt
from matplotlib import ticker
from PixelSky import SkyMap
from scipy.spatial.transform import Rotation as R
from ... | [
"math.atan2",
"numpy.sin",
"numpy.linalg.norm",
"numpy.exp",
"healpy.query_disc",
"sklearn.neighbors.NearestNeighbors",
"numpy.linspace",
"itertools.product",
"healpy.ang2vec",
"numpy.cos",
"Parser.Parser",
"numpy.arctan",
"numpy.dot",
"healpy.rotator.angdist",
"cmfg.profile2d",
"healp... | [((565, 591), 'Parser.Parser', 'Parser', (['"""../set/POL02.ini"""'], {}), "('../set/POL02.ini')\n", (571, 591), False, 'from Parser import Parser\n'), ((596, 618), 'cmfg.profile2d', 'cmfg.profile2d', (['config'], {}), '(config)\n', (610, 618), False, 'import cmfg\n'), ((805, 857), 'healpy.read_map', 'hp.read_map', (['... |
r"""
Least squares error analysis.
Given a data set with gaussian uncertainty on the points, and a model which
is differentiable at the minimum, the parameter uncertainty can be estimated
from the covariance matrix at the minimum. The model and data are wrapped in
a problem object, which must define the following met... | [
"numpy.empty",
"numpy.ones",
"numpy.linalg.cond",
"numpy.linalg.svd",
"numpy.arange",
"numpy.diag",
"numpy.linalg.pinv",
"scipy.linalg.inv",
"numpy.finfo",
"numpy.printoptions",
"numpy.linalg.cholesky",
"numpy.fill_diagonal",
"numpy.asarray",
"numpy.linalg.inv",
"numpy.dot",
"numpy.vst... | [((2400, 2414), 'numpy.dot', 'np.dot', (['J.T', 'r'], {}), '(J.T, r)\n', (2406, 2414), True, 'import numpy as np\n'), ((3047, 3060), 'numpy.asarray', 'np.asarray', (['p'], {}), '(p)\n', (3057, 3060), True, 'import numpy as np\n'), ((3688, 3698), 'numpy.diag', 'np.diag', (['h'], {}), '(h)\n', (3695, 3698), True, 'import... |
import pickle
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import itertools
import os
results = None
# matplotlib.rcParams.update({'font.size': 12})
color_list = plt.cm.tab10(np.linspace(0, 1, 10))
colors = {'lstm': color_list[0], 'pf_e2e': color_list[1... | [
"numpy.sum",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.figure",
"numpy.mean",
"pickle.load",
"matplotlib.pyplot.gca",
"os.path.join",
"matplotlib.pyplot.tight_layout",
"numpy.std",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"numpy.linspace",
"matplotlib.pyplot.xticks",
"mat... | [((7600, 7635), 'matplotlib.pyplot.figure', 'plt.figure', (['"""colorbar"""', '[0.6, 1.35]'], {}), "('colorbar', [0.6, 1.35])\n", (7610, 7635), True, 'import matplotlib.pyplot as plt\n'), ((7640, 7662), 'numpy.array', 'np.array', (['[[0.0, 0.3]]'], {}), '([[0.0, 0.3]])\n', (7648, 7662), True, 'import numpy as np\n'), (... |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
import math
import matplotlib.pyplot as plt
np.random.seed(12)
# Calculation of gamma i (aT*xi+b)
def calc_gamma_i(x, a, b):
a = np.array(a)
result = (np.dot(a, x) + b)
... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"numpy.random.seed",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.legend",
"sklearn.preprocessing.scale",
"numpy.shape",
"nump... | [((178, 196), 'numpy.random.seed', 'np.random.seed', (['(12)'], {}), '(12)\n', (192, 196), True, 'import numpy as np\n'), ((5649, 5666), 'numpy.array', 'np.array', (['train_X'], {}), '(train_X)\n', (5657, 5666), True, 'import numpy as np\n'), ((5678, 5695), 'numpy.array', 'np.array', (['train_Y'], {}), '(train_Y)\n', (... |
import numpy as np
import hcm
# allow voltage control of osc frequency
# here freq is now an array w/ same length as t
def VCO(t, f, osc):
"""Allows control of frequency in time.
f is now a 1-D array with same length as t, so that the frequency can be
specified at each point in time.
Argument 'osc'... | [
"numpy.multiply",
"hcm.ts.time",
"numpy.zeros",
"numpy.concatenate"
] | [((391, 420), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'np.float32'}), '(N, dtype=np.float32)\n', (399, 420), True, 'import numpy as np\n'), ((618, 649), 'numpy.multiply', 'np.multiply', (['signal', 'modulation'], {}), '(signal, modulation)\n', (629, 649), True, 'import numpy as np\n'), ((1047, 1096), 'numpy.concat... |
from mpl_settings import panellabel_fontkwargs, fig_width
import numpy as np
import pylab as pl
from scipy.stats import sem
from scipy.stats import linregress
# # # PARAMETERS # # #
# A : Motion trees
# B : Bar plots
# C : Observer model
# D : Stacked bar plots
ZOOM = 2.
PLOT = ("A","B","C","D")
SAVEFIG = True
fn... | [
"numpy.sum",
"pandas.read_pickle",
"numpy.mean",
"pylab.figure",
"numpy.arange",
"pylab.cm.RdYlGn",
"pylab.matplotlib.rc",
"numpy.unique",
"pylab.draw",
"numpy.max",
"numpy.linspace",
"numpy.bincount",
"scipy.stats.sem",
"pylab.Rectangle",
"numpy.vstack",
"pylab.imread",
"pylab.show"... | [((2622, 2697), 'pylab.matplotlib.rc', 'pl.matplotlib.rc', (['"""figure"""'], {'dpi': "(ZOOM * pl.matplotlib.rcParams['figure.dpi'])"}), "('figure', dpi=ZOOM * pl.matplotlib.rcParams['figure.dpi'])\n", (2638, 2697), True, 'import pylab as pl\n'), ((2764, 2814), 'pandas.read_pickle', 'pandas.read_pickle', (['fname_data'... |
import numpy as np
import os
from tqdm import tqdm
import torch as th
import dgl
from dgl.data.dgl_dataset import DGLDataset
from dgl.data.utils import download, load_graphs, _get_dgl_url, extract_archive
class QM9DatasetV2(DGLDataset):
r"""QM9 dataset for graph property prediction (regression)
This dataset ... | [
"numpy.stack",
"dgl.graph",
"torch.norm",
"os.path.exists",
"dgl.data.utils._get_dgl_url",
"torch.arange",
"dgl.data.utils.extract_archive",
"dgl.data.utils.download",
"os.path.join"
] | [((9410, 9446), 'dgl.data.utils._get_dgl_url', '_get_dgl_url', (['"""dataset/qm9_ver2.zip"""'], {}), "('dataset/qm9_ver2.zip')\n", (9422, 9446), False, 'from dgl.data.utils import download, load_graphs, _get_dgl_url, extract_archive\n'), ((9869, 9909), 'os.path.join', 'os.path.join', (['self.raw_dir', '"""qm9_v2.bin"""... |
import matplotlib.pyplot as plt
from librosa import display
import librosa
import numpy as np
from specAugment import spec_augment_tensorflow
class Wav_helper():
def __init__(self, sig, sr, audio_name):
# super(Wav_plot, self).__init__()
self.sig = sig
self.sr = sr
self.audio_name ... | [
"matplotlib.pyplot.title",
"numpy.abs",
"librosa.display.waveplot",
"numpy.fft.fft",
"librosa.display.specshow",
"numpy.angle",
"librosa.feature.melspectrogram",
"matplotlib.pyplot.colorbar",
"numpy.argsort",
"matplotlib.pyplot.figure",
"numpy.fft.fftfreq",
"specAugment.spec_augment_tensorflow... | [((378, 390), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (388, 390), True, 'import matplotlib.pyplot as plt\n'), ((399, 452), 'librosa.display.waveplot', 'display.waveplot', (['self.sig'], {'sr': 'self.sr', 'x_axis': '"""time"""'}), "(self.sig, sr=self.sr, x_axis='time')\n", (415, 452), False, 'from li... |
from merc.box import Box
from merc.car import Car
from merc.sphere import Sphere
from merc.collision import Collision
import numpy
class Actor:
def __init__(self, id, data):
self.__dict__ = data
self.id = id
self.last_update = 0
self.last_rb_update = 0
def update(self, data, frame_number):
self.last_upda... | [
"numpy.add",
"merc.car.Car",
"numpy.array"
] | [((828, 860), 'numpy.array', 'numpy.array', (["rb_prop['Position']"], {}), "(rb_prop['Position'])\n", (839, 860), False, 'import numpy\n'), ((877, 909), 'numpy.array', 'numpy.array', (["rb_prop['Rotation']"], {}), "(rb_prop['Rotation'])\n", (888, 909), False, 'import numpy\n'), ((1227, 1255), 'numpy.add', 'numpy.add', ... |
import numpy as np
import matplotlib.pyplot as plt
import argparse
def fractal_dimension(array, max_box_size=None, min_box_size=1, n_samples=20, n_offsets=0, plot=False):
"""Calculates the fractal dimension of a 3D numpy array.
Args:
array (np.ndarray): The array to calculate the fractal dimension of.... | [
"numpy.sum",
"argparse.ArgumentParser",
"numpy.log",
"os.path.join",
"numpy.logspace",
"numpy.zeros",
"numpy.histogramdd",
"SimpleITK.GetArrayFromImage",
"numpy.hstack",
"numpy.min",
"numpy.where",
"numpy.array",
"numpy.arange",
"numpy.linspace",
"numpy.round",
"matplotlib.pyplot.subpl... | [((1323, 1340), 'numpy.unique', 'np.unique', (['scales'], {}), '(scales)\n', (1332, 1340), True, 'import numpy as np\n'), ((1463, 1482), 'numpy.where', 'np.where', (['(array > 0)'], {}), '(array > 0)\n', (1471, 1482), True, 'import numpy as np\n'), ((2154, 2166), 'numpy.array', 'np.array', (['Ns'], {}), '(Ns)\n', (2162... |
import numpy as np
from river import utils
def test_dotvecmat_zero_vector_times_matrix_of_ones():
A_numpy = np.array([[1, 1], [1, 1]])
A_river = {(0, 0): 1, (0, 1): 1, (1, 0): 1, (1, 1): 1}
x_numpy = np.array([0, 0])
x_river = {0: 0, 1: 0}
numpy_dotvecmat = x_numpy.dot(A_numpy)
river_dotvecm... | [
"river.utils.math.dotvecmat",
"numpy.array"
] | [((115, 141), 'numpy.array', 'np.array', (['[[1, 1], [1, 1]]'], {}), '([[1, 1], [1, 1]])\n', (123, 141), True, 'import numpy as np\n'), ((215, 231), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (223, 231), True, 'import numpy as np\n'), ((325, 363), 'river.utils.math.dotvecmat', 'utils.math.dotvecmat', ([... |
from scipy.special.orthogonal import jacobi
import torch, os, cv2
from model.model import parsingNet
from utils.common import merge_config
from utils.dist_utils import dist_print
import torch
import scipy.special, tqdm
import numpy as np
import torchvision.transforms as transforms
from data.dataset import LaneTestDatas... | [
"utils.dist_utils.dist_print",
"cv2.VideoWriter_fourcc",
"numpy.sum",
"numpy.argmax",
"cv2.getPerspectiveTransform",
"socket.socket",
"numpy.sin",
"numpy.arange",
"numpy.linalg.norm",
"cv2.VideoWriter",
"torchvision.transforms.Normalize",
"cv2.imshow",
"os.path.join",
"torch.no_grad",
"t... | [((1476, 1494), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (1479, 1494), False, 'from numba import jit\n'), ((1584, 1602), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (1587, 1602), False, 'from numba import jit\n'), ((1540, 1565), 'numpy.arange', 'np.arange', (['mi... |
"""Read a comma or tab-separated text file and perform linear regression."""
def read_file(filename):
"""Read two column contents of file as floats."""
import csv
delimiter = "\t"
xs = []
ys = []
with open(filename, 'r') as fin:
next(fin) # skip headings
if delimiter == ',':
... | [
"csv.reader",
"math.sqrt",
"numpy.ones",
"scipy.stats.distributions.t.ppf",
"numpy.mean",
"numpy.linalg.inv",
"numpy.array",
"numpy.dot",
"scipy.stats.t.ppf",
"numpy.diagonal"
] | [((1569, 1577), 'numpy.linalg.inv', 'inv', (['XTX'], {}), '(XTX)\n', (1572, 1577), False, 'from numpy.linalg import inv\n'), ((1642, 1658), 'numpy.dot', 'dot', (['invXTX', 'XTy'], {}), '(invXTX, XTy)\n', (1645, 1658), False, 'from numpy import dot\n'), ((1831, 1846), 'numpy.dot', 'dot', (['x_array', 'B'], {}), '(x_arra... |
import argparse
import os
import errno
import sys
import glob
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import random
import string
import sys
import numpy as np
import datetime
import pandas as pd
import tqdm
from omniprint.string_generator import create_strings_from_dict
from omniprint.stri... | [
"numpy.random.seed",
"argparse.ArgumentParser",
"omniprint.string_generator.create_strings_from_dict",
"pandas.read_csv",
"datetime.datetime.utcnow",
"os.path.isfile",
"omniprint.string_generator.create_strings_from_dict_equal",
"os.path.join",
"omniprint.utils.add_txt_extension",
"multiprocessing... | [((1956, 2050), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate synthetic text data for text recognition."""'}), "(description=\n 'Generate synthetic text data for text recognition.')\n", (1979, 2050), False, 'import argparse\n'), ((36540, 36594), 'os.path.join', 'os.path.join... |
import numpy as np
import networkx as nx
import sys
from argparse import ArgumentParser
import json
from networkx.readwrite import json_graph
import time
from embed_methods.deepwalk.deepwalk import *
from embed_methods.node2vec.node2vec import *
from embed_methods.graphsage.graphsage import *
from embed_methods.dgi.ex... | [
"networkx.readwrite.json_graph.node_link_graph",
"numpy.save",
"argparse.ArgumentParser",
"time.process_time",
"networkx.Graph",
"scoring.lr"
] | [((385, 423), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Original"""'}), "(description='Original')\n", (399, 423), False, 'from argparse import ArgumentParser\n'), ((2944, 2973), 'numpy.save', 'np.save', (['save_dir', 'embeddings'], {}), '(save_dir, embeddings)\n', (2951, 2973), True, 'import... |
import struct
import operator
import functools
import numpy as np
def read(file, dtype, count):
buffer = np.fromfile(file, dtype=dtype, count=count)
if count == 1:
return buffer[0]
return buffer
def write(file, format, buffer):
if isinstance(buffer, np.ndarray):
buffer = buffer.fla... | [
"numpy.fromfile",
"numpy.asarray",
"struct.pack",
"numpy.reshape",
"functools.reduce"
] | [((111, 154), 'numpy.fromfile', 'np.fromfile', (['file'], {'dtype': 'dtype', 'count': 'count'}), '(file, dtype=dtype, count=count)\n', (122, 154), True, 'import numpy as np\n'), ((446, 474), 'struct.pack', 'struct.pack', (['format', '*buffer'], {}), '(format, *buffer)\n', (457, 474), False, 'import struct\n'), ((905, 9... |
import numpy as np
# Read AutoLAB data file: two blank header lines and time; voltage data
def readAL(fname, I):
data = np.loadtxt(fname,skiprows=2)
m = np.insert(data, 2, values=I, axis=1) # add I column
m[:,0] = m[:,0] - m[0,0] # time begins at 0
return(m)
| [
"numpy.loadtxt",
"numpy.insert"
] | [((129, 158), 'numpy.loadtxt', 'np.loadtxt', (['fname'], {'skiprows': '(2)'}), '(fname, skiprows=2)\n', (139, 158), True, 'import numpy as np\n'), ((167, 203), 'numpy.insert', 'np.insert', (['data', '(2)'], {'values': 'I', 'axis': '(1)'}), '(data, 2, values=I, axis=1)\n', (176, 203), True, 'import numpy as np\n')] |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | [
"mindspore.ops.operations.Sigmoid",
"mindspore.ops.operations.ReduceSum",
"numpy.log",
"math.sqrt",
"mindspore.ops.operations.Erf",
"mindspore.nn.LogSigmoid",
"mindspore.ops.operations.Log",
"mindspore.ops.operations.Exp"
] | [((826, 835), 'mindspore.ops.operations.Exp', 'ops.Exp', ([], {}), '()\n', (833, 835), True, 'from mindspore.ops import operations as ops\n'), ((843, 858), 'mindspore.ops.operations.ReduceSum', 'ops.ReduceSum', ([], {}), '()\n', (856, 858), True, 'from mindspore.ops import operations as ops\n'), ((866, 875), 'mindspore... |
#!/usr/bin/env python
# coding: utf-8
#%% global packages
#import mesa.batchrunner as mb
import numpy as np
#import networkx as nx
#import uuid
import pandas as pd
from IPython.core.display import display
import matplotlib as mpl
#import matplotlib.figure as figure
#import matplotlib.markers as markers
mpl.rc('text'... | [
"sys.path.append",
"matplotlib.rc",
"IPython.core.display.display",
"pandas.read_csv",
"os.getcwd",
"os.path.dirname",
"numpy.polyfit",
"matplotlib.figure.Figure",
"numpy.array",
"numpy.loadtxt",
"numpy.arange",
"os.chdir"
] | [((307, 334), 'matplotlib.rc', 'mpl.rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (313, 334), True, 'import matplotlib as mpl\n'), ((337, 360), 'matplotlib.rc', 'mpl.rc', (['"""font"""'], {'size': '(10)'}), "('font', size=10)\n", (343, 360), True, 'import matplotlib as mpl\n'), ((593, 614), 's... |
import numpy as np
import torch
import torch.nn as nn
from src.models.loss import RMSELoss, RMSLELoss
from sklearn.metrics import r2_score
import pandas as pd
#########################
# EARLY STOPPING
#########################
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve ... | [
"pandas.DataFrame",
"pandas.DataFrame.from_dict",
"torch.nn.L1Loss",
"torch.load",
"sklearn.metrics.r2_score",
"numpy.ones",
"src.models.loss.RMSELoss",
"torch.save",
"numpy.argsort",
"torch.cuda.is_available",
"numpy.array",
"torch.device",
"src.models.loss.RMSLELoss",
"torch.no_grad",
... | [((4116, 4127), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {}), '()\n', (4125, 4127), True, 'import torch.nn as nn\n'), ((4149, 4159), 'src.models.loss.RMSELoss', 'RMSELoss', ([], {}), '()\n', (4157, 4159), False, 'from src.models.loss import RMSELoss, RMSLELoss\n'), ((4182, 4193), 'src.models.loss.RMSLELoss', 'RMSLELoss', (... |
"""
https://matplotlib.org/users/event_handling.html
"""
import warnings
warnings.filterwarnings(action="ignore") # to ignore UserWarning
from imageio import imread
import matplotlib as mpl
mpl.use("TkAgg")
mpl.rcParams['toolbar'] = 'None' # disable toolbar
# Disable default key binding.
# https://github.com/matp... | [
"matplotlib.pyplot.show",
"warnings.filterwarnings",
"imageio.imread",
"matplotlib.use",
"numpy.array",
"matplotlib.pyplot.subplots"
] | [((74, 114), 'warnings.filterwarnings', 'warnings.filterwarnings', ([], {'action': '"""ignore"""'}), "(action='ignore')\n", (97, 114), False, 'import warnings\n'), ((194, 210), 'matplotlib.use', 'mpl.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (201, 210), True, 'import matplotlib as mpl\n'), ((7867, 7881), 'matplotlib.... |
from typing import List
import numpy as np
from bandit.discrete.DiscreteBandit import DiscreteBandit
class EXP3Bandit(DiscreteBandit):
"""
Class representing a Exp3 bandit
Found at https://jeremykun.com/2013/11/08/adversarial-bandits-and-the-exp3-algorithm/
"""
def __init__(self, n_arms: int, ga... | [
"numpy.math.exp",
"numpy.argmax",
"numpy.zeros",
"numpy.ones",
"numpy.max",
"numpy.random.choice"
] | [((651, 674), 'numpy.max', 'np.max', (['self.arm_values'], {}), '(self.arm_values)\n', (657, 674), True, 'import numpy as np\n'), ((715, 730), 'numpy.ones', 'np.ones', (['n_arms'], {}), '(n_arms)\n', (722, 730), True, 'import numpy as np\n'), ((842, 858), 'numpy.zeros', 'np.zeros', (['n_arms'], {}), '(n_arms)\n', (850,... |
"""Evaluate predictions using an oracle that removes false positives."""
import argparse
import collections
import json
import logging
from pathlib import Path
import numpy as np
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from pycocotools import mask as mask_utils
import _init_paths ... | [
"json.dump",
"json.load",
"datasets.task_evaluation._coco_eval_to_box_results",
"datasets.task_evaluation._coco_eval_to_mask_results",
"pycocotools.mask.iou",
"utils.io.save_object",
"collections.defaultdict",
"numpy.any",
"pycocotools.coco.COCO",
"pathlib.Path",
"pycocotools.cocoeval.COCOeval",... | [((1749, 1776), 'pycocotools.coco.COCO', 'COCO', (['args.annotations_json'], {}), '(args.annotations_json)\n', (1753, 1776), False, 'from pycocotools.coco import COCO\n'), ((1796, 1817), 'pathlib.Path', 'Path', (['args.output_dir'], {}), '(args.output_dir)\n', (1800, 1817), False, 'from pathlib import Path\n'), ((1928,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
import matplotlib.cm as cm
import matplotlib.font_manager as fm
import math as m
import ma... | [
"pandas.DataFrame",
"matplotlib.font_manager.FontProperties",
"pandas.read_csv",
"matplotlib.pyplot.close",
"matplotlib.pyplot.legend",
"numpy.nanstd",
"os.system",
"matplotlib.pyplot.figure",
"matplotlib.use",
"pandas.to_datetime",
"numpy.gradient",
"pandas.Grouper",
"datetime.timedelta",
... | [((144, 165), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (158, 165), False, 'import matplotlib\n'), ((635, 722), 'matplotlib.font_manager.FontProperties', 'fm.FontProperties', ([], {'fname': '"""/home/nacorreasa/SIATA/Cod_Califi/AvenirLTStd-Heavy.otf"""'}), "(fname=\n '/home/nacorreasa/SIA... |
# Load the example pcd
import open3d as o3d
import numpy as np
def load_example_pcd(np_file):
d = np.load(np_file, allow_pickle=True, encoding='bytes').item()
xyz = d['xyz'].reshape(-1, 3)
print(xyz)
rgb = d['rgb'].reshape(-1, 3)/255
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(xyz)
... | [
"numpy.load",
"numpy.asarray",
"open3d.io.read_point_cloud",
"open3d.geometry.PointCloud",
"open3d.io.write_point_cloud",
"open3d.visualization.draw_geometries",
"open3d.utility.Vector3dVector"
] | [((247, 272), 'open3d.geometry.PointCloud', 'o3d.geometry.PointCloud', ([], {}), '()\n', (270, 272), True, 'import open3d as o3d\n'), ((287, 318), 'open3d.utility.Vector3dVector', 'o3d.utility.Vector3dVector', (['xyz'], {}), '(xyz)\n', (313, 318), True, 'import open3d as o3d\n'), ((333, 364), 'open3d.utility.Vector3dVe... |
"""Example: optimizing a layout with constraints
This example uses a dummy cost function to optimize turbine types.
"""
import numpy as np
import os
from topfarm.cost_models.dummy import DummyCost
from topfarm._topfarm import TopFarmProblem
from openmdao.drivers.doe_generators import FullFactorialGenerator
from topfar... | [
"matplotlib.pyplot.show",
"openmdao.drivers.doe_generators.FullFactorialGenerator",
"numpy.array",
"topfarm.plotting.NoPlot",
"topfarm.cost_models.dummy.DummyCost",
"matplotlib.pyplot.gcf",
"os.path.split"
] | [((554, 580), 'numpy.array', 'np.array', (['[[0, 0], [6, 6]]'], {}), '([[0, 0], [6, 6]])\n', (562, 580), True, 'import numpy as np\n'), ((628, 648), 'numpy.array', 'np.array', (['[[2], [6]]'], {}), '([[2], [6]])\n', (636, 648), True, 'import numpy as np\n'), ((959, 968), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '(... |
import numpy as np
filename = 'data.txt'
with open(filename, 'r') as f:
lines = f.readlines()
bits = np.array([[int(number) for number in line.strip()] for line in lines])
gamma = np.sum(bits==1, axis=0) > np.sum(bits==0, axis=0)
gamma = gamma.astype(int)
epsilon = 1 - gamma
def to_int(x):
return int('0b... | [
"numpy.sum"
] | [((189, 214), 'numpy.sum', 'np.sum', (['(bits == 1)'], {'axis': '(0)'}), '(bits == 1, axis=0)\n', (195, 214), True, 'import numpy as np\n'), ((215, 240), 'numpy.sum', 'np.sum', (['(bits == 0)'], {'axis': '(0)'}), '(bits == 0, axis=0)\n', (221, 240), True, 'import numpy as np\n'), ((631, 647), 'numpy.sum', 'np.sum', (['... |
import logging
import math
import string
from collections import Counter, defaultdict
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Dict, Tuple
import numpy
class LeontisWesthof(Enum):
cWW = 'cWW'
cWH = 'cWH'
cWS = 'cWS'
cHW = 'cHW'
cHH = 'cHH'
cHS... | [
"math.isnan",
"logging.error",
"numpy.cross",
"collections.defaultdict",
"numpy.array",
"numpy.linalg.norm",
"numpy.dot",
"math.degrees",
"dataclasses.dataclass"
] | [((1382, 1404), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (1391, 1404), False, 'from dataclasses import dataclass\n'), ((1473, 1495), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (1482, 1495), False, 'from dataclasses import dataclass\n'... |
import sys
sys.path.insert(0,'.')
import cv2
import numpy as np
from modules import face_track_server, face_describer_server, face_db, camera_server,face_align_server
from configs import configs
'''
The register app utilize all servers in model
I have a camera product and I need to use it to find all visitors in my ... | [
"modules.face_track_server.FaceTrackServer",
"modules.face_describer_server.FDServer",
"cv2.waitKey",
"sys.path.insert",
"modules.face_db.Model",
"numpy.expand_dims",
"cv2.rectangle",
"cv2.imshow",
"cv2.resize"
] | [((12, 35), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""."""'], {}), "(0, '.')\n", (27, 35), False, 'import sys\n'), ((695, 730), 'modules.face_track_server.FaceTrackServer', 'face_track_server.FaceTrackServer', ([], {}), '()\n', (728, 730), False, 'from modules import face_track_server, face_describer_server, f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.