code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
from sklearn import neighbors, datasets
from sklearn import tree
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
#Training Set
X = np.zeros((22,1))
X[:,0] = np.arange(0,11,.5)
noisesigma = 2.5
Y = np.ravel((2-(X-5)**2 + noisesigma * np.random.randn(22, 1))>0)
#Testing... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.random.randn",
"matplotlib.pyplot.legend",
"numpy.zeros",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.neighbors.KNeighborsClassifier",
"numpy.arange"
] | [((182, 199), 'numpy.zeros', 'np.zeros', (['(22, 1)'], {}), '((22, 1))\n', (190, 199), True, 'import numpy as np\n'), ((208, 229), 'numpy.arange', 'np.arange', (['(0)', '(11)', '(0.5)'], {}), '(0, 11, 0.5)\n', (217, 229), True, 'import numpy as np\n'), ((330, 348), 'numpy.zeros', 'np.zeros', (['(110, 1)'], {}), '((110,... |
import numpy as np
jolts = sorted(np.array(open('input.txt').read().strip().split('\n'), dtype=int))
jolts.append(max(jolts)+3)
last = 0
deltas = []
for n in jolts:
delta = n - last
deltas.append(delta)
last = n
print(np.product(np.unique(deltas, return_counts=True)[1])) | [
"numpy.unique"
] | [((245, 282), 'numpy.unique', 'np.unique', (['deltas'], {'return_counts': '(True)'}), '(deltas, return_counts=True)\n', (254, 282), True, 'import numpy as np\n')] |
from unittest import TestCase
from copy import deepcopy
from numpy import array as np_array
from rptools.rpthermo.rpThermo import (
build_stoichio_matrix,
get_target_rxn_idx,
minimize,
remove_compounds,
# eQuilibrator,
# initThermo,
# get_compounds_from_cache
)
from brs_utils import (
cr... | [
"rptools.rpthermo.rpThermo.minimize",
"copy.deepcopy",
"rptools.rpthermo.rpThermo.build_stoichio_matrix",
"rptools.rplibs.rpPathway",
"chemlite.Reaction.sum_stoichio",
"rptools.rplibs.rpReaction",
"numpy.array",
"rptools.rplibs.rpCompound",
"brs_utils.create_logger"
] | [((490, 703), 'rptools.rplibs.rpCompound', 'rpCompound', ([], {'id': '"""TARGET_0000000001"""', 'smiles': '"""[H]OC(=O)C([H])=C([H])C([H])=C([H])C(=O)O[H]"""', 'inchi': '"""InChI=1S/C6H6O4/c7-5(8)3-1-2-4-6(9)10/h1-4H,(H,7,8)(H,9,10)"""', 'inchikey': '"""TXXHDPDFNKHHGW-UHFFFAOYSA-N"""'}), "(id='TARGET_0000000001', smile... |
import pymbs.symbolics as symbolics
from pymbs.symbolics import zeros, eye
from .frame import Frame
from pymbs.common.sidfilereader import SID, SIDFormatException
from pymbs.common.abstractbody import AbstractBody
import numpy as np
class Body(AbstractBody, Frame):
"""
"""
def __init__(self, name, mass,... | [
"pymbs.common.abstractbody.AbstractBody.__init__",
"pymbs.common.sidfilereader.SID",
"pymbs.symbolics.zeros",
"numpy.array",
"pymbs.symbolics.eye"
] | [((387, 439), 'pymbs.common.abstractbody.AbstractBody.__init__', 'AbstractBody.__init__', (['self', 'name', 'mass', 'cg', 'inertia'], {}), '(self, name, mass, cg, inertia)\n', (408, 439), False, 'from pymbs.common.abstractbody import AbstractBody\n'), ((2087, 2110), 'pymbs.symbolics.zeros', 'symbolics.zeros', (['(3, 3)... |
#!/usr/bin/env python
import os
import itertools
import time
import numpy as np
import pytest
import requests
import astrodata
from astrodata.testing import download_from_archive
from geminidr.core import primitives_visualize
from geminidr.gmos.primitives_gmos_image import GMOSImage
single_aperture_data = [
# (... | [
"os.remove",
"pytest.main",
"numpy.mean",
"glob.glob",
"pytest.mark.parametrize",
"geminidr.core.primitives_visualize.Visualize",
"os.path.join",
"os.chdir",
"astrodata.testing.download_from_archive",
"astrodata.open",
"os.path.exists",
"requests.get",
"itertools.product",
"recipe_system.r... | [((3545, 3618), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input_ads"""', 'single_aperture_data'], {'indirect': '(True)'}), "('input_ads', single_aperture_data, indirect=True)\n", (3568, 3618), False, 'import pytest\n'), ((3620, 3657), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""check_a... |
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software an... | [
"omni.isaac.samples.scripts.rmp_sample.sample.RMPSample",
"pxr.Gf.Vec3d",
"asyncio.sleep",
"carb.settings.get_settings",
"omni.physx.get_physx_interface",
"numpy.array"
] | [((1121, 1132), 'omni.isaac.samples.scripts.rmp_sample.sample.RMPSample', 'RMPSample', ([], {}), '()\n', (1130, 1132), False, 'from omni.isaac.samples.scripts.rmp_sample.sample import RMPSample\n'), ((4666, 4691), 'pxr.Gf.Vec3d', 'Gf.Vec3d', (['(30.0)', '(-20.0)', '(12)'], {}), '(30.0, -20.0, 12)\n', (4674, 4691), Fals... |
import inspect
from typing import Any
import numpy as np
import pandas as pd
from aistac.handlers.abstract_handlers import HandlerFactory
from ds_discovery.intent.abstract_common_intent import AbstractCommonsIntentModel
from ds_discovery.managers.feature_catalog_property_manager import FeatureCatalogPropertyManager
f... | [
"pandas.interval_range",
"pandas.DataFrame.from_dict",
"aistac.handlers.abstract_handlers.HandlerFactory.get_module",
"ds_discovery.components.commons.Commons.list_formatter",
"pandas.get_dummies",
"pandas.merge",
"pandas.Timedelta",
"aistac.components.aistac_commons.DataAnalytics",
"ds_discovery.co... | [((9118, 9145), 'ds_discovery.components.commons.Commons.list_formatter', 'Commons.list_formatter', (['key'], {}), '(key)\n', (9140, 9145), False, 'from ds_discovery.components.commons import Commons\n'), ((13359, 13386), 'ds_discovery.components.commons.Commons.list_formatter', 'Commons.list_formatter', (['key'], {}),... |
from typing import List, Union
import numpy as np
import tensorflow as tf
import nn_utils.math_utils as math_utils
from dataflow.illumination_integration.helper import (
getBilinearFromUv,
)
from nn_utils.math_utils import shape_to_uv, uv_to_direction
@tf.function
def map_levels_to_samples(
num_roughness_0:... | [
"tensorflow.math.floor",
"tensorflow.reshape",
"tensorflow.zeros_like",
"dataflow.illumination_integration.helper.getBilinearFromUv",
"tensorflow.math.ceil",
"tensorflow.random.uniform",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.debugging.assert_shapes",
"numpy.linspace",
"nn_utils.math... | [((457, 485), 'nn_utils.math_utils.shape_to_uv', 'shape_to_uv', (['*env_shape[:-1]'], {}), '(*env_shape[:-1])\n', (468, 485), False, 'from nn_utils.math_utils import shape_to_uv, uv_to_direction\n'), ((501, 525), 'tensorflow.reshape', 'tf.reshape', (['uvs', '[-1, 2]'], {}), '(uvs, [-1, 2])\n', (511, 525), True, 'import... |
"""Modulator Module that implements various wireless modulators
These modulators are meant to turn arbitrary bit patterns to analog waveforms for wireless
transmission.
"""
import numpy as np
class OFDM:
"""Class that creates OFDM signals.
This class will set up an OFDM modulator to create random OFDM sign... | [
"numpy.fft.ifft",
"numpy.random.seed",
"numpy.fft.fft",
"numpy.log2",
"numpy.zeros",
"numpy.ones",
"numpy.random.randint",
"numpy.arange",
"numpy.reshape",
"numpy.linalg.norm",
"numpy.int",
"numpy.sqrt"
] | [((2355, 2380), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (2369, 2380), True, 'import numpy as np\n'), ((2539, 2611), 'numpy.zeros', 'np.zeros', (['(self.fft_size + self.cp_length, n_symbols)'], {'dtype': '"""complex64"""'}), "((self.fft_size + self.cp_length, n_symbols), dtype='compl... |
import json
import numpy as np
from pdb import set_trace
names = ['DUT','ECSSD','HKU_IS','MSRA1000','SOD']
ext='json'
reduced_name = 'reduced'
dump = {}
dump['cols'] = ['max.abs', 'min.abs', 'median.abs', 'mean.abs', 'var.abs']
for name in names:
with open('{}.{}'.format(name,ext), 'r') as f:
stat = js... | [
"json.dump",
"json.load",
"numpy.array"
] | [((343, 357), 'numpy.array', 'np.array', (['stat'], {}), '(stat)\n', (351, 357), True, 'import numpy as np\n'), ((482, 500), 'json.dump', 'json.dump', (['dump', 'f'], {}), '(dump, f)\n', (491, 500), False, 'import json\n'), ((318, 330), 'json.load', 'json.load', (['f'], {}), '(f)\n', (327, 330), False, 'import json\n')... |
from pathlib import Path
import os
import sys
import shutil
import _init_paths
from utils import BBFormat, CoordinatesType
import numpy as np
# Get current path to set default folders
currentPath = os.path.dirname(os.path.abspath(__file__))
# Get folder details
gtFolder = Path(os.path.join(currentPath, ... | [
"os.path.abspath",
"os.makedirs",
"os.path.isdir",
"numpy.arange",
"shutil.rmtree",
"os.path.join",
"os.listdir",
"sys.exit"
] | [((578, 603), 'numpy.arange', 'np.arange', (['(0.1)', '(1.0)', '(0.05)'], {}), '(0.1, 1.0, 0.05)\n', (587, 603), True, 'import numpy as np\n'), ((2148, 2191), 'shutil.rmtree', 'shutil.rmtree', (['savePath'], {'ignore_errors': '(True)'}), '(savePath, ignore_errors=True)\n', (2161, 2191), False, 'import shutil\n'), ((219... |
# --------------------------------------------------------------------
# jokettt project, v. 0.1
# by <NAME> <<EMAIL>>
# ---
# Tic Tac Toe Board class definition
# --------------------------------------------------------------------
"""Implementation of the Board class: a board to play Tic Tac Toe game."""
__all__ = ['... | [
"numpy.empty",
"random.seed",
"random.randint"
] | [((11916, 11946), 'numpy.empty', 'np.empty', (['[3, 3, 2]'], {'dtype': 'int'}), '([3, 3, 2], dtype=int)\n', (11924, 11946), True, 'import numpy as np\n'), ((12203, 12216), 'random.seed', 'random.seed', ([], {}), '()\n', (12214, 12216), False, 'import random\n'), ((12389, 12419), 'random.randint', 'random.randint', (['(... |
import numpy as np
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank, size = comm.rank, comm.size
import dedalus.public as de
import matplotlib.pyplot as plt
import os
from scipy.special import erf
import time
import logging
root = logging.root
for h in root.handlers: h.setLevel("INFO")
logger = logging.getLogger(__nam... | [
"numpy.meshgrid",
"os.makedirs",
"os.path.isdir",
"dedalus.public.IVP",
"dedalus.public.Fourier",
"dedalus.public.Domain",
"time.time",
"dedalus.public.Compound",
"dedalus.public.Chebyshev",
"numpy.sin",
"os.path.join",
"logging.getLogger",
"numpy.sqrt"
] | [((297, 324), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (314, 324), False, 'import logging\n'), ((373, 388), 'numpy.sqrt', 'np.sqrt', (['(η / Re)'], {}), '(η / Re)\n', (380, 388), True, 'import numpy as np\n'), ((585, 615), 'os.path.join', 'os.path.join', (['"""runs"""', 'sim_name'],... |
import math
import numpy as np
import matplotlib.pyplot as plt
def create_plot():
"Funcție ajutătoare pentru crearea graficului."
# Creez un subplot
fig, ax = plt.subplots(1, dpi=200)
# Setez axele de coordonate
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
... | [
"numpy.abs",
"matplotlib.pyplot.show",
"numpy.exp",
"math.log2",
"matplotlib.pyplot.subplots"
] | [((1627, 1637), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1635, 1637), True, 'import matplotlib.pyplot as plt\n'), ((2256, 2266), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2264, 2266), True, 'import matplotlib.pyplot as plt\n'), ((3927, 3937), 'matplotlib.pyplot.show', 'plt.show', ([], {})... |
from dreaml.dataframe.transform import BatchTransform
from dreaml.dataframe.dataframe import DataFrame
from pcabasis import PCABasis
from dot import Dot
import numpy as np
import numpy.linalg as la
_auto_dir = "auto/"
class PCA(BatchTransform):
def func(self,target_df,X_pca_df,X_full_df=None,num_bases=50):
... | [
"numpy.linalg.svd",
"numpy.mean",
"numpy.real"
] | [((448, 482), 'numpy.mean', 'np.mean', (['X_pca_df.r_matrix'], {'axis': '(0)'}), '(X_pca_df.r_matrix, axis=0)\n', (455, 482), True, 'import numpy as np\n'), ((1000, 1018), 'numpy.mean', 'np.mean', (['X'], {'axis': '(0)'}), '(X, axis=0)\n', (1007, 1018), True, 'import numpy as np\n'), ((1082, 1094), 'numpy.linalg.svd', ... |
# module containing the External Compton radiative process
import numpy as np
from astropy.constants import c, sigma_T, G
from ..utils.math import (
trapz_loglog,
log,
axes_reshaper,
gamma_to_integrate,
mu_to_integrate,
phi_to_integrate,
)
from ..utils.conversion import nu_to_epsilon_prime, to_R... | [
"numpy.trapz",
"numpy.linspace",
"numpy.power"
] | [((2018, 2058), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', 'self.phi_size'], {}), '(0, 2 * np.pi, self.phi_size)\n', (2029, 2058), True, 'import numpy as np\n'), ((4886, 4922), 'numpy.trapz', 'np.trapz', (['integral_gamma', 'mu'], {'axis': '(0)'}), '(integral_gamma, mu, axis=0)\n', (4894, 4922), True, 'im... |
# pylint: disable=no-self-use,invalid-name
import numpy
import pytest
from allennlp.common.checks import ConfigurationError
from allennlp.common.testing import AllenNlpTestCase
from allennlp.data.fields import MultiLabelField
from allennlp.data.vocabulary import Vocabulary
class TestMultiLabelField(AllenNlpTestCase)... | [
"allennlp.data.vocabulary.Vocabulary",
"allennlp.data.fields.MultiLabelField",
"pytest.raises",
"numpy.array"
] | [((387, 473), 'allennlp.data.fields.MultiLabelField', 'MultiLabelField', (['[2, 3]'], {'skip_indexing': '(True)', 'label_namespace': '"""test1"""', 'num_labels': '(5)'}), "([2, 3], skip_indexing=True, label_namespace='test1',\n num_labels=5)\n", (402, 473), False, 'from allennlp.data.fields import MultiLabelField\n'... |
#encoding: utf-8
import copy
import csv
import numpy as np
# number of motif
Nm = 8
def countMotifs(A,nodN):
rd=np.argsort(sum(np.transpose(A)))
rdA=A[rd]
rdA[:,]=rdA[:,rd]
A2=np.array(np.matrix(A)**2)
A3=np.array(np.matrix(A)**3)
A4=np.array(np.matrix(A)**4)
num_triangle=count_triangle(... | [
"numpy.matrix",
"numpy.sum",
"csv.writer",
"numpy.transpose",
"copy.copy",
"numpy.nonzero"
] | [((785, 797), 'copy.copy', 'copy.copy', (['A'], {}), '(A)\n', (794, 797), False, 'import copy\n'), ((1607, 1619), 'copy.copy', 'copy.copy', (['A'], {}), '(A)\n', (1616, 1619), False, 'import copy\n'), ((2739, 2753), 'csv.writer', 'csv.writer', (['fc'], {}), '(fc)\n', (2749, 2753), False, 'import csv\n'), ((135, 150), '... |
# -*- coding: utf-8 -*-
"""
Collection of tools for writing formatted text to files.
"""
import numpy as np
from pyyeti import ytools
def getith(i, args, fncs):
"""
Return list with i'th value from each input, typically called by
:func:`vecwrite`.
Parameters
----------
i : integer
Sp... | [
"numpy.size",
"numpy.ndim"
] | [((5983, 5995), 'numpy.ndim', 'np.ndim', (['arg'], {}), '(arg)\n', (5990, 5995), True, 'import numpy as np\n'), ((6068, 6083), 'numpy.size', 'np.size', (['arg', '(0)'], {}), '(arg, 0)\n', (6075, 6083), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
def sigmoid(x: np.ndarray) -> np.ndarray:
sigmoid_range = 34.538776394910684
x = np.clip(x, -sigmoid_range, sigmoid_range)
return 1.0 / (1.0 + np.exp(-x))
# Intersection of Union
# bboxesX[:4] is numpy array of xyxy (xmin, ymin, xmax, ymax)... | [
"numpy.minimum",
"numpy.maximum",
"numpy.argmax",
"numpy.clip",
"numpy.insert",
"numpy.finfo",
"numpy.exp",
"numpy.delete",
"numpy.concatenate"
] | [((155, 196), 'numpy.clip', 'np.clip', (['x', '(-sigmoid_range)', 'sigmoid_range'], {}), '(x, -sigmoid_range, sigmoid_range)\n', (162, 196), True, 'import numpy as np\n'), ((809, 851), 'numpy.maximum', 'np.maximum', (['bboxes1[:, :2]', 'bboxes2[:, :2]'], {}), '(bboxes1[:, :2], bboxes2[:, :2])\n', (819, 851), True, 'imp... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 23:39:52 2021
@author: Jonas
"""
# Import packages.
import cvxpy as cp
import numpy as np
# Generate data.
m = 20
n = 15
np.random.seed(1)
A = np.random.randn(m, n)
b = np.random.randn(m)
# Define and solve the CVXPY problem.
x = cp.Variable(n)
cost = cp.sum_squares(... | [
"numpy.random.seed",
"numpy.random.randn",
"cvxpy.norm",
"cvxpy.Variable",
"cvxpy.sum_squares",
"cvxpy.Minimize"
] | [((173, 190), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (187, 190), True, 'import numpy as np\n'), ((195, 216), 'numpy.random.randn', 'np.random.randn', (['m', 'n'], {}), '(m, n)\n', (210, 216), True, 'import numpy as np\n'), ((221, 239), 'numpy.random.randn', 'np.random.randn', (['m'], {}), '(m)\n... |
#%%
import os
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers, losses, optimizers, Sequential
tf.random.set_seed(22)
np.random.seed(22)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
assert tf.__version__.startswith('2.')
batchsz = 128 # 批量大小
total_words... | [
"tensorflow.random.set_seed",
"numpy.random.seed",
"tensorflow.keras.datasets.imdb.get_word_index",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.GRU",
"tensorflow.keras.layers.ReLU",
"tensorflow.keras.datasets.imdb.load_data",
"tensorflow.data.Dataset.... | [((165, 187), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(22)'], {}), '(22)\n', (183, 187), True, 'import tensorflow as tf\n'), ((188, 206), 'numpy.random.seed', 'np.random.seed', (['(22)'], {}), '(22)\n', (202, 206), True, 'import numpy as np\n'), ((255, 286), 'tensorflow.__version__.startswith', 'tf.__ver... |
"""
Coordination number
===================
This filter calculates the coordination number of the atoms in the system.
It uses the values specified in the bonding table to determine whether two
atoms are bonded. If no minimum/maximum bond lengths are specified for a
given pair of elements then bonds between them will... | [
"numpy.zeros",
"six.moves.range"
] | [((1854, 1902), 'numpy.zeros', 'np.zeros', (['(NSpecies, NSpecies)'], {'dtype': 'np.float64'}), '((NSpecies, NSpecies), dtype=np.float64)\n', (1862, 1902), True, 'import numpy as np\n'), ((1926, 1974), 'numpy.zeros', 'np.zeros', (['(NSpecies, NSpecies)'], {'dtype': 'np.float64'}), '((NSpecies, NSpecies), dtype=np.float... |
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics.pairwise import chi2_kernel, additive_chi2_kernel
from sklearn.base import BaseEstimator
from sklearn.pipeline import Pipeline
def bhattacharyya(x, y):
return (1 - np.dot(np.sqrt(x), np.sqrt(y.T)... | [
"sklearn.pipeline.Pipeline",
"numpy.sqrt",
"sklearn.preprocessing.StandardScaler",
"sklearn.svm.SVC"
] | [((652, 687), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'with_mean': 'with_mean'}), '(with_mean=with_mean)\n', (666, 687), False, 'from sklearn.preprocessing import StandardScaler\n'), ((935, 1009), 'sklearn.svm.SVC', 'SVC', ([], {'C': 'C', 'kernel': 'kernel', 'gamma': 'gamma', 'class_weight': 'cl... |
import numpy as np
def train_test_split(data, test_size, random_state=None):
np.random.seed(random_state)
shuffled_indices = np.random.permutation(len(data))
test_set_size = int(len(data) * test_size)
test_indices = shuffled_indices[:test_set_size]
train_indices = shuffled_indices[test_set_size:]
... | [
"numpy.random.seed"
] | [((83, 111), 'numpy.random.seed', 'np.random.seed', (['random_state'], {}), '(random_state)\n', (97, 111), True, 'import numpy as np\n')] |
import numpy as np
class Model(object):
def __init__(self):
"""Model init
Use python list to store every layer
"""
self.layers = []
def add(self, layer):
"""add layer
Parameters
----------
layer : {Layer-like, scalar}
"""
... | [
"numpy.mean",
"numpy.array",
"numpy.log",
"numpy.argmax"
] | [((1950, 1963), 'numpy.mean', 'np.mean', (['loss'], {}), '(loss)\n', (1957, 1963), True, 'import numpy as np\n'), ((6836, 6852), 'numpy.array', 'np.array', (['result'], {}), '(result)\n', (6844, 6852), True, 'import numpy as np\n'), ((1556, 1573), 'numpy.log', 'np.log', (['predict_y'], {}), '(predict_y)\n', (1562, 1573... |
#! /usr/bin/env python3
from astropy.table import Table
import dateutil
import dateutil.parser
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.cm import viridis_r
import argparse
import sys
import os
import multiprocessing as mp
import datetime
__author__ = ["<NAME... | [
"astropy.table.Table.read",
"argparse.ArgumentParser",
"matplotlib.pyplot.close",
"os.path.exists",
"matplotlib.pyplot.figure",
"numpy.where",
"matplotlib.dates.DateFormatter",
"numpy.choose",
"datetime.datetime.strptime",
"multiprocessing.Pool",
"sys.exit",
"numpy.log10",
"matplotlib.pyplot... | [((648, 668), 'astropy.table.Table.read', 'Table.read', (['filename'], {}), '(filename)\n', (658, 668), False, 'from astropy.table import Table\n'), ((817, 843), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 8)'}), '(figsize=(5, 8))\n', (827, 843), True, 'import matplotlib.pyplot as plt\n'), ((1517, 1... |
import numpy as np
from math import sin, exp, pi, ceil
def f(x):
return exp(3*x)*sin(2*x)
def trapezoid( start, end, h, f) :
points= ceil((end - start) / h)
x = np.linspace(start, end, points+1) # N+1 points make N subintervals
y = f(x)
trapezoidIntegral = (h / 2) * (y[0]+y[points]+np.sum(2*y[1... | [
"math.exp",
"numpy.sum",
"math.ceil",
"math.sin",
"numpy.linspace"
] | [((145, 168), 'math.ceil', 'ceil', (['((end - start) / h)'], {}), '((end - start) / h)\n', (149, 168), False, 'from math import sin, exp, pi, ceil\n'), ((177, 212), 'numpy.linspace', 'np.linspace', (['start', 'end', '(points + 1)'], {}), '(start, end, points + 1)\n', (188, 212), True, 'import numpy as np\n'), ((79, 89)... |
import sys
import nltk
import sklearn
import pandas
import numpy
# for checking the versions
print('Python: {}'.format(sys.version))
print('NLTK: {}'.format(nltk.__version__))
print('Scikit-learn: {}'.format(sklearn.__version__))
print('pandas: {}'.format(pandas.__version__))
print('numpy: {}'.format(numpy.__version__... | [
"matplotlib.pyplot.suptitle",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.bar",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.figure",
"sklearn.ensemble.VotingClassifier",
"sklearn.svm.SVC",
"pandas.read_table",
"sklearn.linea... | [((420, 485), 'pandas.read_table', 'pd.read_table', (['"""SMSSpamCollection"""'], {'header': 'None', 'encoding': '"""utf-8"""'}), "('SMSSpamCollection', header=None, encoding='utf-8')\n", (433, 485), True, 'import pandas as pd\n'), ((694, 708), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (70... |
from collections import OrderedDict
import logging
logger = logging.getLogger('tensorprob')
import numpy as np
import tensorflow as tf
from . import config
from .utilities import (
classproperty,
Description,
generate_name,
ModelSubComponet,
Region,
set_logp_to_neg_inf
)
class ModelError(Run... | [
"tensorflow.add_n",
"tensorflow.reduce_sum",
"tensorflow.constant",
"tensorflow.initialize_variables",
"tensorflow.assign",
"tensorflow.to_int32",
"tensorflow.equal",
"tensorflow.Graph",
"numpy.int32",
"collections.OrderedDict",
"tensorflow.gradients",
"logging.getLogger"
] | [((60, 91), 'logging.getLogger', 'logging.getLogger', (['"""tensorprob"""'], {}), "('tensorprob')\n", (77, 91), False, 'import logging\n'), ((3363, 3373), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (3371, 3373), True, 'import tensorflow as tf\n'), ((6680, 6693), 'collections.OrderedDict', 'OrderedDict', ([], {})... |
import gym
import numpy as np
from abc import ABC
from io import BytesIO
from PIL import Image
from eventobjects.action import Action, RESET_ACTION
class AndroidDeviceEnv(gym.Env, ABC):
"""
The AndroidDeviceEnv implements the gym Env interface in order to interface
with an Android device through the abs... | [
"io.BytesIO",
"numpy.array",
"gym.spaces.Box"
] | [((1828, 1934), 'gym.spaces.Box', 'gym.spaces.Box', ([], {'low': '(0)', 'high': '(255)', 'shape': '[image_height, image_width, self.NUM_CHANNELS]', 'dtype': 'np.uint8'}), '(low=0, high=255, shape=[image_height, image_width, self.\n NUM_CHANNELS], dtype=np.uint8)\n', (1842, 1934), False, 'import gym\n'), ((5305, 5324... |
"""module with functions that handle .phn annotation files from the TIMIT dataset
"""
import pathlib
from typing import ClassVar, Optional
import warnings
import attr
import numpy as np
import pandas as pd
import pandera
from pandera.typing import Series
import soundfile
import crowsetta
from crowsetta.typing import ... | [
"crowsetta.validation.validate_ext",
"soundfile.info",
"crowsetta.Sequence.from_keyword",
"pandas.read_csv",
"crowsetta.Annotation",
"attr.cmp_using",
"numpy.around",
"pathlib.Path",
"pandera.Field",
"attr.converters.optional",
"warnings.warn"
] | [((572, 587), 'pandera.Field', 'pandera.Field', ([], {}), '()\n', (585, 587), False, 'import pandera\n'), ((628, 643), 'pandera.Field', 'pandera.Field', ([], {}), '()\n', (641, 643), False, 'import pandera\n'), ((679, 705), 'pandera.Field', 'pandera.Field', ([], {'coerce': '(True)'}), '(coerce=True)\n', (692, 705), Fal... |
import numpy as np
from tqdm import trange, tqdm
from utils import frokf
import scipy.io as sio
## 配置
con_terms_linear5 = ['x1(t-1)', 'x1(t-2)', 'x1(t-2)', 'x1(t-3)', 'x1(t-2)', 'x4(t-1)', 'x5(t-1)', 'x4(t-1)', 'x5(t-1)'] # 9
con_terms_nonlinear5 = ['x1(t-1)', 'x1(t-2)', 'x1(t-2)*x1(t-2)', 'x1(t-3)', 'x1(t-2)*x1(t-2... | [
"numpy.stack",
"tqdm.tqdm",
"tqdm.trange",
"numpy.linspace",
"numpy.sqrt"
] | [((1115, 1137), 'numpy.linspace', 'np.linspace', (['(0.5)', '(4)', '(8)'], {}), '(0.5, 4, 8)\n', (1126, 1137), True, 'import numpy as np\n'), ((1263, 1292), 'tqdm.tqdm', 'tqdm', (["['linear', 'nonlinear']"], {}), "(['linear', 'nonlinear'])\n", (1267, 1292), False, 'from tqdm import trange, tqdm\n'), ((1310, 1323), 'tqd... |
import time
from os import environ
import numpy as np
from smartredis import Client, Dataset
from ..error import SmartSimError
from ..log import get_logger
logger = get_logger(__name__)
def form_name(*args):
return "_".join(str(arg) for arg in args if arg is not None)
class TrainingDataUploader:
"""A cla... | [
"smartredis.Client",
"numpy.floor",
"time.sleep",
"numpy.arange",
"numpy.random.shuffle"
] | [((3008, 3048), 'smartredis.Client', 'Client', ([], {'address': 'address', 'cluster': 'cluster'}), '(address=address, cluster=cluster)\n', (3014, 3048), False, 'from smartredis import Client, Dataset\n'), ((9527, 9539), 'numpy.arange', 'np.arange', (['(0)'], {}), '(0)\n', (9536, 9539), True, 'import numpy as np\n'), ((... |
'''
Usage
'''
import numpy as np
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.nn.modules.utils import _single, _pair, _triple
from torch.nn.modules.conv import _ConvNd
from torch.nn.modules import Module
from torch.nn import functional as F
from torch.autograd import Variable
i... | [
"torch.t",
"torch.ones",
"torch.eye",
"math.sqrt",
"torch.log",
"torch.svd",
"torch.autograd.Variable",
"torch.nn.functional.conv2d",
"torch.cat",
"torch.diag",
"numpy.ones",
"torch.exp",
"torch.Tensor",
"torch.qr",
"torch.nn.modules.utils._pair"
] | [((695, 710), 'torch.autograd.Variable', 'Variable', (['input'], {}), '(input)\n', (703, 710), False, 'from torch.autograd import Variable\n'), ((833, 843), 'torch.t', 'torch.t', (['W'], {}), '(W)\n', (840, 843), False, 'import torch\n'), ((1389, 1407), 'torch.nn.modules.utils._pair', '_pair', (['kernel_size'], {}), '(... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017 - for information on the respective copyright owner
# see the NOTICE file and/or the repository https://github.com/boschresearch/statestream
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.... | [
"numpy.abs",
"numpy.sum",
"numpy.std",
"numpy.median",
"numpy.zeros",
"numpy.max",
"numpy.mean",
"numpy.min",
"numpy.reshape",
"numpy.linalg.norm",
"numpy.var",
"numpy.prod"
] | [((5014, 5062), 'numpy.reshape', 'np.reshape', (['metric_val', '[x.shape[1], y.shape[1]]'], {}), '(metric_val, [x.shape[1], y.shape[1]])\n', (5024, 5062), True, 'import numpy as np\n'), ((1143, 1153), 'numpy.mean', 'np.mean', (['a'], {}), '(a)\n', (1150, 1153), True, 'import numpy as np\n'), ((1194, 1203), 'numpy.var',... |
from pandas import DataFrame
import seaborn
from sgld_test.gradients_of_likelihood import manual_grad, grad_log_prior
from sgld_test.mcmc_convergance.cosnt import CHAIN_SIZE, NUMBER_OF_TESTS, NO_OF_SAMPELS_IN_TEST, SEED, SAMPLE_SIZE
from sgld_test.likelihoods import gen_X, log_probability
from stat_test.linear_time imp... | [
"numpy.load",
"numpy.random.seed",
"sgld_test.gradients_of_likelihood.manual_grad",
"sgld_test.gradients_of_likelihood.grad_log_prior",
"sgld_test.likelihoods.gen_X",
"stat_test.quadratic_time.QuadraticMultiple",
"numpy.array",
"stat_test.quadratic_time.GaussianQuadraticTest",
"stat_test.linear_time... | [((471, 495), 'numpy.load', 'np.load', (['"""./samples.npy"""'], {}), "('./samples.npy')\n", (478, 495), True, 'import numpy as np\n'), ((497, 517), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (511, 517), True, 'import numpy as np\n'), ((522, 540), 'sgld_test.likelihoods.gen_X', 'gen_X', (['SAMPL... |
import numpy as np
from scipy.spatial.transform import Rotation
def no_termination(observation):
return False
def position_close_to_goal(observation):
dist_to_goal = np.linalg.norm(
observation["goal_object_position"]
- observation["object_position"]
)
# return dist_to_goal < 0.01
... | [
"scipy.spatial.transform.Rotation.from_quat",
"numpy.linalg.norm"
] | [((178, 267), 'numpy.linalg.norm', 'np.linalg.norm', (["(observation['goal_object_position'] - observation['object_position'])"], {}), "(observation['goal_object_position'] - observation[\n 'object_position'])\n", (192, 267), True, 'import numpy as np\n'), ((663, 721), 'scipy.spatial.transform.Rotation.from_quat', '... |
#!/usr/bin/python3
'''Advent of Code 2018 Day 17 solution'''
# pylint: disable=too-many-arguments
import re
import sys
from typing import TextIO, Tuple, List, Set
import numpy
sys.setrecursionlimit(10000)
Input = Tuple[Tuple[int, int, int, int], List[List[int]]]
def printmap(inputs: Input, visited: Set[Tuple[int, ... | [
"numpy.full",
"sys.setrecursionlimit",
"re.compile"
] | [((179, 207), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10000)'], {}), '(10000)\n', (200, 207), False, 'import sys\n'), ((879, 931), 're.compile', 're.compile', (['"""([xy])=(\\\\d+), [xy]=(\\\\d+)\\\\.\\\\.(\\\\d+)"""'], {}), "('([xy])=(\\\\d+), [xy]=(\\\\d+)\\\\.\\\\.(\\\\d+)')\n", (889, 931), False, 'imp... |
import numpy as np
class PolicyIteration:
def __init__(self, grid, policy, actions, small_change: float, gamma: float) -> None:
self.grid = grid
self.policy = policy
self.actions = actions
self.rows, self.cols = self.grid.grid_board.shape
self.value_function = np.zeros((self... | [
"numpy.abs",
"numpy.zeros",
"numpy.all"
] | [((306, 338), 'numpy.zeros', 'np.zeros', (['(self.rows, self.cols)'], {}), '((self.rows, self.cols))\n', (314, 338), True, 'import numpy as np\n'), ((2449, 2480), 'numpy.zeros', 'np.zeros', (['(self.rows * self.cols)'], {}), '(self.rows * self.cols)\n', (2457, 2480), True, 'import numpy as np\n'), ((3716, 3757), 'numpy... |
from copy import deepcopy
from typing import Any, Dict, List
import numpy as np
import torch
import torch.optim as opt
from genrl.agents import OffPolicyAgent
from genrl.utils import get_env_properties, get_model, safe_mean
class DQN(OffPolicyAgent):
"""Base DQN Class
Paper: https://arxiv.org/abs/1312.5602... | [
"copy.deepcopy",
"numpy.argmax",
"numpy.random.rand",
"torch.mul",
"genrl.utils.safe_mean",
"numpy.exp",
"genrl.utils.get_model",
"torch.as_tensor",
"genrl.utils.get_env_properties"
] | [((2222, 2264), 'genrl.utils.get_env_properties', 'get_env_properties', (['self.env', 'self.network'], {}), '(self.env, self.network)\n', (2240, 2264), False, 'from genrl.utils import get_env_properties, get_model, safe_mean\n'), ((2652, 2672), 'copy.deepcopy', 'deepcopy', (['self.model'], {}), '(self.model)\n', (2660,... |
import os
import pickle
import shlex
import tempfile
import time
from threading import Thread, Event
from typing import Optional, Dict
import numpy as np
import pytest
from numpy.random import RandomState
from rlai.agents.mdp import StochasticMdpAgent
from rlai.environments.gridworld import Gridworld, GridworldFeatur... | [
"numpy.allclose",
"rlai.q_S_A.tabular.TabularStateActionValueEstimator",
"pickle.load",
"rlai.gpi.utils.update_policy_iteration_plot",
"rlai.gpi.temporal_difference.iteration.iterate_value_q_pi",
"os.path.dirname",
"shlex.split",
"numpy.random.RandomState",
"rlai.q_S_A.function_approximation.models.... | [((1244, 1262), 'numpy.random.RandomState', 'RandomState', (['(12345)'], {}), '(12345)\n', (1255, 1262), False, 'from numpy.random import RandomState\n'), ((1297, 1338), 'rlai.environments.gridworld.Gridworld.example_4_1', 'Gridworld.example_4_1', (['random_state', 'None'], {}), '(random_state, None)\n', (1318, 1338), ... |
import json
import random
import numpy as np
import MDAnalysis as mda
class ZLayer():
def __init__(self):
self.lattice = None
self.name = None
self.zdepth = 0
class Molecule():
def __init__(self):
self.path = None
self.name = "Empty"
self.color = "#FFFFFF"
... | [
"numpy.amin",
"numpy.zeros",
"MDAnalysis.Universe",
"numpy.amax",
"numpy.mean",
"numpy.array",
"numpy.where"
] | [((3143, 3207), 'numpy.zeros', 'np.zeros', (['(self.lattice_height, self.lattice_width)'], {'dtype': '"""int"""'}), "((self.lattice_height, self.lattice_width), dtype='int')\n", (3151, 3207), True, 'import numpy as np\n'), ((2601, 2652), 'numpy.zeros', 'np.zeros', (['(self.lattice_height, self.lattice_width)'], {}), '(... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
bar_width = 0.012
line_width = 2.5
opacity = 0.7
num_layouts=5
df = pd.read_csv('blocksize_new.csv' , delimiter=',')
buck_arr = df.values[:,0]
lat_arr = df.values[:,1]
block_widths = [4, 8, 16, 32, 64]
index = np.arange(0, 0.1, 0.1/5)
ticks = ra... | [
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"pandas.read_csv",
"numpy.arange",
"matplotlib.pyplot.figlegend",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
] | [((142, 189), 'pandas.read_csv', 'pd.read_csv', (['"""blocksize_new.csv"""'], {'delimiter': '""","""'}), "('blocksize_new.csv', delimiter=',')\n", (153, 189), True, 'import pandas as pd\n'), ((285, 311), 'numpy.arange', 'np.arange', (['(0)', '(0.1)', '(0.1 / 5)'], {}), '(0, 0.1, 0.1 / 5)\n', (294, 311), True, 'import n... |
import math
import numpy as np
def Rotation_euler_vector(euler_vector, theta):
ux = euler_vector[0]
uy = euler_vector[1]
uz = euler_vector[2]
# Check if vector are normalized
norm = math.sqrt(ux**2+uy**2+uz*2)
if norm != 1:
ux = ux/norm
uy = uy/norm
uz = uz/norm
R1... | [
"math.sqrt",
"math.sin",
"numpy.sin",
"numpy.array",
"math.cos",
"numpy.cos",
"numpy.dot"
] | [((204, 241), 'math.sqrt', 'math.sqrt', (['(ux ** 2 + uy ** 2 + uz * 2)'], {}), '(ux ** 2 + uy ** 2 + uz * 2)\n', (213, 241), False, 'import math\n'), ((790, 851), 'numpy.array', 'np.array', (['[[R11, R12, R13], [R21, R22, R23], [R31, R32, R33]]'], {}), '([[R11, R12, R13], [R21, R22, R23], [R31, R32, R33]])\n', (798, 8... |
# Import pandas
import pandas as pd
# Use numpy to convert to arrays
import numpy as np
# Import csv
import csv
# To do square root on MSE
from math import sqrt
# To enables split (train and test) of the data
from sklearn.model_selection import train_test_split
# Import svm
from sklearn import svm
# Import ... | [
"sklearn.svm.SVR",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"numpy.mean",
"numpy.array",
"sklearn.metrics.mean_squared_error"
] | [((435, 576), 'pandas.read_csv', 'pd.read_csv', (['"""D:/TIF/TIF SEM.7/Frontier Technology/Hotel Recommendations/GitHub Documentation/clean_train_one_percent.csv"""'], {'sep': '""","""'}), "(\n 'D:/TIF/TIF SEM.7/Frontier Technology/Hotel Recommendations/GitHub Documentation/clean_train_one_percent.csv'\n , sep=',... |
"""Pair plot between variables of latent space"""
from configparser import ConfigParser, ExtendedInterpolation
import glob
import time
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sdss.utils.managefiles import FileDirectory
from sdss.utils.configfile import Configu... | [
"numpy.load",
"sdss.utils.managefiles.FileDirectory",
"seaborn.scatterplot",
"pandas.read_csv",
"sdss.utils.configfile.ConfigurationFile",
"time.time",
"configparser.ExtendedInterpolation",
"glob.glob",
"matplotlib.pyplot.subplots"
] | [((425, 436), 'time.time', 'time.time', ([], {}), '()\n', (434, 436), False, 'import time\n'), ((659, 678), 'sdss.utils.configfile.ConfigurationFile', 'ConfigurationFile', ([], {}), '()\n', (676, 678), False, 'from sdss.utils.configfile import ConfigurationFile\n'), ((694, 709), 'sdss.utils.managefiles.FileDirectory', ... |
from __future__ import print_function
import numpy as np
from copy import deepcopy
import os
def dense_to_one_hot(labels_dense, num_classes):
"""Convert class labels from scalars to one-hot vectors."""
sample_size = len(labels_dense)
labels_one_hot = np.zeros((sample_size, num_classes))
labels_one_hot... | [
"numpy.ones",
"numpy.isnan",
"matplotlib.pylab.axis",
"numpy.base_repr",
"matplotlib.pylab.gcf",
"sklearn.manifold.LocallyLinearEmbedding",
"numpy.mean",
"matplotlib.pylab.suptitle",
"numpy.exp",
"numpy.arange",
"matplotlib.pylab.close",
"matplotlib.pylab.title",
"sklearn.manifold.MDS",
"o... | [((265, 301), 'numpy.zeros', 'np.zeros', (['(sample_size, num_classes)'], {}), '((sample_size, num_classes))\n', (273, 301), True, 'import numpy as np\n'), ((546, 570), 'h5py.File', 'h5py.File', (['filename', '"""w"""'], {}), "(filename, 'w')\n", (555, 570), False, 'import h5py\n'), ((1181, 1208), 'matplotlib.pylab.fig... |
#!/usr/bin/python
import os
import sys
import time
import math
import config.config_read as rsd
import config.config_init as cfg
import config.ColorPrompt as CP
import services.tools as tls
import io_data.data_acces_file as daf
import interface.inline_print as iprint
import services.process as prc
import plot.plot_dat... | [
"io_data.data_acces_file.save_lists_to_file",
"services.process.flip_3d",
"services.process.process_cube_HIPP",
"config.config_read.get_label_binary_codes",
"services.tools.get_convention_name",
"services.tools.split_lists_to_binary_groups",
"services.tools.get_dimensions_cubes_PPC",
"io_data.data_acc... | [((1111, 1175), 'io_data.data_acces_file.save_lists_to_file', 'daf.save_lists_to_file', ([], {'path_file': 'file_path', 'data_list': 'list_data'}), '(path_file=file_path, data_list=list_data)\n', (1133, 1175), True, 'import io_data.data_acces_file as daf\n'), ((2264, 2277), 'time.sleep', 'time.sleep', (['(1)'], {}), '(... |
import sys, os
import numpy as np
import math
sys.path.insert (0, '/home/tensor/aa_dpe_emulate/include/')
sys.path.insert (0, '/home/tensor/aa_dpe_emulate/src/')
from data_convert import *
from instrn_proto import *
from tile_instrn_proto import *
dict_temp = {}
dict_list = []
i_temp = i_receive(mem_addr=768, vtile_id... | [
"numpy.save",
"sys.path.insert"
] | [((47, 105), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/home/tensor/aa_dpe_emulate/include/"""'], {}), "(0, '/home/tensor/aa_dpe_emulate/include/')\n", (62, 105), False, 'import sys, os\n'), ((107, 161), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""/home/tensor/aa_dpe_emulate/src/"""'], {}), "(0, '/home/... |
import math
import os
import random
import albumentations as A
import cv2
import dlib
import numpy as np
import skimage
from albumentations import DualTransform
from albumentations.pytorch import ToTensorV2
from scipy.ndimage import binary_dilation
from skimage import measure, draw
from config import BASE_DIR
detect... | [
"albumentations.Normalize",
"os.path.join",
"albumentations.Blur",
"cv2.line",
"numpy.zeros_like",
"numpy.multiply",
"albumentations.OpticalDistortion",
"scipy.ndimage.binary_dilation",
"numpy.ones_like",
"albumentations.FancyPCA",
"math.sqrt",
"skimage.draw.polygon",
"random.random",
"dli... | [((325, 357), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (355, 357), False, 'import dlib\n'), ((391, 462), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""libs"""', '"""shape_predictor_68_face_landmarks.dat"""'], {}), "(BASE_DIR, 'libs', 'shape_predictor_68_face_landmarks.da... |
import cobra
import re
import numpy as np
import pandas as pd
from cobra.flux_analysis.sampling import OptGPSampler
from cobra.core.reaction import Reaction as cobraReaction
from cobra.util.solver import set_objective
import rpy2.robjects as ro
from rpy2.robjects import numpy2ri
import warnings
import copy
from six imp... | [
"numpy.diag_indices_from",
"cobra.util.solver.set_objective",
"cobra.io.load_matlab_model",
"Data_module.DataParser",
"Order_module.FluxOrder",
"cobra.io.save_matlab_model",
"six.iteritems",
"cobra.core.reaction.Reaction",
"cobra.flux_analysis.find_blocked_reactions",
"numpy.savetxt",
"Helper_me... | [((537, 556), 'rpy2.robjects.numpy2ri.activate', 'numpy2ri.activate', ([], {}), '()\n', (554, 556), False, 'from rpy2.robjects import numpy2ri\n'), ((19753, 19808), 'cobra.util.solver.set_objective', 'set_objective', (['cobra_model', 'coefficients'], {'additive': '(True)'}), '(cobra_model, coefficients, additive=True)\... |
import numpy as np
def body_hash(body):
"""
:param body: 1-D np array with n atoms, for bodies (-1 for not a body)
:return:
"""
ret = {}
print('Build body hash...')
natoms = len(body)
bodies = list(set(list(body)))
bodies.remove(-1)
idxes = np.arange(natoms)
for b in bodies... | [
"numpy.arange"
] | [((283, 300), 'numpy.arange', 'np.arange', (['natoms'], {}), '(natoms)\n', (292, 300), True, 'import numpy as np\n')] |
# !/usr/bin/python
# -*- coding: UTF-8 -*-
##########################
# Creator: Javy
# Creat Time: 20170416
# Email: <EMAIL>
# Description: Machine Learning - Chapter tree
##########################
import sys
sys.path.append('/home/javy/Documents/python')
import imp
imp.reload(module)
# Sample zero
from sklearn i... | [
"imp.reload",
"sklearn.datasets.load_iris",
"sklearn.preprocessing.StandardScaler",
"numpy.random.seed",
"sklearn.metrics.accuracy_score",
"sklearn.tree.DecisionTreeClassifier",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.exp",
"sklearn.svm.SVC",
"sys.path.append",
"matplotlib.pyplot.ax... | [((213, 259), 'sys.path.append', 'sys.path.append', (['"""/home/javy/Documents/python"""'], {}), "('/home/javy/Documents/python')\n", (228, 259), False, 'import sys\n'), ((272, 290), 'imp.reload', 'imp.reload', (['module'], {}), '(module)\n', (282, 290), False, 'import imp\n'), ((353, 374), 'matplotlib.Use', 'matplotli... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
2019/12/18
READ GDSC DRUG RESPONSE DATA
"""
import os
import pandas as pd
import numpy as np
from functools import reduce
def read_GDSC_response(GDSC_drug_response_frames, GDSC_drug_name, X_source, GDSC_drug_id=None):
# X_source has to be a DataFrame with genes in co... | [
"numpy.intersect1d",
"numpy.unique"
] | [((1429, 1484), 'numpy.intersect1d', 'np.intersect1d', (['y_source.index', 'X_source_response.index'], {}), '(y_source.index, X_source_response.index)\n', (1443, 1484), True, 'import numpy as np\n'), ((1067, 1110), 'numpy.unique', 'np.unique', (["GDSC_drug_response_df['DRUG_ID']"], {}), "(GDSC_drug_response_df['DRUG_ID... |
# Third Party
import numpy as np
import tensorflow as tf
# First Party
import smdebug.tensorflow as smd
from smdebug.core.collection import CollectionKeys
from smdebug.trials import create_trial
def get_data():
images = np.zeros((64, 224))
labels = np.zeros((64, 5))
inputs = {"Image_input": images}
o... | [
"tensorflow.keras.optimizers.Adadelta",
"smdebug.tensorflow.KerasHook",
"tensorflow.keras.layers.Dense",
"numpy.zeros",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.Input",
"smdebug.trials.create_trial"
] | [((227, 246), 'numpy.zeros', 'np.zeros', (['(64, 224)'], {}), '((64, 224))\n', (235, 246), True, 'import numpy as np\n'), ((260, 277), 'numpy.zeros', 'np.zeros', (['(64, 5)'], {}), '((64, 5))\n', (268, 277), True, 'import numpy as np\n'), ((424, 463), 'smdebug.tensorflow.KerasHook', 'smd.KerasHook', (['trial_dir'], {'s... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 3 10:14:53 2020
@author: <NAME>
"""
# to remove the warning in my code
from warnings import simplefilter
simplefilter(action='ignore', category=FutureWarning)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linea... | [
"pandas.DataFrame",
"matplotlib.pyplot.show",
"warnings.simplefilter",
"pandas.read_csv",
"sklearn.metrics.accuracy_score",
"pandas.cut",
"sklearn.linear_model.LogisticRegression",
"numpy.where",
"sklearn.metrics.confusion_matrix"
] | [((162, 215), 'warnings.simplefilter', 'simplefilter', ([], {'action': '"""ignore"""', 'category': 'FutureWarning'}), "(action='ignore', category=FutureWarning)\n", (174, 215), False, 'from warnings import simplefilter\n'), ((768, 854), 'pandas.read_csv', 'pd.read_csv', (['"""D:\\\\Studies\\\\Machine Learning\\\\Titani... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
import pytest
import fairlearn.metrics as metrics
from test.unit.input_convertors import conversions_for_1d
# ===========================================================
def mock_func(y_true, y_pred):
... | [
"numpy.multiply",
"numpy.sum",
"numpy.ones",
"numpy.isnan",
"fairlearn.metrics.make_group_metric",
"pytest.raises",
"fairlearn.metrics.metric_by_group",
"pytest.mark.parametrize",
"pytest.approx"
] | [((331, 345), 'numpy.sum', 'np.sum', (['y_true'], {}), '(y_true)\n', (337, 345), True, 'import numpy as np\n'), ((581, 641), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""transform_gid"""', 'conversions_for_1d'], {}), "('transform_gid', conversions_for_1d)\n", (604, 641), False, 'import pytest\n'), ((647,... |
import os
import numpy as np
import pickle
import argparse
import glob
import scipy
from tqdm import tqdm
from youtube8m.video_level_nn_models.defaults import YOUTUBE8M_LABELS_N
from scipy.sparse import lil_matrix
def build_index(video_ids, features, scores):
unique_ids = np.unique(video_ids)
index = {unique_... | [
"pickle.dump",
"argparse.ArgumentParser",
"os.path.dirname",
"numpy.unique",
"os.path.join",
"numpy.concatenate"
] | [((279, 299), 'numpy.unique', 'np.unique', (['video_ids'], {}), '(video_ids)\n', (288, 299), True, 'import numpy as np\n'), ((960, 992), 'numpy.concatenate', 'np.concatenate', (['features'], {'axis': '(0)'}), '(features, axis=0)\n', (974, 992), True, 'import numpy as np\n'), ((1006, 1036), 'numpy.concatenate', 'np.conc... |
from __future__ import print_function
import unittest
import numpy as np
from keras import Input, Model
from keras.layers import BatchNormalization, Dense, Flatten
from keras.optimizers import Adam
from keras.utils.np_utils import to_categorical
from mode_normalization import ModeNormalization
class ExecutionTest(... | [
"numpy.random.uniform",
"keras.Input",
"keras.Model",
"numpy.testing.assert_almost_equal",
"keras.layers.Flatten",
"keras.optimizers.Adam",
"numpy.not_equal",
"mode_normalization.ModeNormalization",
"keras.layers.BatchNormalization",
"keras.layers.Dense",
"numpy.mean",
"numpy.vstack"
] | [((458, 497), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(50, 10, 10, 3)'}), '(size=(50, 10, 10, 3))\n', (475, 497), True, 'import numpy as np\n'), ((512, 536), 'keras.Input', 'Input', ([], {'shape': '(10, 10, 3)'}), '(shape=(10, 10, 3))\n', (517, 536), False, 'from keras import Input, Model\n'), ((590... |
# This file is distributed under MIT license as part of the project flocksims.
# See LICENSE file for details.
# (c) <NAME>, 2019
# Quick script to sweep some parameters for the flocking simulations
import os, sys
import numpy as np
import mkl
mkl.set_num_threads(1)
from multiprocessing import Pool
def flocking(args... | [
"numpy.logspace",
"mkl.set_num_threads",
"os.system",
"numpy.array",
"multiprocessing.Pool"
] | [((246, 268), 'mkl.set_num_threads', 'mkl.set_num_threads', (['(1)'], {}), '(1)\n', (265, 268), False, 'import mkl\n'), ((739, 753), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (748, 753), False, 'import os, sys\n'), ((791, 813), 'numpy.logspace', 'np.logspace', (['(-3)', '(2)', '(50)'], {}), '(-3, 2, 50)\n', (... |
"""
Copyright 2020 The OneFlow Authors. 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 applicable law or agr... | [
"oneflow.compatible.single_client.scope.placement",
"oneflow.compatible.single_client.zeros_initializer",
"unittest.main",
"oneflow.compatible.single_client.FunctionConfig",
"test_util.GenArgDict",
"numpy.random.rand",
"oneflow.compatible.single_client.global_function",
"oneflow.compatible.single_clie... | [((1751, 1783), 'oneflow.compatible.single_client.unittest.skip_unless_1n1d', 'flow.unittest.skip_unless_1n1d', ([], {}), '()\n', (1781, 1783), True, 'import oneflow.compatible.single_client as flow\n'), ((1003, 1030), 'oneflow.compatible.single_client.regularizers.l2', 'flow.regularizers.l2', (['(4e-05)'], {}), '(4e-0... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 MIT Probabilistic Computing Project.
# Released under Apache 2.0; refer to LICENSE.txt.
import numpy as np
import pytest
from cgpm.utils.general import get_prng
from cgpm.utils.test import gen_data_table
from cgpm2.categorical import Categorical
from cgpm2.crp import CRP... | [
"cgpm2.normal.Normal",
"cgpm2.walks.remove_cgpm",
"cgpm2.transition_views.get_cgpm_view_proposals_existing",
"numpy.allclose",
"cgpm2.categorical.Categorical",
"cgpm2.walks.add_cgpm",
"numpy.transpose",
"cgpm2.product.Product",
"cgpm.utils.general.get_prng",
"cgpm2.transition_views.get_cgpm_view_p... | [((1504, 1544), 'cgpm2.product.Product', 'Product', (['[view0, view1, view2]'], {'rng': 'prng'}), '([view0, view1, view2], rng=prng)\n', (1511, 1544), False, 'from cgpm2.product import Product\n'), ((1602, 1872), 'cgpm.utils.test.gen_data_table', 'gen_data_table', ([], {'n_rows': '(10)', 'view_weights': '[0.4, 0.6]', '... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
"tvm.tir.const",
"tvm.te.placeholder",
"tvm.te.reduce_axis",
"numpy.random.uniform",
"tvm.nd.array",
"tvm.transform.PassContext",
"numpy.zeros",
"tvm.build",
"tvm.contrib.nvcc.have_tensorcore",
"tvm.auto_tensorize.WMMAFp16Fp32Bias",
"tvm.te.thread_axis",
"tvm.te.create_schedule",
"tvm.auto_t... | [((1965, 2005), 'tvm.te.reduce_axis', 'te.reduce_axis', (['(0, kernel_h)'], {'name': '"""kh"""'}), "((0, kernel_h), name='kh')\n", (1979, 2005), False, 'from tvm import te\n'), ((2011, 2051), 'tvm.te.reduce_axis', 'te.reduce_axis', (['(0, kernel_w)'], {'name': '"""kw"""'}), "((0, kernel_w), name='kw')\n", (2025, 2051),... |
import time
import torch
import torch.nn.functional as F
import random
import numpy as np
from modules.optimizer import Optimizer
from model.biaffine_ner import NERParser
from config.conf import args_config, data_config
from utils.dataset import DataLoader
from utils.datautil import load_data, create_vocab, batch_varia... | [
"numpy.random.seed",
"torch.manual_seed",
"config.conf.data_config",
"torch.cuda.manual_seed",
"torch.cuda.device_count",
"time.time",
"utils.datautil.batch_variable",
"torch.cuda.manual_seed_all",
"logger.logger.logger.info",
"random.seed",
"torch.cuda.is_available",
"torch.device",
"utils.... | [((11161, 11178), 'random.seed', 'random.seed', (['(1347)'], {}), '(1347)\n', (11172, 11178), False, 'import random\n'), ((11183, 11203), 'numpy.random.seed', 'np.random.seed', (['(2343)'], {}), '(2343)\n', (11197, 11203), True, 'import numpy as np\n'), ((11208, 11231), 'torch.manual_seed', 'torch.manual_seed', (['(145... |
import pdb
import sys
import operator
from collections import OrderedDict
import subprocess
import numpy as np
import json
import math
from transformers import *
import sys
import random
import time
SINGLETONS_TAG = "_singletons_ "
EMPTY_TAG = "_empty_ "
OTHER_TAG = "OTHER"
AMBIGUOUS = "AMB"
MAX_VAL = 20
TAIL_THRES... | [
"random.randint",
"json.dumps",
"time.time",
"numpy.array",
"numpy.exp",
"numpy.inner",
"numpy.linalg.norm",
"collections.OrderedDict",
"pdb.set_trace",
"sys.exit"
] | [((669, 690), 'numpy.array', 'np.array', (['embeds_list'], {}), '(embeds_list)\n', (677, 690), True, 'import numpy as np\n'), ((2311, 2324), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2322, 2324), False, 'from collections import OrderedDict\n'), ((2345, 2358), 'collections.OrderedDict', 'OrderedDict',... |
# -*- coding: utf-8 -*-
import os
import matplotlib.pyplot as plt
import numpy as np
def plot2d_simplex(simplex, ind):
fig_dir = "./"
plt.cla()
n = 1000
x1 = np.linspace(-256, 1024, n)
x2 = np.linspace(-256, 1024, n)
X, Y = np.meshgrid(x1, x2)
Z = np.sqrt(X ** 2 + Y ** 2)
plt.contour(... | [
"matplotlib.pyplot.xlim",
"numpy.meshgrid",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.cla",
"numpy.arange",
"numpy.linspace",
"matplotlib.pyplot.gca",
"numpy.sqrt"
] | [((145, 154), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (152, 154), True, 'import matplotlib.pyplot as plt\n'), ((177, 203), 'numpy.linspace', 'np.linspace', (['(-256)', '(1024)', 'n'], {}), '(-256, 1024, n)\n', (188, 203), True, 'import numpy as np\n'), ((213, 239), 'numpy.linspace', 'np.linspace', (['(-25... |
from glob import glob
import io
import itertools
import os
import platform
import sys
import tempfile
from cachetools import LRUCache, cached
import numpy as np
from quaternion import rotate_vectors
from cadquery import Compound, Location
from cadquery.occ_impl.shapes import downcast
from .utils import distance
fro... | [
"OCP.gp.gp_Quaternion",
"OCP.gp.gp_Vec",
"OCP.StlAPI.StlAPI_Writer",
"OCP.TopExp.TopExp_Explorer",
"cadquery.occ_impl.shapes.downcast",
"OCP.BinTools.BinTools.Read_s",
"numpy.linalg.norm",
"sys.getsizeof",
"glob.glob",
"OCP.Bnd.Bnd_Box",
"cachetools.LRUCache",
"OCP.BRepGProp.BRepGProp.VolumePr... | [((1540, 1594), 'cachetools.LRUCache', 'LRUCache', ([], {'maxsize': '(16 * 1024 * 1024)', 'getsizeof': 'get_size'}), '(maxsize=16 * 1024 * 1024, getsizeof=get_size)\n', (1548, 1594), False, 'from cachetools import LRUCache, cached\n'), ((5933, 5960), 'cachetools.cached', 'cached', (['cache'], {'key': 'make_key'}), '(ca... |
# Tencent is pleased to support the open source community by making PocketFlow available.
#
# Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | [
"tensorflow.logging.info",
"tensorflow.reshape",
"tensorflow.ConfigProto",
"tensorflow.app.flags.DEFINE_boolean",
"utils.multi_gpu_wrapper.MultiGpuWrapper.broadcast_global_variables",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow.get_variable",
"os.path.dirname",
"tensorflow.variable_scope",
... | [((1443, 1544), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""uql_weight_bits"""', '(4)', '"""Number of bits to use for quantizing weights"""'], {}), "('uql_weight_bits', 4,\n 'Number of bits to use for quantizing weights')\n", (1470, 1544), True, 'import tensorflow as tf\n'), ((1547, 1... |
#
# Copyright 2019-2021 <NAME>
# 2020-2021 <NAME>
# 2019 <NAME>
#
# ### MIT license
#
# 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 withou... | [
"numpy.frombuffer",
"numpy.dtype",
"re.match",
"numpy.fliplr",
"datetime.datetime.strptime"
] | [((10193, 10208), 'numpy.dtype', 'np.dtype', (['"""<i2"""'], {}), "('<i2')\n", (10201, 10208), True, 'import numpy as np\n'), ((11613, 11638), 'numpy.fliplr', 'np.fliplr', (['unscaleddata.T'], {}), '(unscaleddata.T)\n', (11622, 11638), True, 'import numpy as np\n'), ((10280, 10295), 'numpy.dtype', 'np.dtype', (['"""<i4... |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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 applicab... | [
"numpy.argmax",
"basisnet.personalization.centralized_emnist.emnist_models.get_model_builder",
"absl.logging.info",
"absl.flags.DEFINE_boolean",
"numpy.tile",
"numpy.nanmean",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"absl.flags.DEFINE_bool",
"absl.flags.mark_flag_as_required",
"ab... | [((1079, 1173), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""client_datasets_random_seed"""', '(1)', '"""Random seed for client sampling."""'], {}), "('client_datasets_random_seed', 1,\n 'Random seed for client sampling.')\n", (1099, 1173), False, 'from absl import flags\n'), ((1191, 1282), 'absl.flags... |
"""
Theory:
morphological transformation are some simple operation based on the image shape.
It needs 2 inputs, one is our original image, second one is called
<structuring element> or <kernel> which describe the nature of the operation.
"""
import cv2
import numpy as np
def org_imge_kernel():
img = cv2.imread('mo... | [
"cv2.dilate",
"cv2.waitKey",
"cv2.morphologyEx",
"cv2.getStructuringElement",
"cv2.imshow",
"numpy.ones",
"cv2.imread",
"cv2.erode",
"cv2.destroyAllWindows"
] | [((306, 342), 'cv2.imread', 'cv2.imread', (['"""morphological_j.png"""', '(0)'], {}), "('morphological_j.png', 0)\n", (316, 342), False, 'import cv2\n'), ((356, 381), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (363, 381), True, 'import numpy as np\n'), ((490, 503), 'cv2.waitKey', 'cv... |
import time
import prettytable as pt
import numpy as np
import mxnet as mx
from poi.eval.reid.re_ranking import re_ranking, c_distance_opt
import logging
class ReIDMetric(object):
def __init__(self, pTest):
self.p = pTest
self.gpu = self.p.gpus[0]
self.distmat = None
self.q_pids = ... | [
"json.load",
"numpy.invert",
"numpy.asarray",
"time.time",
"numpy.argsort",
"numpy.any",
"numpy.mean",
"numpy.array",
"prettytable.PrettyTable",
"mxnet.gpu",
"logging.getLogger"
] | [((576, 587), 'time.time', 'time.time', ([], {}), '()\n', (585, 587), False, 'import time\n'), ((970, 1002), 'numpy.argsort', 'np.argsort', (['self.distmat'], {'axis': '(1)'}), '(self.distmat, axis=1)\n', (980, 1002), True, 'import numpy as np\n'), ((2545, 2560), 'numpy.mean', 'np.mean', (['all_AP'], {}), '(all_AP)\n',... |
import itertools
import numpy as np
import scipy.ndimage
import scipy.spatial
from .. import utils
from ..preprocessing import image as preprocessing_image
def _generate_centers_and_final_shape(img_shape,
stride,
first_center):
"""
... | [
"numpy.where",
"numpy.array",
"numpy.concatenate",
"itertools.product"
] | [((637, 667), 'itertools.product', 'itertools.product', (['*dim_ranges'], {}), '(*dim_ranges)\n', (654, 667), False, 'import itertools\n'), ((2117, 2144), 'numpy.concatenate', 'np.concatenate', (['result_list'], {}), '(result_list)\n', (2131, 2144), True, 'import numpy as np\n'), ((2571, 2623), 'numpy.where', 'np.where... |
import numpy as np
from MLP_Classification.MLP import MLP
from mnist import MNIST
import math
mndata = MNIST('/Users/elvis/Documents/DSI/python-mnist/data')
train_images, train_labels = mndata.load_training()
test_images, test_labels = mndata.load_testing()
train_x = []
train_y = []
test_x = []
test_y = []
for i in ... | [
"numpy.zeros",
"numpy.multiply",
"MLP_Classification.MLP.MLP",
"mnist.MNIST"
] | [((104, 157), 'mnist.MNIST', 'MNIST', (['"""/Users/elvis/Documents/DSI/python-mnist/data"""'], {}), "('/Users/elvis/Documents/DSI/python-mnist/data')\n", (109, 157), False, 'from mnist import MNIST\n'), ((757, 772), 'MLP_Classification.MLP.MLP', 'MLP', (['(28 * 28)', '(3)'], {}), '(28 * 28, 3)\n', (760, 772), False, 'f... |
import script_tools as st
import registration as reg
import numpy as np
import landmarks
import dist_table as dt
#import matplotlib
import matplotlib.pyplot as plt
from matplotlib import mlab
import scipy.ndimage
# Windows
#dataset_path = "C:/cygwin64/home/johan/itkAlphaCut/assets/01.png"
#bin_path = "C:/cygwin64/hom... | [
"registration.Registration",
"numpy.std",
"numpy.savetxt",
"numpy.zeros",
"numpy.argmin",
"numpy.mean",
"numpy.array",
"numpy.linalg.norm",
"script_tools.read_csv"
] | [((672, 761), 'registration.Registration', 'reg.Registration', (['parallel_count', 'bin_path'], {'dim': 'image_dimensions', 'enable_logging': '(True)'}), '(parallel_count, bin_path, dim=image_dimensions,\n enable_logging=True)\n', (688, 761), True, 'import registration as reg\n'), ((2613, 2702), 'registration.Regist... |
# Module to import functions from in examples for multiprocessing backend
import numpy as np
def stochastic_function_seeded(max_value, random_state):
rng = np.random.RandomState(random_state)
return rng.randint(max_value, size=5)
def stochastic_function(max_value):
"""Randomly generate integer up to a m... | [
"numpy.random.randint",
"numpy.random.RandomState"
] | [((162, 197), 'numpy.random.RandomState', 'np.random.RandomState', (['random_state'], {}), '(random_state)\n', (183, 197), True, 'import numpy as np\n'), ((348, 384), 'numpy.random.randint', 'np.random.randint', (['max_value'], {'size': '(5)'}), '(max_value, size=5)\n', (365, 384), True, 'import numpy as np\n')] |
import mxnet as mx
import numpy as np
import minibatch
class TestLoader(mx.io.DataIter):
def __init__(self, imdb, batch_size=1, shuffle=False):
self.imdb = imdb
self.batch_size = batch_size
self.shuffle = shuffle
self.size = len(imdb)
self.index = np.arange(self.size)
... | [
"numpy.zeros",
"minibatch.get_minibatch",
"numpy.arange",
"numpy.array",
"mxnet.nd.array",
"mxnet.cpu",
"minibatch.get_testbatch",
"numpy.random.shuffle"
] | [((293, 313), 'numpy.arange', 'np.arange', (['self.size'], {}), '(self.size)\n', (302, 313), True, 'import numpy as np\n'), ((1997, 2026), 'minibatch.get_testbatch', 'minibatch.get_testbatch', (['imdb'], {}), '(imdb)\n', (2020, 2026), False, 'import minibatch\n'), ((3009, 3029), 'numpy.arange', 'np.arange', (['self.siz... |
import networkx as nx
import scipy.sparse.csgraph
import numpy as np
import gym
import pickle
WALLS = {
'Small':
np.array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]),
'Cross':
np.array([[0, 0, 0, 0, 0, 0, 0],
... | [
"networkx.shortest_path_length",
"numpy.random.choice",
"numpy.random.uniform",
"pickle.dump",
"numpy.random.seed",
"numpy.random.rand",
"numpy.floor",
"gym.spaces.Discrete",
"numpy.float",
"matplotlib.use",
"numpy.array",
"numpy.linalg.norm",
"numpy.linspace",
"numpy.random.normal",
"ne... | [((126, 192), 'numpy.array', 'np.array', (['[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]'], {}), '([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])\n', (134, 192), True, 'import numpy as np\n'), ((269, 449), 'numpy.array', 'np.array', (['[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0... |
import csv
import cpsc2018
import os
import argparse
import numpy as np
import sys
'''
cspc2018_challenge score
Written by: <NAME>, <NAME>, <NAME>
School of Instrument Science and Engineering
Southeast University, China
<EMAIL>
'''
'''
Score the prediction answers by comparing ... | [
"numpy.sum",
"argparse.ArgumentParser",
"csv.DictReader",
"numpy.zeros",
"numpy.int"
] | [((2247, 2279), 'numpy.zeros', 'np.zeros', (['(9, 9)'], {'dtype': 'np.float'}), '((9, 9), dtype=np.float)\n', (2255, 2279), True, 'import numpy as np\n'), ((5452, 5477), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5475, 5477), False, 'import argparse\n'), ((2335, 2352), 'csv.DictReader', 'c... |
"""
.. codeauthor:: <NAME> <<EMAIL>>
"""
import functools
import platform
import numpy as np
import pytest
from pde import DiffusionPDE, FileStorage, MemoryStorage, UnitGrid
from pde.fields import FieldCollection, ScalarField, Tensor2Field, VectorField
from pde.tools.misc import module_available
def test_storage_w... | [
"functools.partial",
"pde.DiffusionPDE",
"numpy.testing.assert_allclose",
"pde.fields.FieldCollection",
"pde.UnitGrid",
"pde.fields.VectorField.random_uniform",
"pde.FileStorage",
"pde.tools.misc.module_available",
"pytest.raises",
"numpy.array",
"numpy.arange",
"pde.fields.ScalarField.random_... | [((7957, 8006), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dtype"""', '[bool, complex]'], {}), "('dtype', [bool, complex])\n", (7980, 8006), False, 'import pytest\n'), ((396, 411), 'pde.UnitGrid', 'UnitGrid', (['[dim]'], {}), '([dim])\n', (404, 411), False, 'from pde import DiffusionPDE, FileStorage, M... |
import sys
import os
import getopt
from six.moves import xrange
import h5py, time
import tensorflow as tf
import numpy as np
from utils import leaky_relu, leaky_relu2, batch_norm_wrapper
from data_loader import load_data_new, load_neighbour, load_labelMatrix, load_structMatrix
from meshvae import meshVAE
### Some hyp... | [
"os.mkdir",
"tensorflow.reduce_sum",
"getopt.getopt",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.constant_initializer",
"tensorflow.nn.tanh",
"tensorflow.reshape",
"tensorflow.nn.l2_normalize",
"tensorflow.ConfigProto",
"tensorflow.multiply",
"tensorflow.matmul",
"data_loader.load... | [((846, 1122), 'getopt.getopt', 'getopt.getopt', (['sys.argv[1:]', '"""a:b:c:d:e:l:f:x:y:m:n:p:s:r:k:"""', "['KLpart', 'Trippart', 'Part2Global', 'KLglobal', 'Tripglobal',\n 'learning_rate', 'epoch_num', 'BoundPart', 'BoundGlobal', 'HidePart',\n 'HideGlobal', 'matname', 'batch_size', 'restore_path', 'ckpt_path']"... |
#!/usr/bin/env python3
"""
This module runs DaoChen's version Variational-Quantum-Eigensolver on Helium
Example running it partially using CK infrastructure (assuming the current directory is $HOME/CK/ck-rigetti/program/rigetti-vqe) :
time ck virtual `ck search env:* --tags=forestopenfermion` `ck search env:* --t... | [
"numpy.sum",
"pyquil.paulis.PauliTerm",
"json.dumps",
"time.time",
"inspect.getsource",
"numpy.dot",
"hackathon_utils.cmdline_parse_and_report",
"pyquil.quil.Program",
"pyquil.paulis.PauliTerm.from_list",
"json.JSONEncoder.default"
] | [((5121, 5132), 'time.time', 'time.time', ([], {}), '()\n', (5130, 5132), False, 'import time\n'), ((6682, 6898), 'hackathon_utils.cmdline_parse_and_report', 'cmdline_parse_and_report', ([], {'num_params': '(2)', 'q_device_name_default': '"""QVM"""', 'q_device_name_help': '"""Real devices: \'8Q-Agave\' or \'19Q-Acorn\'... |
import unittest
import numpy as np
from .. import utils
class Dummy(unittest.TestCase):
def test_log_zgrid(self):
value = np.array([0.1, 0.21568801, 0.34354303, 0.48484469, 0.64100717, 0.8135934])
np.testing.assert_allclose(utils.log_zgrid([0.1, 1], 0.1), value, rtol=1e-06, atol=0, equal_nan=... | [
"numpy.array"
] | [((137, 211), 'numpy.array', 'np.array', (['[0.1, 0.21568801, 0.34354303, 0.48484469, 0.64100717, 0.8135934]'], {}), '([0.1, 0.21568801, 0.34354303, 0.48484469, 0.64100717, 0.8135934])\n', (145, 211), True, 'import numpy as np\n')] |
import numpy as np
from time import time
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix
from sklearn.tree import DecisionTreeClassifier
from sklearn. ensemble import AdaBoostClassifier
from sklearn.decomposition import PCA
f... | [
"pandas.read_csv",
"sklearn.preprocessing.LabelEncoder",
"sklearn.tree.DecisionTreeClassifier",
"time.time",
"sklearn.model_selection.KFold",
"sklearn.neighbors.KNeighborsClassifier",
"numpy.array",
"numpy.loadtxt",
"sklearn.decomposition.PCA",
"sklearn.svm.SVC",
"sklearn.metrics.confusion_matri... | [((3616, 3656), 'pandas.read_csv', 'pd.read_csv', (['"""car_2class.data"""'], {'header': '(0)'}), "('car_2class.data', header=0)\n", (3627, 3656), True, 'import pandas as pd\n'), ((3753, 3782), 'numpy.loadtxt', 'np.loadtxt', (['"""page-blocks.txt"""'], {}), "('page-blocks.txt')\n", (3763, 3782), True, 'import numpy as ... |
from flask import Flask, render_template, request
import pickle
import pandas as pd
import numpy as np
from woe_enc import WoeEncoder
import __main__
__main__.WoeEncoder = WoeEncoder
app = Flask(__name__)
# Loading the necessary pickle files
with open('ohe_transformer.pkl', 'rb') as file:
ohe_transformer = pick... | [
"pandas.DataFrame",
"flask.Flask",
"numpy.hstack",
"numpy.min",
"pickle.load",
"numpy.array",
"numpy.linalg.norm",
"flask.render_template",
"numpy.round",
"pandas.concat"
] | [((192, 207), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (197, 207), False, 'from flask import Flask, render_template, request\n'), ((316, 333), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (327, 333), False, 'import pickle\n'), ((387, 404), 'pickle.load', 'pickle.load', (['file'], {}), '(... |
#simsets.py
# need a set of sets, to find an ordering over all.
# related to contigs, but with repeated sets.
import numpy as np
import string
import copy
# function to flatten lists
def f(E):
if E==[]:
return []
elif type(E) != list:
return [E]
else:
a = f(E[0])
b = f(E[... | [
"copy.deepcopy",
"numpy.savetxt",
"numpy.zeros",
"numpy.transpose",
"numpy.max",
"numpy.where",
"numpy.random.randint",
"numpy.random.normal",
"numpy.random.choice",
"numpy.random.sample"
] | [((8051, 8118), 'numpy.savetxt', 'np.savetxt', ([], {'X': 'sema', 'fmt': '"""%s"""', 'delimiter': '"""\t"""', 'fname': '"""setmatrix.tsv"""'}), "(X=sema, fmt='%s', delimiter='\\t', fname='setmatrix.tsv')\n", (8061, 8118), True, 'import numpy as np\n'), ((8326, 8386), 'numpy.savetxt', 'np.savetxt', ([], {'X': 'gesc2', '... |
import numpy as np
import torch
from torch import nn
from core import *
from collections import namedtuple
from itertools import count
torch.backends.cudnn.benchmark = True
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
cpu = torch.device("cpu")
@cat.register(torch.Tensor)
def _(*xs):
re... | [
"torch.cuda.synchronize",
"torch.sqrt",
"torch.cat",
"torchvision.datasets.CIFAR10",
"numpy.mean",
"torch.device",
"torch.ones",
"torch.utils.data.DataLoader",
"torch.nn.ReflectionPad2d",
"numpy.cumsum",
"torch.nn.functional.nll_loss",
"torch.nn.functional.log_softmax",
"torch.zeros",
"ite... | [((253, 272), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (265, 272), False, 'import torch\n'), ((871, 882), 'functools.lru_cache', 'cache', (['None'], {}), '(None)\n', (876, 882), True, 'from functools import lru_cache as cache\n'), ((5351, 5377), 'collections.namedtuple', 'namedtuple', (['"""Ide... |
from numpy import array, einsum, arccos, newaxis, zeros, vstack
from statistics import median, mean
from numpy.linalg import norm
from numpy import triu_indices
import argparse, logging
import cPickle as pickle
from gensim.models.keyedvectors import KeyedVectors as vDB
from pdb import set_trace as st
load_vectors=vDB... | [
"statistics.median",
"argparse.ArgumentParser",
"numpy.einsum",
"numpy.triu_indices",
"logging.info",
"numpy.array",
"numpy.linalg.norm",
"numpy.arccos"
] | [((592, 617), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (615, 617), False, 'import argparse, logging\n'), ((1200, 1261), 'logging.info', 'logging.info', (["('Fitting distances from: %s ...\\n' % args.embed)"], {}), "('Fitting distances from: %s ...\\n' % args.embed)\n", (1212, 1261), False... |
#!/usr/bin/python3
# ssr101b.py
# This moves camera toward shorter distance averaged.
# <NAME> 2021 12/3
# How to execute
# sudo pigpiod
# pyhton3 ssrXY.py
import modules.keyin as keyin # キーボード入力を監視するモジュール
import modules.rc3c as rc
import modules.vl53_6a as tof
import time
import numpy as np
SLEEP=0.1
PERIOD=0.3
s... | [
"modules.keyin.Keyboard",
"time.time",
"modules.rc3c.KeyAssign",
"modules.vl53_6a.start",
"numpy.sqrt"
] | [((324, 338), 'modules.rc3c.KeyAssign', 'rc.KeyAssign', ([], {}), '()\n', (336, 338), True, 'import modules.rc3c as rc\n'), ((359, 370), 'modules.vl53_6a.start', 'tof.start', ([], {}), '()\n', (368, 370), True, 'import modules.vl53_6a as tof\n'), ((378, 394), 'modules.keyin.Keyboard', 'keyin.Keyboard', ([], {}), '()\n'... |
"""
This package contains the main convex hull calculation function
to calculate the points of a convex hull from a given array of
points.
"""
import numpy as np
from myConvexHull.point_utils import *
from myConvexHull.dtype import *
from myConvexHull.line_utils import *
from enum import Enum
def convex_hull(points,... | [
"numpy.append",
"numpy.random.randint",
"numpy.ndarray",
"numpy.delete"
] | [((4428, 4446), 'numpy.ndarray', 'np.ndarray', (['[0, 2]'], {}), '([0, 2])\n', (4438, 4446), True, 'import numpy as np\n'), ((4458, 4496), 'numpy.append', 'np.append', (['hull', '[left_vertex]'], {'axis': '(0)'}), '(hull, [left_vertex], axis=0)\n', (4467, 4496), True, 'import numpy as np\n'), ((4508, 4547), 'numpy.appe... |
#
# Copyright (c) 2021 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
#
"""
Spectral Residual algorithm for anomaly detection
"""
import logging
import numpy as np
from me... | [
"numpy.pad",
"numpy.average",
"numpy.abs",
"numpy.copy",
"merlion.transform.resample.TemporalResample",
"numpy.angle",
"numpy.fft.fft",
"numpy.asarray",
"numpy.ones",
"merlion.utils.UnivariateTimeSeries",
"numpy.where",
"numpy.arange",
"numpy.exp",
"merlion.utils.UnivariateTimeSeries.empty... | [((507, 534), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (524, 534), False, 'import logging\n'), ((683, 717), 'merlion.transform.resample.TemporalResample', 'TemporalResample', ([], {'granularity': 'None'}), '(granularity=None)\n', (699, 717), False, 'from merlion.transform.resample i... |
import math
import time
import copy
import numpy as np
from mcts import MCTS
from node import Node
from collections import OrderedDict
# TODO Implementation is very similar to mcts. Notable exception is children,
# which is now a dict and subgoal related things. Still, needs generalization.
class SMCTS(MCTS):
d... | [
"node.Node",
"copy.copy",
"time.time",
"numpy.random.choice",
"collections.OrderedDict",
"math.log"
] | [((710, 723), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (721, 723), False, 'from collections import OrderedDict\n'), ((1762, 1768), 'node.Node', 'Node', ([], {}), '()\n', (1766, 1768), False, 'from node import Node\n'), ((1965, 1978), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1976, ... |
import matplotlib.pyplot as plt
import numpy as np
N = 100
r0 = 0.6
x = 0.9*np.random.rand(N)
y = 0.9*np.random.rand(N)
area = np.pi*(10 * np.random.rand(N))**2 # 0 to 10 point radii
c = np.sqrt(area)
r = np.sqrt(x*x + y*y)
area1 = np.ma.masked_where(r < r0, area)
area2 = np.ma.masked_where(r >= r0, area)
plt.scatter... | [
"matplotlib.pyplot.show",
"numpy.ma.masked_where",
"matplotlib.pyplot.scatter",
"numpy.sin",
"numpy.arange",
"numpy.cos",
"numpy.random.rand",
"numpy.sqrt"
] | [((189, 202), 'numpy.sqrt', 'np.sqrt', (['area'], {}), '(area)\n', (196, 202), True, 'import numpy as np\n'), ((207, 229), 'numpy.sqrt', 'np.sqrt', (['(x * x + y * y)'], {}), '(x * x + y * y)\n', (214, 229), True, 'import numpy as np\n'), ((234, 266), 'numpy.ma.masked_where', 'np.ma.masked_where', (['(r < r0)', 'area']... |
"""Test basic handler functions."""
import copy
from six import text_type
from webtest import AppError
from webtest import TestApp as App
import numpy as np
from pydap.model import BaseType, StructureType, SequenceType
from pydap.lib import walk
from pydap.exceptions import ConstraintExpressionError
from pydap.handl... | [
"pydap.lib.walk",
"pydap.handlers.lib.apply_selection",
"pydap.parsers.parse_projection",
"pydap.tests.datasets.VerySimpleSequence.sequence.data.copy",
"pydap.model.BaseType",
"numpy.testing.assert_array_equal",
"pydap.handlers.lib.ConstraintExpression",
"copy.copy",
"six.text_type",
"pydap.handle... | [((1218, 1251), 'pydap.handlers.lib.get_handler', 'get_handler', (['"""file.foo"""', 'handlers'], {}), "('file.foo', handlers)\n", (1229, 1251), False, 'from pydap.handlers.lib import load_handlers, get_handler, BaseHandler, ExtensionNotSupportedError, apply_selection, apply_projection, ConstraintExpression, IterData\n... |
#!/usr/bin/env python
import os
import sys
import json
import copy
import h5py
import numpy as np
import pandas as pd
from types import SimpleNamespace
import torch
from torch import nn
from torch.utils.data import DataLoader
from sklearn.metrics import r2_score
sys.path.append('/storage/yaari/mutation_density/pytorch... | [
"sys.path.append",
"pandas.DataFrame",
"h5py.File",
"json.load",
"copy.deepcopy",
"os.makedirs",
"torch.utils.data.DataLoader",
"numpy.empty",
"os.path.realpath",
"sklearn.metrics.r2_score",
"os.path.exists",
"torch.no_grad",
"os.path.join",
"types.SimpleNamespace"
] | [((264, 328), 'sys.path.append', 'sys.path.append', (['"""/storage/yaari/mutation_density/pytorch/nets/"""'], {}), "('/storage/yaari/mutation_density/pytorch/nets/')\n", (279, 328), False, 'import sys\n'), ((329, 388), 'sys.path.append', 'sys.path.append', (['"""/storage/yaari/mutation_density/pytorch/"""'], {}), "('/s... |
import mdtraj
import parmed as pmd
import numpy as np
from parmed.tools import change
from openmmtools import forces
from qmhub import *
from get_charges import *
from simtk.openmm import openmm
from simtk.openmm import app
from simtk import unit
def set_restrained_atoms(top_file, coords_file, ligand_selection, rec... | [
"simtk.openmm.openmm.MonteCarloBarostat",
"simtk.openmm.app.StateDataReporter",
"simtk.openmm.app.Simulation",
"mdtraj.load",
"simtk.openmm.openmm.LangevinIntegrator",
"numpy.array",
"parmed.load_file",
"simtk.openmm.app.DCDReporter",
"openmmtools.forces.HarmonicRestraintForce"
] | [((350, 390), 'parmed.load_file', 'pmd.load_file', (['top_file'], {'xyz': 'coords_file'}), '(top_file, xyz=coords_file)\n', (363, 390), True, 'import parmed as pmd\n'), ((2166, 2261), 'simtk.openmm.openmm.LangevinIntegrator', 'openmm.LangevinIntegrator', (['(298 * unit.kelvin)', '(1 / unit.picosecond)', '(0.002 * unit.... |
import numpy as np
import torch
from torch import nn, optim
from torch.utils.data import TensorDataset, DataLoader, random_split
import data_handler
import damage_detector
import config
torch.autograd.set_detect_anomaly(True)
device = torch.device("cuda" if config.cuda else "cpu")
detector = damage_detector.De... | [
"data_handler.get_dataset",
"data_handler.get_location",
"torch.utils.data.DataLoader",
"damage_detector.loss_function",
"torch.cuda.device_count",
"damage_detector.Detector",
"torch.autograd.set_detect_anomaly",
"torch.utils.data.TensorDataset",
"numpy.array",
"torch.device",
"torch.nn.DataPara... | [((193, 232), 'torch.autograd.set_detect_anomaly', 'torch.autograd.set_detect_anomaly', (['(True)'], {}), '(True)\n', (226, 232), False, 'import torch\n'), ((243, 289), 'torch.device', 'torch.device', (["('cuda' if config.cuda else 'cpu')"], {}), "('cuda' if config.cuda else 'cpu')\n", (255, 289), False, 'import torch\... |
import numpy as np
class CostFunction(object):
"""CostFunction: Base class for all cost functions
Performs basic error handling and inits common attributes
"""
def __init__(self, y_train, y_hat, X_train):
super(CostFunction, self).__init__()
self._check_array_dims(y_train,... | [
"numpy.dot",
"numpy.square",
"numpy.sum",
"numpy.log"
] | [((1675, 1708), 'numpy.dot', 'np.dot', (['self.X_train.T', 'self.loss'], {}), '(self.X_train.T, self.loss)\n', (1681, 1708), True, 'import numpy as np\n'), ((2392, 2410), 'numpy.log', 'np.log', (['self.y_hat'], {}), '(self.y_hat)\n', (2398, 2410), True, 'import numpy as np\n'), ((2454, 2476), 'numpy.log', 'np.log', (['... |
'''
This code is part of QuTIpy.
(c) Copyright <NAME>, 2021
This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
Any modifications or derivative works of t... | [
"numpy.array",
"qutipy.su.su_structure_constants"
] | [((1221, 1232), 'numpy.array', 'np.array', (['p'], {}), '(p)\n', (1229, 1232), True, 'import numpy as np\n'), ((986, 1011), 'qutipy.su.su_structure_constants', 'su_structure_constants', (['d'], {}), '(d)\n', (1008, 1011), False, 'from qutipy.su import su_structure_constants\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.