code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
# -*- coding: utf-8 -*-
'''
This code calculates changes in the ratio between different population-weighted GDP deciles and quintiles
by <NAME> (<EMAIL>)
'''
import pandas as pd
import numpy as np
from netCDF4 import Dataset
import _env
datasets = _env.datasets
scenarios = _env.scenarios
gdp_year = 201... | [
"pandas.DataFrame",
"numpy.size",
"_env.mkdirs",
"pandas.read_csv",
"numpy.median",
"numpy.percentile",
"numpy.where",
"pandas.ExcelWriter"
] | [((599, 671), 'pandas.read_csv', 'pd.read_csv', (["(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv')"], {}), "(_env.odir_root + 'basic_stats' + '/Country_Basic_Stats.csv')\n", (610, 671), True, 'import pandas as pd\n'), ((1834, 1898), 'numpy.where', 'np.where', (["(itbl_gdp_baseline[sgdp_year + '_pop_ratio_... |
__author__ = "<NAME>"
__copyright__ = "2021, Hamilton-Jacobi Analysis in Python"
__license__ = "Molux Licence"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Completed"
import argparse
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import os, sys
from os.path import abspath, dirname... | [
"matplotlib.pyplot.subplot",
"os.path.abspath",
"argparse.ArgumentParser",
"os.path.join",
"matplotlib.pyplot.clf",
"numpy.ones",
"Grids.createGrid",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.figure",
"numpy.array",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.pause"
] | [((625, 747), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""2D Plotter for Various Implicit Initial Conditions for the Value Function"""'}), "(description=\n '2D Plotter for Various Implicit Initial Conditions for the Value Function'\n )\n", (648, 747), False, 'import argparse\n')... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
from statsmodels import robust
class Singular_description(object):
'''
Display statistics from every numerical column in data set.
Base class for Mutual description instance.
Outcomes are repre... | [
"seaborn.set_style",
"numpy.average",
"scipy.stats.mode",
"numpy.median",
"numpy.std",
"scipy.stats.entropy",
"matplotlib.pyplot.yticks",
"pandas.unique",
"numpy.percentile",
"scipy.stats.variation",
"scipy.stats.skew",
"numpy.mean",
"numpy.subtract.outer",
"seaborn.distplot",
"matplotli... | [((784, 810), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (797, 810), True, 'import seaborn as sns\n'), ((838, 852), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (850, 852), True, 'import matplotlib.pyplot as plt\n'), ((909, 979), 'seaborn.distplot', 'sns.distp... |
'''
Script to convert a MAF to a vcf4.2 file using python >=3.6.
Created by <NAME>
8 March 2018
'''
import os
import sys
from optparse import OptionParser
import subprocess
from functools import wraps
import datetime
import time
import numpy as np
def OptionParsing():
usage = 'usage: %prog -i <*.maf> -o <director... | [
"sys.stdout.write",
"subprocess.Popen",
"os.path.abspath",
"optparse.OptionParser",
"os.system",
"time.time",
"sys.stdout.flush",
"numpy.arange",
"functools.wraps",
"sys.exit",
"datetime.datetime.now",
"numpy.random.shuffle"
] | [((349, 368), 'optparse.OptionParser', 'OptionParser', (['usage'], {}), '(usage)\n', (361, 368), False, 'from optparse import OptionParser\n'), ((1695, 1710), 'functools.wraps', 'wraps', (['function'], {}), '(function)\n', (1700, 1710), False, 'from functools import wraps\n'), ((2702, 2724), 'sys.stdout.write', 'sys.st... |
import numpy as np
from pomegranate import *
import json
################################################################################
# LOGGING
################################################################################
import logging
# Logging format
FORMAT = '%(asctime)s SigMa %(levelname)-10s: %(message)s... | [
"json.dump",
"numpy.load",
"logging.basicConfig",
"numpy.unique",
"numpy.split",
"numpy.max",
"numpy.where",
"numpy.array",
"numpy.random.permutation",
"os.listdir",
"logging.getLogger",
"numpy.random.sample"
] | [((322, 356), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': 'FORMAT'}), '(format=FORMAT)\n', (341, 356), False, 'import logging\n'), ((453, 480), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (470, 480), False, 'import logging\n'), ((1318, 1340), 'numpy.load', 'np.load', ... |
import os
import datetime
import psycopg2
import numpy as np
import pandas as pd
#import statsmodels.api as sm
from statsmodels.genmod.generalized_linear_model import GLM
from statsmodels.genmod.families import Binomial
from statsmodels.genmod.families.links import probit
DATABASE_URL = os.environ['DATABASE_URL']
... | [
"statsmodels.genmod.generalized_linear_model.GLM",
"statsmodels.genmod.families.links.probit",
"numpy.ones",
"numpy.array",
"statsmodels.genmod.families.Binomial",
"datetime.datetime.now",
"psycopg2.connect"
] | [((327, 376), 'psycopg2.connect', 'psycopg2.connect', (['DATABASE_URL'], {'sslmode': '"""require"""'}), "(DATABASE_URL, sslmode='require')\n", (343, 376), False, 'import psycopg2\n'), ((511, 541), 'numpy.array', 'np.array', (['iris_df.iloc[:, 0:4]'], {}), '(iris_df.iloc[:, 0:4])\n', (519, 541), True, 'import numpy as n... |
import numpy
from sympy import Rational as frac
from sympy import pi, sqrt
from ..helpers import article, fsd, pm, pm_roll, untangle
from ._helpers import E3rScheme
citation = article(
authors=["<NAME>", "<NAME>"],
title="Approximate integration formulas for certain spherically symmetric regions",
journal... | [
"numpy.array",
"sympy.sqrt",
"sympy.Rational"
] | [((553, 563), 'sympy.Rational', 'frac', (['(3)', '(5)'], {}), '(3, 5)\n', (557, 563), True, 'from sympy import Rational as frac\n'), ((572, 583), 'sympy.Rational', 'frac', (['(1)', '(30)'], {}), '(1, 30)\n', (576, 583), True, 'from sympy import Rational as frac\n'), ((824, 832), 'sympy.sqrt', 'sqrt', (['(30)'], {}), '(... |
import numpy as np
import pickle
import os
from pathlib import Path
from metrics.class_imbalance import get_classes, class_proportion
from metrics.phi_div import average_dkl
from metrics.wasserstein import wasserstein_2
def compute_metrics(ds,
split,
inv_temp,
... | [
"os.getcwd",
"numpy.corrcoef",
"metrics.wasserstein.wasserstein_2",
"numpy.array",
"metrics.phi_div.average_dkl",
"numpy.concatenate"
] | [((1107, 1153), 'metrics.phi_div.average_dkl', 'average_dkl', (['party_datasets', 'reference_dataset'], {}), '(party_datasets, reference_dataset)\n', (1118, 1153), False, 'from metrics.phi_div import average_dkl\n'), ((1243, 1302), 'metrics.phi_div.average_dkl', 'average_dkl', (['party_datasets_with_rewards', 'referenc... |
import unittest
from typing import List
import numpy as np
from py_headless_daw.processing.stream.stream_gain import StreamGain
from py_headless_daw.schema.dto.time_interval import TimeInterval
from py_headless_daw.schema.events.event import Event
from py_headless_daw.schema.events.parameter_value_event import Parame... | [
"py_headless_daw.schema.dto.time_interval.TimeInterval",
"py_headless_daw.schema.events.parameter_value_event.ParameterValueEvent",
"numpy.float32",
"numpy.zeros",
"numpy.ones"
] | [((495, 509), 'py_headless_daw.schema.dto.time_interval.TimeInterval', 'TimeInterval', ([], {}), '()\n', (507, 509), False, 'from py_headless_daw.schema.dto.time_interval import TimeInterval\n'), ((606, 645), 'numpy.ones', 'np.ones', ([], {'shape': '(100,)', 'dtype': 'np.float32'}), '(shape=(100,), dtype=np.float32)\n'... |
import matplotlib.pyplot as plt
# import pydicom
import os
from pydicom.filereader import dcmread, read_dicomdir
from glob import glob
import cv2
import numpy as np
cv2.destroyAllWindows()
# window prop
screensize = ((-1440,0),(0,900))
screenwidth = screensize[0][1]-screensize[0][0]
screenheight = screensize[1][1]-scr... | [
"numpy.stack",
"cv2.Canny",
"pydicom.filereader.dcmread",
"cv2.arcLength",
"cv2.threshold",
"cv2.imshow",
"cv2.resizeWindow",
"cv2.namedWindow",
"numpy.array",
"cv2.convertScaleAbs",
"cv2.normalize",
"cv2.moveWindow",
"cv2.destroyAllWindows",
"os.path.join",
"cv2.findContours"
] | [((166, 189), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (187, 189), False, 'import cv2\n'), ((838, 916), 'cv2.normalize', 'cv2.normalize', (['image'], {'dst': 'None', 'alpha': '(0)', 'beta': '(65536)', 'norm_type': 'cv2.NORM_MINMAX'}), '(image, dst=None, alpha=0, beta=65536, norm_type=cv2.NORM... |
import glob
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import xarray as xr
from mpl_toolkits.basemap import Basemap
import gc
import matplotlib
matplotlib.rc('font', size=12)
data_path = 'processed_netcdf'
multibeam_files = glob.glob(data_path + '/*.nc')
multibeam_files.sort()
lon... | [
"matplotlib.pyplot.pcolor",
"matplotlib.rc",
"matplotlib.pyplot.close",
"xarray.open_dataset",
"numpy.isnan",
"matplotlib.pyplot.colorbar",
"gc.collect",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.array",
"glob.glob",
"mpl_toolkits.basemap.Basemap",
"matplotlib.pyplot.savefig"
] | [((180, 210), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {'size': '(12)'}), "('font', size=12)\n", (193, 210), False, 'import matplotlib\n'), ((262, 292), 'glob.glob', 'glob.glob', (["(data_path + '/*.nc')"], {}), "(data_path + '/*.nc')\n", (271, 292), False, 'import glob\n'), ((381, 413), 'numpy.arange', 'np.a... |
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
import math
import numpy as np
def quadratic(**kwargs) -> float:
return sum(x_i ** 2 for _, x_i in kwargs.items())
def ackley(x_1=None, x_2=None, a=20, b=0.2, c=2*math.pi):
d = 2
return -a * np.exp(-b * np.sqrt((x_1... | [
"numpy.arctan2",
"numpy.exp",
"numpy.cos",
"numpy.sqrt"
] | [((526, 554), 'numpy.sqrt', 'np.sqrt', (['(x_1 ** 2 + x_2 ** 2)'], {}), '(x_1 ** 2 + x_2 ** 2)\n', (533, 554), True, 'import numpy as np\n'), ((390, 399), 'numpy.exp', 'np.exp', (['(1)'], {}), '(1)\n', (396, 399), True, 'import numpy as np\n'), ((593, 613), 'numpy.arctan2', 'np.arctan2', (['x_1', 'x_2'], {}), '(x_1, x_... |
import sys
import numpy as np
import quaternionic
import pytest
def test_self_return():
def f1(a, b, c):
d = np.asarray(a).copy()
assert isinstance(a, np.ndarray) and isinstance(a, quaternionic.array)
assert isinstance(b, np.ndarray) and isinstance(b, quaternionic.array)
assert isi... | [
"quaternionic.utilities.ndarray_args",
"numpy.random.seed",
"sys.implementation.name.lower",
"numpy.random.rand",
"numba.complex128",
"numpy.asarray",
"numpy.finfo",
"quaternionic.array",
"quaternionic.array.random",
"quaternionic.utilities.pyguvectorize",
"quaternionic.utilities.type_self_retur... | [((489, 526), 'quaternionic.array.random', 'quaternionic.array.random', (['(17, 3, 4)'], {}), '((17, 3, 4))\n', (514, 526), False, 'import quaternionic\n'), ((535, 572), 'quaternionic.array.random', 'quaternionic.array.random', (['(13, 3, 4)'], {}), '((13, 3, 4))\n', (560, 572), False, 'import quaternionic\n'), ((581, ... |
from unittest import TestCase
import numpy as np
import os
from xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring import DetectorRISE
from xaitk_saliency import GenerateDetectorProposalSaliency
from smqtk_core.configuration import configuration_test_helper
from tests import DATA_DIR, EXPECTED_MASKS_4x6
clas... | [
"xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring.DetectorRISE",
"numpy.random.seed",
"numpy.allclose",
"smqtk_core.configuration.configuration_test_helper",
"numpy.random.randint",
"numpy.array",
"numpy.random.rand",
"os.path.join"
] | [((472, 486), 'xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring.DetectorRISE', 'DetectorRISE', ([], {}), '()\n', (484, 486), False, 'from xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring import DetectorRISE\n'), ((691, 705), 'xaitk_saliency.impls.gen_detector_prop_sal.drise_scoring.DetectorRISE', 'Detec... |
import numpy as np
import autoeap
from numpy.testing import assert_array_almost_equal
import os
PACKAGEDIR = os.path.abspath(os.path.dirname(__file__))
def test_raw_lightcurve():
time,flux,flux_err = autoeap.createlightcurve('EPIC220198696',campaign=8)
lc = np.genfromtxt(os.path.join(PACKAGEDIR,"EPIC22019869... | [
"os.path.dirname",
"os.path.join",
"autoeap.createlightcurve",
"numpy.testing.assert_array_almost_equal"
] | [((126, 151), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (141, 151), False, 'import os\n'), ((206, 259), 'autoeap.createlightcurve', 'autoeap.createlightcurve', (['"""EPIC220198696"""'], {'campaign': '(8)'}), "('EPIC220198696', campaign=8)\n", (230, 259), False, 'import autoeap\n'), ((360... |
# ------------------------------------------------------------------------------
# Hippocampus segmentation task for the HarP dataset
# (http://www.hippocampal-protocol.net/SOPs/index.php)
# ------------------------------------------------------------------------------
import os
import re
import SimpleITK as sitk
imp... | [
"nibabel.Nifti1Image",
"numpy.moveaxis",
"os.makedirs",
"mp.data.datasets.dataset_utils.get_dataset_name",
"os.path.isdir",
"numpy.asarray",
"re.match",
"SimpleITK.GetArrayFromImage",
"mp.data.datasets.dataset_utils.get_original_data_path",
"numpy.min",
"numpy.array",
"SimpleITK.GetImageFromAr... | [((3132, 3198), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])\n', (3140, 3198), True, 'import numpy as np\n'), ((3287, 3320), 'os.path.join', 'os.path.join', (['source_path', 'subset'], {}), '(source_path, subse... |
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
# code changed to Python3
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import tarfile
from IPython.display import display, Image
from scipy import ndima... | [
"sys.stdout.write",
"pickle.dump",
"numpy.random.seed",
"numpy.sum",
"pickle.load",
"numpy.arange",
"sys.stdout.flush",
"numpy.mean",
"numpy.ndarray",
"os.path.join",
"numpy.std",
"os.path.exists",
"numpy.reshape",
"tarfile.open",
"numpy.random.shuffle",
"os.stat",
"urllib.request.ur... | [((2095, 2114), 'numpy.random.seed', 'np.random.seed', (['(133)'], {}), '(133)\n', (2109, 2114), True, 'import numpy as np\n'), ((1683, 1700), 'os.stat', 'os.stat', (['filename'], {}), '(filename)\n', (1690, 1700), False, 'import os\n'), ((3488, 3506), 'os.listdir', 'os.listdir', (['folder'], {}), '(folder)\n', (3498, ... |
import logging
import numpy as np
import math
from .drawing import Camouflage, NoPattern, SolidColor, MultiGradient, ImagePattern, Gradient, Image, Symbol
from .fonts import LANGUAGE_MAP
from .generate import (
dataset_generator,
basic_attribute_sampler,
flatten_mask,
flatten_mask_except_first,
ad... | [
"numpy.random.rand",
"numpy.random.randn",
"numpy.random.choice"
] | [((17287, 17303), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (17301, 17303), True, 'import numpy as np\n'), ((17405, 17445), 'numpy.random.choice', 'np.random.choice', (['alphabet.symbols[:200]'], {}), '(alphabet.symbols[:200])\n', (17421, 17445), True, 'import numpy as np\n'), ((17560, 17598), 'numpy.ran... |
import extract_features as ef
import numpy as np
with open('./input.csv','r',encoding='utf-8') as input_file:
with open('./dataset.csv','w',encoding='utf-8') as dataset:
for line in input_file:
r = line.split(',')
x = r[0].strip()
y = r[1].strip()
example = ef.extractFeatures(x)
r... | [
"numpy.array2string",
"extract_features.extractFeatures"
] | [((294, 315), 'extract_features.extractFeatures', 'ef.extractFeatures', (['x'], {}), '(x)\n', (312, 315), True, 'import extract_features as ef\n'), ((353, 392), 'numpy.array2string', 'np.array2string', (['example'], {'separator': '""","""'}), "(example, separator=',')\n", (368, 392), True, 'import numpy as np\n')] |
# 05 de Junio del 2018
# 31 Mayo 2018
import numpy as np
import matplotlib.pyplot as plt
from time import sleep
import cv2
class Recurrent_Photo:
'''
Recurrent Photo only for testing
'''
def __init__(self, iterations=100, resize=(1280, 720)):
self.camera = cv2.VideoCapture(0)
self.vi... | [
"numpy.abs",
"cv2.waitKey",
"numpy.zeros",
"time.sleep",
"cv2.VideoCapture",
"numpy.array",
"cv2.imshow",
"cv2.resize"
] | [((2183, 2191), 'time.sleep', 'sleep', (['(2)'], {}), '(2)\n', (2188, 2191), False, 'from time import sleep\n'), ((285, 304), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (301, 304), False, 'import cv2\n'), ((326, 373), 'numpy.zeros', 'np.zeros', (['[iterations, resize[1], resize[0], 3]'], {}), '([it... |
#! /usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------... | [
"numpy.mean",
"numpy.equal.outer",
"numpy.invert"
] | [((2254, 2288), 'numpy.equal.outer', 'np.equal.outer', (['grouping', 'grouping'], {}), '(grouping, grouping)\n', (2268, 2288), True, 'import numpy as np\n'), ((2779, 2820), 'numpy.mean', 'np.mean', (['self._ranked_dists[grouping_tri]'], {}), '(self._ranked_dists[grouping_tri])\n', (2786, 2820), True, 'import numpy as n... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import speaksee.data as data
import numpy as np
import torch
'''class TestImageField(object):
def test_preprocessing(self):
field = data.ImageField()
image = ''
expected_image = ''
assert field.preproce... | [
"numpy.asarray",
"speaksee.data.TextField"
] | [((446, 462), 'speaksee.data.TextField', 'data.TextField', ([], {}), '()\n', (460, 462), True, 'import speaksee.data as data\n'), ((966, 1002), 'speaksee.data.TextField', 'data.TextField', ([], {'include_lengths': '(True)'}), '(include_lengths=True)\n', (980, 1002), True, 'import speaksee.data as data\n'), ((1160, 1188... |
import numpy as np
"""
:param MLLD_functions: this class has several functions that are usually used by myself.
"""
class MLLD_functions:
def standardization(self, variable):
"""
:param variable: the array with the variables you wish to standardize
:return: standardized array
"""
... | [
"numpy.std",
"numpy.average",
"numpy.array"
] | [((342, 362), 'numpy.average', 'np.average', (['variable'], {}), '(variable)\n', (352, 362), True, 'import numpy as np\n'), ((385, 401), 'numpy.std', 'np.std', (['variable'], {}), '(variable)\n', (391, 401), True, 'import numpy as np\n'), ((608, 630), 'numpy.array', 'np.array', (['new_variable'], {}), '(new_variable)\n... |
"""User defined module for simulation."""
import numpy
def get_analytical(grid, asol, user_bc):
"""Compute and set the analytical solution.
Arguments
---------
grid : flowx.Grid object
Grid containing data.
asol : string
Name of the variable on the grid.
"""
X, Y = numpy... | [
"numpy.sin",
"numpy.meshgrid",
"numpy.cos"
] | [((315, 345), 'numpy.meshgrid', 'numpy.meshgrid', (['grid.x', 'grid.y'], {}), '(grid.x, grid.y)\n', (329, 345), False, 'import numpy\n'), ((856, 886), 'numpy.meshgrid', 'numpy.meshgrid', (['grid.x', 'grid.y'], {}), '(grid.x, grid.y)\n', (870, 886), False, 'import numpy\n'), ((396, 423), 'numpy.sin', 'numpy.sin', (['(2 ... |
from pipeline.feature_engineering.preprocessing.abstract_preprocessor import Preprocessor
from pipeline.feature_engineering.preprocessing.replacement_strategies.mean_replacement_strategy import MeanReplacementStrategy
from pipeline.feature_engineering.preprocessing.replacement_strategies.del_row_replacement_strategy im... | [
"pipeline.feature_engineering.preprocessing.replacement_strategies.del_row_replacement_strategy.DelRowReplacementStrategy",
"pipeline.feature_engineering.preprocessing.replacement_strategies.replacement_val_replacement_strategy.ReplacementValReplacementStrategy",
"pipeline.feature_engineering.preprocessing.repl... | [((11397, 11440), 'pandas.to_datetime', 'pandas.to_datetime', (['data[column]'], {'unit': 'unit'}), '(data[column], unit=unit)\n', (11415, 11440), False, 'import pandas\n'), ((15773, 15810), 'pandas.concat', 'pandas.concat', (['(labels, data)'], {'axis': '(1)'}), '((labels, data), axis=1)\n', (15786, 15810), False, 'im... |
"""
Sinusoidal Function Sphere function (2 random inputs, scalar output)
======================================================================
In this example, PCE is used to generate a surrogate model for a given set of 2D data.
.. math:: f(x) = x_1^2 + x_2^2
**Description:** Dimensions: 2
**Input Domain:** T... | [
"numpy.meshgrid",
"numpy.random.seed",
"matplotlib.pyplot.show",
"numpy.abs",
"UQpy.distributions.JointIndependent",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.ticker.LinearLocator",
"matplotlib.ticker.FormatStrFormatter",
"numpy.linspace",
"UQpy.distributions.Uniform",
"numpy.var"
... | [((1125, 1142), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (1139, 1142), True, 'import numpy as np\n'), ((1153, 1184), 'UQpy.distributions.Uniform', 'Uniform', ([], {'loc': '(-5.12)', 'scale': '(10.24)'}), '(loc=-5.12, scale=10.24)\n', (1160, 1184), False, 'from UQpy.distributions import Uniform, Jo... |
import numpy as np
import pytest
from fast_carpenter.selection.filters import Counter
@pytest.fixture
def weight_names():
return [
"EventWeight",
# "MuonWeight", "ElectronWeight", "JetWeight",
]
@pytest.fixture
def counter(weight_names):
return Counter(weight_names)
def test_init(weigh... | [
"pytest.raises",
"pytest.approx",
"numpy.array",
"fast_carpenter.selection.filters.Counter"
] | [((277, 298), 'fast_carpenter.selection.filters.Counter', 'Counter', (['weight_names'], {}), '(weight_names)\n', (284, 298), False, 'from fast_carpenter.selection.filters import Counter\n'), ((357, 378), 'fast_carpenter.selection.filters.Counter', 'Counter', (['weight_names'], {}), '(weight_names)\n', (364, 378), False... |
import torch as pt
import numpy as np
from model.PFSeg import PFSeg3D
from medpy.metric.binary import jc,hd95
from dataset.GuidedBraTSDataset3D import GuidedBraTSDataset3D
# from loss.FALoss3D import FALoss3D
import cv2
from loss.TaskFusionLoss import TaskFusionLoss
from loss.DiceLoss import BinaryDiceLoss
from config ... | [
"numpy.sum",
"argparse.ArgumentParser",
"torch.cuda.device_count",
"torch.no_grad",
"torch.nn.MSELoss",
"torch.nn.BCELoss",
"torch.utils.data.DataLoader",
"loss.TaskFusionLoss.TaskFusionLoss",
"cv2.imwrite",
"torch.load",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"tqdm.tqdm",
"model.PFSe... | [((500, 585), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Patch-free 3D Medical Image Segmentation."""'}), "(description='Patch-free 3D Medical Image Segmentation.'\n )\n", (523, 585), False, 'import argparse\n'), ((1956, 2004), 'dataset.GuidedBraTSDataset3D.GuidedBraTSDataset3D', ... |
import numpy as np
import pandas as pd
import torch
import torch.utils.data
import torch.optim as optim
from torch.optim import Adam
from torch.nn import functional as F
from torch.nn import (Dropout, LeakyReLU, Linear, Module, ReLU, Sequential,
Conv2d, ConvTranspose2d, BatchNorm2d, Sigmoid, init, BCELoss, CrossEntropy... | [
"torch.nn.Dropout",
"numpy.sum",
"numpy.argmax",
"torch.argmax",
"torch.cat",
"torch.randn",
"torch.nn.init.constant_",
"numpy.arange",
"torch.nn.BCELoss",
"model.synthesizer.transformer.ImageTransformer",
"torch.nn.Linear",
"numpy.random.choice",
"torch.log",
"numpy.random.shuffle",
"nu... | [((2100, 2124), 'torch.cat', 'torch.cat', (['data_t'], {'dim': '(1)'}), '(data_t, dim=1)\n', (2109, 2124), False, 'import torch\n'), ((6050, 6074), 'torch.stack', 'torch.stack', (['loss'], {'dim': '(1)'}), '(loss, dim=1)\n', (6061, 6074), False, 'import torch\n'), ((1104, 1120), 'torch.nn.Sequential', 'Sequential', (['... |
"""
util.py
Some utility functions
"""
import os
import numpy as np
from sklearn.neighbors import BallTree, radius_neighbors_graph
import networkx as nx
__all__ = ["ORCA_PATH", "pbc", "orbits", "weights", "compute_graph"]
ORCA_PATH = os.path.abspath(os.path.abspath(__file__) + "../../../orca/orca.exe")
def pbc(x0,... | [
"os.path.abspath",
"numpy.abs",
"networkx.from_numpy_matrix",
"sklearn.neighbors.radius_neighbors_graph",
"numpy.log",
"numpy.where",
"numpy.array",
"sklearn.neighbors.BallTree"
] | [((477, 734), 'numpy.array', 'np.array', (['[1, 2, 2, 2, 3, 4, 3, 3, 4, 3, 4, 4, 4, 4, 3, 4, 6, 5, 4, 5, 6, 6, 4, 4, 4,\n 5, 7, 4, 6, 6, 7, 4, 6, 6, 6, 5, 6, 7, 7, 5, 7, 6, 7, 6, 5, 5, 6, 8, 7,\n 6, 6, 8, 6, 9, 5, 6, 4, 6, 6, 7, 8, 6, 6, 8, 7, 6, 7, 7, 8, 5, 6, 6, 4]'], {'dtype': 'np.float'}), '([1, 2, 2, 2, 3, 4... |
"""
@author: <NAME>
@contact: <EMAIL>
"""
import logging
import numpy as np # type: ignore
import sys
from typing import Callable
def ert_type(x, stype, label):
if not isinstance(x, stype):
raise AssertionError(f"{label} should be {stype}, {type(x)} instead")
def ert_multiTypes(x, types, label):
c... | [
"logging.exception",
"logging.warning",
"numpy.iinfo",
"numpy.finfo",
"sys.exit"
] | [((1998, 2060), 'logging.warning', 'logging.warning', (['f"""assert not implemented for dtype \'{dtype}\'"""'], {}), '(f"assert not implemented for dtype \'{dtype}\'")\n', (2013, 2060), False, 'import logging\n'), ((1350, 1365), 'numpy.finfo', 'np.finfo', (['dtype'], {}), '(dtype)\n', (1358, 1365), True, 'import numpy ... |
import ast
import os
import cv2
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from keras.applications.densenet import preprocess_input
from keras.metrics import (categorical_accuracy, top_k_categorical_accuracy)
from keras.models import Model, load_model
DP_DIR = './input... | [
"cv2.line",
"keras.applications.densenet.preprocess_input",
"numpy.random.seed",
"tensorflow.keras.utils.to_categorical",
"cv2.cvtColor",
"pandas.read_csv",
"numpy.zeros",
"numpy.flipud",
"tensorflow.set_random_seed",
"numpy.argsort",
"numpy.array",
"numpy.random.permutation",
"keras.metrics... | [((429, 454), 'numpy.random.seed', 'np.random.seed', ([], {'seed': '(2018)'}), '(seed=2018)\n', (443, 454), True, 'import numpy as np\n'), ((455, 484), 'tensorflow.set_random_seed', 'tf.set_random_seed', ([], {'seed': '(2018)'}), '(seed=2018)\n', (473, 484), True, 'import tensorflow as tf\n'), ((1588, 1635), 'keras.met... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# Adapted from https://github.com/microsoft/CodeXGLUE/blob/main/Text-Code/NL-code-search-Adv/evaluator/evaluator.py
import logging
import sys, json
import numpy as np
def read_answers(filename):
answers = {}
with open(filename) as f:
... | [
"numpy.mean",
"argparse.ArgumentParser",
"sys.exit",
"json.loads"
] | [((1399, 1496), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Evaluate leaderboard predictions for POJ-104 dataset."""'}), "(description=\n 'Evaluate leaderboard predictions for POJ-104 dataset.')\n", (1422, 1496), False, 'import argparse\n'), ((1314, 1329), 'numpy.mean', 'np.mean', ... |
from __future__ import print_function
import argparse
import numpy as np
import os, csv
from dataset import CIFAR10IndexPseudoLabelEnsemble
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms as transforms
import torch.utils.data as Data
import torch.backends.... | [
"dataset.CIFAR10IndexPseudoLabelEnsemble",
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.autograd.grad",
"utils.adjust_learning_rate",
"losses.SupConLoss",
"torch.get_rng_state",
"torch.cuda.device_count",
"models.resnet_cifar_multibn_ensembleFC.resnet18",
"pickle.load",
"tensorboard_lo... | [((886, 911), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (909, 911), False, 'import argparse\n'), ((4093, 4118), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4116, 4118), False, 'import torch\n'), ((4706, 4763), 'utils.TwoCropTransformAdv', 'TwoCropTransformAdv',... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 19 21:04:18 2017
@author: pd
"""
#from IPython import get_ipython
#get_ipython().magic('reset -sf')
import numpy as np
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
from sklearn.cross_... | [
"sklearn.cross_validation.train_test_split",
"matplotlib.pyplot.show",
"sklearn.datasets.make_classification",
"sklearn.tree.DecisionTreeClassifier",
"numpy.arange",
"matplotlib.pyplot.subplots"
] | [((378, 472), 'sklearn.datasets.make_classification', 'datasets.make_classification', (['(750)'], {'n_features': 'n_features', 'n_informative': '(5)', 'random_state': '(29)'}), '(750, n_features=n_features, n_informative=5,\n random_state=29)\n', (406, 472), False, 'from sklearn import datasets\n'), ((507, 561), 'sk... |
#!/usr/bin/python
# coding: utf-8
import sys
import Levenshtein
import numpy as np
assert len(sys.argv) > 1
with open(sys.argv[1], 'r', encoding='utf-8') as file:
lines = file.readlines()
n_lines = len(lines)
distances = np.zeros((n_lines, n_lines), dtype=int)
messages = []
for x in range(n_lines):
for y i... | [
"Levenshtein.distance",
"numpy.zeros"
] | [((229, 268), 'numpy.zeros', 'np.zeros', (['(n_lines, n_lines)'], {'dtype': 'int'}), '((n_lines, n_lines), dtype=int)\n', (237, 268), True, 'import numpy as np\n'), ((384, 424), 'Levenshtein.distance', 'Levenshtein.distance', (['lines[x]', 'lines[y]'], {}), '(lines[x], lines[y])\n', (404, 424), False, 'import Levenshte... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import edward as ed
import numpy as np
import tensorflow as tf
from collections import namedtuple
from edward.models import (
Beta, Dirichlet, DirichletProcess, Gamma, MultivariateNormalDiag,
Normal, P... | [
"tensorflow.test.main",
"tensorflow.ones",
"edward.transform",
"numpy.sum",
"edward.models.Dirichlet",
"tensorflow.zeros",
"collections.namedtuple",
"edward.models.Normal",
"edward.models.Gamma",
"edward.models.Beta",
"tensorflow.contrib.distributions.bijectors.Softplus"
] | [((2782, 2796), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (2794, 2796), True, 'import tensorflow as tf\n'), ((511, 554), 'numpy.sum', 'np.sum', (['(sample > 0.0)'], {'axis': '(0)', 'keepdims': '(True)'}), '(sample > 0.0, axis=0, keepdims=True)\n', (517, 554), True, 'import numpy as np\n'), ((571, 614), ... |
# -*- coding: utf-8 -*-
"""
For testing neuromaps.stats functionality
"""
import numpy as np
import pytest
from neuromaps import stats
@pytest.mark.xfail
def test_compare_images():
assert False
def test_permtest_metric():
rs = np.random.default_rng(12345678)
x, y = rs.random(size=(2, 100))
r, p = ... | [
"neuromaps.stats.efficient_pearsonr",
"numpy.allclose",
"numpy.isnan",
"numpy.random.default_rng",
"pytest.raises",
"neuromaps.stats.permtest_metric"
] | [((241, 272), 'numpy.random.default_rng', 'np.random.default_rng', (['(12345678)'], {}), '(12345678)\n', (262, 272), True, 'import numpy as np\n'), ((320, 347), 'neuromaps.stats.permtest_metric', 'stats.permtest_metric', (['x', 'y'], {}), '(x, y)\n', (341, 347), False, 'from neuromaps import stats\n'), ((359, 420), 'nu... |
import numpy as np
import pytest
import snc.environments.job_generators.discrete_review_job_generator \
as drjg
import snc.environments.controlled_random_walk as crw
import snc.environments.state_initialiser as si
import snc.agents.general_heuristics.random_nonidling_agent \
as random_nonidling_agent
import sn... | [
"snc.environments.job_generators.discrete_review_job_generator.DeterministicDiscreteReviewJobGenerator",
"numpy.zeros_like",
"numpy.ones_like",
"numpy.random.seed",
"numpy.sum",
"snc.agents.general_heuristics.longest_buffer_priority_agent.LongestBufferPriorityAgent",
"numpy.zeros",
"numpy.ones",
"sn... | [((696, 715), 'numpy.ones_like', 'np.ones_like', (['state'], {}), '(state)\n', (708, 715), True, 'import numpy as np\n'), ((1739, 1754), 'numpy.ones', 'np.ones', (['(1, 1)'], {}), '((1, 1))\n', (1746, 1754), True, 'import numpy as np\n'), ((1838, 1876), 'snc.environments.controlled_random_walk.ControlledRandomWalk', 'c... |
import numpy as np
import matplotlib.pyplot as plt
import pprint
def missingIsNan(s):
return np.nan if s == b'?' else float(s)
def makeStandardize(X):
means = X.mean(axis = 0)
stds = X.std(axis = 0)
def standardize(origX):
return (origX - means) / stds
def unstandardize(stdX):
return stds * ... | [
"numpy.linalg.lstsq",
"numpy.isnan",
"numpy.insert",
"numpy.mean",
"numpy.arange",
"numpy.random.shuffle"
] | [((1004, 1020), 'numpy.arange', 'np.arange', (['nRows'], {}), '(nRows)\n', (1013, 1020), True, 'import numpy as np\n'), ((1023, 1046), 'numpy.random.shuffle', 'np.random.shuffle', (['rows'], {}), '(rows)\n', (1040, 1046), True, 'import numpy as np\n'), ((1517, 1544), 'numpy.insert', 'np.insert', (['XtrainS', '(0)', '(1... |
from typing import Tuple, Dict
import random
import numpy as np
import torch
from torchvision import datasets, transforms
from sklearn.metrics.pairwise import cosine_distances
from matplotlib import pyplot as plt
try:
from torch.utils.tensorboard import SummaryWriter
except ImportError:
from tensorboardX im... | [
"matplotlib.pyplot.title",
"sklearn.metrics.pairwise.cosine_distances",
"numpy.random.seed",
"matplotlib.pyplot.show",
"torch.eye",
"torch.manual_seed",
"torch.cuda.random.manual_seed",
"torch.cuda.manual_seed",
"torch.cuda.manual_seed_all",
"random.seed",
"torch.tensor"
] | [((569, 585), 'matplotlib.pyplot.title', 'plt.title', (['label'], {}), '(label)\n', (578, 585), True, 'from matplotlib import pyplot as plt\n'), ((637, 647), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (645, 647), True, 'from matplotlib import pyplot as plt\n'), ((3421, 3438), 'random.seed', 'random.seed', ... |
import os,sys,talib,numpy,math,logging,time,datetime,numbers
from collections import OrderedDict
from baseindicator import BaseIndicator
class EMA(BaseIndicator):
def __init__(self,csdata, config = {}):
config["period"] = config.get("period",30)
config["metric"] = config.get("metric","closed")
... | [
"collections.OrderedDict",
"datetime.datetime.strptime",
"numpy.array",
"baseindicator.BaseIndicator.__init__"
] | [((455, 499), 'baseindicator.BaseIndicator.__init__', 'BaseIndicator.__init__', (['self', 'csdata', 'config'], {}), '(self, csdata, config)\n', (477, 499), False, 'from baseindicator import BaseIndicator\n'), ((2563, 2576), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (2574, 2576), False, 'from collectio... |
# %%
import os
import sys
# os.chdir("../../..")
os.environ['DJANGO_SETTINGS_MODULE'] = 'MAKDataHub.settings'
import django
django.setup()
# %%
import math
import pickle
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from MAKDataHub.services import Services
profile_servi... | [
"django.setup",
"sklearn.preprocessing.StandardScaler",
"sklearn.model_selection.train_test_split",
"sklearn.neighbors.LocalOutlierFactor",
"sklearn.feature_selection.RFE",
"numpy.isnan",
"sklearn.feature_selection.SelectFromModel",
"numpy.mean",
"seaborn.pairplot",
"sklearn.model_selection.Random... | [((124, 138), 'django.setup', 'django.setup', ([], {}), '()\n', (136, 138), False, 'import django\n'), ((325, 351), 'MAKDataHub.services.Services.profile_service', 'Services.profile_service', ([], {}), '()\n', (349, 351), False, 'from MAKDataHub.services import Services\n'), ((370, 396), 'MAKDataHub.services.Services.s... |
import pylab as plt
import numpy as np
from math import *
N=100
t0 = 0.0
t1 = 2.0
t = np.linspace(t0,t1,N)
dt = (t1-t0)/N
one = np.ones((N))
xp = np.zeros((N))
yp = np.zeros((N))
th = np.zeros((N))
x = t*t
y = t
plt.figure()
plt.plot(x,y,'g-')
plt.legend(['Path'],loc='best')
plt.title('Quadratic Path')
plt.show()
d... | [
"pylab.title",
"pylab.show",
"numpy.zeros",
"numpy.ones",
"pylab.figure",
"numpy.linspace",
"pylab.legend",
"pylab.plot",
"numpy.sqrt"
] | [((87, 109), 'numpy.linspace', 'np.linspace', (['t0', 't1', 'N'], {}), '(t0, t1, N)\n', (98, 109), True, 'import numpy as np\n'), ((129, 139), 'numpy.ones', 'np.ones', (['N'], {}), '(N)\n', (136, 139), True, 'import numpy as np\n'), ((147, 158), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (155, 158), True, 'import... |
#!/usr/bin/env python
# gatherUpper.py
import numpy
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
LENGTH = 3
x = None
x_local = numpy.linspace(rank*LENGTH,(rank+1)*LENGTH, LENGTH)
print(x_local)
if rank == 0:
x = numpy.zeros(size*LENGTH)
print (x)
comm.Gather(x_local... | [
"numpy.zeros",
"numpy.linspace"
] | [((173, 231), 'numpy.linspace', 'numpy.linspace', (['(rank * LENGTH)', '((rank + 1) * LENGTH)', 'LENGTH'], {}), '(rank * LENGTH, (rank + 1) * LENGTH, LENGTH)\n', (187, 231), False, 'import numpy\n'), ((262, 288), 'numpy.zeros', 'numpy.zeros', (['(size * LENGTH)'], {}), '(size * LENGTH)\n', (273, 288), False, 'import nu... |
"""Run simulations for SDC model.
Parameters
----------
N_JOBS
Number of cores used for parallelization.
RANDOM_SEED
Seed for the random numbers generator.
SPACE
Types of social space.
Available values: 'uniform', 'lognormal', 'clusters_normal'.
N
Sizes of networks,
NDIM
Number of dimensions of... | [
"numpy.random.seed",
"os.makedirs",
"_.simulate",
"os.path.realpath",
"sklearn.externals.joblib.Memory",
"gc.collect",
"os.path.join",
"pandas.concat"
] | [((1067, 1097), 'os.path.join', 'os.path.join', (['HERE', '"""raw-data"""'], {}), "(HERE, 'raw-data')\n", (1079, 1097), False, 'import os\n'), ((1122, 1158), 'sklearn.externals.joblib.Memory', 'Memory', ([], {'location': '""".cache"""', 'verbose': '(1)'}), "(location='.cache', verbose=1)\n", (1128, 1158), False, 'from ... |
import numpy as np
import scipy.signal as sp
import scipy.spatial.distance as sp_dist
import librosa
class MedianNMF:
y, sr = None,None
n_components = None
def __init__(self,y,sr,n_components = 5):
self.y, self.sr = y,sr
self.n_components = n_components
def decompose(self):
... | [
"librosa.decompose.decompose",
"scipy.signal.savgol_filter",
"librosa.effects.percussive",
"librosa.istft",
"numpy.multiply.outer",
"librosa.magphase",
"librosa.stft"
] | [((438, 458), 'librosa.stft', 'librosa.stft', (['hpss_y'], {}), '(hpss_y)\n', (450, 458), False, 'import librosa\n'), ((521, 540), 'librosa.magphase', 'librosa.magphase', (['D'], {}), '(D)\n', (537, 540), False, 'import librosa\n'), ((940, 989), 'librosa.effects.percussive', 'librosa.effects.percussive', (['self.y'], {... |
import numpy as np
from collections import defaultdict
class Agent:
def __init__(self, nA=6):
""" Initialize agent.
Params
======
- nA: number of actions available to the agent
"""
self.nA = nA
self.Q = defaultdict(lambda: np.zeros(self.nA))
self.ep... | [
"numpy.zeros",
"numpy.arange",
"numpy.ones",
"numpy.argmax"
] | [((636, 660), 'numpy.argmax', 'np.argmax', (['self.Q[state]'], {}), '(self.Q[state])\n', (645, 660), True, 'import numpy as np\n'), ((1397, 1415), 'numpy.arange', 'np.arange', (['self.nA'], {}), '(self.nA)\n', (1406, 1415), True, 'import numpy as np\n'), ((286, 303), 'numpy.zeros', 'np.zeros', (['self.nA'], {}), '(self... |
import numpy as np
class Mesh:
""" Contains all the information about the spatial domain """
def __init__(self,dimension,topology,geometry):
self.Nvoxels = len(topology)
self.dimension = dimension
self.topology = topology # adjaceny matrix (numpy array), 0 along main diagonal, 1 elsew... | [
"numpy.diag",
"numpy.zeros",
"numpy.ones",
"numpy.linspace"
] | [((855, 873), 'numpy.zeros', 'np.zeros', (['(Nx, Nx)'], {}), '((Nx, Nx))\n', (863, 873), True, 'import numpy as np\n'), ((881, 896), 'numpy.ones', 'np.ones', (['(Nx - 1)'], {}), '(Nx - 1)\n', (888, 896), True, 'import numpy as np\n'), ((952, 969), 'numpy.zeros', 'np.zeros', (['(Nx, 2)'], {}), '((Nx, 2))\n', (960, 969),... |
import tensorflow as tf
from tensorflow.python.keras.preprocessing import image as kp_image
# Keras is only used to load VGG19 model as a high level API to TensorFlow
from keras.applications.vgg19 import VGG19
from keras.models import Model
from keras import backend as K
# pillow is used for loading and saving ima... | [
"tensorflow.clip_by_value",
"tensorflow.reshape",
"keras.models.Model",
"numpy.clip",
"tensorflow.matmul",
"tensorflow.Variable",
"tensorflow.global_variables_initializer",
"keras.backend.set_session",
"tensorflow.Session",
"keras.applications.vgg19.VGG19",
"tensorflow.keras.applications.vgg19.p... | [((1538, 1561), 'PIL.Image.open', 'Image.open', (['path_to_img'], {}), '(path_to_img)\n', (1548, 1561), False, 'from PIL import Image\n'), ((1728, 1754), 'tensorflow.python.keras.preprocessing.image.img_to_array', 'kp_image.img_to_array', (['img'], {}), '(img)\n', (1749, 1754), True, 'from tensorflow.python.keras.prepr... |
import dynet as dy
import numpy as np
import moire
from moire import Expression
__all__ = [
'zeros', 'ones', 'full', 'normal', 'bernoulli', 'uniform', 'gumbel',
'zeros_like', 'ones_like', 'full_like', 'normal_like', 'bernoulli_like', 'uniform_like', 'gumbel_like',
'eye', 'diagonal',
'where',
]
def z... | [
"numpy.full",
"numpy.random.uniform",
"numpy.random.gumbel",
"dynet.inputTensor",
"dynet.cmult",
"numpy.zeros",
"numpy.ones",
"numpy.random.normal",
"numpy.eye"
] | [((375, 421), 'numpy.zeros', 'np.zeros', (['(*dim, batch_size)'], {'dtype': 'np.float32'}), '((*dim, batch_size), dtype=np.float32)\n', (383, 421), True, 'import numpy as np\n'), ((433, 492), 'dynet.inputTensor', 'dy.inputTensor', (['a'], {'batched': '(True)', 'device': 'moire.config.device'}), '(a, batched=True, devic... |
"""Tests for the variant of MT2 by <NAME>."""
from typing import Optional, Union
import numpy
import pytest
from .common import mt2_lester, mt2_tombs
def test_simple_example():
computed_val = mt2_tombs(100, 410, 20, 150, -210, -300, -200, 280, 100, 100)
assert computed_val == pytest.approx(412.628)
def t... | [
"numpy.random.uniform",
"numpy.random.seed",
"numpy.errstate",
"numpy.array",
"numpy.testing.assert_allclose",
"pytest.approx"
] | [((880, 901), 'numpy.random.seed', 'numpy.random.seed', (['(42)'], {}), '(42)\n', (897, 901), False, 'import numpy\n'), ((1918, 1983), 'numpy.array', 'numpy.array', (['(100, 410, 20, 150, -210, -300, -200, 280, 100, 100)'], {}), '((100, 410, 20, 150, -210, -300, -200, 280, 100, 100))\n', (1929, 1983), False, 'import nu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# dicomgui.py
"""Main app file that convert DICOM data via a wxPython GUI dialog."""
# Copyright (c) 2018-2020 <NAME>
# Copyright (c) 2009-2017 <NAME>
# Copyright (c) 2009 <NAME>
# This file is part of dicompyler, released under a BSD license.
# See the file license.txt ... | [
"wx.Dialog.__init__",
"os.walk",
"wx.CallAfter",
"os.path.isfile",
"os.path.join",
"numpy.round",
"pyDcmConverter.guiutil.get_icon",
"wx.SystemSettings.GetFont",
"os.path.dirname",
"numpy.transpose",
"numpy.max",
"wx.DirDialog",
"wx.GetApp",
"nibabel.Nifti1Image",
"threading.Thread",
"... | [((592, 617), 'logging.getLogger', 'getLogger', (['"""DcmConverter"""'], {}), "('DcmConverter')\n", (601, 617), False, 'from logging import getLogger, DEBUG, INFO\n'), ((628, 697), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'wx.wxPyDeprecationWarning'}), "('ignore', category=w... |
# Copyright 2017 The TensorFlow 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 applica... | [
"tensorflow.python.platform.test.main",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.client.session.Session",
"numpy.log",
"tensorflow.python.ops.nn_ops.softplus",
"numpy.float32",
"tensorflow.contrib.learn.python.learn.estimators.head_test._assert_no_variables",
"tensorflow.contrib.dis... | [((4270, 4281), 'tensorflow.python.platform.test.main', 'test.main', ([], {}), '()\n', (4279, 4281), False, 'from tensorflow.python.platform import test\n'), ((2756, 2854), 'tensorflow.contrib.distributions.python.ops.estimator.estimator_head_distribution_regression', 'estimator_lib.estimator_head_distribution_regressi... |
import numpy as np
import gym
from random import randint
from metaworld.benchmarks import ML1
class ReachML1Env(gym.Env):
def __init__(self, max_episode_steps=150,out_of_distribution=False, n_train_tasks=50, n_test_tasks=10, **kwargs):
super(ReachML1Env, self).__init__()
self.train_env = ML1.get_t... | [
"metaworld.benchmarks.ML1.get_train_tasks",
"metaworld.benchmarks.ML1.get_test_tasks",
"numpy.array"
] | [((311, 383), 'metaworld.benchmarks.ML1.get_train_tasks', 'ML1.get_train_tasks', (['"""reach-v1"""'], {'out_of_distribution': 'out_of_distribution'}), "('reach-v1', out_of_distribution=out_of_distribution)\n", (330, 383), False, 'from metaworld.benchmarks import ML1\n'), ((408, 479), 'metaworld.benchmarks.ML1.get_test_... |
# Copyright (c) 2018 <NAME>
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
from phylanx import Phylanx
import numpy as np
@Phylanx
def foo(x, y):
return [x, y]
x = np.array([1, 2])
y = np.array([3, 4])
... | [
"numpy.array"
] | [((282, 298), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (290, 298), True, 'import numpy as np\n'), ((303, 319), 'numpy.array', 'np.array', (['[3, 4]'], {}), '([3, 4])\n', (311, 319), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
################################################################
# <NAME> Personality Type Tweets Natural Language Processing
# By <NAME>
# Project can be found at:
# https://www.inertia7.com/projects/109 &
# https://www.inertia7.com/projects/110
###############################################... | [
"os.getcwd",
"sklearn.model_selection.train_test_split",
"pandas.read_csv",
"os.path.isfile",
"numpy.array",
"sys.exit"
] | [((615, 626), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (624, 626), False, 'import sys, os\n'), ((1048, 1075), 'numpy.array', 'np.array', (["['type', 'posts']"], {}), "(['type', 'posts'])\n", (1056, 1075), True, 'import numpy as np\n'), ((1616, 1642), 'os.path.isfile', 'os.path.isfile', (['token_data'], {}), '(token_... |
from __future__ import print_function
import csv
import numpy as np
import re
import Spectrum
#import matplotlib.pyplot as plt
def ReadCSVRef(filename):
with open(filename) as csvfile:
reader = csv.reader(csvfile, delimiter=',')
headers = list(filter(None, next(reader)))
data = []
f... | [
"csv.reader",
"numpy.shape",
"re.findall",
"numpy.array",
"numpy.interp",
"Spectrum.CLSpectrum"
] | [((383, 397), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (391, 397), True, 'import numpy as np\n'), ((207, 241), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (217, 241), False, 'import csv\n'), ((1620, 1657), 'Spectrum.CLSpectrum', 'Spectrum.CLSpectrum',... |
import warnings
from datetime import datetime
import numpy as np
import xarray as xr
import pytest
import ecco_v4_py
from .test_common import all_mds_datadirs, get_test_ds
@pytest.mark.parametrize("mytype",['xda','nparr','list','single'])
def test_extract_dates(mytype):
dints = [[1991,8,9,13,10,15],[1992,10,20,... | [
"numpy.datetime64",
"ecco_v4_py.extract_yyyy_mm_dd_hh_mm_ss_from_datetime64",
"datetime.datetime",
"ecco_v4_py.get_llc_grid",
"numpy.array",
"pytest.mark.parametrize",
"numpy.all"
] | [((176, 245), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mytype"""', "['xda', 'nparr', 'list', 'single']"], {}), "('mytype', ['xda', 'nparr', 'list', 'single'])\n", (199, 245), False, 'import pytest\n'), ((469, 507), 'numpy.array', 'np.array', (['dates'], {'dtype': '"""datetime64[s]"""'}), "(dates, dty... |
from abc import ABC, abstractmethod
import copy
import logging
import numpy as np
from scipy.stats import rankdata
from typing import Dict, NamedTuple, NoReturn, Tuple
from ..lux.game import Game
from ..lux.game_constants import GAME_CONSTANTS
from ..lux.game_objects import Player
def count_city_tiles(game_state: Ga... | [
"numpy.zeros_like",
"numpy.ones_like",
"numpy.maximum",
"logging.warning",
"numpy.empty",
"numpy.empty_like",
"numpy.ones",
"copy.copy",
"scipy.stats.rankdata",
"numpy.where",
"numpy.array",
"numpy.logical_or"
] | [((350, 417), 'numpy.array', 'np.array', (['[player.city_tile_count for player in game_state.players]'], {}), '([player.city_tile_count for player in game_state.players])\n', (358, 417), True, 'import numpy as np\n'), ((801, 868), 'numpy.array', 'np.array', (['[player.research_points for player in game_state.players]']... |
import numpy as np
import matplotlib.pyplot as plt
# To use LaTeX in the plots
plt.rcParams.update({
"text.usetex": True,
"font.family": "sans-serif",
"font.sans-serif": ["Helvetica"]})
# for Palatino and other serif fonts use:
plt.rcParams.update({
"text.usetex": True,
"font.family": "serif",
... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.add",
"numpy.zeros",
"matplotlib.pyplot.rcParams.update",
"numpy.array",
"numpy.exp",
"numpy.linspace",
"numpy.linalg.norm",
"numpy.linalg.inv",
"matplotlib.pyplot.ylabel",
"numpy.log10",
"matplotlib.pyplot.xlabel"
] | [((80, 189), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'text.usetex': True, 'font.family': 'sans-serif', 'font.sans-serif': [\n 'Helvetica']}"], {}), "({'text.usetex': True, 'font.family': 'sans-serif',\n 'font.sans-serif': ['Helvetica']})\n", (99, 189), True, 'import matplotlib.pyplot as pl... |
import sys
from os.path import join
from threading import Timer
import numpy as np
from openal.audio import SoundSource
assets_root = getattr(sys, '_MEIPASS', '.')
def get_sfx(name):
return join(assets_root, 'assets', name)
def new_pt(*values):
return np.array(values or (0, 0, 0), dtype=float)
def vec_m... | [
"numpy.array",
"os.path.join"
] | [((198, 231), 'os.path.join', 'join', (['assets_root', '"""assets"""', 'name'], {}), "(assets_root, 'assets', name)\n", (202, 231), False, 'from os.path import join\n'), ((266, 308), 'numpy.array', 'np.array', (['(values or (0, 0, 0))'], {'dtype': 'float'}), '(values or (0, 0, 0), dtype=float)\n', (274, 308), True, 'im... |
#!/usr/bin/env python3
#pylint: disable = C, R
#pylint: disable = E1101 # no-member (generated-members)
#pylint: disable = C0302 # too-many-lines
"""
This code features the article
"Pareto-based evaluation of national responses to COVID-19 pandemic shows
that saving lives and protecting economy are non-trade-o... | [
"colorsys.rgb_to_hls",
"numpy.isnan",
"numpy.sin",
"pandas.Grouper",
"locale.setlocale",
"matplotlib.patheffects.Normal",
"matplotlib.pyplot.cm.tab10",
"numpy.savetxt",
"dill.load",
"numpy.place",
"matplotlib.dates.DateFormatter",
"matplotlib.patheffects.Stroke",
"matplotlib.pyplot.rc",
"m... | [((1038, 1070), 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ([], {}), '()\n', (1068, 1070), False, 'from pandas.plotting import register_matplotlib_converters\n'), ((1971, 2014), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(8)', 'family': '"""sans-serif"""'}), "(... |
import numpy as np
from absl.testing import parameterized
from keras.preprocessing import image
from keras.utils import data_utils
from tensorflow.python.platform import test
from ..bit import BiT_S_R50x1, BiT_S_R50x3, BiT_S_R101x1, BiT_S_R101x3, BiT_S_R152x4
from ..bit import BiT_M_R50x1, BiT_M_R50x3, BiT_M_R101x1, Bi... | [
"tensorflow.python.platform.test.main",
"numpy.argmax",
"numpy.expand_dims",
"absl.testing.parameterized.parameters",
"keras.utils.data_utils.get_file",
"keras.preprocessing.image.img_to_array"
] | [((814, 853), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['*MODEL_LIST_S'], {}), '(*MODEL_LIST_S)\n', (838, 853), False, 'from absl.testing import parameterized\n'), ((1197, 1236), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['*MODEL_LIST_S'], {}), '(*MODEL_LIST_S)\n... |
"""
The Colloid_output module contains classes to read LB Colloids simulation
outputs and perform post processing. Many classes are available to
provide plotting functionality. ModelPlot and CCModelPlot are useful for
visualizing colloid-surface forces and colloid-colloid forces respectively.
example import of the Col... | [
"matplotlib.pyplot.bar",
"matplotlib.pyplot.quiver",
"numpy.isnan",
"numpy.arange",
"numpy.exp",
"matplotlib.pyplot.gca",
"pandas.DataFrame",
"numpy.meshgrid",
"numpy.std",
"scipy.special.erfc",
"scipy.optimize.least_squares",
"numpy.linspace",
"numpy.var",
"h5py.File",
"numpy.ma.masked_... | [((5546, 5562), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 1]'], {}), '([0, 1])\n', (5554, 5562), True, 'import matplotlib.pyplot as plt\n'), ((6361, 6377), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 1]'], {}), '([0, 1])\n', (6369, 6377), True, 'import matplotlib.pyplot as plt\n'), ((10592, 10608), 'matplotlib.pypl... |
import geopandas as gpd
# required for MAUP: https://github.com/geopandas/geopandas/issues/2199
gpd.options.use_pygeos = False
import pandas as pd
import numpy as np
import shapely
import shapely.geometry
from shapely.geometry import Polygon, Point
from tqdm import tqdm
import maup
import os
#INTRO - need to edit valu... | [
"pandas.DataFrame",
"maup.normalize",
"shapely.geometry.Point",
"numpy.ceil",
"shapely.geometry.Polygon",
"pandas.read_csv",
"maup.assign",
"maup.prorate",
"numpy.isnan",
"geopandas.GeoDataFrame",
"maup.intersections",
"geopandas.clip",
"shapely.geometry.box",
"geopandas.read_file"
] | [((934, 962), 'shapely.geometry.Point', 'Point', (['(-71.411479)', '(41.823544)'], {}), '(-71.411479, 41.823544)\n', (939, 962), False, 'from shapely.geometry import Polygon, Point\n'), ((977, 1021), 'geopandas.GeoDataFrame', 'gpd.GeoDataFrame', ([], {'geometry': '[point]', 'crs': '(4326)'}), '(geometry=[point], crs=43... |
#!/usr/bin/env python
# coding: utf-8
# ## SIMPLE CONVOLUTIONAL NEURAL NETWORK
# In[1]:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
get_ipython().run_line_magic('matplotlib', 'inline')
print ("PACKAGES LOADED")
# # LOAD MNIS... | [
"numpy.argmax",
"tensorflow.reshape",
"tensorflow.ConfigProto",
"tensorflow.matmul",
"tensorflow.nn.conv2d",
"tensorflow.nn.relu",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"matplotlib.pyplot.colorbar",
"tensorflow.placeholder",
"tensorflow.cast",
"tensorflow.initialize_all_variables",
... | [((342, 390), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""data/"""'], {'one_hot': '(True)'}), "('data/', one_hot=True)\n", (367, 390), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), ((2026, 2069), 'tensorflow.placeholder', 'tf.placeholder'... |
import mxnet as mx
import numpy as np
from rcnn.config import config
class LogLossMetric(mx.metric.EvalMetric):
def __init__(self):
super(LogLossMetric, self).__init__('LogLoss')
def update(self, labels, preds):
pred_cls = preds[0].asnumpy()
label = labels[0].asnumpy().astype('int32'... | [
"numpy.arange",
"numpy.sum",
"numpy.log"
] | [((460, 476), 'numpy.sum', 'np.sum', (['cls_loss'], {}), '(cls_loss)\n', (466, 476), True, 'import numpy as np\n'), ((825, 842), 'numpy.sum', 'np.sum', (['bbox_loss'], {}), '(bbox_loss)\n', (831, 842), True, 'import numpy as np\n'), ((429, 440), 'numpy.log', 'np.log', (['cls'], {}), '(cls)\n', (435, 440), True, 'import... |
import numpy as np
from pytest_cases import parametrize_with_cases, case
from snake_learner.direction import Direction
from snake_learner.linalg_util import block_distance, closest_direction, \
project_to_direction
CLOSEST_DIRECTION = "closest_direction"
PROJECT_TO_DIRECTION = "project_to_direction"
@case(tags=... | [
"snake_learner.direction.Direction.RIGHT.to_array",
"snake_learner.linalg_util.block_distance",
"snake_learner.linalg_util.closest_direction",
"snake_learner.direction.Direction.UP.to_array",
"snake_learner.linalg_util.project_to_direction",
"numpy.array",
"pytest_cases.case",
"pytest_cases.parametriz... | [((310, 340), 'pytest_cases.case', 'case', ([], {'tags': '[CLOSEST_DIRECTION]'}), '(tags=[CLOSEST_DIRECTION])\n', (314, 340), False, 'from pytest_cases import parametrize_with_cases, case\n'), ((503, 533), 'pytest_cases.case', 'case', ([], {'tags': '[CLOSEST_DIRECTION]'}), '(tags=[CLOSEST_DIRECTION])\n', (507, 533), Fa... |
import os
import re
import itertools
import cv2
import time
import numpy as np
import torch
from torch.autograd import Variable
from utils.craft_utils import getDetBoxes, adjustResultCoordinates
from data import imgproc
from data.dataset import SynthTextDataSet
import math
import xml.etree.ElementTree as elemTree
#... | [
"data.imgproc.resize_aspect_ratio",
"xml.etree.ElementTree.parse",
"data.imgproc.cvt2HeatmapImg",
"ipdb.set_trace",
"data.imgproc.normalizeMeanVariance",
"os.walk",
"numpy.expand_dims",
"math.sin",
"utils.craft_utils.adjustResultCoordinates",
"cv2.imread",
"numpy.array",
"math.cos",
"itertoo... | [((531, 546), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (539, 546), False, 'import math\n'), ((562, 577), 'math.sin', 'math.sin', (['theta'], {}), '(theta)\n', (570, 577), False, 'import math\n'), ((1181, 1200), 'xml.etree.ElementTree.parse', 'elemTree.parse', (['xml'], {}), '(xml)\n', (1195, 1200), True, '... |
from PIL import Image
import pytesseract
import os
import openpyxl as xl
from pytesseract import Output
from pytesseract import pytesseract as pt
import numpy as np
from matplotlib import pyplot as plt
import cv2
from imutils.object_detection import non_max_suppression
class Scan():
def __init__(self,fol... | [
"numpy.load",
"numpy.abs",
"openpyxl.load_workbook",
"numpy.hsplit",
"numpy.sin",
"numpy.arange",
"cv2.imshow",
"os.chdir",
"numpy.unique",
"cv2.line",
"cv2.selectROI",
"cv2.cvtColor",
"cv2.imwrite",
"cv2.boundingRect",
"cv2.Laplacian",
"numpy.repeat",
"pytesseract.image_to_boxes",
... | [((484, 505), 'os.chdir', 'os.chdir', (['self.folder'], {}), '(self.folder)\n', (492, 505), False, 'import os\n'), ((520, 545), 'PIL.Image.open', 'Image.open', (['self.readfile'], {}), '(self.readfile)\n', (530, 545), False, 'from PIL import Image\n'), ((579, 622), 'pytesseract.image_to_string', 'pytesseract.image_to_s... |
import os
import sys
import numpy as np
import scipy.io as sio
from skimage import io
import time
import math
import skimage
import src.faceutil
from src.faceutil import mesh
from src.faceutil.morphable_model import MorphabelModel
from src.util.matlabutil import NormDirection
from math import sin, cos, asin, acos, atan... | [
"numpy.diagflat",
"numpy.zeros",
"src.faceutil.morphable_model.MorphabelModel",
"math.sin",
"math.cos"
] | [((404, 438), 'src.faceutil.morphable_model.MorphabelModel', 'MorphabelModel', (['"""data/Out/BFM.mat"""'], {}), "('data/Out/BFM.mat')\n", (418, 438), False, 'from src.faceutil.morphable_model import MorphabelModel\n'), ((1060, 1076), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {}), '((4, 4))\n', (1068, 1076), True, 'impor... |
##
# train eeg data of mind commands
# (beta)
#
##
import json
import os
import sys
import time
import pickle
import numpy as np
from mindFunctions import filterDownsampleData
import codecs, json
from scipy.signal import butter, lfilter
from sklearn import svm, preprocessing, metrics
from sklearn.model_selection impo... | [
"pickle.dump",
"json.load",
"sklearn.preprocessing.scale",
"os.getcwd",
"numpy.logspace",
"sklearn.metrics.accuracy_score",
"os.path.basename",
"sklearn.metrics.recall_score",
"sklearn.model_selection.StratifiedShuffleSplit",
"pathlib.Path",
"numpy.array",
"sklearn.metrics.precision_score",
... | [((745, 756), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (754, 756), False, 'import os\n'), ((1302, 1350), 'pathlib.Path', 'Path', (["(traindataFolder + 'training-baseline.json')"], {}), "(traindataFolder + 'training-baseline.json')\n", (1306, 1350), False, 'from pathlib import Path\n'), ((1452, 1475), 'numpy.array', ... |
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
from gui.utils import MessageBox
import numpy as np
class MplCanvas(FigureCanvasQTAgg):
"""
A canvas for matplotlib plots. Contains all plot functionality for Plot Mode
"""
def __init__(self, compo... | [
"matplotlib.figure.Figure",
"numpy.max",
"numpy.min",
"numpy.linspace"
] | [((369, 384), 'matplotlib.figure.Figure', 'Figure', ([], {'dpi': '(100)'}), '(dpi=100)\n', (375, 384), False, 'from matplotlib.figure import Figure\n'), ((21817, 21858), 'numpy.linspace', 'np.linspace', (['V_start', 'V_end', 'V_num_points'], {}), '(V_start, V_end, V_num_points)\n', (21828, 21858), True, 'import numpy a... |
import argparse
import json
from time import time
import os
import shutil
import numpy as np
import torch
from datasets.oxford import get_dataloaders
from datasets.boreas import get_dataloaders_boreas
from datasets.radiate import get_dataloaders_radiate
from networks.under_the_radar import UnderTheRadar
from networks.... | [
"argparse.ArgumentParser",
"utils.vis.draw_masked_radar",
"utils.vis.draw_src_tgt_matches",
"utils.vis.draw_radar",
"torch.set_num_threads",
"numpy.mean",
"datasets.boreas.get_dataloaders_boreas",
"torch.device",
"datasets.radiate.get_dataloaders_radiate",
"torch.no_grad",
"os.path.join",
"shu... | [((739, 764), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (762, 764), False, 'import argparse\n'), ((2589, 2611), 'utils.vis.draw_radar', 'draw_radar', (['batch'], {'i': '(1)'}), '(batch, i=1)\n', (2599, 2611), False, 'from utils.vis import plot_sequences, draw_radar, draw_mask, draw_masked_... |
import logging
import numpy as np
import scipy.sparse
from typing import Union
from .external import closedform_glm_mean, closedform_glm_scale
logger = logging.getLogger("batchglm")
def closedform_norm_glm_mean(
x: Union[np.ndarray, scipy.sparse.csr_matrix],
design_loc: np.ndarray,
constrain... | [
"logging.getLogger",
"numpy.sqrt"
] | [((154, 183), 'logging.getLogger', 'logging.getLogger', (['"""batchglm"""'], {}), "('batchglm')\n", (171, 183), False, 'import logging\n'), ((1961, 1978), 'numpy.sqrt', 'np.sqrt', (['variance'], {}), '(variance)\n', (1968, 1978), True, 'import numpy as np\n')] |
import time
from multiworld.core.image_env import ImageEnv, unormalize_image, normalize_image
from rlkit.core import logger
import cv2
import numpy as np
import os.path as osp
from rlkit.samplers.data_collector.scalor_env import WrappedEnvPathCollector as SCALORWrappedEnvPathCollector
from rlkit.torch.scalor.scalor i... | [
"numpy.load",
"multiworld.register_all_envs",
"multiworld.core.image_env.unormalize_image",
"os.makedirs",
"rlkit.torch.scalor.scalor.SCALOR",
"gym.make",
"cv2.waitKey",
"os.path.exists",
"numpy.zeros",
"multiworld.core.image_env.normalize_image",
"time.time",
"multiworld.core.image_env.ImageE... | [((3941, 3966), 'rlkit.core.logger.get_snapshot_dir', 'logger.get_snapshot_dir', ([], {}), '()\n', (3964, 3966), False, 'from rlkit.core import logger\n'), ((3980, 4003), 'rlkit.torch.scalor.scalor.SCALOR', 'SCALOR', ([], {}), '(**scalor_params)\n', (3986, 4003), False, 'from rlkit.torch.scalor.scalor import SCALOR\n')... |
import perceptron as pc
import numpy as np
def mnist_load(file, samples):
raw_data = np.array(np.genfromtxt(file, delimiter=',', max_rows=samples))
labels = raw_data[:,0]
data = np.delete(raw_data, 0, 1)/255.0
return (data, labels)
def main():
print("loading data...")
samples = 10000
batch... | [
"numpy.delete",
"numpy.genfromtxt",
"perceptron.network"
] | [((666, 726), 'perceptron.network', 'pc.network', (['structure', 'activation_functions', 'train', 'validate'], {}), '(structure, activation_functions, train, validate)\n', (676, 726), True, 'import perceptron as pc\n'), ((99, 151), 'numpy.genfromtxt', 'np.genfromtxt', (['file'], {'delimiter': '""","""', 'max_rows': 'sa... |
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
from gym import spaces, Env
class NXColoringEnv(Env):
def __init__(self, generator=nx.barabasi_albert_graph, **kwargs):
'''
generator — netwokrx graph generator,
kwargs — generator named arguments
'''
self.G = generator(**k... | [
"numpy.full",
"numpy.isin",
"numpy.any",
"networkx.spring_layout",
"networkx.draw",
"gym.spaces.Box",
"numpy.unique"
] | [((342, 383), 'networkx.spring_layout', 'nx.spring_layout', (['self.G'], {'iterations': '(1000)'}), '(self.G, iterations=1000)\n', (358, 383), True, 'import networkx as nx\n'), ((539, 609), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(0)', 'high': '(self.n - 1)', 'shape': '(self.n, 2)', 'dtype': 'np.uint32'}), '(low=... |
import numpy as np
# Note: please don't import any new package. You should solve this problem using only the package(s) above.
#-------------------------------------------------------------------------
'''
Problem 1: Multi-Armed Bandit Problem (15 points)
In this problem, you will implement the epsilon-greedy ... | [
"numpy.random.randint",
"numpy.random.random"
] | [((5139, 5162), 'numpy.random.randint', 'np.random.randint', (['(0)', 'c'], {}), '(0, c)\n', (5156, 5162), True, 'import numpy as np\n'), ((9556, 9574), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (9572, 9574), True, 'import numpy as np\n')] |
import scipy.io
import numpy as np
import os
import random
import json
import pdb
def check_image_voxel_match(cls):
root = os.path.abspath('.')
out_dir = os.path.join(root, '../output', cls)
# out_dir = '/Users/heqian/Research/projects/primitive-based_3d/data/all_classes/chair'
voxel_txt_dir = os.path... | [
"os.path.abspath",
"os.makedirs",
"os.path.exists",
"random.random",
"numpy.array",
"os.path.join"
] | [((129, 149), 'os.path.abspath', 'os.path.abspath', (['"""."""'], {}), "('.')\n", (144, 149), False, 'import os\n'), ((164, 200), 'os.path.join', 'os.path.join', (['root', '"""../output"""', 'cls'], {}), "(root, '../output', cls)\n", (176, 200), False, 'import os\n'), ((313, 346), 'os.path.join', 'os.path.join', (['out... |
#Exercícios Numpy-15
#*******************
import numpy as np
arr=np.ones((10,10))
arr[1:-1,1:-1]=0
print(arr)
print()
arr_zero=np.zeros((8,8))
arr_zero=np.pad(arr_zero,pad_width=1,mode='constant',constant_values=1)
print(arr_zero) | [
"numpy.pad",
"numpy.zeros",
"numpy.ones"
] | [((67, 84), 'numpy.ones', 'np.ones', (['(10, 10)'], {}), '((10, 10))\n', (74, 84), True, 'import numpy as np\n'), ((132, 148), 'numpy.zeros', 'np.zeros', (['(8, 8)'], {}), '((8, 8))\n', (140, 148), True, 'import numpy as np\n'), ((158, 223), 'numpy.pad', 'np.pad', (['arr_zero'], {'pad_width': '(1)', 'mode': '"""constan... |
import numpy as np
class AccelerationSensor:
def __init__(self, measurement_covariance):
self.R_meas = measurement_covariance
def getMeasurements(self, true_accel):
return np.random.multivariate_normal(true_accel, self.R_meas)
| [
"numpy.random.multivariate_normal"
] | [((192, 246), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['true_accel', 'self.R_meas'], {}), '(true_accel, self.R_meas)\n', (221, 246), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# coding: utf-8
# # Loan Classification Project
# In[1]:
# Libraries we need
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.discri... | [
"sklearn.model_selection.GridSearchCV",
"seaborn.heatmap",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"shap.plots.heatmap",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.metrics.classification_report",
"matplotlib.pyplot.figure",
"numpy.arange",
"sklearn.tree.plot_tree",
"p... | [((919, 945), 'pandas.read_csv', 'pd.read_csv', (['"""Dataset.csv"""'], {}), "('Dataset.csv')\n", (930, 945), True, 'import pandas as pd\n'), ((1153, 1180), 'matplotlib.pyplot.hist', 'plt.hist', (["df['BAD']"], {'bins': '(3)'}), "(df['BAD'], bins=3)\n", (1161, 1180), True, 'import matplotlib.pyplot as plt\n'), ((1181, ... |
import datetime
from floodsystem.datafetcher import fetch_measure_levels
from floodsystem.stationdata import build_station_list
from floodsystem.plot import plot_water_levels, plot_water_level_with_fit
stations = build_station_list()
import numpy as np
def test_polt_water_level_with_fit():
x = np.linspace(1, 100... | [
"floodsystem.stationdata.build_station_list",
"numpy.poly1d",
"numpy.linspace",
"numpy.polyfit"
] | [((214, 234), 'floodsystem.stationdata.build_station_list', 'build_station_list', ([], {}), '()\n', (232, 234), False, 'from floodsystem.stationdata import build_station_list\n'), ((302, 330), 'numpy.linspace', 'np.linspace', (['(1)', '(1000)', '(100000)'], {}), '(1, 1000, 100000)\n', (313, 330), True, 'import numpy as... |
from CSIKit.csi import CSIFrame
import ast
import numpy as np
class ESP32CSIFrame(CSIFrame):
# https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_pkt_rx_ctrl_t
__slots__ = ["type", "role", "mac", "rssi", "rate", "sig_mode", "mcs", "bandwidth", "smoot... | [
"ast.literal_eval",
"numpy.array"
] | [((1808, 1838), 'ast.literal_eval', 'ast.literal_eval', (['array_string'], {}), '(array_string)\n', (1824, 1838), False, 'import ast\n'), ((2125, 2155), 'numpy.array', 'np.array', (['array_string_asarray'], {}), '(array_string_asarray)\n', (2133, 2155), True, 'import numpy as np\n')] |
#!/usr/bin/env python
debug = True # enable trace
def trace(x):
global debug
if debug: print(x)
trace("loading...")
from itertools import combinations, combinations_with_replacement
from glob import glob
from math import *
import operator
from os.path import basename
import matplotlib.pyplot as plt
import numpy as... | [
"pandas.DataFrame",
"numpy.abs",
"numpy.arctan2",
"datetime.datetime.today",
"os.path.basename",
"pandas.read_csv",
"numpy.sin",
"numpy.cos",
"glob.glob",
"numpy.sqrt"
] | [((1147, 1161), 'numpy.abs', 'np.abs', (['(fX - Y)'], {}), '(fX - Y)\n', (1153, 1161), True, 'import numpy as np\n'), ((1475, 1520), 'pandas.read_csv', 'pd.read_csv', (['path'], {'sep': '""" """', 'names': 'sample_cols'}), "(path, sep=' ', names=sample_cols)\n", (1486, 1520), True, 'import pandas as pd\n'), ((2149, 218... |
import torch.nn as nn
import torch
import numpy as np
import cv2 as cv
def calculate_EPR(model): #TODO:尝试通过加载预训练权重计算有效感受野
for module in model.modules():
try:
nn.init.constant_(module.weight, 0.05)
nn.init.zeros_(module.bias)
nn.init.zeros_(module.running_mean)
nn.init.ones_(module.running_var)
except E... | [
"torch.ones",
"torch.zeros_like",
"cv2.waitKey",
"numpy.expand_dims",
"torch.nn.init.zeros_",
"numpy.max",
"numpy.where",
"torch.nn.init.constant_",
"torch.nn.init.ones_"
] | [((408, 454), 'torch.ones', 'torch.ones', (['(1)', '(3)', '(640)', '(640)'], {'requires_grad': '(True)'}), '(1, 3, 640, 640, requires_grad=True)\n', (418, 454), False, 'import torch\n'), ((1017, 1030), 'cv2.waitKey', 'cv.waitKey', (['(0)'], {}), '(0)\n', (1027, 1030), True, 'import cv2 as cv\n'), ((1837, 1870), 'numpy.... |
import matplotlib.pyplot as plt
import numpy as np
import numpy.polynomial.polynomial as nppol
class Metawalk:
def __init__(self,
time_intervals=None,
nodes=None,
):
"""
A basic constructor for a ``Metwalks`` object
:param times : A list o... | [
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.plot",
"numpy.polynomial.polynomial.Polynomial",
"matplotlib.pyplot.vlines",
"numpy.around",
"numpy.math.factorial",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.hlines",
"matplotlib.pyplot.subplots"
] | [((4201, 4222), 'numpy.polynomial.polynomial.Polynomial', 'nppol.Polynomial', (['res'], {}), '(res)\n', (4217, 4222), True, 'import numpy.polynomial.polynomial as nppol\n'), ((7457, 7567), 'matplotlib.pyplot.plot', 'plt.plot', (['[self.time_intervals[0]]', '[id_source]'], {'color': 'color', 'marker': '"""o"""', 'alpha'... |
from setuptools import setup, find_packages
from Cython.Distutils.extension import Extension
from Cython.Build import cythonize, build_ext
import numpy
import os
from glob import glob
"""
ext_modules = [Extension("traj_dist.cydist.basic_geographical", ["traj_dist/cydist/basic_geographical.pyx"]),
Extens... | [
"numpy.get_include",
"setuptools.find_packages",
"glob.glob"
] | [((1294, 1324), 'glob.glob', 'glob', (['"""traj_dist/cydist/*.pyx"""'], {}), "('traj_dist/cydist/*.pyx')\n", (1298, 1324), False, 'from glob import glob\n'), ((1950, 1965), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1963, 1965), False, 'from setuptools import setup, find_packages\n'), ((1700, 1719)... |
import numpy as np
from numba import guvectorize
from pygama.dsp.errors import DSPFatal
@guvectorize(["void(float32[:], float32, float32, float32, float32[:])",
"void(float64[:], float64, float64, float64, float64[:])"],
"(n),(),(),()->()", nopython=True, cache=True)
def time_point_thresh(w_... | [
"numpy.floor",
"pygama.dsp.errors.DSPFatal",
"numba.guvectorize",
"numpy.isnan"
] | [((90, 276), 'numba.guvectorize', 'guvectorize', (["['void(float32[:], float32, float32, float32, float32[:])',\n 'void(float64[:], float64, float64, float64, float64[:])']", '"""(n),(),(),()->()"""'], {'nopython': '(True)', 'cache': '(True)'}), "(['void(float32[:], float32, float32, float32, float32[:])',\n 'voi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Redundant misc. functions to be eventually removed from AC_tools.
"""
import os
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
from pandas import DataFrame
# time
import time
import datetime as datetime
# math
from m... | [
"pandas.DataFrame",
"numpy.linspace"
] | [((4158, 4204), 'pandas.DataFrame', 'DataFrame', (['data'], {'index': 'dates', 'columns': "['data']"}), "(data, index=dates, columns=['data'])\n", (4167, 4204), False, 'from pandas import DataFrame\n'), ((2254, 2314), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'extra_points_point_on_edge'], {'endpoint': '(True)'}... |
import numpy as np
import magpie
# check cartesian
def test_get_xedges():
xedges = magpie.grids.get_xedges(1., 2)
xedges = np.round(xedges, decimals=2)
assert len(xedges) == 3, "Length of xedges is incorrect."
assert xedges[-1] - xedges[0] == 1., "xedges range is incorrect."
xedges = magpie.grids... | [
"magpie.grids.polargrid",
"numpy.sum",
"magpie.grids.grid1d",
"magpie.grids.grid3d",
"magpie.grids.xmid2edges",
"magpie.grids.get_xedges",
"magpie.grids.polarEA_grid",
"numpy.shape",
"magpie.grids.polarEA_npix",
"magpie.grids.polarEA_area",
"magpie.grids.xedges2mid",
"numpy.round",
"magpie.g... | [((90, 121), 'magpie.grids.get_xedges', 'magpie.grids.get_xedges', (['(1.0)', '(2)'], {}), '(1.0, 2)\n', (113, 121), False, 'import magpie\n'), ((134, 162), 'numpy.round', 'np.round', (['xedges'], {'decimals': '(2)'}), '(xedges, decimals=2)\n', (142, 162), True, 'import numpy as np\n'), ((308, 350), 'magpie.grids.get_x... |
import sys, os, random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing i... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.figaspect",
"numpy.load",
"sklearn.preprocessing.StandardScaler",
"random.shuffle",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.figure",
"numpy.mean",
"sklearn.neural_network.MLPClassifier",
"sklearn.svm.SVC",
"numpy.interp",
"os.path.join",
... | [((1137, 1191), 'os.path.join', 'os.path.join', (['dirpath', '"""../datasets/breast-cancer.npz"""'], {}), "(dirpath, '../datasets/breast-cancer.npz')\n", (1149, 1191), False, 'import sys, os, random\n'), ((1202, 1251), 'os.path.join', 'os.path.join', (['dirpath', '"""../datasets/diabetes.npz"""'], {}), "(dirpath, '../d... |
import gzip
import sys
import argparse
import re
import logging
import numpy as np
import pandas as p
from itertools import product, tee
from collections import Counter, OrderedDict
from Bio import SeqIO
def generate_feature_mapping(kmer_len):
BASE_COMPLEMENT = {"A":"T","T":"A","G":"C","C":"G"}
kmer_hash = ... | [
"gzip.open",
"argparse.ArgumentParser",
"Bio.SeqIO.parse",
"numpy.zeros",
"numpy.array",
"itertools.product",
"itertools.tee"
] | [((355, 387), 'itertools.product', 'product', (['"""ATGC"""'], {'repeat': 'kmer_len'}), "('ATGC', repeat=kmer_len)\n", (362, 387), False, 'from itertools import product, tee\n'), ((664, 675), 'itertools.tee', 'tee', (['seq', 'n'], {}), '(seq, n)\n', (667, 675), False, 'from itertools import product, tee\n'), ((971, 100... |
# -*- coding: utf-8 -*-
'''
<NAME>
1. a. Frequentist confidence intervals do not respect the physical limitations imposed on a system, ie non-negativity of a mass.
b. Typically, that the probability to be found outside the interval on both sides of the distribution is 16% (or (100-CL)/2 %).
Of... | [
"matplotlib.pyplot.title",
"numpy.sum",
"matplotlib.pyplot.clf",
"numpy.polyfit",
"matplotlib.pyplot.bar",
"numpy.histogram",
"numpy.exp",
"numpy.random.normal",
"numpy.linspace",
"matplotlib.pyplot.errorbar",
"math.isnan",
"scipy.stats.chi2",
"matplotlib.pyplot.ylabel",
"numpy.log",
"ma... | [((8154, 8178), 'numpy.linspace', 'np.linspace', (['(0)', '(5)', '(10000)'], {}), '(0, 5, 10000)\n', (8165, 8178), True, 'import numpy as np\n'), ((8204, 8236), 'numpy.exp', 'np.exp', (['(-theExponential.lookup_x)'], {}), '(-theExponential.lookup_x)\n', (8210, 8236), True, 'import numpy as np\n'), ((8448, 8457), 'matpl... |
# Copyright 2019 The DMLab2D 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 applicable law or agreed to in... | [
"dmlab2d.runfiles_helper.find",
"absl.testing.absltest.main",
"numpy.dtype",
"numpy.testing.assert_array_equal"
] | [((8160, 8175), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (8173, 8175), False, 'from absl.testing import absltest\n'), ((3413, 3470), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['observations[0]', '[1, 2, 3]'], {}), '(observations[0], [1, 2, 3])\n', (3442, 3470), True, ... |
import numpy as np
import random
import numbers
import cv2
from PIL import Image
import wpcv
from wpcv.utils.ops import pil_ops, polygon_ops
from wpcv.utils.data_aug.base import Compose, Zip
from wpcv.utils.data_aug import img_aug
class ToPILImage(object):
def __init__(self):
self.to = img_aug.ToPILImage(... | [
"wpcv.utils.ops.pil_ops.vflip",
"wpcv.utils.ops.polygon_ops.get_translate_range",
"wpcv.utils.ops.pil_ops.resize_keep_ratio",
"wpcv.utils.ops.polygon_ops.scale",
"random.randint",
"wpcv.utils.ops.pil_ops.scale",
"wpcv.utils.ops.polygon_ops.translate",
"wpcv.utils.data_aug.img_aug.ToPILImage",
"wpcv.... | [((301, 321), 'wpcv.utils.data_aug.img_aug.ToPILImage', 'img_aug.ToPILImage', ([], {}), '()\n', (319, 321), False, 'from wpcv.utils.data_aug import img_aug\n'), ((1855, 1891), 'wpcv.utils.ops.pil_ops.scale', 'pil_ops.scale', (['img', '(scaleX, scaleY)'], {}), '(img, (scaleX, scaleY))\n', (1868, 1891), False, 'from wpcv... |
#
# INF 552 Homework 3
# Part 2: Fast Map
# Group Members: <NAME> (zhan198), <NAME> (minyihua), <NAME> (jeffyjac)
# Date: 2/27/2018
# Programming Language: Python 3.6
#
import numpy as np
import matplotlib.pyplot as plt
DIMENSION = 2
DATA_SIZE = 10
# WORDS = ["acting", "activist", "compute", "coward","forward","in... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.scatter",
"numpy.power",
"numpy.zeros",
"numpy.amax",
"numpy.where",
"matplotlib.pyplot.subplots"
] | [((470, 508), 'numpy.zeros', 'np.zeros', ([], {'shape': '(DATA_SIZE, DATA_SIZE)'}), '(shape=(DATA_SIZE, DATA_SIZE))\n', (478, 508), True, 'import numpy as np\n'), ((516, 554), 'numpy.zeros', 'np.zeros', ([], {'shape': '(DATA_SIZE, DIMENSION)'}), '(shape=(DATA_SIZE, DIMENSION))\n', (524, 554), True, 'import numpy as np\... |
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import queue
from insomnia.utils import empty_torch_queue
from insomnia.explores.gaussian_noise import GaussianActionNoise
from insomnia.numeric_models import d4pg
from insomnia.numeric_models.misc import l2_projection
cla... | [
"torch.from_numpy",
"numpy.abs",
"torch.nn.BCELoss",
"insomnia.utils.empty_torch_queue",
"insomnia.numeric_models.d4pg.CriticNetwork",
"numpy.asarray",
"numpy.zeros",
"time.time",
"torch.cuda.is_available",
"torch.sum",
"torch.tensor",
"insomnia.numeric_models.misc.l2_projection._l2_project"
] | [((1153, 1270), 'insomnia.numeric_models.d4pg.CriticNetwork', 'd4pg.CriticNetwork', (['beta', 'input_dims', 'fc1_dims', 'fc2_dims', 'n_actions', 'name', 'self.v_min', 'self.v_max', 'self.num_atoms'], {}), '(beta, input_dims, fc1_dims, fc2_dims, n_actions, name,\n self.v_min, self.v_max, self.num_atoms)\n', (1171, 12... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.