code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import argparse
import logging
import os
import copy
from collections import defaultdict
from typing import List
import numpy as np
import torch
from sklearn import metrics
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data.dataloader import DataLoader
from training.models import RNNClassifier
from opera... | [
"torch.manual_seed",
"torch.ones",
"json.JSONEncoder.default",
"torch.sigmoid",
"os.path.join",
"torch.nn.utils.rnn.pad_sequence",
"sklearn.metrics.roc_auc_score",
"sklearn.metrics.recall_score",
"torch.no_grad",
"torch.zeros",
"collections.defaultdict",
"numpy.random.seed",
"copy.deepcopy",... | [((788, 1293), 'training.models.RNNClassifier', 'RNNClassifier', ([], {'arch': 'args.arch', 'static_input_size': 'args.static_input_size', 'dynamic_input_size': 'args.dynamic_input_size', 'static_embedding_size': 'args.static_embedding_size', 'hidden_size': 'args.hidden_size', 'dropout': 'args.dropout', 'rnn_layers': '... |
import os
import torch
import numpy as np
import json
import dgl
import constants
def read_partitions_file(part_file):
"""
Utility method to read metis partitions, which is the output of
pm_dglpart2
Parameters:
-----------
part_file : string
file name which is the output of metis part... | [
"os.makedirs",
"dgl.data.utils.load_tensors",
"os.path.join",
"dgl.save_graphs",
"numpy.array",
"dgl.data.utils.save_tensors",
"numpy.concatenate",
"json.load",
"numpy.loadtxt",
"json.dump"
] | [((692, 744), 'numpy.loadtxt', 'np.loadtxt', (['part_file'], {'delimiter': '""" """', 'dtype': 'np.int64'}), "(part_file, delimiter=' ', dtype=np.int64)\n", (702, 744), True, 'import numpy as np\n'), ((6200, 6252), 'numpy.loadtxt', 'np.loadtxt', (['nodes_file'], {'delimiter': '""" """', 'dtype': '"""int64"""'}), "(node... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 <NAME> <<EMAIL>>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline in source files... | [
"numpy.mean",
"wavestate.utilities.mpl.mplfigB",
"numpy.argsort",
"numpy.array",
"numpy.argmin"
] | [((755, 768), 'numpy.array', 'np.array', (['arg'], {}), '(arg)\n', (763, 768), True, 'import numpy as np\n'), ((1066, 1079), 'numpy.array', 'np.array', (['arg'], {}), '(arg)\n', (1074, 1079), True, 'import numpy as np\n'), ((1920, 1939), 'numpy.argmin', 'np.argmin', (['self.R_m'], {}), '(self.R_m)\n', (1929, 1939), Tru... |
import scipy.misc as misc
import torch
import copy
import torchvision.models as models
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
# FCN Net model class for semantic segmentation
##############################################This is a standart FCN with the lat layer split into prediction o... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.ModuleList",
"torchvision.models.resnet101",
"torch.nn.Conv2d",
"numpy.array",
"torch.nn.functional.interpolate",
"torch.nn.functional.softmax",
"torch.cat"
] | [((1029, 1062), 'torchvision.models.resnet101', 'models.resnet101', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (1045, 1062), True, 'import torchvision.models as models\n'), ((1289, 1304), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (1302, 1304), True, 'import torch.nn as nn\n'), ((2094, 2109),... |
import argparse
import numpy as np
from util import load_data, separate_data
from grakel import GraphKernel
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
def convert(graphs):
X = []
y = []
for graph in graphs:
edge = {i: neighbors for i, neighbors in enumerate(graph.neighb... | [
"util.load_data",
"argparse.ArgumentParser",
"util.separate_data",
"numpy.array",
"grakel.GraphKernel",
"numpy.random.seed",
"sklearn.metrics.accuracy_score",
"sklearn.svm.SVC"
] | [((535, 591), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""WL subtree kernel"""'}), "(description='WL subtree kernel')\n", (558, 591), False, 'import argparse\n'), ((1521, 1538), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1535, 1538), True, 'import numpy as np\n'),... |
import logging
from gensim.models import word2vec
import numpy as np
from scipy import linalg
'''
计算案件之间的相似度
首先对句子分词,然后获取每个单词对应的词向量
然后将所有单词对应的词向量相加求平均值,作为句子的向量
最后,计算句子的向量的夹角余弦值,作为它们之间的相似度
'''
logging.basicConfig(
format='%(asctime)s : %(levelname)s : %(message)s',
level=logging.I... | [
"logging.basicConfig",
"gensim.models.word2vec.Word2Vec",
"numpy.argsort",
"numpy.dot",
"numpy.zeros",
"gensim.models.word2vec.LineSentence",
"scipy.linalg.norm"
] | [((224, 319), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.INFO)\n", (243, 319), False, 'import logging\n'), ((361, 392), 'gensim.models.word2vec.LineSe... |
import functools
import warnings
import numpy as np
import numpy.linalg as npla
import sys, os
import time
from PES.compute_covariance import *
from PES.initial_sample import *
from PES.hyper_samples import *
from PES.utilities import *
from PES.sample_minimum import *
from PES.PES import *
from PES.compute... | [
"numpy.eye",
"numpy.asarray",
"numpy.array",
"numpy.zeros",
"functools.partial",
"numpy.random.seed",
"numpy.vstack",
"numpy.argmin",
"time.time",
"warnings.filterwarnings"
] | [((2329, 2362), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (2352, 2362), False, 'import warnings\n'), ((2431, 2451), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2445, 2451), True, 'import numpy as np\n'), ((3120, 3153), 'warnings.filterwarnings'... |
import pandas as pd
from hydroDL.data import usgs, gageII, gridMET, ntn, GLASS, transform, dbBasin
import numpy as np
import matplotlib.pyplot as plt
from hydroDL.post import axplot, figplot
from hydroDL import kPath, utils
import json
import os
import importlib
from hydroDL.master import basinFull
from hydroDL.app.wa... | [
"hydroDL.data.dbBasin.DataFrameBasin",
"pandas.read_csv",
"os.path.join",
"numpy.nanmean",
"hydroDL.master.basinFull.nameFolder",
"numpy.isnan",
"numpy.nansum",
"numpy.load",
"matplotlib.pyplot.subplots"
] | [((350, 380), 'hydroDL.data.dbBasin.DataFrameBasin', 'dbBasin.DataFrameBasin', (['"""G200"""'], {}), "('G200')\n", (372, 380), False, 'from hydroDL.data import usgs, gageII, gridMET, ntn, GLASS, transform, dbBasin\n'), ((1029, 1084), 'os.path.join', 'os.path.join', (['kPath.dirWQ', '"""modelStat"""', '"""WRTDS-dbBasin"... |
from scipy import signal
import matplotlib.pyplot as plt
import numpy as np
import pyqtgraph
import PyQt5.QtGui as qtg
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2Q... | [
"matplotlib.backends.backend_qt5agg.NavigationToolbar2QT",
"numpy.sqrt",
"matplotlib.pyplot.ylabel",
"scipy.signal.spectrogram",
"matplotlib.pyplot.pcolormesh",
"numpy.sin",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"pyqtgraph.ImageItem",
"numpy.max",
"numpy.exp",
"PyQt5.QtGui.QVBoxLayout",
... | [((344, 368), 'matplotlib.use', 'matplotlib.use', (['"""Qt5Agg"""'], {}), "('Qt5Agg')\n", (358, 368), False, 'import matplotlib\n'), ((1485, 1502), 'numpy.exp', 'np.exp', (['(-time / 5)'], {}), '(-time / 5)\n', (1491, 1502), True, 'import numpy as np\n'), ((1533, 1558), 'scipy.signal.spectrogram', 'signal.spectrogram',... |
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this open-source project.
""" Define the functions to load data. """
import os
import json
import argparse
import numpy as np
def load_data(data_dir, interval=100, data_type='2D'):
music_data, d... | [
"numpy.tile",
"os.listdir",
"os.path.join",
"argparse.ArgumentTypeError",
"numpy.array"
] | [((360, 380), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (370, 380), False, 'import os\n'), ((465, 494), 'os.path.join', 'os.path.join', (['data_dir', 'fname'], {}), '(data_dir, fname)\n', (477, 494), False, 'import os\n'), ((1518, 1538), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\... |
# pylint: disable=no-self-use,invalid-name
import numpy
from allennlp.common.testing.test_case import AllenNlpTestCase
from allennlp.data.fields import ArrayField, ListField
class TestArrayField(AllenNlpTestCase):
def test_get_padding_lengths_correctly_returns_ordered_shape(self):
shape = [3, 4, 5, 6]
... | [
"numpy.ones",
"allennlp.data.fields.ArrayField",
"numpy.array",
"numpy.zeros",
"allennlp.data.fields.ListField",
"numpy.testing.assert_array_equal"
] | [((335, 353), 'numpy.zeros', 'numpy.zeros', (['shape'], {}), '(shape)\n', (346, 353), False, 'import numpy\n'), ((376, 393), 'allennlp.data.fields.ArrayField', 'ArrayField', (['array'], {}), '(array)\n', (386, 393), False, 'from allennlp.data.fields import ArrayField, ListField\n'), ((653, 670), 'numpy.ones', 'numpy.on... |
from src import geometry_profiles as gp
import typing
import numpy as np
class LightProfile(gp.GeometryProfile):
def __init__(
self,
centre: typing.Tuple[float, float] = (0.0, 0.0),
axis_ratio: float = 1.0,
angle: float = 0.0,
normalization: float = 0.1,
... | [
"numpy.exp"
] | [((2831, 2918), 'numpy.exp', 'np.exp', (['(-7.66924 * ((grid_elliptical_radii / self.radius) ** (1.0 / 7.66924) - 1.0))'], {}), '(-7.66924 * ((grid_elliptical_radii / self.radius) ** (1.0 / 7.66924) -\n 1.0))\n', (2837, 2918), True, 'import numpy as np\n'), ((4536, 4623), 'numpy.exp', 'np.exp', (['(-1.67838 * ((grid... |
from abc import ABC, abstractmethod
from copy import deepcopy
import numpy as np
import tensorflow as tf
# source: http://geomalgorithms.com/a06-_intersect-2.html
# source: https://www.erikrotteveel.com/python/three-dimensional-ray-tracing-in-python/
gpu_phy_devices = tf.config.list_physical_devices('GPU')
try:
f... | [
"tensorflow.meshgrid",
"tensorflow.shape",
"tensorflow.reduce_sum",
"tensorflow.logical_not",
"tensorflow.linalg.cross",
"tensorflow.config.list_physical_devices",
"tensorflow.math.atan2",
"copy.deepcopy",
"tensorflow.ones_like",
"tensorflow.cast",
"tensorflow.tensordot",
"tensorflow.not_equal... | [((271, 309), 'tensorflow.config.list_physical_devices', 'tf.config.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (302, 309), True, 'import tensorflow as tf\n'), ((523, 558), 'tensorflow.constant', 'tf.constant', (['np.pi'], {'dtype': 'precision'}), '(np.pi, dtype=precision)\n', (534, 558), True, 'import te... |
import numpy as np
import xlwings as xw
"""
To activate a function in the excel file, press "Import Functions"
in the xlwings tab
"""
@xw.func
def get_crack_width(c_nom_tension, c_nom_compression, c_dur, moment, \
is_shear_present, shear_bar_diameter, \
rf_diameter_first_layer = 0, rf_spacing_first_layer = 0,... | [
"numpy.log",
"numpy.sqrt"
] | [((8361, 8419), 'numpy.sqrt', 'np.sqrt', (['((A_s * E_s) ** 2 + 2 * b * A_s * E_s * E_ceff * d)'], {}), '((A_s * E_s) ** 2 + 2 * b * A_s * E_s * E_ceff * d)\n', (8368, 8419), True, 'import numpy as np\n'), ((12865, 12891), 'numpy.log', 'np.log', (['(1 + self.f_cm / 10)'], {}), '(1 + self.f_cm / 10)\n', (12871, 12891), ... |
import torch
import torch.nn as nn
import numpy as np
import FrEIA.framework as Ff
from .. import InvertibleArchitecture
__all__ = ['beta_0', 'beta_1', 'beta_2', 'beta_4', 'beta_8', 'beta_16', 'beta_32', 'beta_inf']
model_base_url = 'https://heibox.uni-heidelberg.de/seafhttp/files/6f91503d-7459-4080-b10a-e979f8b3d2... | [
"torch.optim.SGD",
"FrEIA.framework.ReversibleGraphNet",
"numpy.sqrt",
"torch.log_softmax",
"torch.mean",
"FrEIA.framework.OutputNode",
"torch.load",
"torch.eye",
"FrEIA.framework.InputNode",
"torch.argmax",
"torch.hub.load_state_dict_from_url",
"torch.mm",
"torch.sum",
"torch.logsumexp",
... | [((2890, 2976), 'torch.optim.SGD', 'torch.optim.SGD', (['self.optimizer_params', 'self.lr'], {'momentum': '(0.9)', 'weight_decay': '(1e-05)'}), '(self.optimizer_params, self.lr, momentum=0.9, weight_decay=\n 1e-05)\n', (2905, 2976), False, 'import torch\n'), ((3735, 3791), 'FrEIA.framework.ReversibleGraphNet', 'Ff.R... |
import numpy as np
from skimage.morphology import label
from scipy.sparse import csr_matrix
from scipy.spatial import cKDTree as KDTree
import pandas as pd
import itertools
from tqdm import tqdm
def compute_M(data):
cols = np.arange(data.size)
return csr_matrix((cols, (data.ravel(), cols)),
... | [
"pandas.Series",
"numpy.mean",
"numpy.multiply",
"numpy.unique",
"numpy.amin",
"numpy.array",
"numpy.zeros",
"numpy.unravel_index",
"numpy.vstack",
"numpy.nanmax",
"pandas.DataFrame",
"numpy.all",
"numpy.amax",
"numpy.arange"
] | [((237, 257), 'numpy.arange', 'np.arange', (['data.size'], {}), '(data.size)\n', (246, 257), True, 'import numpy as np\n'), ((650, 728), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['cycle', 'ch', 'x', 'y', 'z', 'Intensities_window_5x5']"}), "(columns=['cycle', 'ch', 'x', 'y', 'z', 'Intensities_window_5x5'])\... |
from unittest import TestCase
import numpy as np
from pyecsca.sca import Trace, welch_ttest, student_ttest, ks_test
class TTestTests(TestCase):
def setUp(self):
self.a = Trace(np.array([20, 80], dtype=np.dtype("i1")))
self.b = Trace(np.array([30, 42], dtype=np.dtype("i1")))
self.c = Tra... | [
"pyecsca.sca.welch_ttest",
"pyecsca.sca.ks_test",
"pyecsca.sca.student_ttest",
"numpy.array",
"numpy.dtype"
] | [((829, 880), 'pyecsca.sca.welch_ttest', 'welch_ttest', (['[a, b]', '[b, c]'], {'dof': '(True)', 'p_value': '(True)'}), '([a, b], [b, c], dof=True, p_value=True)\n', (840, 880), False, 'from pyecsca.sca import Trace, welch_ttest, student_ttest, ks_test\n'), ((492, 539), 'pyecsca.sca.welch_ttest', 'welch_ttest', (['[sel... |
#!/usr/bin/env python
# coding: utf-8
# # Data Analysis
# This module will explore the stage of data analysis using the lens of a bias-aware methodology. We will make use of Jupyter notebooks to aid our exploratory data analysis, in order to understand how social, cognitive, and statistical biases interact and affect ... | [
"numpy.array",
"numpy.linspace",
"numpy.random.seed",
"matplotlib.pyplot.ion",
"numpy.logspace",
"numpy.random.randn",
"matplotlib.pyplot.subplots"
] | [((1216, 1225), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (1223, 1225), True, 'import matplotlib.pyplot as plt\n'), ((1281, 1305), 'numpy.random.seed', 'np.random.seed', (['(19680801)'], {}), '(19680801)\n', (1295, 1305), True, 'import numpy as np\n'), ((1728, 1757), 'matplotlib.pyplot.subplots', 'plt.subpl... |
from classes import Stock, format
import numpy as np
import os
from datetime import date, timedelta
from dateutil.parser import parse
import sys
# datapath = 'formated/SZ#002673.json'
datapath = 'formated/SH#600007.json'
# datapath = 'formated/SZ#000553.json'
# amount = float(10000)
stock = Stock()
def getFiles(dir... | [
"dateutil.parser.parse",
"os.walk",
"os.path.join",
"datetime.timedelta",
"datetime.date",
"sys.stdout.flush",
"classes.Stock",
"numpy.arange",
"sys.stdout.write"
] | [((294, 301), 'classes.Stock', 'Stock', ([], {}), '()\n', (299, 301), False, 'from classes import Stock, format\n'), ((384, 400), 'os.walk', 'os.walk', (['dirname'], {}), '(dirname)\n', (391, 400), False, 'import os\n'), ((837, 853), 'datetime.date', 'date', (['(2016)', '(1)', '(1)'], {}), '(2016, 1, 1)\n', (841, 853),... |
"""
.. module:: Residue
:synopsis: This module implements the Residue class.
"""
# Third-party modules
import numpy as np
# Local modules
from src.atom import Atom
class Residue:
"""
.. class:: Residue
This class groups informations about a residue.
Attributes:
name (str): Name of the... | [
"numpy.einsum",
"src.atom.Atom"
] | [((495, 505), 'src.atom.Atom', 'Atom', (['"""CA"""'], {}), "('CA')\n", (499, 505), False, 'from src.atom import Atom\n'), ((529, 539), 'src.atom.Atom', 'Atom', (['"""CB"""'], {}), "('CB')\n", (533, 539), False, 'from src.atom import Atom\n'), ((562, 571), 'src.atom.Atom', 'Atom', (['"""C"""'], {}), "('C')\n", (566, 571... |
import numpy
import ipdb
import util
import dtw
def score(model, orig_mat, list_of_random_startend):
list_of_gen_mat = []
for idx, tup in enumerate(list_of_random_startend):
now_start = tup[0].copy()
now_end = tup[1].copy()
list_of_gen_mat.append(
util.generalize_via_dmp(no... | [
"util.generalize_via_dmp",
"numpy.linalg.norm"
] | [((294, 344), 'util.generalize_via_dmp', 'util.generalize_via_dmp', (['now_start', 'now_end', 'model'], {}), '(now_start, now_end, model)\n', (317, 344), False, 'import util\n'), ((515, 546), 'numpy.linalg.norm', 'numpy.linalg.norm', (['(x - y)'], {'ord': '(2)'}), '(x - y, ord=2)\n', (532, 546), False, 'import numpy\n'... |
#pragma pylint: disable=fixme,line-too-long,missing-docstring,invalid-name,no-member,dangerous-default-value,protected-access,unused-import,assignment-from-no-return,redefined-outer-name
import sys
import math
from ctypes import sizeof, c_float, c_void_p, c_uint, string_at
from OpenGL.GL import * #pylint: disable=... | [
"numpy.identity",
"sys.exit",
"numpy.cross",
"math.tan",
"imgui.color_edit3",
"math.radians",
"numpy.ascontiguousarray",
"numpy.array",
"numpy.dot",
"numpy.linalg.inv",
"math.cos",
"numpy.vstack",
"numpy.linalg.norm",
"numpy.matrix",
"math.sin"
] | [((501, 535), 'numpy.array', 'np.array', (['[x, y]'], {'dtype': 'np.float32'}), '([x, y], dtype=np.float32)\n', (509, 535), True, 'import numpy as np\n'), ((728, 765), 'numpy.array', 'np.array', (['[x, y, z]'], {'dtype': 'np.float32'}), '([x, y, z], dtype=np.float32)\n', (736, 765), True, 'import numpy as np\n'), ((681... |
#!/usr/bin/env python3
# Developed by <NAME> and <NAME>
# This file is covered by the LICENSE file in the root of this project.
# Brief: A custom keras padding layer.
# pad([1 2 3 4], 2) -> [3, 4, 1, 2, 3, 4, 1]
import numpy as np
from keras.layers import Layer
from keras.models import Sequential
import keras.ba... | [
"numpy.array",
"keras.backend.backend",
"keras.backend.concatenate",
"keras.models.Sequential"
] | [((1975, 1987), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1985, 1987), False, 'from keras.models import Sequential\n'), ((2760, 2772), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2770, 2772), False, 'from keras.models import Sequential\n'), ((1117, 1128), 'keras.backend.backend', 'K.ba... |
import os.path
from algs.DQN.dqn_agent import DQN
from algs.agent import Agent
from configs.config_phaser import *
import torch
import numpy as np
import random
class METADQNAgent(Agent):
def __init__(self, conf_path, round_number, inter_name,
list_traffic_name=None):
super().__init__(con... | [
"torch.load",
"torch.Tensor",
"numpy.max",
"torch.nn.MSELoss",
"numpy.array",
"numpy.vstack",
"torch.save",
"algs.DQN.dqn_agent.DQN",
"random.random"
] | [((1336, 1360), 'algs.DQN.dqn_agent.DQN', 'DQN', (['self.__conf_traffic'], {}), '(self.__conf_traffic)\n', (1339, 1360), False, 'from algs.DQN.dqn_agent import DQN\n'), ((1385, 1403), 'torch.nn.MSELoss', 'torch.nn.MSELoss', ([], {}), '()\n', (1401, 1403), False, 'import torch\n'), ((1790, 1811), 'torch.load', 'torch.lo... |
import matplotlib.pyplot as plt
import numpy as np
import os,glob,sys,importlib,pickle#,scipy,coolbox,pybedtools,
# from tqdm import tqdm
from scipy.stats import rankdata
import pandas as pd
import networkx as nx
import seaborn as sns
from joblib import delayed, wrap_non_picklable_objects
from pathlib import Path
impor... | [
"sys.path.insert",
"pandas.read_csv",
"numpy.array",
"seaborn.violinplot",
"networkx.convert_matrix.to_pandas_edgelist",
"numpy.arange",
"numpy.divide",
"pandas.unique",
"numpy.repeat",
"numpy.histogramdd",
"seaborn.despine",
"pathlib.Path",
"extremal_bi.calculate_Fitness",
"networkx.from_... | [((561, 605), 'sys.path.insert', 'sys.path.insert', (['(1)', '"""./nestedness_analysis/"""'], {}), "(1, './nestedness_analysis/')\n", (576, 605), False, 'import os, glob, sys, importlib, pickle\n'), ((917, 1022), 'pandas.read_csv', 'pd.read_csv', (["('data/gcn/cc_' + patt + '.txt')"], {'index_col': '(False)', 'sep': '"... |
import numpy as np
def dtw(series_1, series_2, norm_func = np.linalg.norm):
matrix = np.zeros((len(series_1) + 1, len(series_2) + 1))
matrix[0,:] = np.inf
matrix[:,0] = np.inf
matrix[0,0] = 0
for i, vec1 in enumerate(series_1):
for j, vec2 in enumerate(series_2):
cost = norm_func(vec1 - vec2)
matrix[i + 1... | [
"numpy.argmin"
] | [((901, 949), 'numpy.argmin', 'np.argmin', (['[option_diag, option_up, option_left]'], {}), '([option_diag, option_up, option_left])\n', (910, 949), True, 'import numpy as np\n')] |
"""Bayesian polynomial mixture model."""
# pylint: disable=invalid-name
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
class BayesianPolynomialMixture: # pylint: disable=too-few-public-methods
"""Handles creation of a polynomial mixtu... | [
"numpy.float64",
"tensorflow.linalg.LinearOperatorDiag",
"numpy.expand_dims",
"tensorflow.linalg.matmul"
] | [((973, 1019), 'numpy.expand_dims', 'np.expand_dims', (['self.coefficient_precisions', '(0)'], {}), '(self.coefficient_precisions, 0)\n', (987, 1019), True, 'import numpy as np\n'), ((1863, 1878), 'numpy.float64', 'np.float64', (['(0.0)'], {}), '(0.0)\n', (1873, 1878), True, 'import numpy as np\n'), ((1886, 1901), 'num... |
# Copyright 2020 Makani Technologies LLC
#
# 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... | [
"numpy.cross",
"numpy.arcsin",
"numpy.array",
"makani.analysis.aero.hover_model.hover_model.GetParams",
"numpy.arctan2",
"numpy.expand_dims",
"numpy.linalg.norm",
"numpy.concatenate",
"numpy.shape",
"numpy.rad2deg"
] | [((5190, 5223), 'numpy.linalg.norm', 'np.linalg.norm', (['local_vel'], {'axis': '(1)'}), '(local_vel, axis=1)\n', (5204, 5223), True, 'import numpy as np\n'), ((1303, 1371), 'makani.analysis.aero.hover_model.hover_model.GetParams', 'hover_model.GetParams', (['wing_model', 'wing_serial'], {'use_wake_model': '(False)'}),... |
import argparse
import os
import random
import time
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import accuracy_score
from sklearn.utils import shuffle
from analysis import rocstories as rocstories_analysis
from analysis import pw as pw_analysis
from analysis import pw_retrieved as pw_r... | [
"torch.nn.CrossEntropyLoss",
"utils.make_path",
"torch.cuda.device_count",
"numpy.array",
"torch.cuda.is_available",
"datasets.pw",
"numpy.arange",
"utils.ResultLogger",
"text_utils.TextEncoder",
"argparse.ArgumentParser",
"numpy.random.seed",
"numpy.concatenate",
"loss.MultipleChoiceLossCom... | [((805, 853), 'numpy.zeros', 'np.zeros', (['(n_batch, 2, n_ctx, 2)'], {'dtype': 'np.int32'}), '((n_batch, 2, n_ctx, 2), dtype=np.int32)\n', (813, 853), True, 'import numpy as np\n'), ((864, 911), 'numpy.zeros', 'np.zeros', (['(n_batch, 2, n_ctx)'], {'dtype': 'np.float32'}), '((n_batch, 2, n_ctx), dtype=np.float32)\n', ... |
import cv2
import numpy as np
from imutils.video import FileVideoStream
import imutils
import time
vs = FileVideoStream('messi.webm').start()
while vs.more():
frame=vs.read()
if frame is None:
continue
output=frame.copy()
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
gray=cv2.medianBlur(gray,5)
gray=cv2.adaptiveT... | [
"numpy.ones",
"imutils.video.FileVideoStream",
"cv2.erode",
"cv2.medianBlur",
"cv2.HoughCircles",
"cv2.imshow",
"cv2.adaptiveThreshold",
"cv2.circle",
"cv2.destroyAllWindows",
"numpy.around",
"cv2.cvtColor",
"cv2.dilate",
"cv2.waitKey"
] | [((976, 999), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (997, 999), False, 'import cv2\n'), ((233, 272), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (245, 272), False, 'import cv2\n'), ((278, 301), 'cv2.medianBlur', 'cv2.medianBlur', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by <NAME> at 1/25/21
"""paper_plot_fig3.py
:description : script
:param :
:returns:
:rtype:
"""
import os
import matplotlib
import numpy as np
import pandas as pd
matplotlib.rc('font', family="Arial")
matplotlib.rcParams["font.family"] = 'Arial' # 'sans-s... | [
"pandas.read_csv",
"pandas.DataFrame.from_dict",
"os.chdir",
"numpy.array",
"matplotlib.rc",
"matplotlib.pyplot.cm.get_cmap",
"matplotlib.pyplot.subplots"
] | [((226, 263), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {'family': '"""Arial"""'}), "('font', family='Arial')\n", (239, 263), False, 'import matplotlib\n'), ((377, 436), 'os.chdir', 'os.chdir', (['"""../../ComplementaryData/Step_04_Pan_Core_model/"""'], {}), "('../../ComplementaryData/Step_04_Pan_Core_model/')... |
from skimage import exposure
from scipy.misc import imread
from scipy import ndimage
import numpy as np
import random
import os
from data_augmentation import *
from AxonDeepSeg.patch_management_tools import apply_legacy_preprocess, apply_preprocess
import functools
import copy
def generate_list_transformations(transf... | [
"numpy.mean",
"scipy.ndimage.distance_transform_edt",
"random.choice",
"numpy.reshape",
"numpy.multiply",
"os.listdir",
"numpy.where",
"AxonDeepSeg.patch_management_tools.apply_legacy_preprocess",
"numpy.random.choice",
"numpy.asarray",
"numpy.max",
"numpy.stack",
"numpy.zeros",
"functools... | [((3080, 3100), 'numpy.zeros_like', 'np.zeros_like', (['patch'], {}), '(patch)\n', (3093, 3100), True, 'import numpy as np\n'), ((2665, 2697), 'random.choice', 'random.choice', (['L_transformations'], {}), '(L_transformations)\n', (2678, 2697), False, 'import random\n'), ((3289, 3353), 'numpy.where', 'np.where', (['((p... |
import dpctl
import syclbuffer as sb
import numpy as np
X = np.full((10 ** 4, 4098), 1e-4, dtype="d")
# warm-up
print("=" * 10 + " Executing warm-up " + "=" * 10)
print("NumPy result: ", X.sum(axis=0))
dpctl.set_default_queue("opencl", "cpu", 0)
print(
"SYCL({}) result: {}".format(
dpctl.get_current_queu... | [
"syclbuffer.columnwise_total",
"numpy.full",
"dpctl.get_current_queue",
"dpctl.set_default_queue"
] | [((61, 104), 'numpy.full', 'np.full', (['(10 ** 4, 4098)', '(0.0001)'], {'dtype': '"""d"""'}), "((10 ** 4, 4098), 0.0001, dtype='d')\n", (68, 104), True, 'import numpy as np\n'), ((205, 248), 'dpctl.set_default_queue', 'dpctl.set_default_queue', (['"""opencl"""', '"""cpu"""', '(0)'], {}), "('opencl', 'cpu', 0)\n", (228... |
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
import warnings
warnings.filterwarnings("ignore")
import gym
import pybullet_envs
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
import torch.multiprocessing as mp
import time
impo... | [
"torch.nn.ReLU",
"torch.nn.Tanh",
"torch.nn.init.constant_",
"numpy.array",
"torch.cuda.is_available",
"gym.make",
"collections.deque",
"torch.distributions.Normal",
"torch.nn.LeakyReLU",
"time.time",
"warnings.filterwarnings",
"torch.cat",
"torch.nn.init.normal_",
"statistics.mean",
"to... | [((69, 102), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (92, 102), False, 'import warnings\n'), ((422, 457), 'gym.make', 'gym.make', (['"""HalfCheetahBulletEnv-v0"""'], {}), "('HalfCheetahBulletEnv-v0')\n", (430, 457), False, 'import gym\n'), ((737, 762), 'torch.cuda.i... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 by University of Kassel and Fraunhofer Institute for Wind Energy and Energy
# System Technology (IWES), Kassel. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
from sys import stderr
from numpy imp... | [
"numpy.ones",
"numpy.conj",
"numpy.exp",
"sys.stderr.write",
"numpy.zeros",
"numba.jit",
"numpy.empty",
"numpy.argsort",
"numpy.nonzero",
"numpy.resize",
"scipy.sparse.csr_matrix"
] | [((606, 636), 'numba.jit', 'jit', ([], {'nopython': '(True)', 'cache': '(True)'}), '(nopython=True, cache=True)\n', (609, 636), False, 'from numba import jit\n'), ((945, 976), 'numpy.empty', 'empty', (['(nb * 5)'], {'dtype': 'complex128'}), '(nb * 5, dtype=complex128)\n', (950, 976), False, 'from numpy import ones, con... |
import numpy as np
from scipy import optimize
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import ipywidgets as widgets
from ipywidgets import interact, interact_manual
def interactive_capdemand(q_0,a,a_base,amin,amax,b_0,b_base,bmin,bmax,k_0,k_base,kmin,kmax,theta,theta_base,thetamin,thetamax,... | [
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.empty",
"ipywidgets.FloatSlider",
"matplotlib.pyplot.legend"
] | [((388, 406), 'numpy.empty', 'np.empty', (['q_0.size'], {}), '(q_0.size)\n', (396, 406), True, 'import numpy as np\n'), ((752, 802), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'frameon': '(False)', 'figsize': '(8, 5)', 'dpi': '(100)'}), '(frameon=False, figsize=(8, 5), dpi=100)\n', (762, 802), True, 'import matplo... |
import os
import malmoenv
import argparse
from pathlib import Path
import time
from PIL import Image
from collections import deque
import gym
from gym import spaces
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from a2c_ppo_acktr import algo, utils
f... | [
"a2c_ppo_acktr.storage.RolloutStorage",
"time.sleep",
"torch.from_numpy",
"torch.cuda.is_available",
"numpy.mean",
"a2c_ppo_acktr.utils.cleanup_log_dir",
"collections.deque",
"malmoenv.make",
"pathlib.Path",
"torch.set_num_threads",
"numpy.max",
"numpy.min",
"arguments.get_args",
"os.path.... | [((596, 606), 'arguments.get_args', 'get_args', ([], {}), '()\n', (604, 606), False, 'from arguments import get_args\n'), ((717, 745), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (734, 745), False, 'import torch\n'), ((750, 787), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_... |
#!/usr/bin/env python
# Copyright 2014-2019 The PySCF Developers. 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
#
# U... | [
"pyscf.gto.Mole",
"pyscf.scf.UHF",
"pyscf.lib.logger.timer",
"pyscf.gto.M",
"time.clock",
"pyscf.prop.magnetizability.rhf._get_dia_1e",
"pyscf.lib.logger.Logger",
"numpy.dot",
"numpy.einsum",
"pyscf.lib.finger",
"pyscf.prop.nmr.uhf.solve_mo1",
"pyscf.scf.jk.get_jk",
"time.time"
] | [((1332, 1357), 'numpy.dot', 'numpy.dot', (['orboa', 'orboa.T'], {}), '(orboa, orboa.T)\n', (1341, 1357), False, 'import numpy\n'), ((1369, 1394), 'numpy.dot', 'numpy.dot', (['orbob', 'orbob.T'], {}), '(orbob, orbob.T)\n', (1378, 1394), False, 'import numpy\n'), ((1429, 1484), 'numpy.dot', 'numpy.dot', (['(orboa * mo_e... |
### ------------------------------------------------------------------------- ###
### Create binary files of raw stim vid luminance values fitted to world cam stim vid presentation timings
### use world camera vids for timing, use raw vid luminance values extracted via bonsai
### also save world cam luminance as sanity... | [
"zipfile.ZipFile",
"matplotlib.image.imread",
"time.sleep",
"numpy.array",
"cv2.destroyAllWindows",
"datetime.timedelta",
"logging.info",
"numpy.genfromtxt",
"numpy.save",
"os.remove",
"os.path.exists",
"os.listdir",
"argparse.ArgumentParser",
"shutil.copy2",
"logging.INFO",
"numpy.emp... | [((1262, 1273), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1271, 1273), False, 'import os\n'), ((1388, 1411), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1409, 1411), False, 'import datetime\n'), ((2942, 2985), 'os.path.join', 'os.path.join', (['analysed_drive', '"""rawStimLums"""'], {}), "(a... |
import copy
from datetime import datetime
from typing import Callable
import numpy as np
import torch
from ga.individual import statistics
from utils.timing import timing
class Population:
def __init__(self, individual, pop_size, max_generation, p_mutation, p_crossover, p_inversion):
self.pop_size = pop... | [
"ga.individual.statistics",
"datetime.datetime.now",
"torch.save",
"copy.deepcopy",
"numpy.save"
] | [((2579, 2610), 'ga.individual.statistics', 'statistics', (['self.new_population'], {}), '(self.new_population)\n', (2589, 2610), False, 'from ga.individual import statistics\n'), ((2852, 2883), 'ga.individual.statistics', 'statistics', (['self.new_population'], {}), '(self.new_population)\n', (2862, 2883), False, 'fro... |
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
@dataclass
class Recall:
docid: str
n_items: int
score: float
@classmethod
def from_line(cls, line: str) -> Recall:
try:
... | [
"pandas.DataFrame",
"numpy.array"
] | [((1547, 1638), 'pandas.DataFrame', 'pd.DataFrame', (['mat'], {'index': 'docids', 'columns': '[r.n_items for r in info_list[:mat.shape[1]]]'}), '(mat, index=docids, columns=[r.n_items for r in info_list[:mat.\n shape[1]]])\n', (1559, 1638), True, 'import pandas as pd\n'), ((1462, 1510), 'numpy.array', 'np.array', ([... |
"""
Copyright 2021 ETH Zurich, author: <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writin... | [
"numpy.tile",
"numpy.abs",
"xarray.ufuncs.log",
"numpy.isnan",
"numpy.timedelta64",
"numpy.meshgrid",
"numpy.arange"
] | [((1453, 1478), 'xarray.ufuncs.log', 'xu.log', (['data.loc[varname]'], {}), '(data.loc[varname])\n', (1459, 1478), True, 'import xarray.ufuncs as xu\n'), ((2873, 2933), 'numpy.meshgrid', 'np.meshgrid', (['constant_maps.longitude', 'constant_maps.latitude'], {}), '(constant_maps.longitude, constant_maps.latitude)\n', (2... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
# K-means step1
def k_means_step1(img, Class=5):
# get shape
H, W, C = img.shape
# initiate random seed
np.random.seed(0)
# reshape
img = np.reshape(img, (H * W, -1))
# select one index randomly
i = np.random.choice(np.ara... | [
"numpy.reshape",
"cv2.imshow",
"numpy.sum",
"numpy.zeros",
"cv2.destroyAllWindows",
"numpy.random.seed",
"numpy.argmin",
"cv2.waitKey",
"numpy.arange",
"cv2.imread"
] | [((826, 851), 'cv2.imshow', 'cv2.imshow', (['"""result"""', 'out'], {}), "('result', out)\n", (836, 851), False, 'import cv2\n'), ((852, 866), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (863, 866), False, 'import cv2\n'), ((867, 890), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (888, ... |
import numpy as np
from scipy import stats
def uma_função_fictícia():
"""Não faz nada, mas tem requisitos. :)"""
matriz1 = np.random.rand(5, 5)
print(stats.describe(matriz1))
if __name__ == '__main__':
uma_função_fictícia()
| [
"scipy.stats.describe",
"numpy.random.rand"
] | [((133, 153), 'numpy.random.rand', 'np.random.rand', (['(5)', '(5)'], {}), '(5, 5)\n', (147, 153), True, 'import numpy as np\n'), ((164, 187), 'scipy.stats.describe', 'stats.describe', (['matriz1'], {}), '(matriz1)\n', (178, 187), False, 'from scipy import stats\n')] |
"""Utilities used in the Kadenze Academy Course on Deep Learning w/ Tensorflow.
Creative Applications of Deep Learning w/ Tensorflow.
Kadenze, Inc.
<NAME>
Copyright <NAME>, June 2016.
"""
import matplotlib.pyplot as plt
import tensorflow as tf
import urllib
import numpy as np
import zipfile
import os
from scipy.io im... | [
"tarfile.open",
"numpy.sqrt",
"tensorflow.shape",
"zipfile.ZipFile",
"tensorflow.multiply",
"numpy.array",
"tensorflow.log",
"os.walk",
"os.path.exists",
"tensorflow.Graph",
"numpy.mean",
"numpy.reshape",
"tensorflow.random_normal",
"os.listdir",
"tensorflow.pow",
"tensorflow.Session",... | [((664, 685), 'os.path.exists', 'os.path.exists', (['fname'], {}), '(fname)\n', (678, 685), False, 'import os\n'), ((1004, 1073), 'six.moves.urllib.request.urlretrieve', 'urllib.request.urlretrieve', (['path'], {'filename': 'fname', 'reporthook': 'progress'}), '(path, filename=fname, reporthook=progress)\n', (1030, 107... |
import numpy as np
import logging
from collections import Counter
import pandas as pd
import jieba
import shelve
import gensim
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
# model = gensim.models.word2vec.Word2Vec.load('F:\\YX\\word2vec\\word2vec\\word2vec_wx')
... | [
"logging.basicConfig",
"jieba.cut",
"numpy.logaddexp",
"collections.Counter",
"numpy.dot",
"shelve.open"
] | [((134, 229), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.INFO)\n", (153, 229), False, 'import logging\n'), ((535, 561), 'numpy.dot', 'np.dot', (['iwor... |
# Import base tools
import os
## Note, for mac osx compatability import something from shapely.geometry before importing fiona or geopandas
## https://github.com/Toblerity/Shapely/issues/553 * Import shapely before rasterio or fioana
from shapely import geometry
import rasterio
import random
from cw_tiler import main
... | [
"logging.getLogger",
"cw_nets.Ternaus_tools.tn_tools.get_model",
"cw_nets.Ternaus_tools.tn_tools.predict",
"cw_nets.Ternaus_tools.tn_tools.unpad",
"cw_nets.Ternaus_tools.tn_tools.get_img_transform",
"shapely.geometry.box",
"cw_tiler.main.calculate_analysis_grid",
"cw_tiler.utils.calculate_UTM_crs",
... | [((735, 762), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (752, 762), False, 'import logging\n'), ((2042, 2067), 'shapely.geometry.box', 'geometry.box', (['*utm_bounds'], {}), '(*utm_bounds)\n', (2054, 2067), False, 'from shapely import geometry\n'), ((2357, 2502), 'cw_tiler.main.calcu... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 9 13:27:16 2019
@author: <NAME> and <NAME>
"""
import os
import numpy as np
from osgeo import gdal
#datagen = ImageDataGenerator()
#TASK TO DO.
#THERE ARE TWO IMAGES TO LOAD HERE. 1 IS THE MAIN SAT IMAGE AND THE OTHER IS THE WATER IMAGE.
def load_data(batch... | [
"osgeo.gdal.Open",
"numpy.intersect1d",
"os.listdir",
"numpy.random.choice",
"numpy.array",
"numpy.zeros",
"numpy.einsum",
"numpy.expand_dims"
] | [((677, 699), 'os.listdir', 'os.listdir', (['data_water'], {}), '(data_water)\n', (687, 699), False, 'import os\n'), ((718, 738), 'os.listdir', 'os.listdir', (['data_sat'], {}), '(data_sat)\n', (728, 738), False, 'import os\n'), ((757, 797), 'numpy.intersect1d', 'np.intersect1d', (['images_water', 'images_sat'], {}), '... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 13 10:27:00 2017
@author: ben
"""
import numpy as np
class ATL06_pair:
def __init__(self, D6=None, pair_data=None):
if D6 is not None:
#initializes based on input D6, assumed to contain one pair
# 2a. Set pair_data x and y
... | [
"numpy.mean",
"numpy.zeros"
] | [((327, 344), 'numpy.mean', 'np.mean', (['D6.x_atc'], {}), '(D6.x_atc)\n', (334, 344), True, 'import numpy as np\n'), ((409, 426), 'numpy.mean', 'np.mean', (['D6.y_atc'], {}), '(D6.y_atc)\n', (416, 426), True, 'import numpy as np\n'), ((521, 542), 'numpy.mean', 'np.mean', (['D6.dh_fit_dy'], {}), '(D6.dh_fit_dy)\n', (52... |
import time
import torch
import torch.nn as nn
import torch.utils as utils
from torch.autograd import Variable
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np
# import matplotlib
# matplotlib.use('agg')
import ma... | [
"torch.nn.ReLU",
"torch.nn.CrossEntropyLoss",
"torch.max",
"torch.nn.MSELoss",
"numpy.array",
"torch.cuda.is_available",
"torch.nn.BatchNorm2d",
"torch.nn.Sigmoid",
"numpy.random.random",
"numpy.where",
"numpy.random.seed",
"matplotlib.pyplot.axis",
"torchvision.transforms.ToTensor",
"torc... | [((761, 786), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (784, 786), False, 'import torch\n'), ((918, 993), 'torchvision.datasets.MNIST', 'dset.MNIST', (['"""./data"""'], {'train': '(True)', 'transform': 'mnist_transforms', 'download': '(True)'}), "('./data', train=True, transform=mnist_tra... |
# ----------------------------------------------------------------------------
#
# MantaFlow fluid solver framework
# Copyright 2019-2020 <NAME>, <NAME>
#
# This program is free software, distributed under the terms of the
# Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Training (PRE vers... | [
"logging.getLogger",
"logging.StreamHandler",
"matplotlib.pyplot.hist",
"tensorflow.keras.callbacks.LearningRateScheduler",
"tensorflow.keras.utils.plot_model",
"tensorflow.keras.models.load_model",
"tensorflow.compat.v1.set_random_seed",
"tensorflow.compat.v1.Session",
"numpy.arange",
"os.path.ex... | [((463, 482), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (480, 482), False, 'import os, sys, glob, pickle, argparse, logging\n'), ((665, 781), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Parse parameters"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'... |
import tensorflow as tf
import gym
from tqdm import tqdm
import numpy as np
import random
from src.agent.agent import BaseAgent
from src.agent.k_step_planning_agent_with_retrain import KStepPlanningAgent
class DDPGAgent(BaseAgent):
def __init__(self, sess, action_type, actor, critic, gamma, env, replay_buffer, noi... | [
"tensorflow.Summary",
"numpy.reshape",
"tensorflow.train.Saver",
"src.agent.k_step_planning_agent_with_retrain.KStepPlanningAgent",
"numpy.array",
"numpy.expand_dims",
"random.random",
"numpy.amax"
] | [((1226, 1249), 'src.agent.k_step_planning_agent_with_retrain.KStepPlanningAgent', 'KStepPlanningAgent', (['env'], {}), '(env)\n', (1244, 1249), False, 'from src.agent.k_step_planning_agent_with_retrain import KStepPlanningAgent\n'), ((6981, 6993), 'tensorflow.Summary', 'tf.Summary', ([], {}), '()\n', (6991, 6993), Tru... |
import os
import pickle
from logging import getLogger
import numpy as np
import pandas as pd
import cv2
import torch
from tqdm import tqdm
from scipy.interpolate import InterpolatedUnivariateSpline
from car_motion_attack.model_scnn import SCNNOpenPilot
from car_motion_attack.model_ultrafast import UltraFastOpenPilot
... | [
"logging.getLogger",
"car_motion_attack.model_polylanenet.PolyLaneNetOpenPilot",
"numpy.array",
"numpy.nanmean",
"numpy.sin",
"numpy.save",
"numpy.arange",
"car_motion_attack.car_motion.CarMotion",
"car_motion_attack.utils.rgb2yuv",
"numpy.random.random",
"car_motion_attack.model_ultrafast.Ultra... | [((1140, 1155), 'logging.getLogger', 'getLogger', (['None'], {}), '(None)\n', (1149, 1155), False, 'from logging import getLogger\n'), ((2360, 2565), 'car_motion_attack.car_motion.CarMotion', 'CarMotion', (['self.list_bgr_img', 'self.df_sensors', 'self.global_bev_mask', 'self.roi_mat'], {'left_lane_pos': 'left_lane_pos... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 28 19:36:17 2016
@author: Xiaoqing
"""
from Layer import Layer
from Weights import Weights
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import numpy as np
import copy
class NeuralNet():
def __init__(self, n_Hlayer, n_... | [
"Weights.Weights",
"sklearn.model_selection.train_test_split",
"numpy.argmax",
"numpy.array",
"numpy.zeros",
"Layer.Layer",
"numpy.shape",
"sklearn.metrics.accuracy_score"
] | [((1344, 1359), 'numpy.array', 'np.array', (['y_new'], {}), '(y_new)\n', (1352, 1359), True, 'import numpy as np\n'), ((2431, 2468), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.3)'}), '(X, y, test_size=0.3)\n', (2447, 2468), False, 'from sklearn.model_selection import ... |
# ==============================================================================
# MIT License
#
# Copyright 2020 Institute for Automotive Engineering of RWTH Aachen University.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "S... | [
"numpy.array"
] | [((1450, 1547), 'numpy.array', 'np.array', (['[[660.22842, 0.452129, 619.723806], [0.0, 661.579398, 356.276106], [0.0, \n 0.0, 1.0]]'], {}), '([[660.22842, 0.452129, 619.723806], [0.0, 661.579398, 356.276106],\n [0.0, 0.0, 1.0]])\n', (1458, 1547), True, 'import numpy as np\n'), ((1599, 1697), 'numpy.array', 'np.a... |
# Something
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Magic to get the library directory properly
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
from common import moving_average
def graph_seed_scatter(sdlabel,
xdata,
... | [
"numpy.histogram",
"numpy.greater",
"numpy.int32",
"os.path.dirname",
"numpy.isnan",
"pandas.DataFrame",
"common.moving_average",
"pandas.concat"
] | [((2401, 2450), 'numpy.histogram', 'np.histogram', (["df['free']"], {'bins': '(10)', 'range': '(0, 200)'}), "(df['free'], bins=10, range=(0, 200))\n", (2413, 2450), True, 'import numpy as np\n'), ((2487, 2536), 'numpy.histogram', 'np.histogram', (["df['near']"], {'bins': '(10)', 'range': '(0, 200)'}), "(df['near'], bin... |
import numpy as np
import utils.utils as utils
import os
def argsProcessor():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--outputDir", help="output Directory of Data")
parser.add_argument("-i", "--inputDir", help="input Directory of data")
parser.add_argument("-s"... | [
"numpy.save",
"utils.utils.unison_shuffled_copies",
"argparse.ArgumentParser",
"utils.utils.load_data"
] | [((112, 137), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (135, 137), False, 'import argparse\n'), ((688, 762), 'utils.utils.load_data', 'utils.load_data', (['inputDataDir', 'GT_DIR'], {'size': 'size', 'debug': 'Debug', 'limit': '(10000)'}), '(inputDataDir, GT_DIR, size=size, debug=Debug, li... |
# Copyright 2019 The Texar 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 ... | [
"numpy.prod",
"torch.split",
"texar.torch.utils.utils.map_structure",
"texar.torch.core.get_activation_fn",
"torch.full",
"texar.torch.utils.nest.pack_sequence_as",
"texar.torch.utils.nest.flatten",
"torch.Size",
"texar.torch.utils.utils.check_or_get_instance",
"torch.nn.Parameter",
"torch.resha... | [((1929, 1954), 'texar.torch.utils.nest.flatten', 'nest.flatten', (['output_size'], {}), '(output_size)\n', (1941, 1954), False, 'from texar.torch.utils import nest\n'), ((1973, 1994), 'texar.torch.utils.nest.flatten', 'nest.flatten', (['outputs'], {}), '(outputs)\n', (1985, 1994), False, 'from texar.torch.utils import... |
# coding=utf-8
# Copyright 2022 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... | [
"gfsa.datasets.graph_edge_util.nth_child_edge_types",
"tensorflow.io.gfile.GFile",
"gfsa.generic_ast_graphs.build_ast_graph_schema",
"gfsa.automaton_builder.AutomatonBuilder",
"gfsa.datasets.graph_bundle.pad_example",
"tensor2tensor.data_generators.text_encoder.SubwordTextEncoder",
"gfsa.jax_util.pad_to... | [((1820, 1849), 'dataclasses.field', 'dataclasses.field', ([], {'init': '(False)'}), '(init=False)\n', (1837, 1849), False, 'import dataclasses\n'), ((1876, 1905), 'dataclasses.field', 'dataclasses.field', ([], {'init': '(False)'}), '(init=False)\n', (1893, 1905), False, 'import dataclasses\n'), ((1954, 1983), 'datacla... |
# import libraries
from flask import Flask, jsonify, request
import feature
from tensorflow import keras
import numpy as np
# Creating Flask app
app = Flask(__name__)
# Loading pre-trained keras model
def loadModel():
path = "F:\Chrome Extension\Trawling-Chrome-Extention\Server\models48xLSTM-32xDense"
mode... | [
"numpy.reshape",
"flask.Flask",
"flask.jsonify",
"numpy.array",
"flask.request.get_json",
"tensorflow.keras.models.load_model",
"feature.featureExtraction"
] | [((153, 168), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (158, 168), False, 'from flask import Flask, jsonify, request\n'), ((324, 353), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['path'], {}), '(path)\n', (347, 353), False, 'from tensorflow import keras\n'), ((475, 505), 'featu... |
import numpy as np
from . import ilossfunc
class SumSquareError(ilossfunc.ILossFunc):
def __init__(self):
pass
def get_loss(self, prediction: np.array, label: np.array) -> np.array:
if prediction.ndim == 1:
prediction = prediction.reshape(1, prediction.size)
label = la... | [
"numpy.sum"
] | [((410, 443), 'numpy.sum', 'np.sum', (['((prediction - label) ** 2)'], {}), '((prediction - label) ** 2)\n', (416, 443), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
#
# shape of sound buffers:
# 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.],
# ... | [
"numpy.copy",
"os.listdir",
"pygame.init",
"pygame.quit",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.display.flip",
"os.path.join",
"pygame.font.SysFont",
"numpy.zeros",
"numpy.concatenate",
"hsampler.ui.Command.cmd_nop",
"soundfile.read",
"pyaudio.PyAudio",
"random.randint"
... | [((672, 689), 'pyaudio.PyAudio', 'pyaudio.PyAudio', ([], {}), '()\n', (687, 689), False, 'import pyaudio\n'), ((6452, 6478), 'random.randint', 'random.randint', (['(0)', '(9999999)'], {}), '(0, 9999999)\n', (6466, 6478), False, 'import random\n'), ((6684, 6711), 'numpy.concatenate', 'np.concatenate', (['self.blocks'], ... |
import sys
import moderngl
import numpy as np
from pyrr import Matrix44
from shadevolution import models, fresnel, shader, plot
class Evaluator:
"""
An evaluator that runs a genetic algorithm using OpenGL for the fitness evaluation.
"""
gl_version = (4, 1)
def __init__(self, window, size=(2048,... | [
"numpy.mean",
"numpy.frombuffer",
"shadevolution.shader.diff",
"pyrr.Matrix44.perspective_projection",
"shadevolution.models.load_crate",
"pyrr.Matrix44.from_eulers",
"numpy.linalg.norm",
"shadevolution.fresnel.create_program",
"shadevolution.shader.write",
"pyrr.Matrix44.from_translation",
"pyr... | [((766, 798), 'shadevolution.fresnel.create_program', 'fresnel.create_program', (['self.ctx'], {}), '(self.ctx)\n', (788, 798), False, 'from shadevolution import models, fresnel, shader, plot\n'), ((874, 893), 'shadevolution.models.load_crate', 'models.load_crate', ([], {}), '()\n', (891, 893), False, 'from shadevoluti... |
import numpy as np
import matplotlib.pyplot as plt
def generate_water_stats():
cov = np.array([[1.2, 1], [1, 1]])
mean = np.array([3.2, 3.5])
values = np.random.multivariate_normal(mean=mean, cov=cov, size=100)
return values[:, 0]*5, values[:, 1]
def plot_stats_without_lobf(x, y):
plt.scatt... | [
"matplotlib.pyplot.ylabel",
"numpy.random.multivariate_normal",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.array",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show"
] | [((91, 119), 'numpy.array', 'np.array', (['[[1.2, 1], [1, 1]]'], {}), '([[1.2, 1], [1, 1]])\n', (99, 119), True, 'import numpy as np\n'), ((131, 151), 'numpy.array', 'np.array', (['[3.2, 3.5]'], {}), '([3.2, 3.5])\n', (139, 151), True, 'import numpy as np\n'), ((166, 225), 'numpy.random.multivariate_normal', 'np.random... |
import unittest
import logging
import numpy as np
import pandas as pd
import scipy.stats as stats
from batchglm.api.models.glm_nb import Simulator
import diffxpy.api as de
class TestExtremeValues(unittest.TestCase):
def test_t_test_zero_variance(self, n_cells: int = 2000, n_genes: int = 100):
"""
... | [
"logging.getLogger",
"batchglm.api.models.glm_nb.Simulator",
"diffxpy.api.test.t_test",
"scipy.stats.kstest",
"numpy.exp",
"numpy.random.randint",
"unittest.main"
] | [((1825, 1840), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1838, 1840), False, 'import unittest\n'), ((977, 1034), 'batchglm.api.models.glm_nb.Simulator', 'Simulator', ([], {'num_observations': 'n_cells', 'num_features': 'n_genes'}), '(num_observations=n_cells, num_features=n_genes)\n', (986, 1034), False, 'f... |
import numpy as np
import torch
import torch.nn as nn
class ConditionalGenerator(nn.Module):
def __init__(self, n_classes, latent_dim, img_shape):
super(ConditionalGenerator, self).__init__()
self.img_shape = img_shape
self.label_emb = nn.Embedding(n_classes, n_classes)
def block(... | [
"torch.nn.Sigmoid",
"numpy.prod",
"torch.nn.Dropout",
"torch.nn.Tanh",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm1d",
"torch.nn.Linear",
"torch.nn.Embedding"
] | [((266, 300), 'torch.nn.Embedding', 'nn.Embedding', (['n_classes', 'n_classes'], {}), '(n_classes, n_classes)\n', (278, 300), True, 'import torch.nn as nn\n'), ((1319, 1353), 'torch.nn.Embedding', 'nn.Embedding', (['n_classes', 'n_classes'], {}), '(n_classes, n_classes)\n', (1331, 1353), True, 'import torch.nn as nn\n'... |
from unittest import TestCase
import numpy as np
import pandas as pd
from copulas.univariate.gaussian import GaussianUnivariate
class TestGaussianUnivariate(TestCase):
def test___init__(self):
"""On init, default values are set on instance."""
# Setup / Run
copula = GaussianUnivariate(... | [
"pandas.Series",
"copulas.univariate.gaussian.GaussianUnivariate",
"numpy.mean",
"copulas.univariate.gaussian.GaussianUnivariate.from_dict",
"numpy.std"
] | [((301, 321), 'copulas.univariate.gaussian.GaussianUnivariate', 'GaussianUnivariate', ([], {}), '()\n', (319, 321), False, 'from copulas.univariate.gaussian import GaussianUnivariate\n'), ((547, 567), 'copulas.univariate.gaussian.GaussianUnivariate', 'GaussianUnivariate', ([], {}), '()\n', (565, 567), False, 'from copu... |
import numpy as np
class MF():
'''
Matrix Factorisation alogrithm based on <NAME>'s method
Key input is the sparse user-item ratings array, with user ratings in an array with
a row per user, and a column per item. Values are the users known rating, or zero if
no rating is available.
The output is a user-item ... | [
"numpy.random.rand",
"numpy.subtract",
"numpy.sum",
"numpy.array",
"numpy.matmul"
] | [((2603, 2681), 'numpy.array', 'np.array', (['[[1, 0, 0, 4, 5], [2, 5, 1, 5, 5], [1, 4, 1, 5, 4], [4, 1, 4, 0, 3]]'], {}), '([[1, 0, 0, 4, 5], [2, 5, 1, 5, 5], [1, 4, 1, 5, 4], [4, 1, 4, 0, 3]])\n', (2611, 2681), True, 'import numpy as np\n'), ((847, 895), 'numpy.random.rand', 'np.random.rand', (['self.users', 'self.la... |
import numpy as np
from sklearn import preprocessing
from sklearn.naive_bayes import GaussianNB
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
# Initialise Flask App
app = Flask(__name__)
api = Api(app)
# For labelling the dataset
le = preprocessing.LabelEncoder()
# Creating a Gauss... | [
"sklearn.preprocessing.LabelEncoder",
"flask_restful.reqparse.RequestParser",
"flask_restful.Api",
"flask.Flask",
"sklearn.naive_bayes.GaussianNB",
"numpy.float32"
] | [((207, 222), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (212, 222), False, 'from flask import Flask\n'), ((229, 237), 'flask_restful.Api', 'Api', (['app'], {}), '(app)\n', (232, 237), False, 'from flask_restful import reqparse, abort, Api, Resource\n'), ((272, 300), 'sklearn.preprocessing.LabelEncoder... |
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation
import json
import nibabel as nib
from scipy.ndimage.interpolation import zoom
def save_history(filename, trainer):
"""Save the history from a torchsample trainer to file."""
with open(f... | [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.ylabel",
"nibabel.load",
"scipy.ndimage.interpolation.zoom",
"scipy.ndimage.zoom",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.asarray",
"matplotlib.colors.ListedColormap",
"numpy.take",
"numpy.linspace",
"matplotl... | [((2194, 2212), 'numpy.zeros', 'np.zeros', (['(256, 4)'], {}), '((256, 4))\n', (2202, 2212), True, 'import numpy as np\n'), ((2270, 2292), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(256)'], {}), '(0, 1, 256)\n', (2281, 2292), True, 'import numpy as np\n'), ((2343, 2387), 'matplotlib.colors.ListedColormap', 'mpl... |
#!/usr/bin/env python
"""Unique Crater Distribution Functions
Functions for extracting craters from model target predictions and filtering
out duplicates.
"""
from __future__ import absolute_import, division, print_function
from PIL import Image
import matplotlib
import cv2
import matplotlib.pyplot as plt
import numpy... | [
"numpy.column_stack",
"numpy.sin",
"pandas.HDFStore",
"utils.template_match_target.template_match_t",
"numpy.save",
"os.path.exists",
"utils.processing.get_id",
"numpy.where",
"numpy.asarray",
"os.mkdir",
"numpy.vstack",
"numpy.concatenate",
"numpy.abs",
"h5py.File",
"numpy.cos",
"util... | [((960, 990), 'h5py.File', 'h5py.File', (["CP['dir_data']", '"""r"""'], {}), "(CP['dir_data'], 'r')\n", (969, 990), False, 'import h5py\n'), ((1162, 1183), 'utils.processing.preprocess', 'proc.preprocess', (['Data'], {}), '(Data)\n', (1177, 1183), True, 'import utils.processing as proc\n'), ((1197, 1224), 'keras.models... |
import itertools
import numpy as np
from ..sequences import Genome
def in_silico_mutagenesis_sequences(sequence,
mutate_n_bases=1,
reference_sequence=Genome,
start_position=0,
... | [
"numpy.copy",
"itertools.product"
] | [((5634, 5651), 'numpy.copy', 'np.copy', (['encoding'], {}), '(encoding)\n', (5641, 5651), True, 'import numpy as np\n'), ((4506, 4539), 'itertools.product', 'itertools.product', (['*pos_mutations'], {}), '(*pos_mutations)\n', (4523, 4539), False, 'import itertools\n')] |
"""
Area calculations
-----------------
Calculates the area of pixels for a give grid input.
"""
def earth_radius(lat):
"""Calculate the radius of the earth for a given latitude
Args:
lat (array, float): latitude value (-90 : 90)
Returns:
array: radius in metres
"""
from numpy i... | [
"numpy.deg2rad",
"numpy.cos",
"numpy.sin",
"numpy.meshgrid",
"numpy.gradient"
] | [((355, 367), 'numpy.deg2rad', 'deg2rad', (['lat'], {}), '(lat)\n', (362, 367), False, 'from numpy import cos, deg2rad, gradient, meshgrid\n'), ((1135, 1153), 'numpy.meshgrid', 'meshgrid', (['lat', 'lon'], {}), '(lat, lon)\n', (1143, 1153), False, 'from numpy import cos, deg2rad, gradient, meshgrid\n'), ((1201, 1223), ... |
# -*- coding: utf-8 -*-
from abc import ABC, abstractmethod
import numpy as np
import pandas as pd
class ExogenousBaseModel(ABC):
"""
Exogenous Abstract Base Class.
"""
model = None
@abstractmethod
def __init__(self):
self.fitted = None
pass
def __s... | [
"numpy.append",
"pandas.Series"
] | [((1523, 1564), 'numpy.append', 'np.append', (['self.fitted', 'exo_object.fitted'], {}), '(self.fitted, exo_object.fitted)\n', (1532, 1564), True, 'import numpy as np\n'), ((1616, 1632), 'pandas.Series', 'pd.Series', (['array'], {}), '(array)\n', (1625, 1632), True, 'import pandas as pd\n')] |
from __future__ import division
from builtins import str
import numpy as np
import os
import pickle as Pickle
from flarestack.core.results import ResultsHandler
from flarestack.data.icecube.ps_tracks.ps_v002_p01 import ps_v002_p01
from flarestack.shared import plot_output_dir, flux_to_k, analysis_dir
from flarestack.ut... | [
"pickle.dump",
"os.makedirs",
"flarestack.core.results.ResultsHandler",
"flarestack.shared.plot_output_dir",
"builtins.str",
"matplotlib.pyplot.close",
"numpy.linspace",
"matplotlib.pyplot.figure",
"flarestack.icecube_utils.reference_sensitivity.reference_sensitivity",
"matplotlib.pyplot.tight_lay... | [((1046, 1071), 'numpy.linspace', 'np.linspace', (['(0.5)', '(-0.5)', '(3)'], {}), '(0.5, -0.5, 3)\n', (1057, 1071), True, 'import numpy as np\n'), ((1101, 1126), 'numpy.linspace', 'np.linspace', (['(-90.0)', '(90)', '(7)'], {}), '(-90.0, 90, 7)\n', (1112, 1126), True, 'import numpy as np\n'), ((2911, 2923), 'matplotli... |
import streamlit as st
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import altair as alt
from requests import get
import re
import os
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import datetime
import time
import matplotlib.pyplo... | [
"streamlit.table",
"pandas.read_csv",
"urllib.request.Request",
"time.sleep",
"datetime.timedelta",
"streamlit.header",
"pandas.date_range",
"pandas.to_datetime",
"pandas.unique",
"datetime.date",
"numpy.datetime64",
"streamlit.set_page_config",
"pandas.DataFrame",
"urllib.request.urlopen"... | [((449, 484), 'geopy.geocoders.Nominatim', 'Nominatim', ([], {'user_agent': '"""myuseragent"""'}), "(user_agent='myuseragent')\n", (458, 484), False, 'from geopy.geocoders import Nominatim\n'), ((669, 768), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': '"""O/U Hockey Analytics"""', 'page_icon':... |
import numpy as np
from math import floor, ceil
import torch
from torch import nn
import torch.nn.functional as F
import utils.loggers as lg
class Residual_CNN(nn.Module):
def __init__(self, learning_rate, input_dim, output_dim, hidden_layers, device):
super().__init__()
self._device = device
... | [
"torch.tanh",
"torch.nn.BatchNorm2d",
"math.ceil",
"torch.nn.CrossEntropyLoss",
"torch.nn.LeakyReLU",
"math.floor",
"numpy.reshape",
"torch.from_numpy",
"torch.nn.Conv2d",
"torch.nn.MSELoss",
"torch.nn.Linear"
] | [((560, 577), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.3)'], {}), '(0.3)\n', (572, 577), False, 'from torch import nn\n'), ((748, 791), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (["hidden_layers[0]['filters']"], {}), "(hidden_layers[0]['filters'])\n", (762, 791), False, 'from torch import nn\n'), ((1727, 1744), 'tor... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# csv paths
colorCSV = pd.read_csv('../input/style-classifier/Multi_Label_dataset/Tasks/color.csv')
dofCSV = pd.read_csv('../input/style-classifier/Multi_Label_dataset/Tasks/dof.csv')
paletteCSV = pd.read_csv('../input/style-classifier/Multi_Label_... | [
"matplotlib.pyplot.savefig",
"pandas.read_csv",
"numpy.array",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((95, 171), 'pandas.read_csv', 'pd.read_csv', (['"""../input/style-classifier/Multi_Label_dataset/Tasks/color.csv"""'], {}), "('../input/style-classifier/Multi_Label_dataset/Tasks/color.csv')\n", (106, 171), True, 'import pandas as pd\n'), ((181, 255), 'pandas.read_csv', 'pd.read_csv', (['"""../input/style-classifier/... |
import torch
import numpy as np
import mmcv
import cv2
def get_mask_size(proposals_list, base_size, ratio_max):
ratio = 1.0
for proposals in proposals_list:
ratios = proposals[:, 2] / proposals[:, 3]
assert ratios.min() >= 1.0
ratio = max(ratio, ratios.ceil().max())
ratio = float(mi... | [
"cv2.warpAffine",
"mmcv.imresize",
"numpy.stack",
"numpy.zeros",
"cv2.getRotationMatrix2D",
"numpy.maximum",
"numpy.int",
"numpy.float32",
"torch.cat"
] | [((532, 577), 'numpy.zeros', 'np.zeros', (['(rows * 2, cols * 2)'], {'dtype': '"""uint8"""'}), "((rows * 2, cols * 2), dtype='uint8')\n", (540, 577), True, 'import numpy as np\n'), ((723, 809), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['(x + cols_start, y + rows_start)', '(theta * 180 / np.pi)', '(1)'], {... |
from scipy import stats
import numpy as np
__all__ = ['chisquare', 'kolsmi']
def kolsmi(dist, fit_result, data):
"""Perform a Kolmogorow-Smirnow-Test for goodness of fit.
This tests the H0 hypothesis, if data is a sample of dist
Args:
dist: A mle.Distribution instance
fit_result... | [
"numpy.sum",
"numpy.histogram"
] | [((2053, 2105), 'numpy.histogram', 'np.histogram', (['data[var.name]'], {'bins': 'bins', 'range': 'range'}), '(data[var.name], bins=bins, range=range)\n', (2065, 2105), True, 'import numpy as np\n'), ((2470, 2482), 'numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (2476, 2482), True, 'import numpy as np\n')] |
from model import Model, Optimizer
import numpy as np
IMAGE_SIZE = 28
class ClientModel(Model):
def __init__(self, lr, num_classes, max_batch_size=None, seed=None, optimizer=None):
self.num_classes = num_classes
super(ClientModel, self).__init__(lr, seed, max_batch_size, optimizer=ErmOptimizer()... | [
"numpy.exp",
"numpy.dot",
"numpy.zeros",
"numpy.matmul",
"numpy.linalg.norm"
] | [((1583, 1595), 'numpy.zeros', 'np.zeros', (['(50)'], {}), '(50)\n', (1591, 1595), True, 'import numpy as np\n'), ((2920, 2944), 'numpy.matmul', 'np.matmul', (['image', 'self.w'], {}), '(image, self.w)\n', (2929, 2944), True, 'import numpy as np\n'), ((3198, 3220), 'numpy.zeros', 'np.zeros', (['self.w.shape'], {}), '(s... |
import time
import os
import pickle
import argparse
import multiprocessing as mp
from multiprocessing import Pool
import numpy as np
from single_peaked_bandits.solvers import OptimalSolver
from single_peaked_bandits.helpers import (
get_reward_for_policy,
)
from single_peaked_bandits.constants import RESULTS_FOLD... | [
"argparse.ArgumentParser",
"os.makedirs",
"single_peaked_bandits.helpers.get_reward_for_policy",
"make_plots.make_plots",
"os.path.join",
"multiprocessing.get_context",
"numpy.linspace",
"single_peaked_bandits.solvers.OptimalSolver",
"time.time",
"numpy.arange"
] | [((662, 673), 'time.time', 'time.time', ([], {}), '()\n', (671, 673), False, 'import time\n'), ((805, 861), 'single_peaked_bandits.helpers.get_reward_for_policy', 'get_reward_for_policy', (['bandit.noise_free_arms', 'T', 'policy'], {}), '(bandit.noise_free_arms, T, policy)\n', (826, 861), False, 'from single_peaked_ban... |
import numpy as np
def identity_function(x):
return x
def leaky_relu(x):
return np.max(0.1 * x, x)
def relu(x):
return np.max(0, x)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def tanh(x):
return np.tanh(x)
def step_function(x):
return np.array(x > 0, dtype=np.int)
def softmax(x):
... | [
"numpy.exp",
"numpy.array",
"numpy.tanh",
"numpy.max"
] | [((92, 110), 'numpy.max', 'np.max', (['(0.1 * x)', 'x'], {}), '(0.1 * x, x)\n', (98, 110), True, 'import numpy as np\n'), ((137, 149), 'numpy.max', 'np.max', (['(0)', 'x'], {}), '(0, x)\n', (143, 149), True, 'import numpy as np\n'), ((226, 236), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (233, 236), True, 'import n... |
import torch
import torch.nn as nn
import torch.utils.data as data
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import argparse
# import matplotlib.pyplot as plt
import numpy as np
from torch.autograd import Variable
# from sklearn.decomposition import PCA
import sett... | [
"numpy.logical_not",
"classifier.Classifier",
"torch.from_numpy",
"torch.nn.functional.sigmoid",
"torch.cuda.is_available",
"argparse.ArgumentParser",
"numpy.random.random",
"numpy.concatenate",
"torchvision.transforms.ToTensor",
"torch.autograd.Variable",
"numpy.abs",
"numpy.random.choice",
... | [((772, 838), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""MNIST noise active learning"""'}), "(description='MNIST noise active learning')\n", (795, 838), False, 'import argparse\n'), ((1329, 1425), 'torchvision.datasets.MNIST', 'torchvision.datasets.MNIST', (['"""datasets/MNIST"""'], ... |
# import
import numpy as np
import json
import pandas as pd
import torch
import os
def seed_everything(seed):
np.random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
torch.manual_seed(seed)
seed_everything(42)
class TrainPipeline:
def __init__(self, hparams, gpu, model, Dataset_train):
... | [
"torch.manual_seed",
"os.makedirs",
"json.dump",
"numpy.random.seed",
"numpy.round"
] | [((116, 136), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (130, 136), True, 'import numpy as np\n'), ((186, 209), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (203, 209), False, 'import torch\n'), ((2196, 2265), 'os.makedirs', 'os.makedirs', (["(self.hparams['debug_path']... |
"""
Unit test for util (i.e. for the parameterisation maths)
"""
import numpy as np
from fourbody import util
def test_inv_mass_stationary():
"""
Test invariant mass of a stationary particle gets calculated correctly
"""
b0_mass = 5279.65
momentum = np.array([[0.0]])
energy = np.array([[b0_... | [
"numpy.allclose",
"numpy.add",
"fourbody.util._invariant_masses",
"fourbody.util.m_plus_minus",
"numpy.array",
"numpy.linspace",
"numpy.cos",
"fourbody.util.phi",
"numpy.sin"
] | [((275, 292), 'numpy.array', 'np.array', (['[[0.0]]'], {}), '([[0.0]])\n', (283, 292), True, 'import numpy as np\n'), ((306, 327), 'numpy.array', 'np.array', (['[[b0_mass]]'], {}), '([[b0_mass]])\n', (314, 327), True, 'import numpy as np\n'), ((609, 637), 'numpy.array', 'np.array', (['[[-2405.25192233]]'], {}), '([[-24... |
# -*- coding: utf-8 -*-
import sys
import pandas
import numpy
sys.path.append('../')
import heatmap
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.lines import Line2D
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['FreeSans', ]
matplotlib.rcParams['mathtext.fontset'] = 'custom'
matp... | [
"pandas.read_csv",
"matplotlib.colors.LinearSegmentedColormap.from_list",
"heatmap.Clustergram",
"sys.path.append",
"numpy.arange"
] | [((63, 85), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (78, 85), False, 'import sys\n'), ((400, 488), 'pandas.read_csv', 'pandas.read_csv', (['"""./rRNAs_analysis/final_distance_matrix.tsv"""'], {'sep': '"""\t"""', 'index_col': '(0)'}), "('./rRNAs_analysis/final_distance_matrix.tsv', sep='\... |
from distutils.version import LooseVersion
from io import StringIO
from itertools import product
from string import ascii_lowercase
import struct
import sys
import types
import warnings
import numpy as np
from numpy.random import RandomState
from numpy.testing import (
assert_allclose,
assert_almost_equal,
... | [
"numpy.random.standard_normal",
"struct.calcsize",
"numpy.sqrt",
"numpy.testing.assert_equal",
"numpy.linalg.pinv",
"arch.univariate.volatility.ARCH",
"numpy.array",
"scipy.stats.chi2",
"numpy.isfinite",
"pytest.fixture",
"pandas.testing.assert_frame_equal",
"arch.univariate.mean.ConstantMean"... | [((1871, 1923), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'params': '[True, False]'}), "(scope='module', params=[True, False])\n", (1885, 1923), False, 'import pytest\n'), ((39622, 39736), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""volatility"""', '[GARCH, EGARCH, RiskMetrics20... |
import random
import math
import numpy as np
import cv2
import matplotlib.pyplot as plt
__author__ = '__Girish_Hegde__'
class Sampler:
def __init__(self, radius=1, center=(0, 0), method='rejection_sample'):
self.radius = radius
self.r2 = radius**2
self.cx, self.cy = ce... | [
"cv2.imshow",
"math.cos",
"numpy.array",
"cv2.circle",
"numpy.zeros",
"random.random",
"math.sin",
"cv2.waitKey"
] | [((3885, 3922), 'numpy.zeros', 'np.zeros', (['(hw, hw, 3)'], {'dtype': 'np.uint8'}), '((hw, hw, 3), dtype=np.uint8)\n', (3893, 3922), True, 'import numpy as np\n'), ((3995, 4071), 'cv2.circle', 'cv2.circle', (['coord_frame', '(hw // 2 + cx, hw - (hw // 2 + cy))', 'r', '(255, 0, 0)'], {}), '(coord_frame, (hw // 2 + cx, ... |
"""
Trainer for BiGAN/ALI
"""
import numpy as np
import torch
from torch.autograd import Variable
from tqdm import tqdm
from ....common import FloatTensor
from ....utils.plot import get_visdom_line_plotter
class Trainer(object):
def __init__(self, trick_dict=None):
if trick_dict is None:
sel... | [
"numpy.random.normal",
"numpy.array",
"tqdm.tqdm",
"numpy.random.randn"
] | [((2503, 2520), 'tqdm.tqdm', 'tqdm', (['data_loader'], {}), '(data_loader)\n', (2507, 2520), False, 'from tqdm import tqdm\n'), ((4567, 4605), 'numpy.array', 'np.array', (['[dis_loss_lst, gen_loss_lst]'], {}), '([dis_loss_lst, gen_loss_lst])\n', (4575, 4605), True, 'import numpy as np\n'), ((4745, 4775), 'numpy.array',... |
'''
SFCMapper.py
Updated: 2/6/18
This script contains methods to generate space filling curves and uses them to
map high dimensional data into lower dimensions.
'''
import numpy as np
class SFCMapper(object):
"""
SFCMapper object is used to generate 3D and 2D space filling curves and map
the traveseral o... | [
"numpy.array",
"numpy.log2",
"numpy.zeros",
"numpy.sqrt"
] | [((723, 749), 'numpy.sqrt', 'np.sqrt', (['(self.size_3d ** 3)'], {}), '(self.size_3d ** 3)\n', (730, 749), True, 'import numpy as np\n'), ((1423, 1439), 'numpy.zeros', 'np.zeros', (['[s, s]'], {}), '([s, s])\n', (1431, 1439), True, 'import numpy as np\n'), ((1039, 1060), 'numpy.log2', 'np.log2', (['self.size_3d'], {}),... |
import inspect
from abc import abstractmethod, ABCMeta
from typing import Callable, Union, Optional, List
from joblib import Memory
# import cupy as cp
from warnings import warn
import numpy as np
from scipy.integrate import quad
# from Operator import Quadrature
from decorators import timer, vectorize
location = ... | [
"decorators.vectorize",
"numpy.less",
"numpy.repeat",
"scipy.integrate.quad",
"numpy.square",
"joblib.Memory",
"numpy.array",
"warnings.warn",
"numpy.vectorize",
"inspect.getsource"
] | [((342, 401), 'joblib.Memory', 'Memory', (['location'], {'verbose': '(0)', 'bytes_limit': '(1024 * 1024 * 1024)'}), '(location, verbose=0, bytes_limit=1024 * 1024 * 1024)\n', (348, 401), False, 'from joblib import Memory\n'), ((7869, 7896), 'numpy.vectorize', 'np.vectorize', (['__q_estimator'], {}), '(__q_estimator)\n'... |
from dataclasses import dataclass
import flowpost.wake.helpers.wake_stats as ws
from wake_config import WakeCaseParams
import flowpost.IO.pyTecIO.tecreader as tecreader
import os
import numpy as np
from ...calc.stats import VelocityStatistics, ReynoldsStresses
###########################################################... | [
"flowpost.wake.helpers.wake_stats.compute_field_acf_index",
"flowpost.wake.helpers.wake_stats.rotate_velocities",
"numpy.savez",
"scipy.signal.welch",
"os.makedirs",
"scipy.stats.kurtosis",
"dataclasses.dataclass",
"os.path.join",
"scipy.stats.skew",
"flowpost.wake.helpers.wake_stats.transform_wak... | [((586, 607), 'dataclasses.dataclass', 'dataclass', ([], {'init': '(False)'}), '(init=False)\n', (595, 607), False, 'from dataclasses import dataclass\n'), ((1596, 1649), 'numpy.gradient', 'np.gradient', (['self.vx', '(-self.dy / 1000)', '(self.dx / 1000)'], {}), '(self.vx, -self.dy / 1000, self.dx / 1000)\n', (1607, 1... |
import numpy
import random
import sys
from nsga2 import Nsga2
class Mtsp(object):
@staticmethod
def crossover_sequence_ox(parent_sequence_a, parent_sequence_b):
sequence_length = len(parent_sequence_a)
child_sequence_a = [None] * sequence_length
child_sequence_b = [None] * sequence_le... | [
"nsga2.Nsga2",
"numpy.zeros",
"random.shuffle",
"random.randrange"
] | [((343, 376), 'random.randrange', 'random.randrange', (['sequence_length'], {}), '(sequence_length)\n', (359, 376), False, 'import random\n'), ((394, 427), 'random.randrange', 'random.randrange', (['sequence_length'], {}), '(sequence_length)\n', (410, 427), False, 'import random\n'), ((1276, 1300), 'random.randrange', ... |
import sys
import tensorflow as tf
import pdb
import numpy as np
import myParams
import GTools as GT
import scipy.io
import h5py
import time
FLAGS = tf.app.flags.FLAGS
def setup_inputs(sess, filenames, image_size=None, capacity_factor=3, TestStuff=False):
batch_size=myParams.myDict['batch_size']
channel... | [
"tensorflow.image.resize_images",
"tensorflow.imag",
"tensorflow.get_variable",
"tensorflow.transpose",
"tensorflow.scatter_nd_update",
"numpy.int32",
"tensorflow.multiply",
"tensorflow.real",
"tensorflow.TFRecordReader",
"GTools.TFGenerateRandomSinPhase",
"tensorflow.reduce_mean",
"tensorflow... | [((35891, 35910), 'tensorflow.TFRecordReader', 'tf.TFRecordReader', ([], {}), '()\n', (35908, 35910), True, 'import tensorflow as tf\n'), ((35933, 35974), 'tensorflow.train.string_input_producer', 'tf.train.string_input_producer', (['filenames'], {}), '(filenames)\n', (35963, 35974), True, 'import tensorflow as tf\n'),... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.utils.data as data
import numpy as np
import torch
import json
import cv2
import os
from utils.image import flip, color_aug
from utils.image import get_affine_transform, affine_transform
from utils... | [
"numpy.clip",
"math.cos",
"numpy.array",
"utils.image.get_affine_transform",
"numpy.arange",
"numpy.random.random",
"cv2.minAreaRect",
"numpy.concatenate",
"numpy.abs",
"cv2.warpAffine",
"numpy.int0",
"cv2.resize",
"utils.image.color_aug",
"cv2.imread",
"numpy.random.randn",
"math.ceil... | [((530, 608), 'numpy.array', 'np.array', (['[box[0], box[1], box[0] + box[2], box[1] + box[3]]'], {'dtype': 'np.float32'}), '([box[0], box[1], box[0] + box[2], box[1] + box[3]], dtype=np.float32)\n', (538, 608), True, 'import numpy as np\n'), ((1736, 1771), 'numpy.array', 'np.array', (['corners'], {'dtype': 'np.float32... |
#!/usr/bin/env python
import argparse as ap
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as clr
from hmmlearn.hmm import GaussianHMM
import scipy.stats as scistats
import logging
import pickle
import os, ntpath
import tables
import cooler
from scipy.sparse import csr_matrix, triu, lil_ma... | [
"numpy.log",
"numpy.count_nonzero",
"numpy.array",
"logging.info",
"numpy.arange",
"numpy.histogram",
"argparse.ArgumentParser",
"numpy.where",
"numpy.ma.masked_where",
"matplotlib.pyplot.close",
"numpy.isinf",
"hmmlearn.hmm.GaussianHMM",
"numpy.tile",
"numpy.triu_indices",
"tables.open_... | [((20269, 20344), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s - %(message)s', level=logging.INFO)\n", (20288, 20344), False, 'import logging\n'), ((20354, 20373), 'argparse.ArgumentParser', 'ap.ArgumentParser', ([], {}... |
import numpy as np
a = np.arange(6)
b = a.reshape(2,3)
c = np.arange(24).reshape(2,3,4)
d = np.arange(100).reshape(2, -1)
e = np.arange(100).reshape(-1, 5)
f = np.ravel(c)
g = np.arange(10).reshape(2,-1)
print(a, a.shape)
print(b, b.shape)
print(c, c.shape)
print(d, d.shape)
print(e, e.shape)
print(f, f.shape)
... | [
"numpy.ravel",
"numpy.arange"
] | [((25, 37), 'numpy.arange', 'np.arange', (['(6)'], {}), '(6)\n', (34, 37), True, 'import numpy as np\n'), ((166, 177), 'numpy.ravel', 'np.ravel', (['c'], {}), '(c)\n', (174, 177), True, 'import numpy as np\n'), ((62, 75), 'numpy.arange', 'np.arange', (['(24)'], {}), '(24)\n', (71, 75), True, 'import numpy as np\n'), ((... |
"""Test tilted backpropagation algorithm"""
import numpy as np
import odtbrain
from common_methods import create_test_sino_3d, create_test_sino_3d_tilted, \
cutout, get_test_parameter_set
def test_3d_backprop_phase_real():
sino, angles = create_test_sino_3d()
parameters = get_test_parameter_set(2)
#... | [
"numpy.allclose",
"common_methods.get_test_parameter_set",
"odtbrain.backpropagate_3d_tilted",
"numpy.array",
"numpy.dot",
"common_methods.create_test_sino_3d_tilted",
"common_methods.cutout",
"numpy.cos",
"numpy.sin",
"odtbrain.backpropagate_3d",
"common_methods.create_test_sino_3d"
] | [((250, 271), 'common_methods.create_test_sino_3d', 'create_test_sino_3d', ([], {}), '()\n', (269, 271), False, 'from common_methods import create_test_sino_3d, create_test_sino_3d_tilted, cutout, get_test_parameter_set\n'), ((289, 314), 'common_methods.get_test_parameter_set', 'get_test_parameter_set', (['(2)'], {}), ... |
from torchvision import datasets, transforms
import torch
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np
def load_train_data(dataset_name, batch_size, val_split=0.9, dataset_seed=0, resolution=32):
if dataset_name.lower() == "mnist":
dataset = datasets.MNIST('./data/mnist', tr... | [
"torch.utils.data.sampler.SubsetRandomSampler",
"torchvision.transforms.Grayscale",
"numpy.random.seed",
"torch.utils.data.DataLoader",
"torchvision.transforms.Resize",
"torchvision.transforms.ToTensor",
"numpy.random.shuffle"
] | [((1483, 1511), 'numpy.random.seed', 'np.random.seed', (['dataset_seed'], {}), '(dataset_seed)\n', (1497, 1511), True, 'import numpy as np\n'), ((1516, 1542), 'numpy.random.shuffle', 'np.random.shuffle', (['indices'], {}), '(indices)\n', (1533, 1542), True, 'import numpy as np\n'), ((1690, 1724), 'torch.utils.data.samp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.