code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
"""
rig_hardware.py
Hardware Interface and Mock Layers for Hydration project Rig subsystem.
"""
from abc import ABC, abstractmethod
import configparser
import time, threading
import numpy, serial
import re
from pymodbus.client.sync import ModbusSerialClient
from pymodbus.payload import BinaryPayloadDecoder
from . imp... | [
"threading.Thread.__init__",
"HydrationServo.homing_motor",
"HydrationServo.set_position_unique",
"HydrationServo.set_home",
"HydrationServo.get_torque",
"numpy.abs",
"HydrationServo.clear_alert",
"time.time",
"time.sleep",
"HydrationServo.set_speed_rpm",
"numpy.array",
"HydrationServo.stop_al... | [((343, 370), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (368, 370), False, 'import configparser\n'), ((4443, 4454), 'time.time', 'time.time', ([], {}), '()\n', (4452, 4454), False, 'import time, threading\n'), ((5408, 5419), 'time.time', 'time.time', ([], {}), '()\n', (5417, 5419), Fal... |
from collections import OrderedDict
import pandas as pd
import numpy as np
from datetime import date, timedelta
pd.options.display.float_format = '{:.8f}'.format
def _generate_random_tickers(n_tickers=None):
min_ticker_len = 3
max_ticker_len = 5
tickers = []
if not n_tickers:
n_tickers = np... | [
"pandas.DataFrame",
"datetime.date",
"numpy.isclose",
"numpy.random.randint",
"numpy.array",
"pandas.Series",
"datetime.timedelta",
"collections.OrderedDict"
] | [((468, 528), 'numpy.random.randint', 'np.random.randint', (['min_ticker_len', 'max_ticker_len', 'n_tickers'], {}), '(min_ticker_len, max_ticker_len, n_tickers)\n', (485, 528), True, 'import numpy as np\n'), ((911, 940), 'numpy.random.randint', 'np.random.randint', (['(1999)', '(2017)'], {}), '(1999, 2017)\n', (928, 94... |
import numpy as np
def linear_interpolate(data):
"""
A function to linearly interpolate the data of a signal
"""
nans = np.isnan(data)
x = lambda z: z.nonzero()[0]
data[nans] = np.interp(x(nans), x(~nans), data[~nans])
return data
| [
"numpy.isnan"
] | [((139, 153), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (147, 153), True, 'import numpy as np\n')] |
"""test_compare.py"""
import numpy as np
import impyute as impy
mask = np.zeros((5, 5), dtype=bool)
mask[0][0] = True
data_m = impy.dataset.test_data(mask=mask)
labels = np.array([1, 0, 1, 1, 0])
imputed_mode = []
imputed_mode.append(["mode", (impy.mode(np.copy(data_m)), labels)])
imputed_mode.append(["mean", (impy.me... | [
"numpy.copy",
"numpy.zeros",
"numpy.array",
"impyute.util.compare",
"impyute.dataset.test_data"
] | [((72, 100), 'numpy.zeros', 'np.zeros', (['(5, 5)'], {'dtype': 'bool'}), '((5, 5), dtype=bool)\n', (80, 100), True, 'import numpy as np\n'), ((128, 161), 'impyute.dataset.test_data', 'impy.dataset.test_data', ([], {'mask': 'mask'}), '(mask=mask)\n', (150, 161), True, 'import impyute as impy\n'), ((171, 196), 'numpy.arr... |
# read in the JSON-data from the request and convert them to a scopus query string
# (one could add alternative query targets here, for example transforming the individual query strings to a WoS-Search
import random
import numpy as np
from model.KeywordFrequency import KeywordFrequency
from model.SdgWheel import SdgW... | [
"model.SdgWheel.SdgWheel",
"service.eids_service.load_eid_list",
"random.uniform",
"numpy.empty",
"random.shuffle",
"nltk.corpus.stopwords.words",
"nltk.FreqDist",
"model.KeywordFrequency.KeywordFrequency"
] | [((4789, 4816), 'nltk.FreqDist', 'nltk.FreqDist', (['clean_tokens'], {}), '(clean_tokens)\n', (4802, 4816), False, 'import nltk\n'), ((5421, 5477), 'numpy.empty', 'np.empty', (['(primary_length, primary_length)'], {'dtype': 'object'}), '((primary_length, primary_length), dtype=object)\n', (5429, 5477), True, 'import nu... |
import re
import ujson
from collections import defaultdict, OrderedDict
import numpy as np
from events_classifier import EventClassifier
from max_heap import MaxHeap
from models_manager import Method
from word2vec_wiki_model import Word2VecWikiModel
min_year = 1981
max_year = 2015
all_years = list(range(min_year, ma... | [
"events_classifier.EventClassifier",
"word2vec_wiki_model.Word2VecWikiModel",
"re.escape",
"collections.defaultdict",
"max_heap.MaxHeap",
"numpy.mean",
"numpy.array",
"collections.OrderedDict"
] | [((1084, 1101), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1095, 1101), False, 'from collections import defaultdict, OrderedDict\n'), ((1852, 1865), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1863, 1865), False, 'from collections import defaultdict, OrderedDict\n'), ((3257,... |
import argparse
import cv2
import json
import numpy as np
import torch
from torch.autograd import Function
from torchvision import models
class FeatureExtractor():
""" Class for extracting activations and
registering gradients from targetted intermediate layers """
def __init__(self, model, pre_features,... | [
"numpy.uint8",
"numpy.maximum",
"argparse.ArgumentParser",
"json.load",
"numpy.std",
"numpy.float32",
"numpy.transpose",
"numpy.zeros",
"numpy.clip",
"cv2.imread",
"numpy.max",
"numpy.mean",
"torch.cuda.is_available",
"numpy.min",
"torch.sum",
"cv2.resize",
"torch.from_numpy"
] | [((3346, 3380), 'torch.from_numpy', 'torch.from_numpy', (['preprocessed_img'], {}), '(preprocessed_img)\n', (3362, 3380), False, 'import torch\n'), ((8972, 8997), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (8995, 8997), False, 'import argparse\n'), ((9723, 9741), 'numpy.clip', 'np.clip', ([... |
from __future__ import absolute_import
from ann_benchmarks.algorithms.base import BaseANN
import subprocess
import struct
import subprocess
import sys
import os
import glob
import numpy as np
import random
import string
class Countrymaam(BaseANN):
def __init__(self, metric, params):
self._metric = metric... | [
"os.getpid",
"numpy.ravel",
"random.choices",
"struct.pack",
"numpy.array"
] | [((1919, 1932), 'numpy.array', 'np.array', (['ret'], {}), '(ret)\n', (1927, 1932), True, 'import numpy as np\n'), ((557, 601), 'random.choices', 'random.choices', (['string.ascii_lowercase'], {'k': '(16)'}), '(string.ascii_lowercase, k=16)\n', (571, 601), False, 'import random\n'), ((1532, 1566), 'struct.pack', 'struct... |
"""
Dataset loader for CIFAR100
"""
from copy import deepcopy
import torch
import numpy as np
from torch.utils.data import WeightedRandomSampler
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
def wif(id):
"""
Used to fix randomization bug for pytorch dataloader + numpy
Code... | [
"copy.deepcopy",
"torch.utils.data.DataLoader",
"numpy.random.SeedSequence",
"numpy.array",
"torch.initial_seed"
] | [((400, 420), 'torch.initial_seed', 'torch.initial_seed', ([], {}), '()\n', (418, 420), False, 'import torch\n'), ((521, 560), 'numpy.random.SeedSequence', 'np.random.SeedSequence', (['[id, base_seed]'], {}), '([id, base_seed])\n', (543, 560), True, 'import numpy as np\n'), ((1406, 1522), 'torch.utils.data.DataLoader',... |
from magicgui.widgets import FunctionGui
import napari
import inspect
import numpy as np
from ..utils import image_tuple, label_tuple
from ..._const import SetConst
# TODO: add "apply" button to avoid filtering whole image stack.
RANGES = {"None": (None, None),
"gaussian_filter": (0.2, 30),
"med... | [
"numpy.zeros",
"numpy.percentile",
"numpy.hypot",
"inspect.signature",
"numpy.array"
] | [((3978, 4018), 'inspect.signature', 'inspect.signature', (['self.running_function'], {}), '(self.running_function)\n', (3995, 4018), False, 'import inspect\n'), ((5154, 5191), 'numpy.percentile', 'np.percentile', (['layer.data', 'percentile'], {}), '(layer.data, percentile)\n', (5167, 5191), True, 'import numpy as np\... |
## Running random forests
## Importing packages
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sksurv.ensemble import RandomSurvivalForest
import matplotlib.pyplot as plt
import csv
from sksurv.preprocessing import OneHotEncoder
## Import data and removing variables..... | [
"matplotlib.pyplot.title",
"pandas.DataFrame",
"sksurv.ensemble.RandomSurvivalForest",
"matplotlib.pyplot.show",
"csv.writer",
"pandas.read_csv",
"sksurv.preprocessing.OneHotEncoder",
"numpy.asarray",
"numpy.dtype",
"matplotlib.pyplot.legend",
"numpy.array",
"matplotlib.pyplot.ylabel",
"matp... | [((335, 364), 'pandas.read_csv', 'pd.read_csv', (['"""allimputed.csv"""'], {}), "('allimputed.csv')\n", (346, 364), True, 'import pandas as pd\n'), ((1270, 1315), 'numpy.dtype', 'np.dtype', (["[('fstat', '?'), ('lenfol', '<f8')]"], {}), "([('fstat', '?'), ('lenfol', '<f8')])\n", (1278, 1315), True, 'import numpy as np\... |
#<NAME> UIN 327003625 TAMU 2022
#Numerical Simulations 430
#Hmwk 1 graphing and plotting exat solutions
# -*- coding: utf-8 -*
import sys
import numpy as np
import matplotlib.pyplot as plt
"""
#code for initial finite difference model test, delta x = 1/(2**2) cm
a = np.matrix([[-3,1,-0],[1,-3,1],[0,1,-3]])
a_matrix_i... | [
"numpy.nditer",
"numpy.zeros",
"numpy.linspace",
"numpy.cosh",
"numpy.dot",
"numpy.sinh"
] | [((1531, 1556), 'numpy.zeros', 'np.zeros', (['(2 ** n - 1, 1)'], {}), '((2 ** n - 1, 1))\n', (1539, 1556), True, 'import numpy as np\n'), ((1694, 1736), 'numpy.dot', 'np.dot', (['a_matrix_inverse', 'resultant_matrix'], {}), '(a_matrix_inverse, resultant_matrix)\n', (1700, 1736), True, 'import numpy as np\n'), ((1761, 1... |
import os
from libdvid import DVIDNodeService
import numpy as np
import h5py
server_addres = "slowpoke1:32768"
uuid = "341635bc8c864fa5acbaf4558122c0d5" # "4b178ac089ee443c9f422b02dcd9f2af"
# the dvid server needs to be started before calling this (see readme)
node_service = DVIDNodeService(server_addres, uuid)
de... | [
"h5py.File",
"numpy.array",
"os.path.join",
"numpy.unique",
"libdvid.DVIDNodeService"
] | [((279, 315), 'libdvid.DVIDNodeService', 'DVIDNodeService', (['server_addres', 'uuid'], {}), '(server_addres, uuid)\n', (294, 315), False, 'from libdvid import DVIDNodeService\n'), ((1063, 1112), 'os.path.join', 'os.path.join', (['save_folder', "('%s.h5' % dataset_name)"], {}), "(save_folder, '%s.h5' % dataset_name)\n"... |
"""Individuals."""
from typing import List, Tuple
import math
import numpy as np
import random
# Custom types
Chromosome = List[float]
SearchSpace = Tuple[float, float]
class AB:
"""Approximated Brachistochrone.
Approximated brachistochrones are the individuals that going to be evolving
during the ma... | [
"random.randint",
"numpy.sqrt"
] | [((1646, 1704), 'numpy.sqrt', 'np.sqrt', (['(bin_width ** 2 + (points[i + 1] - points[i]) ** 2)'], {}), '(bin_width ** 2 + (points[i + 1] - points[i]) ** 2)\n', (1653, 1704), True, 'import numpy as np\n'), ((1276, 1310), 'random.randint', 'random.randint', (['*self.search_space'], {}), '(*self.search_space)\n', (1290, ... |
import tensorflow as tf
import numpy as np
from layers.layers import *
from utils import DynamicRunningStat, LimitedRunningStat, RunningStat
import random
eps = 1e-12
class RND:
# Random Network Distillation class
def __init__(self, sess, input_spec, network_spec_target, network_spec_predictor, obs_to_state... | [
"utils.RunningStat",
"tensorflow.compat.v1.losses.mean_squared_error",
"tensorflow.compat.v1.clip_by_global_norm",
"tensorflow.compat.v1.variable_scope",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.train.Saver",
"numpy.clip",
"tensorflow.compat.v1.disable_eager_execution",
"tensorflow.... | [((605, 618), 'utils.RunningStat', 'RunningStat', ([], {}), '()\n', (616, 618), False, 'from utils import DynamicRunningStat, LimitedRunningStat, RunningStat\n'), ((643, 666), 'utils.RunningStat', 'RunningStat', ([], {'shape': '(9269)'}), '(shape=9269)\n', (654, 666), False, 'from utils import DynamicRunningStat, Limit... |
#!/usr/bin/env python
import glob, os, shutil, stat, subprocess, sys
import numpy as np
from os.path import expanduser
HOME = expanduser("~")
CWD = os.getcwd()
import socket
hostname = socket.gethostname()
WRKDIRBASE = (os.path.abspath('..') + '/Simulations/')
if 'lxkb' in hostname:
print ('\n*** LAUNCHING FOR... | [
"os.mkdir",
"os.path.abspath",
"shutil.rmtree",
"os.getcwd",
"subprocess.check_output",
"os.path.exists",
"socket.gethostname",
"subprocess.call",
"numpy.linspace",
"shutil.copytree",
"os.path.expanduser"
] | [((127, 142), 'os.path.expanduser', 'expanduser', (['"""~"""'], {}), "('~')\n", (137, 142), False, 'from os.path import expanduser\n'), ((150, 161), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (159, 161), False, 'import glob, os, shutil, stat, subprocess, sys\n'), ((188, 208), 'socket.gethostname', 'socket.gethostname'... |
"""
generate_plots_memory.py is a Python routine that can be used to generate
the plots of <NAME>, <NAME>, and <NAME>, "Leading-order nonlinear
gravitational waves from reheating magnetogeneses".
It reads the pickle run variables that can be generated by the routine
initialize_memory.py.
The function run() executes ... | [
"matplotlib.pyplot.title",
"cosmoGW.ks_infla",
"matplotlib.pyplot.yscale",
"spectra.plot_neg_pos",
"numpy.logspace",
"numpy.argsort",
"matplotlib.pyplot.figure",
"pta.read_PTA_data",
"dirs.read_dirs",
"matplotlib.pyplot.gca",
"cosmoGW.as_a0_rat",
"matplotlib.pyplot.fill_between",
"matplotlib... | [((538, 552), 'os.chdir', 'os.chdir', (['HOME'], {}), '(HOME)\n', (546, 552), False, 'import os\n'), ((692, 706), 'os.chdir', 'os.chdir', (['dir0'], {}), '(dir0)\n', (700, 706), False, 'import os\n'), ((500, 511), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (509, 511), False, 'import os\n'), ((724, 738), 'os.chdir', 'o... |
"""Utility methods managing inference based on a trained model
"""
import os
import sys
import warnings
from functools import partial
from multiprocessing import Pool, cpu_count
import numpy as np
from scipy import stats, special
import emcee
import matplotlib.pyplot as plt
DEBUG = False
def get_normal_logpdf(mu, ... | [
"numpy.random.seed",
"numpy.sum",
"numpy.empty",
"numpy.isnan",
"numpy.exp",
"scipy.special.logsumexp",
"multiprocessing.cpu_count",
"emcee.backends.HDFBackend",
"matplotlib.pyplot.close",
"os.path.dirname",
"numpy.isfinite",
"numpy.linspace",
"numpy.random.choice",
"matplotlib.pyplot.subp... | [((778, 803), 'numpy.array', 'np.array', (['[mu, log_sigma]'], {}), '([mu, log_sigma])\n', (786, 803), True, 'import numpy as np\n'), ((811, 843), 'numpy.any', 'np.any', (['(candidate < bounds_lower)'], {}), '(candidate < bounds_lower)\n', (817, 843), True, 'import numpy as np\n'), ((1713, 1765), 'emcee.backends.HDFBac... |
import numpy as np
import matplotlib.pyplot as plt
import cv2
import pdb
import argparse
import os
import shutil
# finish the ntu
def getArgs():
parse = argparse.ArgumentParser()
parse.add_argument('--mode', type=str, help='ori or test', default='ori')
parse.add_argument('--data_path', type=str, help='the ... | [
"matplotlib.pyplot.xlim",
"numpy.load",
"argparse.ArgumentParser",
"os.makedirs",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"matplotlib.pyplot.scatter",
"os.path.exists",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.cla",
"numpy.array",
"shutil.rmtree"
... | [((158, 183), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (181, 183), False, 'import argparse\n'), ((951, 984), 'numpy.load', 'np.load', (['data_path'], {'mmap_mode': '"""r"""'}), "(data_path, mmap_mode='r')\n", (958, 984), True, 'import numpy as np\n'), ((1477, 1489), 'matplotlib.pyplot.fig... |
import os, xlrd, numpy as np, tensorflow as tf, matplotlib.pyplot as plt
# opent the xls file for reading
xlsfile = xlrd.open_workbook('fire_theft.xls', encoding_override='utf-8')
# there can be many sheets in xls document
sheet = xlsfile.sheet_by_index(0)
# ask the sheet for each row of data explicitly
data = np.as... | [
"tensorflow.abs",
"matplotlib.pyplot.show",
"tensorflow.subtract",
"tensorflow.summary.scalar",
"matplotlib.pyplot.plot",
"os.getcwd",
"xlrd.open_workbook",
"matplotlib.pyplot.legend",
"tensorflow.Session",
"tensorflow.placeholder",
"tensorflow.multiply",
"tensorflow.Variable",
"numpy.mean",... | [((117, 180), 'xlrd.open_workbook', 'xlrd.open_workbook', (['"""fire_theft.xls"""'], {'encoding_override': '"""utf-8"""'}), "('fire_theft.xls', encoding_override='utf-8')\n", (135, 180), False, 'import os, xlrd, numpy as np, tensorflow as tf, matplotlib.pyplot as plt\n'), ((498, 560), 'tensorflow.placeholder', 'tf.plac... |
from __future__ import absolute_import
import os
import glob
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
class TimeDataset(Dataset):
def __init__(self):
self.seq_dir = 'H:/datasets/OTB100/BlurBody'
self.img_files = sorted(glob.glob(self.seq_dir + '/img/*.jpg')... | [
"torch.utils.data.DataLoader",
"numpy.array",
"numpy.loadtxt",
"glob.glob",
"torch.from_numpy"
] | [((1665, 1726), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'timeDataset', 'batch_size': '(10)', 'shuffle': '(False)'}), '(dataset=timeDataset, batch_size=10, shuffle=False)\n', (1675, 1726), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((342, 430), 'numpy.loadtxt', 'np.loadtxt', (["(... |
#!/user/bin/python
import numpy as np
from matplotlib.pylab import *
import time
# Define Parameters
N = 50 # lattice length
T = 1. # Temperature
J = 2. # Interaction Energy
h = 0.0 # External field, dramatically increases calculation time if not 0
steps = -1 # number of total steps, inf if negative
update_ix = 1000 #... | [
"numpy.random.randint",
"numpy.exp",
"numpy.random.random"
] | [((849, 869), 'numpy.random.randint', 'np.random.randint', (['N'], {}), '(N)\n', (866, 869), True, 'import numpy as np\n'), ((883, 903), 'numpy.random.randint', 'np.random.randint', (['N'], {}), '(N)\n', (900, 903), True, 'import numpy as np\n'), ((552, 597), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(... |
from subprocess import call
import os
from urllib.request import urlretrieve
from keras.preprocessing.image import load_img, img_to_array
import numpy as np
def load_data(model):
img_size = 0
if(model=="Resnet"):
img_size=224
else:
img_size=299
print(img_size)
... | [
"os.path.join",
"keras.preprocessing.image.img_to_array",
"numpy.array",
"os.listdir"
] | [((466, 486), 'os.listdir', 'os.listdir', (['"""Images"""'], {}), "('Images')\n", (476, 486), False, 'import os\n'), ((1039, 1056), 'numpy.array', 'np.array', (['x_train'], {}), '(x_train)\n', (1047, 1056), True, 'import numpy as np\n'), ((1081, 1097), 'numpy.array', 'np.array', (['x_test'], {}), '(x_test)\n', (1089, 1... |
from typing import Any, Protocol, TypeVar, Union, Tuple, Iterator, Optional, Iterable, Callable, overload
import numpy as np
import numpy.typing as npt
from .typing import Arr3i, Index3, Vec3i
SliceOpt = Union[int, slice, None]
def to_slice(s: SliceOpt = None) -> slice:
if isinstance(s, slice):
return ... | [
"numpy.asarray",
"numpy.zeros"
] | [((3303, 3329), 'numpy.asarray', 'np.asarray', (['low'], {'dtype': 'int'}), '(low, dtype=int)\n', (3313, 3329), True, 'import numpy as np\n'), ((3358, 3385), 'numpy.asarray', 'np.asarray', (['high'], {'dtype': 'int'}), '(high, dtype=int)\n', (3368, 3385), True, 'import numpy as np\n'), ((5059, 5127), 'numpy.asarray', '... |
'''
Created on 15 Aug 2013
@author: <NAME>
'''
import math
import textwrap
import tkinter
from tkinter import messagebox
import numpy as np
np.seterr(all="ignore")
from core.isopach import Isopach
from settings import Model
from desktop import helper_functions
from desktop.thread_handlers import ... | [
"desktop.frames.results_frame.ResultsFrame",
"desktop.frames.model_frame.ModelFrame",
"desktop.thread_handlers.ThreadHandler",
"desktop.helper_functions.roundToSF",
"numpy.seterr",
"textwrap.wrap",
"tkinter.messagebox.showerror",
"desktop.frames.isopach_frame.IsopachFrame",
"tkinter.ttk.Style",
"c... | [((155, 178), 'numpy.seterr', 'np.seterr', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (164, 178), True, 'import numpy as np\n'), ((976, 1008), 'tkinter.ttk.Frame.__init__', 'tkinter.ttk.Frame.__init__', (['self'], {}), '(self)\n', (1002, 1008), False, 'import tkinter\n'), ((1069, 1084), 'desktop.thread_handlers... |
"""
Very simple implementation for MNIST training code with Chainer using
Multi Layer Perceptron (MLP) model
This code is to explain the basic of training procedure.
"""
from __future__ import print_function
import time
import os
import numpy as np
import six
import chainer
import chainer.functions as F
import chain... | [
"chainer.optimizers.Adam",
"chainer.functions.softmax_cross_entropy",
"six.moves.range",
"os.makedirs",
"chainer.cuda.get_device",
"os.path.exists",
"time.time",
"numpy.random.permutation",
"chainer.functions.accuracy",
"chainer.datasets.get_mnist",
"chainer.links.Linear"
] | [((2597, 2622), 'chainer.optimizers.Adam', 'chainer.optimizers.Adam', ([], {}), '()\n', (2620, 2622), False, 'import chainer\n'), ((2709, 2737), 'chainer.datasets.get_mnist', 'chainer.datasets.get_mnist', ([], {}), '()\n', (2735, 2737), False, 'import chainer\n'), ((1425, 1454), 'chainer.functions.softmax_cross_entropy... |
# ## Helper classes and functions
import re
import io
from string import digits
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.pyplot import figure
import tensorflow as tf
def preprocess(sentence):
"""
"""
#sentence = unicode_to_ascii(sentence.lowe... | [
"matplotlib.pyplot.title",
"tensorflow.reshape",
"matplotlib.pyplot.figure",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.math.equal",
"tensorflow.cast",
"tensorflow.keras.preprocessing.sequence.pad_sequences",
"io.open",
"matplotlib.ticker.MultipleLocator",
"re.sub",
"ma... | [((428, 455), 're.sub', 're.sub', (['""" +"""', '""" """', 'sentence'], {}), "(' +', ' ', sentence)\n", (434, 455), False, 'import re\n'), ((470, 495), 're.sub', 're.sub', (['"""\'"""', '""""""', 'sentence'], {}), '("\'", \'\', sentence)\n', (476, 495), False, 'import re\n'), ((586, 624), 're.sub', 're.sub', (['"""([?.... |
import pytorch_lightning as pl
import torch
from xmuda.models.modules import Net2DFeat, Net3DFeat, FuseNet
from xmuda.models.LMSCNet import LMSCNet
from xmuda.common.utils.metrics import Metrics
import pickle
import numpy as np
import time
import os.path as osp
class RecNetLMSC(pl.LightningModule):
def __init__(s... | [
"xmuda.models.LMSCNet.LMSCNet",
"xmuda.common.utils.metrics.Metrics",
"pickle.load",
"numpy.array",
"os.path.join"
] | [((402, 649), 'numpy.array', 'np.array', (['[5417730330.0, 15783539.0, 125136.0, 118809.0, 646799.0, 821951.0, 262978.0,\n 283696.0, 204750.0, 61688703.0, 4502961.0, 44883650.0, 2269923.0, \n 56840218.0, 15719652.0, 158442623.0, 2061623.0, 36970522.0, 1151988.0, \n 334146.0]'], {}), '([5417730330.0, 15783539.0... |
import os
from joblib.parallel import Parallel, delayed
import numpy as np
from tqdm import tqdm
from lost_ds.functional.api import (remove_empty,
is_multilabel,
label_selection,
)
from lost_ds.im_util import get_imagesize, ... | [
"numpy.full",
"os.path.join",
"lost_ds.im_util.get_imagesize",
"joblib.parallel.delayed",
"lost_ds.im_util.get_fs",
"lost_ds.functional.api.label_selection",
"lost_ds.geometry.lost_geom.LOSTGeometries",
"joblib.parallel.Parallel",
"lost_ds.functional.api.is_multilabel",
"lost_ds.functional.api.rem... | [((944, 970), 'lost_ds.functional.api.is_multilabel', 'is_multilabel', (['df', 'lbl_col'], {}), '(df, lbl_col)\n', (957, 970), False, 'from lost_ds.functional.api import remove_empty, is_multilabel, label_selection\n'), ((3626, 3644), 'lost_ds.im_util.get_fs', 'get_fs', (['filesystem'], {}), '(filesystem)\n', (3632, 36... |
"""
@author: ludvigolsen
"""
from typing import List, Tuple, Union
import numpy as np
import pandas as pd
from utipy.utils.check_instance import check_instance
from utipy.utils.convert_to_type import convert_to_type
# TODO: Cythonize
def window(x: Union[list, np.ndarray, pd.Series], size: int = 2, gap: int = 1, samp... | [
"utipy.utils.check_instance.check_instance",
"utipy.utils.convert_to_type.convert_to_type",
"numpy.int32"
] | [((1512, 1529), 'utipy.utils.check_instance.check_instance', 'check_instance', (['x'], {}), '(x)\n', (1526, 1529), False, 'from utipy.utils.check_instance import check_instance\n'), ((1538, 1570), 'utipy.utils.convert_to_type.convert_to_type', 'convert_to_type', (['x', '"""np.ndarray"""'], {}), "(x, 'np.ndarray')\n", (... |
import pandas as pd
import numpy as np
import cv2
from skimage import transform as trans
def warping(img, landmark):
'''
Return warped img. Size 112x112
:param np.array img: Full frame image
:param np.array landmark: array with 5 key points coordinates of the face
:return: warped image
:rtyp... | [
"pandas.read_csv",
"cv2.imwrite",
"numpy.zeros",
"skimage.transform.SimilarityTransform",
"cv2.warpAffine",
"cv2.imread",
"numpy.array"
] | [((380, 513), 'numpy.array', 'np.array', (['[[30.2946, 51.6963], [65.5318, 51.5014], [48.0252, 71.7366], [33.5493, \n 92.3655], [62.7299, 92.2041]]'], {'dtype': 'np.float32'}), '([[30.2946, 51.6963], [65.5318, 51.5014], [48.0252, 71.7366], [\n 33.5493, 92.3655], [62.7299, 92.2041]], dtype=np.float32)\n', (388, 51... |
#
# idaho-camera-traps.py
#
# Prepare the Idaho Camera Traps dataset for release on LILA.
#
#%% Imports and constants
import json
import os
import numpy as np
import dateutil
import pandas as pd
import datetime
import shutil
from tqdm import tqdm
from bson import json_util
from collections import defaultdict
# Mu... | [
"pandas.read_csv",
"collections.defaultdict",
"os.path.isfile",
"pathlib.Path",
"visualization.visualize_db.DbVizOptions",
"os.path.join",
"os.path.dirname",
"humanfriendly.format_size",
"datetime.timedelta",
"multiprocessing.pool.Pool",
"shutil.copyfile",
"datetime.datetime.now",
"os.startf... | [((664, 689), 'os.path.isdir', 'os.path.isdir', (['input_base'], {}), '(input_base)\n', (677, 689), False, 'import os\n'), ((697, 723), 'os.path.isdir', 'os.path.isdir', (['output_base'], {}), '(output_base)\n', (710, 723), False, 'import os\n'), ((731, 763), 'os.path.isdir', 'os.path.isdir', (['output_image_base'], {}... |
import logging
from urllib import error, request
import os
import glob
import h5py
import numpy as np
logging.basicConfig(level=logging.INFO)
S_URL_CREATIS_PREFIX = "https://www.creatis.insa-lyon.fr/EvaluationPlatform/picmus/dataset"
pt_exp = os.path.abspath(os.path.dirname(__file__))
TO_PYMUS="/".join(pt_exp.split(... | [
"h5py.File",
"logging.error",
"os.makedirs",
"logging.basicConfig",
"os.path.dirname",
"os.path.exists",
"urllib.request.urlopen",
"logging.info",
"numpy.array",
"glob.glob"
] | [((103, 142), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (122, 142), False, 'import logging\n'), ((262, 287), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (277, 287), False, 'import os\n'), ((440, 470), 'os.path.exists', 'os.path... |
from joblib import Parallel, delayed, parallel_backend
from lshiftml.helpers.helpers import grouper
from copy import deepcopy
import numpy as np
import time
from rascal.representations import SphericalInvariants as SOAP
def get_features(frames,calculator,hypers):
calculatorinstance = calculator(**hypers)
#prin... | [
"joblib.parallel_backend",
"lshiftml.helpers.helpers.grouper",
"joblib.Parallel",
"joblib.delayed",
"numpy.concatenate"
] | [((944, 967), 'numpy.concatenate', 'np.concatenate', (['results'], {}), '(results)\n', (958, 967), True, 'import numpy as np\n'), ((757, 794), 'joblib.parallel_backend', 'parallel_backend', ([], {'backend': '"""threading"""'}), "(backend='threading')\n", (773, 794), False, 'from joblib import Parallel, delayed, paralle... |
import os
import sys
import pickle
import json
import random
import operator
import inspect
import numpy as np
import matplotlib.pyplot as plt
import pylatex as tex
from cycler import cycler
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.ticker as plticker
from scipy.stats import pearsonr
from scipy.stats i... | [
"cycler.cycler",
"numpy.abs",
"numpy.argmin",
"json.dumps",
"matplotlib.pyplot.figure",
"numpy.mean",
"pickle.load",
"numpy.exp",
"matplotlib.pyplot.gca",
"pylatex.utils.escape_latex",
"simulator.plot.Plot",
"os.path.join",
"pylatex.Figure",
"os.path.abspath",
"numpy.zeros_like",
"nump... | [((126276, 126293), 'numpy.asarray', 'np.asarray', (['array'], {}), '(array)\n', (126286, 126293), True, 'import numpy as np\n'), ((1978, 2012), 'os.path.join', 'os.path.join', (['dirname', 'file_prefix'], {}), '(dirname, file_prefix)\n', (1990, 2012), False, 'import os\n'), ((2103, 2128), 'os.listdir', 'os.listdir', (... |
from datetime import datetime, timedelta, timezone
from enum import Enum
import logging
import pickle
from typing import Collection, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
import aiomcache
import numpy as np
import pandas as pd
import sentry_sdk
from sqlalchemy import and_, desc, insert, outer... | [
"athenian.api.models.metadata.github.PushCommit.node_id.in_any_values",
"athenian.api.controllers.miners.github.dag_accelerated.partition_dag",
"athenian.api.models.metadata.github.NodeCommit.acc_id.in_",
"numpy.argsort",
"athenian.api.models.metadata.github.PushCommit.committed_date.between",
"athenian.a... | [((3314, 3376), 'logging.getLogger', 'logging.getLogger', (["('%s.extract_commits' % metadata.__package__)"], {}), "('%s.extract_commits' % metadata.__package__)\n", (3331, 3376), False, 'import logging\n'), ((7429, 7497), 'numpy.in1d', 'np.in1d', (['branch_repos_names', 'default_repos_names'], {'assume_unique': '(True... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import pickle
import numpy as np
import tensorflow as tf
from nnli.parser import SNLI
from nnli import util
from nnli import tfutil
from nnli import embeddings as E
from nnli import evaluation
from nnli.models import ConditionalB... | [
"tensorflow.contrib.layers.xavier_initializer",
"pickle.dump",
"numpy.random.seed",
"argparse.ArgumentParser",
"nnli.generators.InstanceGenerator",
"nnli.util.semi_sort",
"nnli.regularizers.neutral_acl",
"nnli.regularizers.entailment_reflexive_acl",
"tensorflow.variables_initializer",
"nnli.tfutil... | [((648, 677), 'os.path.basename', 'os.path.basename', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (664, 677), False, 'import os\n'), ((1232, 1336), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Regularising RTE/NLI models via Adversarial Training"""'], {'formatter_class': 'fmt'}), "('Regularising RTE/NLI mo... |
import cv2
import numpy as np
print("OpenCV Version:", cv2.__version__)
img = cv2.imread("images/color-paint.jpg")
# Get the size of the image
print(img.shape)
# Define Corners
width, height = 250, 350
pts1 = np.float32([[111,219],[287,188],[152,482],[352,440]])
pts2 = np.float32([[0,0],[width,0],[0,height],[width,... | [
"cv2.warpPerspective",
"cv2.getPerspectiveTransform",
"cv2.waitKey",
"numpy.float32",
"cv2.imread",
"cv2.imshow"
] | [((80, 116), 'cv2.imread', 'cv2.imread', (['"""images/color-paint.jpg"""'], {}), "('images/color-paint.jpg')\n", (90, 116), False, 'import cv2\n'), ((213, 273), 'numpy.float32', 'np.float32', (['[[111, 219], [287, 188], [152, 482], [352, 440]]'], {}), '([[111, 219], [287, 188], [152, 482], [352, 440]])\n', (223, 273), ... |
import argparse
import h5py
import numpy as np
import grsn
def load_all_data(input_hdf):
print("Loading data: ", args.input_hdf)
with h5py.File(args.input_hdf, "r") as f_in:
ctypes = [k for k in f_in.keys() if k != "index"]
patients_ls = [f_in[ct]['columns'][:] for ct in ctypes]
... | [
"h5py.File",
"argparse.ArgumentParser",
"grsn.grsn",
"numpy.empty",
"h5py.string_dtype"
] | [((1752, 1777), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1775, 1777), False, 'import argparse\n'), ((2253, 2299), 'grsn.grsn', 'grsn.grsn', (['arr', 'args.set_size', 'args.iterations'], {}), '(arr, args.set_size, args.iterations)\n', (2262, 2299), False, 'import grsn\n'), ((146, 176), 'h... |
# Based on the code from: https://github.com/tkipf/keras-gcn
import tensorflow as tf
from tensorflow.keras import activations, initializers, constraints
from tensorflow.keras import regularizers
import tensorflow.keras.backend as K
import scipy.sparse as sp
import numpy as np
import pickle, copy
class GCN(tf.keras.Mo... | [
"pickle.dump",
"tensorflow.sparse.retain",
"tensorflow.keras.losses.CategoricalCrossentropy",
"tensorflow.floor",
"tensorflow.matmul",
"numpy.arange",
"pickle.load",
"tensorflow.keras.regularizers.serialize",
"tensorflow.keras.initializers.get",
"scipy.sparse.eye",
"tensorflow.keras.regularizers... | [((14074, 14107), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'lr': '(0.01)'}), '(lr=0.01)\n', (14098, 14107), True, 'import tensorflow as tf\n'), ((14208, 14266), 'tensorflow.keras.losses.CategoricalCrossentropy', 'tf.keras.losses.CategoricalCrossentropy', ([], {'from_logits': '(False)'}), '(... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
from pandas_datareader import data as pdr
# Import our data
def get_stock(stocks, start, end):
stockdata = pdr.get_data_yahoo(stocks, start, end)
stockdata = stockdata['Close']
returns = stockdata.pct_change()
... | [
"numpy.full",
"matplotlib.pyplot.title",
"pandas_datareader.data.get_data_yahoo",
"numpy.sum",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"datetime.timedelta",
"numpy.inner",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"datetime.datetime.now",
"numpy.linalg.cholesky"
] | [((535, 552), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (550, 552), True, 'import datetime as dt\n'), ((761, 776), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (767, 776), True, 'import numpy as np\n'), ((985, 1028), 'numpy.full', 'np.full', ([], {'shape': '(T, mc_sims)', 'fill_value': '... |
import sys
import time
import math
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import torchvision as vsn
#from apex.fp16_utils import FP16_Optimizer
from mod... | [
"sys.stdout.write",
"utils.evaluations.DiceLoss",
"argparse.ArgumentParser",
"numpy.mean",
"torch.no_grad",
"pandas.DataFrame",
"torch.load",
"torch.cuda.set_device",
"utils.evaluations.FocalLoss2d",
"utils.evaluations.ConsistencyLoss",
"torch.nn.BCEWithLogitsLoss",
"torchvision.utils.save_ima... | [((566, 613), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""TGS Salt"""'}), "(description='TGS Salt')\n", (589, 613), False, 'import argparse\n'), ((3831, 3844), 'utils.evaluations.FocalLoss2d', 'FocalLoss2d', ([], {}), '()\n', (3842, 3844), False, 'from utils.evaluations import FocalLo... |
import numpy as np
import xlsxwriter
import tableprint
from random import randint
import xlrd
import matplotlib.pyplot as plt
from num2words import num2words
import sys
import itertools
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
plt.rcParams.update({'font.size':7})
... | [
"matplotlib.pyplot.title",
"tableprint.table",
"itertools.cycle",
"matplotlib.pyplot.tight_layout",
"warnings.simplefilter",
"numpy.power",
"numpy.max",
"matplotlib.pyplot.rcParams.update",
"num2words.num2words",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend... | [((282, 319), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 7}"], {}), "({'font.size': 7})\n", (301, 319), True, 'import matplotlib.pyplot as plt\n'), ((247, 278), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (268, 278), False, 'import warnings... |
import numpy as np #Numpy maths
def XYZ_equatorial(X, Y, Z, X_error=None, Y_error=None, Z_error=None):
"""
Transforms Galactic position XYZ to equatorial coordinates (ra,dec) and distance. All inputs must be numpy arrays of the same dimension.
param X: Galactic position X toward Galactic center (parsec)
param Y:... | [
"numpy.size",
"numpy.arctan2",
"numpy.SQRT",
"numpy.sqrt"
] | [((935, 945), 'numpy.size', 'np.size', (['X'], {}), '(X)\n', (942, 945), True, 'import numpy as np\n'), ((1392, 1425), 'numpy.SQRT', 'np.SQRT', (['(X ** 2 + Y ** 2 + Z ** 2)'], {}), '(X ** 2 + Y ** 2 + Z ** 2)\n', (1399, 1425), True, 'import numpy as np\n'), ((1499, 1523), 'numpy.sqrt', 'np.sqrt', (['(X ** 2 + Y ** 2)'... |
# -*- coding: utf-8 -*-
import sys
sys.path.insert(0, '../../')
import numpy as np
import pandas as pd
import mut.thermo
import mut.bayes
import mut.stats
import joblib
import multiprocessing as mp
cpus = mp.cpu_count() - 2
import tqdm
constants = mut.thermo.load_constants()
# Load the prior predictive check data.
pr... | [
"pandas.DataFrame",
"numpy.sum",
"numpy.argmax",
"pandas.read_csv",
"numpy.median",
"numpy.std",
"sys.path.insert",
"numpy.mean",
"joblib.Parallel",
"joblib.delayed",
"numpy.var",
"pandas.concat",
"multiprocessing.cpu_count"
] | [((35, 63), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../../"""'], {}), "(0, '../../')\n", (50, 63), False, 'import sys\n'), ((331, 398), 'pandas.read_csv', 'pd.read_csv', (['"""../../data/Chure2019_IND_prior_predictive_checks.csv"""'], {}), "('../../data/Chure2019_IND_prior_predictive_checks.csv')\n", (342, 3... |
#!/usr/bin/env python
__author__ = "XXX"
__email__ = "XXX"
import logging
import math
import numpy as np
import pandas as pd
from constants import *
log = logging.getLogger(__name__)
def _split_pandas_data_with_ratios(data, ratios, seed=SEED, shuffle=False):
"""Helper function to split pandas DataFrame with g... | [
"logging.warning",
"math.fsum",
"numpy.cumsum",
"pandas.concat",
"logging.getLogger"
] | [((159, 186), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (176, 186), False, 'import logging\n'), ((2893, 2910), 'pandas.concat', 'pd.concat', (['splits'], {}), '(splits)\n', (2902, 2910), True, 'import pandas as pd\n'), ((4050, 4066), 'pandas.concat', 'pd.concat', (['train'], {}), '(t... |
import numpy as np
import pandangas as pg
import pandangas.simulation as sim
import pandangas.topology as top
import pytest
import fluids
from thermo.chemical import Chemical
from tests.test_core import fix_create
def test_scaled_loads(fix_create):
net = fix_create
assert sim._scaled_loads_as_dict(net) == ... | [
"pandangas.simulation._run_sim",
"pandangas.create_pipe",
"pandangas.simulation._p_min_loads_as_dict",
"pandangas.simulation._dp_from_m_dot_vec",
"fluids.nearest_material_roughness",
"pandangas.simulation._scaled_loads_as_dict",
"fluids.material_roughness",
"pandangas.create_empty_network",
"pytest.... | [((1584, 1600), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1598, 1600), False, 'import pytest\n'), ((735, 748), 'pandangas.simulation._i_mat', 'sim._i_mat', (['g'], {}), '(g)\n', (745, 748), True, 'import pandangas.simulation as sim\n'), ((799, 863), 'numpy.array', 'np.array', (['[[1.0, 0.0, 1.0], [-1.0, -1... |
# Copyright 2016-2020 <NAME>. See also the LICENSE file.
import numpy as np
class SphericalLinearPreferenceModel:
def __init__(self, shape=512, rng=None):
"""
Create model object.
:param shape: shape of the vector to learn the preference from.
"""
self._rng = rng or np.ran... | [
"numpy.full",
"numpy.cumprod",
"numpy.flip",
"numpy.expand_dims",
"numpy.errstate",
"numpy.random.RandomState",
"numpy.ones",
"numpy.cumsum",
"numpy.sin",
"numpy.array",
"numpy.cos",
"numpy.arccos",
"numpy.concatenate"
] | [((3925, 3966), 'numpy.full', 'np.full', (['ones_shape', '(1.0)'], {'dtype': 'phi.dtype'}), '(ones_shape, 1.0, dtype=phi.dtype)\n', (3932, 3966), True, 'import numpy as np\n'), ((3980, 3991), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (3986, 3991), True, 'import numpy as np\n'), ((4042, 4071), 'numpy.cumprod', 'n... |
"""Test the surface_io module."""
from collections import OrderedDict
import shutil
import logging
import pytest
import json
import numpy as np
import xtgeo
import yaml
import fmu.dataio
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
CFG = OrderedDict()
CFG["model"] = {"name": "Test", "revision"... | [
"pytest.warns",
"json.dumps",
"yaml.safe_load",
"numpy.ma.ones",
"collections.OrderedDict",
"shutil.copytree",
"logging.getLogger"
] | [((198, 225), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (215, 225), False, 'import logging\n'), ((264, 277), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (275, 277), False, 'from collections import OrderedDict\n'), ((668, 690), 'yaml.safe_load', 'yaml.safe_load', (['st... |
# Carregar o dataset MNIST
# Obs: Este script é baseado na versão do livro http://neuralnetworksanddeeplearning.com/, com a devida autorização do autor.
# Imports
import pickle
import gzip
import numpy as np
def load_data():
f = gzip.open('../data/processed/mnist.pkl.gz', 'rb')
training_data, validation_data... | [
"numpy.zeros",
"pickle.load",
"gzip.open",
"numpy.reshape"
] | [((236, 285), 'gzip.open', 'gzip.open', (['"""../data/processed/mnist.pkl.gz"""', '"""rb"""'], {}), "('../data/processed/mnist.pkl.gz', 'rb')\n", (245, 285), False, 'import gzip\n'), ((334, 367), 'pickle.load', 'pickle.load', (['f'], {'encoding': '"""latin1"""'}), "(f, encoding='latin1')\n", (345, 367), False, 'import ... |
import pickle
import os
import pandas as pd
from datetime import datetime as dt
import numpy as np
from VaccineAllocation import load_config_file,config_path
from reporting.plotting import plot_multi_tier_sims
from reporting.report_pdf import generate_report
from reporting.output_processors import build_report
from pip... | [
"pipelinemultitier.read_hosp",
"numpy.sum",
"csv.writer",
"numpy.median",
"numpy.std",
"datetime.datetime",
"numpy.percentile",
"numpy.max",
"numpy.mean",
"numpy.array",
"pickle.load",
"numpy.where",
"numpy.round",
"os.listdir",
"numpy.unique"
] | [((5023, 5043), 'os.listdir', 'os.listdir', (['"""output"""'], {}), "('output')\n", (5033, 5043), False, 'import os\n'), ((5153, 5168), 'datetime.datetime', 'dt', (['(2020)', '(2)', '(28)'], {}), '(2020, 2, 28)\n', (5155, 5168), True, 'from datetime import datetime as dt\n'), ((5179, 5211), 'pipelinemultitier.read_hosp... |
#!/usr/bin/env python
import numpy as np
import pickle
import rospy
import sys
from sensor_stick.pcl_helper import *
from sensor_stick.training_helper import spawn_model
from sensor_stick.training_helper import delete_model
from sensor_stick.training_helper import initial_setup
from sensor_stick.training_helper import... | [
"sensor_stick.features.compute_normal_histograms",
"sensor_stick.training_helper.spawn_model",
"sensor_stick.features.compute_color_histograms",
"sensor_stick.training_helper.initial_setup",
"rospy.ServiceProxy",
"rospy.init_node",
"sensor_stick.training_helper.delete_model",
"sensor_stick.training_he... | [((619, 683), 'rospy.ServiceProxy', 'rospy.ServiceProxy', (['"""/feature_extractor/get_normals"""', 'GetNormals'], {}), "('/feature_extractor/get_normals', GetNormals)\n", (637, 683), False, 'import rospy\n'), ((760, 791), 'rospy.init_node', 'rospy.init_node', (['"""capture_node"""'], {}), "('capture_node')\n", (775, 7... |
"""This submodule contains the DSLRImage class and its Monochrome subclass.
The DSLRImage class serves the purpose of containing all needed information
for a frame, as well as the methods for binning, extracting monochrome
channels, and writing the file to FITS format.
"""
import os
from enum import IntEnum
from fract... | [
"matplotlib.pyplot.show",
"os.makedirs",
"numpy.log",
"matplotlib.pyplot.axes",
"photutils.CircularAperture",
"os.path.dirname",
"photutils.centroids.fit_2dgaussian",
"numpy.zeros",
"astropy.time.Time",
"datetime.datetime",
"photutils.CircularAnnulus",
"rawkit.raw.Raw",
"matplotlib.pyplot.fi... | [((1983, 2010), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {'dtype': 'int'}), '((4, 4), dtype=int)\n', (1991, 2010), True, 'import numpy as np\n'), ((1591, 1597), 'rawkit.raw.Raw', 'Raw', (['f'], {}), '(f)\n', (1594, 1597), False, 'from rawkit.raw import Raw\n'), ((11521, 11555), 'numpy.mean', 'np.mean', (['[s.r for s in ... |
import cv2
import numpy as np
import random
import torch
import imgaug as ia
import imgaug.augmenters as iaa
import copy
# points = [
# [(10.5, 20.5)], # points on first image
# [(50.5, 50.5), (60.5, 60.5), (70.5, 70.5)] # points on second image
# ]
# image = cv2.imread('000000472375.jpg')
# inp_bbox = [np.arr... | [
"imgaug.augmenters.AverageBlur",
"imgaug.augmenters.MedianBlur",
"imgaug.augmenters.LinearContrast",
"imgaug.augmenters.Sometimes",
"imgaug.augmenters.Superpixels",
"random.random",
"imgaug.augmenters.PerspectiveTransform",
"imgaug.augmenters.Grayscale",
"numpy.array",
"imgaug.augmenters.Add",
"... | [((1194, 1209), 'random.random', 'random.random', ([], {}), '()\n', (1207, 1209), False, 'import random\n'), ((1888, 1911), 'imgaug.augmenters.Sometimes', 'iaa.Sometimes', (['(0.5)', 'aug'], {}), '(0.5, aug)\n', (1901, 1911), True, 'import imgaug.augmenters as iaa\n'), ((1558, 1575), 'numpy.array', 'np.array', (['[imag... |
"""
%%
%% function ubezier(TRI,X,Y,Z,XP,YP,ZP,pchar,color)
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% Tracé d'une surface de Bézier et de ses points de contrôle
%%
%% Données : TRI liste des facettes triangulaires de la surface
%% Données : X, Y, Z coordonnées des ... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.cm.get_cmap",
"numpy.shape",
"matplotlib.pyplot.figure"
] | [((1133, 1145), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1143, 1145), True, 'import matplotlib.pyplot as plt\n'), ((1439, 1452), 'numpy.shape', 'np.shape', (['XP1'], {}), '(XP1)\n', (1447, 1452), True, 'import numpy as np\n'), ((1483, 1496), 'numpy.shape', 'np.shape', (['XP2'], {}), '(XP2)\n', (1491... |
import os
import cv2
import shutil
import numpy as np
import subprocess as sp
from imageio import imread
from typing import Any, Dict, List, Optional, Tuple
class CameraIntrinsicsHelper():
def __init__(self):
self.blurry_thresh = 100.0
self.sfm_workspace_dir = 'data/debug_sfm/'
self.sfm_i... | [
"numpy.sum",
"numpy.argmax",
"cv2.cvtColor",
"subprocess.check_output",
"numpy.split",
"numpy.nonzero",
"numpy.diff",
"numpy.array",
"os.path.join",
"os.listdir",
"numpy.all",
"cv2.Laplacian"
] | [((424, 463), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2GRAY'], {}), '(image, cv2.COLOR_RGB2GRAY)\n', (436, 463), False, 'import cv2\n'), ((1363, 1389), 'numpy.array', 'np.array', (['blurry_indicator'], {}), '(blurry_indicator)\n', (1371, 1389), True, 'import numpy as np\n'), ((1465, 1490), 'numpy.diff'... |
import pytest
import numpy as np
import pyEMA
def test_complex_freq_to_freq_and_damp():
f = 13
x = 0.00324
fc = -x*2*np.pi*f + 1j*2*np.pi*f * np.sqrt(1-x**2)
f_, x_ = pyEMA.complex_freq_to_freq_and_damp(fc)
np.testing.assert_almost_equal(f, f_, 5)
np.testing.assert_almost_equal(x, x_, 5) | [
"pyEMA.complex_freq_to_freq_and_damp",
"numpy.sqrt",
"numpy.testing.assert_almost_equal"
] | [((187, 226), 'pyEMA.complex_freq_to_freq_and_damp', 'pyEMA.complex_freq_to_freq_and_damp', (['fc'], {}), '(fc)\n', (222, 226), False, 'import pyEMA\n'), ((232, 272), 'numpy.testing.assert_almost_equal', 'np.testing.assert_almost_equal', (['f', 'f_', '(5)'], {}), '(f, f_, 5)\n', (262, 272), True, 'import numpy as np\n'... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 21 15:21:59 2020
@author: Reuben
"""
import unittest
import numpy as np
import npsolve.soft_functions as soft
class Test_lim_scalar(unittest.TestCase):
def setUp(self):
self.vals = [-1000, 2.5, 3.5, 1000]
self.limit = 3.0
def test_m100... | [
"npsolve.soft_functions.within",
"npsolve.soft_functions.clip",
"npsolve.soft_functions.floor",
"npsolve.soft_functions.lim",
"npsolve.soft_functions.negdiff",
"npsolve.soft_functions.posdiff",
"npsolve.soft_functions.outside",
"npsolve.soft_functions.gaussian",
"npsolve.soft_functions.step",
"num... | [((349, 404), 'npsolve.soft_functions.lim', 'soft.lim', (['self.vals[0]', 'self.limit'], {'side': '(1)', 'scale': '(0.001)'}), '(self.vals[0], self.limit, side=1, scale=0.001)\n', (357, 404), True, 'import npsolve.soft_functions as soft\n'), ((499, 554), 'npsolve.soft_functions.lim', 'soft.lim', (['self.vals[1]', 'self... |
import sys
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os
import numpy as np
from PIL import Image
import img2vid as i2v
import glob
import yt
sys.path.append("/home/fionnlagh/forked_amrvac/amrvac/tools/python")
#from amrvac_pytools.datfiles.reading import amrvac_reader
#from amrvac_pytool... | [
"sys.path.append",
"amrvac_pytools.load_datfile",
"numpy.zeros",
"yt.SlicePlot",
"numpy.array",
"yt.load_uniform_grid"
] | [((172, 240), 'sys.path.append', 'sys.path.append', (['"""/home/fionnlagh/forked_amrvac/amrvac/tools/python"""'], {}), "('/home/fionnlagh/forked_amrvac/amrvac/tools/python')\n", (187, 240), False, 'import sys\n'), ((637, 677), 'amrvac_pytools.load_datfile', 'apt.load_datfile', (["(Full_path + '0020.dat')"], {}), "(Full... |
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from deepneuro.utilities.conversion import read_image_files
def create_mosaic(input_volume, output_filepath=None, label_volume=None, generate_outline=True, mask_value=0, step=1, dim=2, cols=8, label_buffer=5, rotate_90=3, flip=True):
"... | [
"numpy.sum",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.margins",
"matplotlib.pyplot.figure",
"numpy.rot90",
"numpy.arange",
"matplotlib.pyplot.gca",
"numpy.unique",
"numpy.zeros_like",
"deepneuro.utilities.conversion.read_image_files",
"numpy.copy",
"matplotlib.pyplot.imshow",
"matplotlib.... | [((2032, 2062), 'deepneuro.utilities.conversion.read_image_files', 'read_image_files', (['input_volume'], {}), '(input_volume)\n', (2048, 2062), False, 'from deepneuro.utilities.conversion import read_image_files\n'), ((8689, 8721), 'numpy.zeros', 'np.zeros', (['(3, 3, 3)'], {'dtype': 'float'}), '((3, 3, 3), dtype=floa... |
import pickle, sys, time
import numpy as np
from scipy.special import logsumexp
def add_block(b,envelope):
'''
Add single block to row-based envelope
'''
(sx,sy,ex,ey) = b
for i in range(sx,ex):
this_min = sy
this_max = ey
if i < len(envelope):
if this_min < enve... | [
"numpy.zeros",
"numpy.concatenate",
"numpy.copy"
] | [((3152, 3181), 'numpy.copy', 'np.copy', (['full_envelope[u1:u2]'], {}), '(full_envelope[u1:u2])\n', (3159, 3181), True, 'import numpy as np\n'), ((3370, 3426), 'numpy.concatenate', 'np.concatenate', (['(envelope, [envelope[-1], envelope[-1]])'], {}), '((envelope, [envelope[-1], envelope[-1]]))\n', (3384, 3426), True, ... |
from amuse.test.amusetest import TestWithMPI
import os
import sys
import numpy
import math
from amuse.community.phantom.interface import PhantomInterface, Phantom
from amuse.datamodel import Particles
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.ic import p... | [
"amuse.community.phantom.interface.Phantom",
"numpy.arange",
"amuse.datamodel.Particles"
] | [((3984, 3993), 'amuse.community.phantom.interface.Phantom', 'Phantom', ([], {}), '()\n', (3991, 3993), False, 'from amuse.community.phantom.interface import PhantomInterface, Phantom\n'), ((4100, 4109), 'amuse.community.phantom.interface.Phantom', 'Phantom', ([], {}), '()\n', (4107, 4109), False, 'from amuse.community... |
import tensorflow as tf
from tensorflow.python.ops.rnn_cell import LSTMStateTuple
from memory import Memory
import utility
import os
import numpy as np
class Dual_DNC:
def __init__(self, controller_class, input_size1, input_size2, output_size,
memory_words_num = 256, memory_word_size = 64, memory... | [
"tensorflow.cond",
"tensorflow.slice",
"tensorflow.reduce_sum",
"tensorflow.clip_by_value",
"tensorflow.trainable_variables",
"tensorflow.reshape",
"numpy.ones",
"tensorflow.train.AdamOptimizer",
"tensorflow.matmul",
"numpy.exp",
"tensorflow.split",
"os.path.join",
"memory.Memory",
"utilit... | [((2047, 2093), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""decoder_point"""'}), "(tf.int32, name='decoder_point')\n", (2061, 2093), True, 'import tensorflow as tf\n'), ((2124, 2170), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""encode1_point"""'}), "(tf.int32, nam... |
import matplotlib as plt
plt.use('agg')
import sys
import numpy as np
import ngene as ng
import pylab as plt
import ccgpack as ccg
from glob import glob
import tensorflow as tf
from random import choice,shuffle
from matplotlib.colors import LogNorm
#print( ' *cnn* : cnn without any dropout , with kernel size = 5, fi... | [
"numpy.load",
"numpy.log",
"tensorflow.contrib.layers.flatten",
"random.shuffle",
"tensorflow.layers.dense",
"ccgpack.filters",
"random.choice",
"numpy.expand_dims",
"tensorflow.layers.average_pooling2d",
"numpy.random.randint",
"pylab.use",
"numpy.array",
"tensorflow.layers.conv2d",
"glob... | [((25, 39), 'pylab.use', 'plt.use', (['"""agg"""'], {}), "('agg')\n", (32, 39), True, 'import pylab as plt\n'), ((5376, 5431), 'ngene.Model', 'ng.Model', (['dp'], {'restore': '(1)', 'model_add': 'model_add', 'arch': 'arch'}), '(dp, restore=1, model_add=model_add, arch=arch)\n', (5384, 5431), True, 'import ngene as ng\n... |
#import json
#import os
#import random
import numpy as np
from Snake import Snake
from Board import Board
class Direction():
"""class providing outcomes of any given direction our snake may travel in """
def __init__(self, vectorI, vectorJ, boardData):
self.i=vectorI
self.j... | [
"numpy.mean",
"Snake.Snake",
"Board.Board"
] | [((345, 361), 'Snake.Snake', 'Snake', (['boardData'], {}), '(boardData)\n', (350, 361), False, 'from Snake import Snake\n'), ((378, 394), 'Board.Board', 'Board', (['boardData'], {}), '(boardData)\n', (383, 394), False, 'from Board import Board\n'), ((3735, 3750), 'numpy.mean', 'np.mean', (['nTurns'], {}), '(nTurns)\n',... |
# to come
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def _plotResult(test_predictions, label_data):
plt.figure(figsize=(20, 15), dpi=60)
MEDIUM_SIZE = 10
BIGGER_SIZE = 14
plt.rc('font', size=MEDIUM_SIZE)
plt.rc('axes', titlesize=BIGGER_SIZE)
plt.rc(... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"numpy.load",
"matplotlib.pyplot.show",
"tensorflow.keras.models.load_model",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.rc",
"numpy.linspace",
"matplotli... | [((137, 173), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 15)', 'dpi': '(60)'}), '(figsize=(20, 15), dpi=60)\n', (147, 173), True, 'import matplotlib.pyplot as plt\n'), ((221, 253), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': 'MEDIUM_SIZE'}), "('font', size=MEDIUM_SIZE)\n", (227, 25... |
from IMLearn.learners import UnivariateGaussian, MultivariateGaussian
import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
import plotly.express as px
pio.templates.default = "simple_white"
# for some reason that's the only way i get it to display
# pio.renderers.default = "svg"
# ... | [
"IMLearn.learners.UnivariateGaussian",
"numpy.set_printoptions",
"numpy.random.seed",
"numpy.abs",
"numpy.argmax",
"numpy.zeros",
"IMLearn.learners.MultivariateGaussian",
"numpy.amax",
"numpy.random.multivariate_normal",
"numpy.array",
"numpy.random.normal",
"numpy.linspace",
"plotly.express... | [((363, 395), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)'}), '(precision=3)\n', (382, 395), True, 'import numpy as np\n'), ((506, 550), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(10)', 'scale': '(1)', 'size': '(1000)'}), '(loc=10, scale=1, size=1000)\n', (522, 550), True, 'i... |
# -*- coding: utf-8 -*-
# test_simulateSNR.py
# This module provides the tests for the simulateSNR function.
# Copyright 2014 <NAME>
# This file is part of python-deltasigma.
#
# python-deltasigma is a 1:1 Python replacement of Richard Schreier's
# MATLAB delta sigma toolbox (aka "delsigma"), upon which it is heavily ... | [
"deltasigma.realizeNTF",
"deltasigma.simulateSNR",
"deltasigma.mapABCD",
"numpy.allclose",
"pkg_resources.resource_filename",
"deltasigma.stuffABCD",
"numpy.array",
"deltasigma.synthesizeNTF",
"numpy.exp",
"deltasigma.realizeQNTF",
"numpy.linspace",
"deltasigma.synthesizeQNTF",
"scipy.signal... | [((1146, 1217), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""test_data/test_snr_amp.mat"""'], {}), "(__name__, 'test_data/test_snr_amp.mat')\n", (1177, 1217), False, 'import pkg_resources\n'), ((1671, 1712), 'deltasigma.synthesizeNTF', 'ds.synthesizeNTF', (['order', 'osr', '(2... |
import numpy as np
from skimage.transform import resize
from segmentation_net.tf_record import _bytes_feature, _int64_feature
# from Preprocessing.Normalization import PrepNormalizer
from useful_wsi import get_image
def generate_unet_possible(i):
"""
I was a bit lazy and instead of deriving the formula, I ... | [
"skimage.transform.resize",
"numpy.array",
"useful_wsi.get_image"
] | [((2295, 2319), 'useful_wsi.get_image', 'get_image', (['slide', 'inputs'], {}), '(slide, inputs)\n', (2304, 2319), False, 'from useful_wsi import get_image\n'), ((2336, 2351), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (2344, 2351), True, 'import numpy as np\n'), ((3273, 3331), 'skimage.transform.resize',... |
import os
import time
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
# import the training utilities
from model_utils import load_data_set, train
# define the methods
methods = {'Kumaraswamy', 'Nalisnick', 'Dirichlet', 'Softmax', 'KingmaM2'}
# specify if you want to save plots (other... | [
"os.mkdir",
"numpy.random.seed",
"argparse.ArgumentParser",
"os.getcwd",
"tensorflow.reset_default_graph",
"model_utils.load_data_set",
"matplotlib.pyplot.close",
"os.path.exists",
"model_utils.train",
"time.time",
"os.path.join",
"tensorflow.random.set_random_seed"
] | [((1503, 1528), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1526, 1528), False, 'import argparse\n'), ((2388, 2399), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2397, 2399), False, 'import os\n'), ((2445, 2472), 'os.path.exists', 'os.path.exists', (['dir_results'], {}), '(dir_results)\n', ... |
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.style as style
def autolabel(rects, plot_axes):
"""
Attach a text label above each bar displaying its width
"""
totals = []
for i in rects:
totals.append(i.get_width())
total = sum(totals)
for rect in rects[:-1]:
... | [
"math.exp",
"matplotlib.style.use",
"pandas.read_csv",
"numpy.log2",
"matplotlib.pyplot.subplots"
] | [((1353, 1393), 'matplotlib.style.use', 'style.use', (["['ggplot', 'fivethirtyeight']"], {}), "(['ggplot', 'fivethirtyeight'])\n", (1362, 1393), True, 'import matplotlib.style as style\n'), ((1461, 1507), 'pandas.read_csv', 'pd.read_csv', (['"""../docker_reports/Code2flow.csv"""'], {}), "('../docker_reports/Code2flow.c... |
import numpy as np
import scipy as sp
def lqr_inf(Fm, fv, Cm, cv, discount=0.99, K=100):
"""
Infinite Horizon LQR
"""
K, k, Vxx, Vx, Qtt, Qt = lqr_fin(K, Fm, fv, Cm, cv, discount=discount)
return K[0], k[0], Vxx[0], Vx[0], Qtt[0], Qt[0]
def lqr_fin(T, Fm, fv, Cm, cv, discount=1.0):
"""
Di... | [
"scipy.linalg.cholesky",
"numpy.zeros",
"scipy.linalg.solve_triangular"
] | [((1322, 1343), 'numpy.zeros', 'np.zeros', (['(T, dX, dX)'], {}), '((T, dX, dX))\n', (1330, 1343), True, 'import numpy as np\n'), ((1353, 1370), 'numpy.zeros', 'np.zeros', (['(T, dX)'], {}), '((T, dX))\n', (1361, 1370), True, 'import numpy as np\n'), ((1381, 1412), 'numpy.zeros', 'np.zeros', (['(T, dX + dU, dX + dU)'],... |
import numpy as np
import torch
import logging
import pickle
from dataclasses import dataclass, field
from typing import List, Optional
from skimage.filters import threshold_otsu
from cellmincer.opto_utils import crop_center
logger = logging.getLogger()
@dataclass
class PaddedMovieTorch:
t_padding: int
x_p... | [
"numpy.pad",
"torch.mean",
"torch.median",
"skimage.filters.threshold_otsu",
"numpy.std",
"numpy.ones",
"logging.getLogger",
"dataclasses.field",
"numpy.mean",
"torch.std",
"torch.device",
"torch.zeros",
"torch.tensor"
] | [((237, 256), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (254, 256), False, 'import logging\n'), ((725, 752), 'dataclasses.field', 'field', ([], {'default_factory': 'list'}), '(default_factory=list)\n', (730, 752), False, 'from dataclasses import dataclass, field\n'), ((789, 816), 'dataclasses.field', ... |
import logging
import sys
from os.path import join, exists
from typing import Union, Optional, Dict, Any, List
from dataclasses import dataclass, replace
import numpy as np
from gpv2 import file_paths
from gpv2.data.dataset import Dataset, WebQaExample
from gpv2.model.model import PredictionArg
from gpv2.utils.py_ut... | [
"gpv2.data.dataset.Dataset.register",
"gpv2.utils.py_utils.int_to_str",
"gpv2.utils.py_utils.load_json_object",
"gpv2.model.model.PredictionArg.register",
"os.path.exists",
"numpy.random.RandomState",
"logging.info",
"gpv2.utils.py_utils.dump_json_object",
"os.path.join",
"dataclasses.replace",
... | [((381, 420), 'gpv2.model.model.PredictionArg.register', 'PredictionArg.register', (['"""webqa-answers"""'], {}), "('webqa-answers')\n", (403, 420), False, 'from gpv2.model.model import PredictionArg\n'), ((1037, 1062), 'gpv2.data.dataset.Dataset.register', 'Dataset.register', (['"""webqa"""'], {}), "('webqa')\n", (105... |
import json
from pathlib import Path
import numpy as np
import pandas as pd
class Index:
def __init__(self, index_path, index_type, articles_path, mapping, metadata, k, num_workers):
self.index = self.load_index(index_path, index_type)
self.index_type = index_type
self.articles_path = art... | [
"json.load",
"nmslib.init",
"faiss.read_index",
"pathlib.Path",
"numpy.array",
"pandas.isna"
] | [((5936, 5954), 'pathlib.Path', 'Path', (['dataset_path'], {}), '(dataset_path)\n', (5940, 5954), False, 'from pathlib import Path\n'), ((585, 632), 'nmslib.init', 'nmslib.init', ([], {'method': '"""hnsw"""', 'space': '"""cosinesimil"""'}), "(method='hnsw', space='cosinesimil')\n", (596, 632), False, 'import nmslib\n')... |
import numpy as np
import random
from settree.set_data import SetDataset
########################################################################################################################
# EXP 1: First quarter
#####################################################################################################... | [
"numpy.random.uniform",
"numpy.random.randn",
"numpy.random.laplace",
"settree.set_data.SetDataset",
"numpy.array",
"numpy.random.normal",
"numpy.random.rand"
] | [((2693, 2734), 'numpy.array', 'np.array', (['([0] * (n // 2) + [1] * (n // 2))'], {}), '([0] * (n // 2) + [1] * (n // 2))\n', (2701, 2734), True, 'import numpy as np\n'), ((3720, 3761), 'numpy.array', 'np.array', (['([0] * (n // 2) + [1] * (n // 2))'], {}), '([0] * (n // 2) + [1] * (n // 2))\n', (3728, 3761), True, 'i... |
import argparse
from tqdm import tqdm
import re
import itertools
from collections import Counter
import numpy as np
from sklearn.model_selection import train_test_split
#from data import create_data,pad_sequences
import mxnet as mx
import os
import pickle
import time
from data import SentimentIter
from mod... | [
"models.model_cnn.sent_model",
"numpy.random.seed",
"argparse.ArgumentParser",
"mxnet.random.seed",
"mxnet.metric.Accuracy",
"time.time",
"mxnet.cpu",
"data.SentimentIter",
"mxnet.gpu",
"mxnet.model.load_checkpoint"
] | [((416, 473), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Semtiment training"""'}), "(description='Semtiment training')\n", (439, 473), False, 'import argparse\n'), ((1662, 1687), 'mxnet.random.seed', 'mx.random.seed', (['args.seed'], {}), '(args.seed)\n', (1676, 1687), True, 'import ... |
from random import shuffle
from numpy import cos, sin, pi, round, random
def generatePointsCoordinates_Circle(num_points):
points_coordinate = []
r = 0.5
for n in range(1, num_points + 1):
points_coordinate.append([round(r + r*cos((2 * pi * n) / num_points), 4), round(r + r*sin((2 * pi * n) / num_p... | [
"numpy.sin",
"numpy.cos"
] | [((248, 276), 'numpy.cos', 'cos', (['(2 * pi * n / num_points)'], {}), '(2 * pi * n / num_points)\n', (251, 276), False, 'from numpy import cos, sin, pi, round, random\n'), ((296, 324), 'numpy.sin', 'sin', (['(2 * pi * n / num_points)'], {}), '(2 * pi * n / num_points)\n', (299, 324), False, 'from numpy import cos, sin... |
# ********** modules ********** #
# chainer
import chainer
from chainer import cuda
from chainer.training import extensions
# others
import numpy as np
import argparse
import glob, os
import random
# network, which named "Looking to Listen at the Cocktail Party"
from network import Audio_Visual_Net
# ********** setu... | [
"chainer.optimizers.Adam",
"numpy.random.seed",
"argparse.ArgumentParser",
"chainer.training.Trainer",
"chainer.training.updaters.StandardUpdater",
"chainer.training.extensions.Evaluator",
"network.Audio_Visual_Net",
"chainer.training.extensions.PrintReport",
"chainer.serializers.load_npz",
"chain... | [((335, 352), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (349, 352), True, 'import numpy as np\n'), ((490, 515), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (513, 515), False, 'import argparse\n'), ((1811, 1901), 'network.Audio_Visual_Net', 'Audio_Visual_Net', ([], {'spec... |
from rdkit.Chem import AllChem
import collections
import logging
import os
import re
import numpy as np
from rdkit import Chem
import pkg_resources
from typing import List
from transformers import BertTokenizer
SMI_REGEX_PATTERN = r"(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>>?|\... | [
"numpy.full",
"rdkit.Chem.MolToSmiles",
"numpy.stack",
"rdkit.Chem.AllChem.ReactionFromSmarts",
"numpy.zeros",
"pkg_resources.resource_filename",
"os.path.isfile",
"collections.namedtuple",
"collections.OrderedDict",
"rdkit.Chem.MolFromSmiles",
"re.compile"
] | [((5576, 5679), 'collections.namedtuple', 'collections.namedtuple', (['"""InputFeatures"""', "['input_ids', 'input_mask', 'segment_ids', 'lm_label_ids']"], {}), "('InputFeatures', ['input_ids', 'input_mask',\n 'segment_ids', 'lm_label_ids'])\n", (5598, 5679), False, 'import collections\n'), ((5703, 5811), 'collectio... |
###############################################################################
# Imports
###############################################################################
import numpy as np
from scipy.stats import norm
from scipy.special import erfc
import h5py
from astropy import constants as const
import pkg_resources... | [
"numpy.abs",
"numpy.sum",
"pkg_resources.resource_filename",
"numpy.shape",
"numpy.exp",
"numpy.zeros_like",
"warnings.simplefilter",
"numpy.max",
"numpy.linspace",
"numpy.random.choice",
"numpy.log10",
"scipy.stats.norm.ppf",
"h5py.File",
"numpy.median",
"numpy.percentile",
"numpy.min... | [((531, 566), 'warnings.simplefilter', 'simplefilter', (['"""always"""', 'UserWarning'], {}), "('always', UserWarning)\n", (543, 566), False, 'from warnings import simplefilter, warn\n'), ((580, 650), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['"""forecaster"""', '"""fitting_parameters.h5""... |
#!/usr/bin/env python
"""
These are some useful data management functions
"""
#========================================================================
# Import what you need
#========================================================================
import numpy as np
import pandas as pd
#============================... | [
"pandas.read_csv",
"numpy.floor",
"numpy.random.permutation"
] | [((891, 916), 'pandas.read_csv', 'pd.read_csv', (['behav_data_f'], {}), '(behav_data_f)\n', (902, 916), True, 'import pandas as pd\n'), ((1035, 1062), 'numpy.floor', 'np.floor', (["df['AGE_AT_SCAN']"], {}), "(df['AGE_AT_SCAN'])\n", (1043, 1062), True, 'import numpy as np\n'), ((2567, 2603), 'numpy.random.permutation', ... |
from types import CoroutineType
import pybullet as p
import pybullet_data
import numpy as np
import gym
from gym import spaces
class humanoid(gym.Env):
def __init__(self) -> None:
super(humanoid, self).__init__()
p.connect(p.GUI)
p.resetDebugVisualizerCamera(cameraDistance=1.5, cameraYaw=-4... | [
"pybullet.resetSimulation",
"pybullet.resetDebugVisualizerCamera",
"pybullet.connect",
"pybullet.getQuaternionFromEuler",
"pybullet.getContactPoints",
"pybullet.getLinkState",
"pybullet.enableJointForceTorqueSensor",
"pybullet.setJointMotorControlArray",
"pybullet.setGravity",
"pybullet.setTimeSte... | [((234, 250), 'pybullet.connect', 'p.connect', (['p.GUI'], {}), '(p.GUI)\n', (243, 250), True, 'import pybullet as p\n'), ((259, 378), 'pybullet.resetDebugVisualizerCamera', 'p.resetDebugVisualizerCamera', ([], {'cameraDistance': '(1.5)', 'cameraYaw': '(-45)', 'cameraPitch': '(-20)', 'cameraTargetPosition': '[0, 0, 0.1... |
import random
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import dill
#don't ask how I came up with these numbers
SIZE_H1 = 50
SIZE_H2 = 100
SIZE_H3 = 60
class Actor(torch.nn.Module):
"""Defines custom model
Inherits from torch.nn... | [
"torch.nn.BatchNorm1d",
"dill.dump",
"numpy.concatenate",
"torch.nn.Linear"
] | [((570, 611), 'torch.nn.Linear', 'torch.nn.Linear', (['self._dim_input', 'SIZE_H1'], {}), '(self._dim_input, SIZE_H1)\n', (585, 611), False, 'import torch\n'), ((631, 664), 'torch.nn.Linear', 'torch.nn.Linear', (['SIZE_H1', 'SIZE_H2'], {}), '(SIZE_H1, SIZE_H2)\n', (646, 664), False, 'import torch\n'), ((684, 717), 'tor... |
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau
from GCN.dataset import Dataset
from GCN import model as m
from GCN.callback import *
from datetime import datetime
import numpy as np
import time
import csv
import os
class Trainer(object):
def __init__(self, dataset):
self.dat... | [
"csv.writer",
"numpy.std",
"keras.callbacks.ModelCheckpoint",
"os.walk",
"time.time",
"GCN.dataset.Dataset",
"numpy.mean",
"numpy.array",
"keras.callbacks.EarlyStopping",
"keras.callbacks.ReduceLROnPlateau",
"datetime.datetime.now"
] | [((1149, 1742), 'GCN.dataset.Dataset', 'Dataset', (["self.hyper['dataset']"], {'batch': 'batch', 'normalize': 'normalize', 'use_atom_symbol': 'use_atom_symbol', 'use_atom_symbol_extended': 'use_atom_symbol_extended', 'use_atom_number': 'use_atom_number', 'use_degree': 'use_degree', 'use_hybridization': 'use_hybridizati... |
# made by <NAME> 1610110007
# written in python using pytorch library
import matplotlib
import torchvision
from torch.utils.data import DataLoader as DataLoader
import torch.nn as nn
from PIL import Image
from torchvision.utils import save_image
import numpy
import torch
import os
epochs = 10
batch_size = 100;
DATA... | [
"torch.nn.Dropout",
"torch.ones",
"torch.nn.BCELoss",
"torch.utils.data.DataLoader",
"torch.nn.Tanh",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.nn.LeakyReLU",
"numpy.array",
"torch.rand",
"torch.zeros",
"torchvision.transforms.Normalize",
"torchvision.datasets.MNIST",
"torchvision.tran... | [((659, 749), 'torchvision.datasets.MNIST', 'torchvision.datasets.MNIST', ([], {'root': 'DATA_PATH', 'train': '(True)', 'transform': 'trans', 'download': '(True)'}), '(root=DATA_PATH, train=True, transform=trans,\n download=True)\n', (685, 749), False, 'import torchvision\n'), ((761, 833), 'torchvision.datasets.MNIS... |
"""
Belief Propogation Search
"""
import torch
import faiss
import numpy as np
import torchvision
from einops import rearrange,repeat
import nnf_utils as nnf_utils
from nnf_share import padBurst,getBlockLabels,tileBurst,padAndTileBatch,padLocs,locs2flow,mode_vals,mode_ndarray
from bnnf_utils import runBurstNnf,evalAt... | [
"sys.path.append",
"torch.mean",
"nnf_share.getBlockLabels",
"torch.LongTensor",
"nnf_share.locs2flow",
"bnnf_utils.runBurstNnf",
"torch.cat",
"nnf_share.padLocs",
"nnf_share.padAndTileBatch",
"numpy.isclose",
"einops.rearrange",
"easydict.EasyDict",
"sub_burst.evalAtLocs",
"torch.zeros",
... | [((506, 571), 'sys.path.append', 'sys.path.append', (['"""/home/gauenk/Documents/experiments/cl_gen/lib/"""'], {}), "('/home/gauenk/Documents/experiments/cl_gen/lib/')\n", (521, 571), False, 'import sys\n'), ((1940, 1963), 'easydict.EasyDict', 'edict', (["{'h': h, 'w': w}"], {}), "({'h': h, 'w': w})\n", (1945, 1963), T... |
from pathlib import Path
from tqdm.notebook import tqdm
from tqdm import trange
import pandas as po
import numpy as np
import warnings
import pickle
import nltk
import math
import os
import random
import re
import torch
import torch.nn as nn
from transformers import AdamW, get_linear_schedule_with_warmup
from transform... | [
"pandas.DataFrame",
"utils.average_precision_score",
"torch.utils.data.DataLoader",
"pandas.read_csv",
"rank.write_preds",
"torch.load",
"tqdm.notebook.tqdm",
"os.path.exists",
"torch.save",
"pathlib.Path",
"transformers.get_linear_schedule_with_warmup",
"transformers.AdamW",
"torch.utils.da... | [((1889, 1902), 'pathlib.Path', 'Path', (['"""data/"""'], {}), "('data/')\n", (1893, 1902), False, 'from pathlib import Path\n'), ((8336, 8384), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'batch_size': 'BATCH_SIZE'}), '(train_dataset, batch_size=BATCH_SIZE)\n', (8346, 8384), False, 'from torch.ut... |
import numpy as np
def persistence(labels):
# converts trajectory of cluster labels to states and time spent per state
# in the format [label,time spent]
states = []
current = [labels[0],0]
for label in labels:
if label == current[0]:
current[1]+=1
else:
stat... | [
"numpy.shape",
"numpy.array",
"numpy.log"
] | [((409, 425), 'numpy.array', 'np.array', (['states'], {}), '(states)\n', (417, 425), True, 'import numpy as np\n'), ((977, 991), 'numpy.shape', 'np.shape', (['path'], {}), '(path)\n', (985, 991), True, 'import numpy as np\n'), ((1117, 1151), 'numpy.array', 'np.array', (['[states[i:i + edges, 0]]'], {}), '([states[i:i +... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 8 15:19:36 2016
@author: virati
This is now the actual code for doing OnTarget/OffTarget LFP Ephys
THIS APPEARS to do the chirp template search
"""
import numpy as np
import pandas as pd
from collections import defaultdict, OrderedDict
import scipy.signal as sig
import m... | [
"matplotlib.pyplot.title",
"matplotlib.rc",
"numpy.abs",
"matplotlib.pyplot.boxplot",
"matplotlib.pyplot.suptitle",
"collections.defaultdict",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.linalg.norm",
"numpy.arange",
"scipy.interpolate.interp1d",
"sys.path.append",
"matplotlib.pyplot.cl... | [((364, 388), 'seaborn.set_context', 'sns.set_context', (['"""paper"""'], {}), "('paper')\n", (379, 388), True, 'import seaborn as sns\n'), ((389, 410), 'seaborn.set', 'sns.set', ([], {'font_scale': '(3)'}), '(font_scale=3)\n', (396, 410), True, 'import seaborn as sns\n'), ((411, 433), 'seaborn.set_style', 'sns.set_sty... |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import logging, uuid
__version__ = "0.1.0"
from d3m.container.dataset import D3MDatasetLoader, Dataset
from d3m.metadata import base as metadata_base, problem
from d3m.metadata.base import Metadata
from d3m.metadata.pipeline import Pipeline, PrimitiveStep
import problem_p... | [
"pickle.dump",
"os.chmod",
"json.load",
"os.makedirs",
"uuid.uuid4",
"d3m.metadata.problem.parse_problem_description",
"os.path.exists",
"datamart_nyu.RESTDatamart",
"d3m.metadata.base.Metadata",
"d3m.container.dataset.D3MDatasetLoader",
"numpy.array",
"datamart.DatamartQuery"
] | [((751, 772), 'd3m.metadata.base.Metadata', 'Metadata', (['problem_doc'], {}), '(problem_doc)\n', (759, 772), False, 'from d3m.metadata.base import Metadata\n'), ((5116, 5140), 'd3m.metadata.base.Metadata', 'Metadata', (['problem_schema'], {}), '(problem_schema)\n', (5124, 5140), False, 'from d3m.metadata.base import M... |
"""
This module is for normalization and data clipping as we described in Methods section.
"""
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from collections import Counter
def random_partition(train_df, test_df, n_genes=978, annotation_col='nc_label', seed=0, validation_rati... | [
"numpy.random.seed",
"numpy.sum",
"sklearn.preprocessing.StandardScaler",
"numpy.transpose",
"numpy.clip",
"numpy.max",
"numpy.mean",
"numpy.eye"
] | [((562, 582), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (576, 582), True, 'import numpy as np\n'), ((3381, 3406), 'numpy.max', 'np.max', (['label_to_classify'], {}), '(label_to_classify)\n', (3387, 3406), True, 'import numpy as np\n'), ((3435, 3468), 'numpy.eye', 'np.eye', (['n_class'], {'dtype... |
import numpy as np
class Individual:
def __init__(self, bounds):
"""
Class containing information about a population member.
Parameters
----------
bounds : dict
Parameter names mapped to upper / lower bounds.
Attributes
----------
_pn... | [
"numpy.random.uniform"
] | [((852, 887), 'numpy.random.uniform', 'np.random.uniform', (['self.lb', 'self.ub'], {}), '(self.lb, self.ub)\n', (869, 887), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
from collections.abc import MutableSequence
import numpy as np
from .dependent_variable import DependentVariable
from .dimension import Dimension
from .dimension import LabeledDimension
from .dimension import LinearDimension
from .dimension import MonotonicDimension
__author__ = "<NAME>"
__em... | [
"numpy.all"
] | [((2073, 2086), 'numpy.all', 'np.all', (['check'], {}), '(check)\n', (2079, 2086), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
import numpy as np
from pyrecorder.recorders.file import File
from pyrecorder.video import Video
from pymoo.algorithms.genetic_algorithm import GeneticAlgorithm
from pymoo.algorithms.nsga2 import RankAndCrowdingSurvival
from pymoo.algorithms.so_genetic_algorithm import GA
from pymoo.doc... | [
"pyrecorder.recorders.file.File",
"pymoo.model.population.Population.merge",
"pymoo.optimize.minimize",
"pymoo.util.termination.default.SingleObjectiveDefaultTermination",
"numpy.full",
"pymoo.visualization.scatter.Scatter",
"pymoo.docs.parse_doc_string",
"pymoo.operators.crossover.simulated_binary_cr... | [((6676, 6707), 'pymoo.docs.parse_doc_string', 'parse_doc_string', (['MMGA.__init__'], {}), '(MMGA.__init__)\n', (6692, 6707), False, 'from pymoo.docs import parse_doc_string\n'), ((1632, 1659), 'numpy.full', 'np.full', (['P.shape[0]', 'np.nan'], {}), '(P.shape[0], np.nan)\n', (1639, 1659), True, 'import numpy as np\n'... |
import numpy as np
import pandas as pd
#Load data from csv
root_square_cases = pd.read_csv('Test_root_square.csv')
#Convert to numpy array
root_square_cases = np.array(root_square_cases) | [
"pandas.read_csv",
"numpy.array"
] | [((80, 115), 'pandas.read_csv', 'pd.read_csv', (['"""Test_root_square.csv"""'], {}), "('Test_root_square.csv')\n", (91, 115), True, 'import pandas as pd\n'), ((160, 187), 'numpy.array', 'np.array', (['root_square_cases'], {}), '(root_square_cases)\n', (168, 187), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 5 11:57:04 2021
Parses the statistics from main_moabb_pipeline.py
"""
import regex
import numpy as np
integers = regex.compile('^([0-9]*)'+ '\s*' +'([0-9]*)$')
doubles = regex.compile('^([0-9]*\.*[0-9]*)'+ '\s*' +'([0-9]*)$')
with open('./path/to/file') as ... | [
"regex.compile",
"numpy.round",
"numpy.sum"
] | [((172, 221), 'regex.compile', 'regex.compile', (["('^([0-9]*)' + '\\\\s*' + '([0-9]*)$')"], {}), "('^([0-9]*)' + '\\\\s*' + '([0-9]*)$')\n", (185, 221), False, 'import regex\n'), ((230, 289), 'regex.compile', 'regex.compile', (["('^([0-9]*\\\\.*[0-9]*)' + '\\\\s*' + '([0-9]*)$')"], {}), "('^([0-9]*\\\\.*[0-9]*)' + '\\... |
from PIL import Image, ImageDraw
from facenet_pytorch import MTCNN, InceptionResnetV1
import numpy as np
import os
import time
import torch
TARGET_DIR = 'imgs/'
files = [f for f in os.listdir(TARGET_DIR)]
npz = np.load('all2.npz')
#global known_face_encodings, known_face_names, sids
known_face_encodings = npz['encode... | [
"numpy.load",
"os.remove",
"numpy.empty",
"numpy.argmin",
"numpy.linalg.norm",
"os.path.join",
"os.path.exists",
"facenet_pytorch.MTCNN",
"PIL.ImageDraw.Draw",
"numpy.hstack",
"torch.cuda.is_available",
"facenet_pytorch.InceptionResnetV1",
"numpy.savez",
"os.listdir",
"numpy.vstack",
"... | [((213, 232), 'numpy.load', 'np.load', (['"""all2.npz"""'], {}), "('all2.npz')\n", (220, 232), True, 'import numpy as np\n'), ((540, 670), 'facenet_pytorch.MTCNN', 'MTCNN', ([], {'image_size': '(160)', 'margin': '(0)', 'min_face_size': '(20)', 'thresholds': '[0.6, 0.7, 0.7]', 'factor': '(0.709)', 'post_process': '(True... |
from keras.models import Sequential
from keras.layers import Conv2D, MaxPool2D, ZeroPadding2D
from keras.layers.core import Flatten, Dense, Dropout
from keras.applications.mobilenet import preprocess_input, decode_predictions
from keras import backend as K
from keras.utils.conv_utils import convert_kernel
import tensor... | [
"keras.utils.conv_utils.convert_kernel",
"keras.backend.get_session",
"keras.layers.MaxPool2D",
"keras.applications.mobilenet.preprocess_input",
"keras.applications.mobilenet.MobileNet",
"numpy.expand_dims",
"keras.backend.get_value",
"tensorflow.assign",
"keras.layers.Conv2D",
"keras.layers.ZeroP... | [((521, 533), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (531, 533), False, 'from keras.models import Sequential\n'), ((3809, 3838), 'keras.applications.mobilenet.MobileNet', 'MobileNet', ([], {'weights': '"""imagenet"""'}), "(weights='imagenet')\n", (3818, 3838), False, 'from keras.applications.mobilen... |
"""
Implement L2 regularization of a fully connected neural network.
"""
import matplotlib.pyplot as plt
import numpy as np
from coding_neural_network_from_scratch import (initialize_parameters,
L_model_forward,
... | [
"coding_neural_network_from_scratch.sigmoid_gradient",
"coding_neural_network_from_scratch.initialize_parameters",
"numpy.random.seed",
"numpy.sum",
"matplotlib.pyplot.plot",
"numpy.multiply",
"coding_neural_network_from_scratch.relu_gradient",
"numpy.square",
"matplotlib.pyplot.ylabel",
"gradient... | [((1370, 1389), 'coding_neural_network_from_scratch.compute_cost', 'compute_cost', (['AL', 'y'], {}), '(AL, y)\n', (1382, 1389), False, 'from coding_neural_network_from_scratch import initialize_parameters, L_model_forward, compute_cost, relu_gradient, sigmoid_gradient, tanh_gradient, update_parameters, accuracy\n'), (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.