code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import argparse
from PIL import Image
import numpy as np
import onnxruntime as rt
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="StyleTransferONNX")
parser.add_argument('--model', type=str, default=' ', help='ONNX model file', required=True)
parser.add_argument('--input', type=str, d... | [
"numpy.clip",
"PIL.Image.fromarray",
"PIL.Image.open",
"argparse.ArgumentParser",
"numpy.asarray",
"onnxruntime.InferenceSession"
] | [((122, 178), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""StyleTransferONNX"""'}), "(description='StyleTransferONNX')\n", (145, 178), False, 'import argparse\n'), ((504, 535), 'onnxruntime.InferenceSession', 'rt.InferenceSession', (['args.model'], {}), '(args.model)\n', (523, 535), Tr... |
import os
import datetime
import gym
import numpy as np
import matplotlib.pyplot as plt
from es import CMAES
import pandas as pd
import string
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class Agent:
def __init__(self, x, y, layer1_nodes, layer2_nodes):
self.input = np.zeros(x, dtype=np.float128)
... | [
"os.path.exists",
"numpy.reshape",
"es.CMAES",
"numpy.asarray",
"numpy.exp",
"datetime.datetime.today",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.dot",
"matplotlib.pyplot.subplots",
"os.mkdir",
"pandas.DataFrame",
"matplotlib.pyplot.subplot",
"gym.make",
"matplotlib.pyplot.legend... | [((6770, 6784), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (6782, 6784), True, 'import matplotlib.pyplot as plt\n'), ((7360, 7370), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7368, 7370), True, 'import matplotlib.pyplot as plt\n'), ((286, 316), 'numpy.zeros', 'np.zeros', (['x'], {'dty... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from ..losses import build_loss
class ConvBNAct(nn.Sequential):
def __init__(self, in_channels: int, out_channels: int):
super().__init__(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.init.constant_",
"numpy.log",
"torch.nn.init.kaiming_normal_",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.ConvTranspose2d",
"torch.nn.functional.softmax",
"torch.cat"
] | [((1339, 1357), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['(2)', '(2)'], {}), '(2, 2)\n', (1351, 1357), True, 'import torch.nn as nn\n'), ((1385, 1417), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['c5', 'c4', '(2)', '(2)'], {}), '(c5, c4, 2, 2)\n', (1403, 1417), True, 'import torch.nn as nn\n'), ((1445, 1477), 't... |
import numpy as np
import pandas as pd
import unittest
from bdranalytics.sklearn.model_selection import GrowingWindow, IntervalGrowingWindow
def create_time_series_data_set(start_date=pd.datetime(year=2000, month=1, day=1), n_rows=100):
end_date = start_date + pd.Timedelta(days=n_rows-1)
ds = np.random.ran... | [
"numpy.random.rand",
"numpy.arange",
"pandas.Timedelta",
"bdranalytics.sklearn.model_selection.GrowingWindow",
"numpy.random.randint",
"pandas.datetime",
"pandas.date_range"
] | [((187, 225), 'pandas.datetime', 'pd.datetime', ([], {'year': '(2000)', 'month': '(1)', 'day': '(1)'}), '(year=2000, month=1, day=1)\n', (198, 225), True, 'import pandas as pd\n'), ((307, 329), 'numpy.random.rand', 'np.random.rand', (['n_rows'], {}), '(n_rows)\n', (321, 329), True, 'import numpy as np\n'), ((472, 508),... |
"""Implement 3D image thresholding."""
from typing import List, Optional
import numpy.typing as npt
import numpy as np
from ..image_utils import get_xy_block_coords, get_xy_block
from ..gpu import get_image_method
def get_threshold_otsu(image: npt.ArrayLike, blur_sigma=5):
"""Perform Otsu's thresholding with ... | [
"numpy.count_nonzero"
] | [((1495, 1524), 'numpy.count_nonzero', 'np.count_nonzero', (['binary_tile'], {}), '(binary_tile)\n', (1511, 1524), True, 'import numpy as np\n'), ((1270, 1300), 'numpy.count_nonzero', 'np.count_nonzero', (['binary_image'], {}), '(binary_image)\n', (1286, 1300), True, 'import numpy as np\n')] |
import cv2
import logging
import numpy as np
import nibabel as nib
from skimage.measure import label
from skimage.morphology import binary_closing, cube
from fetal_brain_mask.model import Unet
logger = logging.getLogger(__name__)
class MaskingTool:
def __init__(self):
self.model = Unet()
def mask_t... | [
"logging.getLogger",
"skimage.morphology.cube",
"numpy.squeeze",
"numpy.max",
"numpy.array",
"numpy.zeros",
"fetal_brain_mask.model.Unet",
"numpy.moveaxis",
"cv2.resize",
"numpy.bincount",
"skimage.measure.label"
] | [((204, 231), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (221, 231), False, 'import logging\n'), ((298, 304), 'fetal_brain_mask.model.Unet', 'Unet', ([], {}), '()\n', (302, 304), False, 'from fetal_brain_mask.model import Unet\n'), ((436, 460), 'numpy.moveaxis', 'np.moveaxis', (['data... |
# ##### BEGIN GPL LICENSE BLOCK #####
# KeenTools for blender is a blender addon for using KeenTools in Blender.
# Copyright (C) 2019 KeenTools
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, ... | [
"logging.getLogger",
"numpy.ones",
"bpy.data.images.new",
"bpy.data.images.find",
"bpy.data.images.load",
"bpy.data.images.remove"
] | [((918, 950), 'bpy.data.images.find', 'bpy.data.images.find', (['image_name'], {}), '(image_name)\n', (938, 950), False, 'import bpy\n'), ((2513, 2540), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2530, 2540), False, 'import logging\n'), ((3189, 3301), 'bpy.data.images.new', 'bpy.data... |
""" This file contains quantum code in support of Shor's Algorithm
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
import sys
import math
import numpy as np
""" ********* QFT Functions *** """
""" Function to create QFT """
def create_QFT(circuit,up_reg,n,with_sw... | [
"math.pow",
"numpy.zeros"
] | [((3006, 3019), 'numpy.zeros', 'np.zeros', (['[N]'], {}), '([N])\n', (3014, 3019), True, 'import numpy as np\n'), ((2791, 2812), 'math.pow', 'math.pow', (['(2)', '(-(N - i))'], {}), '(2, -(N - i))\n', (2799, 2812), False, 'import math\n'), ((3132, 3153), 'math.pow', 'math.pow', (['(2)', '(-(j - i))'], {}), '(2, -(j - i... |
import sys
sys.path.append('.')
from sslplay.data.digits import DataDigits
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import numpy as np
obj_data = DataDigits()
obj_data.load()
X = obj_data.X
y = obj_data.y
target_names = np.array(["0", "1"... | [
"matplotlib.pyplot.ylabel",
"sklearn.decomposition.PCA",
"matplotlib.pyplot.xlabel",
"sslplay.data.digits.DataDigits",
"numpy.array",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.figure",
"numpy.random.seed",
"matplotlib.pyplot.scatter",
"sys.path.append",
"matplotlib.pyplot.suptit... | [((11, 31), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (26, 31), False, 'import sys\n'), ((227, 239), 'sslplay.data.digits.DataDigits', 'DataDigits', ([], {}), '()\n', (237, 239), False, 'from sslplay.data.digits import DataDigits\n'), ((302, 362), 'numpy.array', 'np.array', (["['0', '1', '2', ... |
from collider.data.sensor import Sensor
from collider.data.message_package import MessagePackage
from scipy.stats import spearmanr
import numpy as np
class FakeForwardReturn(Sensor):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.lastvalue = None
@property
def output_varia... | [
"numpy.random.normal",
"numpy.array",
"scipy.stats.spearmanr"
] | [((660, 700), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'sigma', 'size': '(4000)'}), '(scale=sigma, size=4000)\n', (676, 700), True, 'import numpy as np\n'), ((1036, 1067), 'numpy.array', 'np.array', (["['fakeForwardReturn']"], {}), "(['fakeForwardReturn'])\n", (1044, 1067), True, 'import numpy as np\n'... |
import random
import gym
import sys
import numpy as np
from collections import deque,namedtuple
import os
import time
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.optim import Adam
plt.style.use('seaborn')
class DQN(nn.Module):
def __init__(self,hidden_sz,state_sz, action_sz):
... | [
"torch.nn.ReLU",
"collections.namedtuple",
"collections.deque",
"random.sample",
"numpy.reshape",
"numpy.random.random",
"torch.LongTensor",
"matplotlib.pyplot.style.use",
"torch.nn.MSELoss",
"torch.nn.Linear",
"time.time",
"torch.FloatTensor"
] | [((214, 238), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (227, 238), True, 'import matplotlib.pyplot as plt\n'), ((398, 433), 'torch.nn.Linear', 'nn.Linear', (['state_sz', 'self.hidden_sz'], {}), '(state_sz, self.hidden_sz)\n', (407, 433), True, 'import torch.nn as nn\n'),... |
"""
Some notes:
HDI: Highest Density Interval.
ROPE: Region of Practical Equivalence.
"""
import numpy as np
from matplotlib import pyplot as plt
def ch01_01():
"""
"""
thetas = np.linspace(0, 1, 1001)
print(thetas)
likelihood = lambda r: thetas if r else (1 - thetas)
def posterio... | [
"numpy.random.beta",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.fill_between",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tight_layout",
"numpy.cumsum",
"matplotlib.pyplot.x... | [((203, 226), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(1001)'], {}), '(0, 1, 1001)\n', (214, 226), True, 'import numpy as np\n'), ((548, 567), 'matplotlib.pyplot.plot', 'plt.plot', (['thetas', 'p'], {}), '(thetas, p)\n', (556, 567), True, 'from matplotlib import pyplot as plt\n'), ((572, 595), 'matplotlib.pyp... |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
def uniform_dist(a, b, size):
'''
Sample from a uniform distribution Unif(a,b)
'''
std_unif = torch.rand(size)
return std_unif*(b-a)+a
def safe_log(tens, epsilon:float=1e-5):
'''
Safe log to prevent infi... | [
"numpy.array",
"torch.log",
"torch.rand",
"numpy.arange"
] | [((198, 214), 'torch.rand', 'torch.rand', (['size'], {}), '(size)\n', (208, 214), False, 'import torch\n'), ((346, 371), 'torch.log', 'torch.log', (['(tens + epsilon)'], {}), '(tens + epsilon)\n', (355, 371), False, 'import torch\n'), ((760, 779), 'numpy.array', 'np.array', (['generated'], {}), '(generated)\n', (768, 7... |
import numpy as np
from typing import List, Dict, Tuple
def get_metrics(
y_pred=None,
y_true=None,
metrics: List[str] = ["Accuracy"],
classes: List[str] = ["Ham", "Spam"]
) -> Dict:
if isinstance(y_pred, np.ndarray) == False:
y_pred = y_pred.to_numpy()
if isinstance(y_true, np.ndarray... | [
"numpy.mean",
"numpy.sum"
] | [((1035, 1060), 'numpy.mean', 'np.mean', (['(y_pred == y_true)'], {}), '(y_pred == y_true)\n', (1042, 1060), True, 'import numpy as np\n'), ((1366, 1389), 'numpy.sum', 'np.sum', (['(y_pred * y_true)'], {}), '(y_pred * y_true)\n', (1372, 1389), True, 'import numpy as np\n'), ((1729, 1752), 'numpy.sum', 'np.sum', (['(y_p... |
import tkinter as tk
import psycopg2
import pickle
import time, calendar, requests, datetime
try:
conn = psycopg2.connect(database="postgres", user="postgres", password="<PASSWORD>", host="10.10.100.120")
print("connected")
except:
print ("I am unable to connect to the database")
motions = []
stationMotions = {}... | [
"psycopg2.connect",
"time.sleep",
"calendar.timegm",
"numpy.array",
"cv2.destroyAllWindows",
"cv2.VideoWriter",
"schedule.every",
"cv2.VideoWriter_fourcc",
"random.randint",
"cv2.fillPoly",
"requests.get",
"time.gmtime",
"time.time",
"schedule.run_pending",
"os.path.join",
"cv2.bitwise... | [((4831, 4941), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""rtsp://admin:3J7Bm!j@@10.10.153.21:8221/Streaming/Channels/102/picture?subtype=1"""'], {}), "(\n 'rtsp://admin:3J7Bm!j@@10.10.153.21:8221/Streaming/Channels/102/picture?subtype=1'\n )\n", (4847, 4941), False, 'import cv2\n'), ((5055, 5086), 'cv2.VideoW... |
# Importing all required libraries for the code to function
import tkinter
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg)
from matplotlib import pyplot as plt, animation
from mpl_toolkits import mplot3d
from stl import mesh
import numpy as np
import serial
from serial.tools import list_ports
import t... | [
"csv.DictWriter",
"mpl_toolkits.mplot3d.art3d.Poly3DCollection",
"serial.tools.list_ports.comports",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg",
"matplotlib.use",
"matplotlib.animation.FuncAnimation",
"time.sleep",
"seaborn.set_style",
"matplotlib.pyplot.figure",
"tkinter.Tk",
"numpy.... | [((375, 398), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (389, 398), False, 'import matplotlib\n'), ((455, 481), 'seaborn.set_style', 'sns.set_style', (['"""whitegrid"""'], {}), "('whitegrid')\n", (468, 481), True, 'import seaborn as sns\n'), ((864, 876), 'matplotlib.pyplot.figure', 'plt.... |
import datetime
import utils
import glob
import os
import numpy as np
import pandas as pd
if __name__ == '__main__':
loaddir = "E:/Data/h5/"
labels = ['https', 'netflix']
max_packet_length = 1514
for label in labels:
print("Starting label: " + label)
savedir = loaddir + label + "/"
... | [
"os.path.split",
"datetime.datetime.now",
"pandas.DataFrame",
"numpy.fromstring",
"utils.load_h5",
"glob.glob"
] | [((331, 354), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (352, 354), False, 'import datetime\n'), ((476, 511), 'glob.glob', 'glob.glob', (["(loaddir + label + '*.h5')"], {}), "(loaddir + label + '*.h5')\n", (485, 511), False, 'import glob\n'), ((644, 667), 'os.path.split', 'os.path.split', (['f... |
import numpy as np
import matplotlib.pyplot as plt
""" E is in MeV, D in μm, vB in μm/h, τ in h, and k in (MeV)^-1 """
def E(D, τ=5, vB=2.66, k=.8, n=1.2, a=1, z=1):
return z**2*a*((2*τ*vB/D - 1)/k)**(1/n)
def D(E, τ=5, vB=2.66, k=.8, n=1.2, a=1, z=1):
return np.where(E > 0,
2*τ*vB/(1 + k*(E/(z**2*a))**n),
np.na... | [
"matplotlib.pyplot.ylabel",
"numpy.where",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.rcParams.update",
"numpy.linspace",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show"
] | [((263, 334), 'numpy.where', 'np.where', (['(E > 0)', '(2 * τ * vB / (1 + k * (E / (z ** 2 * a)) ** n))', 'np.nan'], {}), '(E > 0, 2 * τ * vB / (1 + k * (E / (z ** 2 * a)) ** n), np.nan)\n', (271, 334), True, 'import numpy as np\n'), ((353, 415), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.fam... |
from math import floor
import scipy.io as sio
from bokeh.plotting import figure, show, output_file, save, ColumnDataSource
from bokeh.models import HoverTool, CrosshairTool, PanTool, WheelZoomTool, ResetTool, SaveTool, CustomJS
from bokeh.models.widgets import Button
from bokeh.layouts import widgetbox, row, column, ... | [
"bokeh.plotting.show",
"bokeh.layouts.widgetbox",
"math.floor",
"numpy.arange",
"bokeh.models.SaveTool",
"scipy.io.loadmat",
"bokeh.plotting.save",
"bokeh.models.widgets.Button",
"bokeh.layouts.gridplot",
"numpy.zeros",
"matplotlib.colors.rgb2hex",
"bokeh.models.WheelZoomTool",
"bokeh.models... | [((533, 554), 'scipy.io.loadmat', 'sio.loadmat', (['filename'], {}), '(filename)\n', (544, 554), True, 'import scipy.io as sio\n'), ((4264, 4350), 'bokeh.models.HoverTool', 'HoverTool', ([], {'tooltips': "[('time', '@time ms'), ('amplitude', '@amp')]", 'names': "['dots']"}), "(tooltips=[('time', '@time ms'), ('amplitud... |
import gpu
import numpy
from bgl import *
from . rectangle import Rectangle
from gpu_extras.batch import batch_for_shader
shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
class InterpolationPreview:
def __init__(self, interpolation, position, width, resolution):
self.interpolation = interpolation
... | [
"numpy.stack",
"gpu.shader.from_builtin",
"gpu_extras.batch.batch_for_shader",
"numpy.linspace"
] | [((132, 175), 'gpu.shader.from_builtin', 'gpu.shader.from_builtin', (['"""2D_UNIFORM_COLOR"""'], {}), "('2D_UNIFORM_COLOR')\n", (155, 175), False, 'import gpu\n'), ((1903, 1947), 'numpy.linspace', 'numpy.linspace', (['left', 'right', 'self.resolution'], {}), '(left, right, self.resolution)\n', (1917, 1947), False, 'imp... |
import cv2
import numpy as np
class drawingCanvas():
def __init__(self):
self.penrange = np.load('penrange.npy')
self.cap = cv2.VideoCapture(0)
self.canvas = None
self.x1,self.y1=0,0
self.val=1
self.draw()
def draw(self):
while True:
... | [
"cv2.flip",
"cv2.inRange",
"cv2.boundingRect",
"cv2.line",
"cv2.imshow",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.VideoCapture",
"cv2.cvtColor",
"cv2.findContours",
"numpy.load",
"numpy.zeros_like",
"cv2.add"
] | [((2327, 2350), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2348, 2350), False, 'import cv2\n'), ((107, 130), 'numpy.load', 'np.load', (['"""penrange.npy"""'], {}), "('penrange.npy')\n", (114, 130), True, 'import numpy as np\n'), ((151, 170), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}... |
from collections import OrderedDict
import numpy as np
import math
import torch
import torch.optim as optim
from torch import nn as nn
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.torch.torch_rl_algorithm import TorchTrainer
def kl_divergence(mu, std):... | [
"numpy.prod",
"collections.OrderedDict",
"math.log",
"torch.min",
"torch.nn.MSELoss",
"rlkit.torch.pytorch_util.get_numpy",
"torch.sum",
"rlkit.torch.pytorch_util.soft_update_from_to",
"rlkit.torch.pytorch_util.zeros"
] | [((489, 530), 'torch.sum', 'torch.sum', (['(weight * (input - target) ** 2)'], {}), '(weight * (input - target) ** 2)\n', (498, 530), False, 'import torch\n'), ((2104, 2116), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (2114, 2116), True, 'from torch import nn as nn\n'), ((2145, 2157), 'torch.nn.MSELoss', 'nn.M... |
import os
import utils
import torch
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import DataLoader
import numpy as np
import data
import scipy.io as sio
from options.training_options import TrainOptions
import utils
import time
from models import AutoEncoderCov3D, AutoEncoderCov3DMem
f... | [
"models.EntropyLossEncap",
"numpy.ones",
"utils.UnNormalize",
"utils.get_model_setting",
"os.path.join",
"options.training_options.TrainOptions",
"utils.Logger",
"torch.nn.MSELoss",
"utils.seed",
"utils.mkdir",
"torchvision.transforms.Normalize",
"torch.utils.data.DataLoader",
"numpy.concate... | [((373, 387), 'options.training_options.TrainOptions', 'TrainOptions', ([], {}), '()\n', (385, 387), False, 'from options.training_options import TrainOptions\n'), ((458, 501), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (470, 501), False, 'import torc... |
import pandas as pd
df = pd.read_csv(r'balanced_reviews.csv')
df.isnull().any(axis = 0)
#handle the missing data
df.dropna(inplace = True)
#leaving the reviews with rating 3 and collect reviews with
#rating 1, 2, 4 and 5 onyl
df = df [df['overall'] != 3]
import numpy as np
#creating a label... | [
"pickle.dump",
"pandas.read_csv",
"numpy.where",
"sklearn.model_selection.train_test_split",
"sklearn.linear_model.LogisticRegression",
"sklearn.metrics.roc_auc_score",
"sklearn.feature_extraction.text.TfidfVectorizer",
"sklearn.metrics.confusion_matrix"
] | [((29, 64), 'pandas.read_csv', 'pd.read_csv', (['"""balanced_reviews.csv"""'], {}), "('balanced_reviews.csv')\n", (40, 64), True, 'import pandas as pd\n'), ((381, 414), 'numpy.where', 'np.where', (["(df['overall'] > 3)", '(1)', '(0)'], {}), "(df['overall'] > 3, 1, 0)\n", (389, 414), True, 'import numpy as np\n'), ((625... |
#basic components: Embedding Layer, Scaled Dot-Product Attention, Dense Layer
import numpy as np
import torch.nn.functional as F
from torch import nn
import torch
class Embed(nn.Module):
def __init__(self, length, emb_dim,
embeddings=None, trainable=False, dropout=.1):
super(Embed, self... | [
"torch.bmm",
"torch.nn.Dropout",
"numpy.sqrt",
"torch.abs",
"torch.nn.Softmax",
"numpy.power",
"torch.nn.LayerNorm",
"torch.from_numpy",
"torch.nn.init.xavier_normal_",
"torch.cat",
"numpy.zeros",
"numpy.array",
"numpy.cos",
"torch.nn.Linear",
"numpy.sin",
"torch.nn.Conv1d",
"torch.n... | [((367, 440), 'torch.nn.Embedding', 'nn.Embedding', ([], {'num_embeddings': 'length', 'embedding_dim': 'emb_dim', 'padding_idx': '(0)'}), '(num_embeddings=length, embedding_dim=emb_dim, padding_idx=0)\n', (379, 440), False, 'from torch import nn\n'), ((792, 811), 'torch.nn.Dropout', 'nn.Dropout', (['dropout'], {}), '(d... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName : core_recorder.py
# @Time : 2020/9/25 12:29
# @Author : 陈嘉昕
# @Demand : 声音复杂记录
import threading
import logging
import wave
from pyaudio import PyAudio, paInt16
import numpy as np
import queue
import time
class CoreRecorder(threading.Thread):
... | [
"logging.getLogger",
"threading.Thread.__init__",
"wave.open",
"threading.Lock",
"numpy.fromstring",
"threading.Event",
"queue.Queue",
"pyaudio.PyAudio",
"time.time"
] | [((591, 622), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (616, 622), False, 'import threading\n'), ((736, 752), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (750, 752), False, 'import threading\n'), ((826, 871), 'logging.getLogger', 'logging.getLogger', (["(__name__ +... |
import featext.feature_processing
from featext.mfcc import Mfcc
import numpy as np
import system.gmm_em as gmm
import system.ivector as ivector
import system.backend as backend
# UPDATE THIS FOLDER (folder to spoken digit dataset recordings):
data_folder = '/home/ville/files/recordings/'
speakers = ['jackson', 'nicol... | [
"featext.mfcc.Mfcc",
"numpy.mean",
"numpy.reshape",
"system.ivector.TMatrix",
"system.backend.GPLDA",
"system.gmm_em.GMM",
"numpy.argmax",
"system.backend.preprocess",
"system.backend.compute_mean",
"numpy.zeros",
"numpy.empty",
"numpy.cov",
"system.ivector.Ivector",
"numpy.arange"
] | [((551, 557), 'featext.mfcc.Mfcc', 'Mfcc', ([], {}), '()\n', (555, 557), False, 'from featext.mfcc import Mfcc\n'), ((863, 921), 'numpy.empty', 'np.empty', (['(n_speakers, n_digits, n_sessions)'], {'dtype': 'object'}), '((n_speakers, n_digits, n_sessions), dtype=object)\n', (871, 921), True, 'import numpy as np\n'), ((... |
import functools
import itertools
import operator
import numpy as np
from qecsim.model import StabilizerCode, cli_description
from qecsim.models.rotatedplanar import RotatedPlanarPauli
@cli_description('Rotated planar (rows INT >= 3, cols INT >= 3)')
class RotatedPlanarCode(StabilizerCode):
r"""
Implements ... | [
"itertools.chain",
"qecsim.model.cli_description",
"operator.index",
"numpy.array",
"functools.lru_cache",
"qecsim.models.rotatedplanar.RotatedPlanarPauli"
] | [((190, 254), 'qecsim.model.cli_description', 'cli_description', (['"""Rotated planar (rows INT >= 3, cols INT >= 3)"""'], {}), "('Rotated planar (rows INT >= 3, cols INT >= 3)')\n", (205, 254), False, 'from qecsim.model import StabilizerCode, cli_description\n'), ((3425, 3446), 'functools.lru_cache', 'functools.lru_ca... |
import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
from treeano.sandbox.nodes import lrn
fX = theano.config.floatX
def ground_truth_normalizer(bc01, k, n, alpha, beta):
"""
This code is adapted from pylearn2.
https://github.com/l... | [
"treeano.nodes.InputNode",
"numpy.testing.assert_equal",
"numpy.testing.assert_allclose",
"numpy.zeros",
"treeano.sandbox.nodes.lrn.LocalResponseNormalizationNode",
"treeano.sandbox.nodes.lrn.LocalResponseNormalization2DNode",
"theano.tensor.tensor4",
"numpy.random.randn"
] | [((1075, 1095), 'numpy.zeros', 'np.zeros', (['c01b.shape'], {}), '(c01b.shape)\n', (1083, 1095), True, 'import numpy as np\n'), ((1963, 2011), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ans', 'res'], {'rtol': '(1e-05)'}), '(ans, res, rtol=1e-05)\n', (1989, 2011), True, 'import numpy as np\n'), ((... |
""" Script to send prediction request.
Usage:
python predict.py --url=YOUR_KF_HOST/models/coco --input_image=YOUR_LOCAL_IMAGE
--output_image=OUTPUT_IMAGE_NAME.
This will save the prediction result as OUTPUT_IMAGE_NAME.
The output image is the input image with the detected bounding boxes.
"""
import argparse
imp... | [
"PIL.Image.fromarray",
"PIL.Image.open",
"json.loads",
"argparse.ArgumentParser",
"numpy.array"
] | [((477, 502), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (500, 502), False, 'import argparse\n'), ((731, 759), 'PIL.Image.open', 'Image.open', (['args.input_image'], {}), '(args.input_image)\n', (741, 759), False, 'from PIL import Image\n'), ((824, 837), 'numpy.array', 'np.array', (['img'],... |
"""
Estimate luminosity function in COSMOS from interferometric follow-up of
Miettinen+ 2014, Younger+ 2007, and Younger+2009.
"""
import numpy
import matplotlib.pyplot as plt
from pylab import savefig
from astropy.table import Table
import matplotlib
def MonteCarloCounts(fluxes, errors):
hist890, bin_edges =... | [
"matplotlib.pyplot.ylabel",
"pylab.savefig",
"numpy.array",
"matplotlib.rc",
"matplotlib.pyplot.errorbar",
"numpy.arange",
"numpy.mean",
"numpy.histogram",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.minorticks_on",
"numpy.exp",
"matplotlib.pyplot.axis",
"matpl... | [((1029, 1048), 'numpy.array', 'numpy.array', (['S_1100'], {}), '(S_1100)\n', (1040, 1048), False, 'import numpy\n'), ((1261, 1279), 'numpy.array', 'numpy.array', (['S_890'], {}), '(S_890)\n', (1272, 1279), False, 'import numpy\n'), ((1318, 1327), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1325, 1327), True... |
#!/usr/bin/env python
"""
analyse Elasticsearch query
"""
import json
from elasticsearch import Elasticsearch
from elasticsearch import logger as es_logger
from collections import defaultdict, Counter
import re
import os
from datetime import datetime
# Preprocess terms for TF-IDF
import numpy as np
import pandas as pd... | [
"logging.getLogger",
"matplotlib.pyplot.boxplot",
"numpy.log10",
"logging.StreamHandler",
"geopy.extra.rate_limiter.RateLimiter",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"pandas.to_timedelta",
"pandas.Grouper",
"seaborn.set_style",
"numpy.array",
"seaborn.scatterplot",
"numpy.linalg.n... | [((1424, 1462), 'elasticsearch.Elasticsearch', 'Elasticsearch', (['"""http://localhost:9200"""'], {}), "('http://localhost:9200')\n", (1437, 1462), False, 'from elasticsearch import Elasticsearch\n'), ((1467, 1502), 'elasticsearch.logger.setLevel', 'es_logger.setLevel', (['logging.WARNING'], {}), '(logging.WARNING)\n',... |
"""
Utility functions for working with DataFrames
"""
import pandas
import numpy as np
TEST_DF = pandas.DataFrame([1,2,3])
class O:
"""
A square shaped block for my PyTetris game.
"""
def __init__(self):
self.type = "O"
self.color = (255, 255, 0)
mold = np.zeros([24, 10]) # fr... | [
"pandas.DataFrame",
"numpy.zeros"
] | [((99, 126), 'pandas.DataFrame', 'pandas.DataFrame', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (115, 126), False, 'import pandas\n'), ((297, 315), 'numpy.zeros', 'np.zeros', (['[24, 10]'], {}), '([24, 10])\n', (305, 315), True, 'import numpy as np\n')] |
from numpy import log, pi, arange, exp
from scipy.optimize import brentq
import matplotlib.pyplot as plot
from matplotlib import rc
import equation
def diagram_sum(x, d):
return 4.*pi/log(d**2 *2.*x)
def diagram_sum_3body(x, d):
point=equation.equation(3.*x,'2D',20.,0.1,d)
point.solve()
g3=point.g3
... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.log",
"equation.equation",
"matplotlib.pyplot.close",
"numpy.exp",
"matplotlib.rc",
"numpy.arange"
] | [((379, 401), 'numpy.arange', 'arange', (['(0.6)', '(5.0)', '(0.05)'], {}), '(0.6, 5.0, 0.05)\n', (385, 401), False, 'from numpy import log, pi, arange, exp\n'), ((578, 599), 'numpy.arange', 'arange', (['(0.6)', '(5.6)', '(1.0)'], {}), '(0.6, 5.6, 1.0)\n', (584, 599), False, 'from numpy import log, pi, arange, exp\n'),... |
# Simulates a network with nodes, where each node can be either a
# transmitter or receiver (but not both) at any time step. The simulation
# examines the coverage based on the signal-to-interference ratio (SINR).
# The network has a random medium access control (MAC) scheme based on a
# determinantal point process, as... | [
"numpy.sqrt",
"numpy.random.rand",
"numpy.random.exponential",
"numpy.array",
"funPalmK.funPalmK",
"numpy.sin",
"numpy.arange",
"numpy.mean",
"funProbCovTXRXDet.funProbCovTXRXDet",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.exp",
"numpy.linspace",
"numpy.random.seed",
"n... | [((2079, 2095), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2088, 2095), True, 'import matplotlib.pyplot as plt\n'), ((2155, 2172), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (2169, 2172), True, 'import numpy as np\n'), ((4619, 4635), 'numpy.linalg.eig', 'np.linalg.eig... |
""" Tests for functions in imaging module
Run at the project directory with:
nosetests code/utils/tests/test_imaging.py
"""
# Loading modules.
from __future__ import absolute_import, division, print_function
import numpy as np
import nibabel as nib
import os
import sys
from numpy.testing import assert_almost_equal... | [
"Image_Visualizing.present_3d",
"numpy.ceil",
"Image_Visualizing.make_mask",
"numpy.sqrt",
"numpy.ones",
"os.path.dirname",
"numpy.zeros",
"Image_Visualizing.present_3d_options",
"numpy.arange"
] | [((717, 734), 'numpy.arange', 'np.arange', (['(100000)'], {}), '(100000)\n', (726, 734), True, 'import numpy as np\n'), ((787, 803), 'Image_Visualizing.present_3d', 'present_3d', (['data'], {}), '(data)\n', (797, 803), False, 'from Image_Visualizing import present_3d, make_mask, present_3d_options\n'), ((886, 903), 'nu... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import h5py
import json
import os
import scipy.misc
import sys
import re
import fnmatch
import datetime
from PIL import Image
import numpy as np
'''
sr... | [
"sys.path.insert",
"argparse.ArgumentParser",
"json.dumps",
"os.path.join",
"utils.face_utils.parse_wider_gt",
"os.path.dirname",
"numpy.array"
] | [((512, 537), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (527, 537), False, 'import os\n'), ((584, 618), 'os.path.join', 'os.path.join', (['this_dir', '""".."""', '""".."""'], {}), "(this_dir, '..', '..')\n", (596, 618), False, 'import os\n'), ((738, 792), 'argparse.ArgumentParser', 'argp... |
"""
=================================================
Deterministic Tracking with EuDX on Tensor Fields
=================================================
In this example we do deterministic fiber tracking on Tensor fields with EuDX
[Garyfallidis12]_.
This example requires to import example `reconst_dti.py` to run. E... | [
"dipy.reconst.dti.quantize_evecs",
"os.path.exists",
"numpy.eye",
"dipy.tracking.streamline.Streamlines",
"nibabel.load",
"dipy.data.get_sphere",
"numpy.isnan",
"dipy.viz.colormap.line_colors",
"sys.exit",
"dipy.viz.window.show",
"dipy.viz.window.record",
"dipy.viz.window.Renderer"
] | [((782, 810), 'nibabel.load', 'nib.load', (['"""tensor_fa.nii.gz"""'], {}), "('tensor_fa.nii.gz')\n", (790, 810), True, 'import nibabel as nib\n'), ((846, 877), 'nibabel.load', 'nib.load', (['"""tensor_evecs.nii.gz"""'], {}), "('tensor_evecs.nii.gz')\n", (854, 877), True, 'import nibabel as nib\n'), ((1506, 1532), 'dip... |
import pandas as pd
import numpy as np
import seaborn as sns
import os
import matplotlib.pyplot as plt
df = pd.read_csv( os.path.join( "fairness-2021", "simple-rank-res.csv" ) )
df["pp"] = [ "fs" if x == 'fairsmote' else x for x in df["pp"] ]
df["pt"] = [ "rs" if x == 'random' else x for x in df["pt"] ]
df["tech"] = [... | [
"seaborn.cubehelix_palette",
"numpy.logical_and",
"matplotlib.pyplot.clf",
"os.path.join",
"matplotlib.pyplot.close",
"matplotlib.pyplot.tight_layout",
"pandas.DataFrame",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.subplots"
] | [((122, 174), 'os.path.join', 'os.path.join', (['"""fairness-2021"""', '"""simple-rank-res.csv"""'], {}), "('fairness-2021', 'simple-rank-res.csv')\n", (134, 174), False, 'import os\n'), ((1416, 1508), 'pandas.DataFrame', 'pd.DataFrame', (["[sub_df[sub_df['tech'] == x].iloc[0][['tech', 'rank']] for x in tech_list]"], {... |
import warnings
import numpy as np
import pandas as pd
import sklearn
from sklearn import metrics
class MetricCatalog:
catalog_dict = {
'accuracy': {
'func': metrics.accuracy_score,
'params': {},
'require_score': False,
'binary': True,
'multi': ... | [
"pandas.Series",
"numpy.mean",
"numpy.abs",
"pandas.DataFrame",
"sklearn.metrics.median_absolute_error",
"numpy.log",
"numpy.zeros_like",
"sklearn.metrics.mean_squared_error",
"sklearn.metrics.log_loss",
"warnings.warn",
"sklearn.metrics.mean_absolute_error",
"pandas.concat",
"numpy.random.s... | [((11681, 11728), 'pandas.Series', 'pd.Series', (['eval_list'], {'index': 'sorted_metric_names'}), '(eval_list, index=sorted_metric_names)\n', (11690, 11728), True, 'import pandas as pd\n'), ((19146, 19179), 'pandas.DataFrame', 'pd.DataFrame', (['col_importance_list'], {}), '(col_importance_list)\n', (19158, 19179), Tr... |
from abc import ABC, abstractmethod
import numpy as np
from .activations import Identity
class Layer(ABC):
def __init__(self, size, input_shape=(None, None)):
'''
Params
------
size : int
number of neurons (size) of output layer
input_shape : (int, ... | [
"numpy.sqrt",
"numpy.dot",
"numpy.random.randn"
] | [((2107, 2129), 'numpy.dot', 'np.dot', (['self.W', 'self.X'], {}), '(self.W, self.X)\n', (2113, 2129), True, 'import numpy as np\n'), ((1633, 1667), 'numpy.random.randn', 'np.random.randn', (['self.OUT', 'self.IN'], {}), '(self.OUT, self.IN)\n', (1648, 1667), True, 'import numpy as np\n'), ((1670, 1703), 'numpy.sqrt', ... |
__copyright__ = """
Copyright (c) 2018 Uber Technologies, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, mer... | [
"pickle.dump",
"multiprocessing.Array",
"pickle.load",
"math.log",
"numpy.random.RandomState"
] | [((1518, 1562), 'multiprocessing.Array', 'multiprocessing.Array', (['ctypes.c_float', 'count'], {}), '(ctypes.c_float, count)\n', (1539, 1562), False, 'import ctypes, multiprocessing\n'), ((1960, 1975), 'pickle.load', 'pickle.load', (['fh'], {}), '(fh)\n', (1971, 1975), False, 'import pickle\n'), ((2320, 2347), 'pickle... |
import random
import glob
import torch
from torch import nn
import numpy as np
from torch.nn import init
import torch.optim as optim
import torch.nn.functional as F
from torch.nn import Parameter as P
from torchvision import transforms, set_image_backend
# set_image_backend('accimage')
from models.pytorch_biggan.dat... | [
"numpy.product",
"torch.nn.ReLU",
"torch.from_numpy",
"torch.nn.init.orthogonal_",
"torch.sum",
"torch.conv2d",
"torch.mean",
"torch.nn.Flatten",
"torch.nn.init.xavier_uniform_",
"numpy.linspace",
"torchvision.transforms.ToTensor",
"random.randint",
"glob.glob",
"torch.abs",
"random.choi... | [((641, 666), 'torch.transpose', 'torch.transpose', (['Sx', '(1)', '(0)'], {}), '(Sx, 1, 0)\n', (656, 666), False, 'import torch\n'), ((894, 945), 'pytorch_pretrained_biggan.one_hot_from_names', 'one_hot_from_names', (["['vase']"], {'batch_size': 'batch_size'}), "(['vase'], batch_size=batch_size)\n", (912, 945), False,... |
#!/usr/bin/python3
import math
import numpy as np
import pdb
import time
import torch
from mseg_semantic.domain_generalization.ccsa_utils import (
contrastive_loss,
paired_euclidean_distance,
downsample_label_map,
sample_pair_indices,
find_matching_pairs,
remove_pairs_from_same_domain,
get_merged_pair_embeddi... | [
"mseg_semantic.domain_generalization.ccsa_utils.sample_pair_indices",
"math.sqrt",
"mseg_semantic.domain_generalization.ccsa_utils.pytorch_random_choice",
"numpy.array",
"torch.arange",
"mseg_semantic.domain_generalization.ccsa_utils.paired_euclidean_distance",
"torch.unique",
"mseg_semantic.domain_ge... | [((854, 914), 'torch.tensor', 'torch.tensor', (['[1.0, 0.0, 0.0, 0.0, 1.0]'], {'dtype': 'torch.float32'}), '([1.0, 0.0, 0.0, 0.0, 1.0], dtype=torch.float32)\n', (866, 914), False, 'import torch\n'), ((959, 1015), 'torch.tensor', 'torch.tensor', (['[0, 1.1, 1.1, 1.1, 0]'], {'dtype': 'torch.float32'}), '([0, 1.1, 1.1, 1.... |
from src.modeling import util
import numpy as np
from dskc import dskc_modeling
def test(model):
x_test, y_test, _ = util.read_test_data()
# predict
y_pred = model.predict(x_test)
# clean
y_pred = np.asarray([x[0] for x in y_pred])
# evaluate
report = dskc_modeling.EvaluationReport(y_te... | [
"dskc.dskc_modeling.EvaluationReport",
"numpy.array",
"src.modeling.util.read_test_data",
"numpy.asarray"
] | [((123, 144), 'src.modeling.util.read_test_data', 'util.read_test_data', ([], {}), '()\n', (142, 144), False, 'from src.modeling import util\n'), ((221, 255), 'numpy.asarray', 'np.asarray', (['[x[0] for x in y_pred]'], {}), '([x[0] for x in y_pred])\n', (231, 255), True, 'import numpy as np\n'), ((285, 354), 'dskc.dskc... |
"""
Derived from keras-yolo3 train.py (https://github.com/qqwweee/keras-yolo3),
with additions from https://github.com/AntonMu/TrainYourOwnYOLO.
"""
import os
import sys
import argparse
import pickle
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
fr... | [
"yolo3.model.preprocess_true_boxes",
"numpy.array",
"yolo3.model.yolo_body",
"numpy.random.seed",
"keras.callbacks.EarlyStopping",
"keras.backend.clear_session",
"keras.models.Model",
"keras.optimizers.Adam",
"keras.callbacks.ReduceLROnPlateau",
"os.path.dirname",
"yolo3.utils.get_random_data",
... | [((1060, 1108), 'os.path.join', 'os.path.join', (['EXPORT_DIR', '"""yolo_annotations.txt"""'], {}), "(EXPORT_DIR, 'yolo_annotations.txt')\n", (1072, 1108), False, 'import os\n'), ((1182, 1223), 'os.path.join', 'os.path.join', (['EXPORT_DIR', '"""classes.names"""'], {}), "(EXPORT_DIR, 'classes.names')\n", (1194, 1223), ... |
#!/usr/bin/env python
'''
Created by Seria at 02/11/2018 3:38 PM
Email: <EMAIL>
_ooOoo_
o888888888o
o88`_ . _`88o
(| 0 0 |)
O \ 。 / O
_____/`-----‘\_____
.’ \|| _ _ ||/ `.
| _ |... | [
"random.random",
"numpy.array",
"random.uniform",
"numpy.transpose"
] | [((2822, 2850), 'numpy.transpose', 'np.transpose', (['img', '(2, 0, 1)'], {}), '(img, (2, 0, 1))\n', (2834, 2850), True, 'import numpy as np\n'), ((7607, 7679), 'random.uniform', 'rand.uniform', (['self.comburant.brightness[0]', 'self.comburant.brightness[1]'], {}), '(self.comburant.brightness[0], self.comburant.bright... |
import obspy
import unittest
import numpy as np
import madpy.checks as ch
import madpy.tests.testdata.config as cfg
class TestChecks(unittest.TestCase):
def test_check_config(self):
class Measurements: pass
self.assertRaises(AttributeError, ch.check_config, Measurements())
... | [
"obspy.read",
"madpy.checks.check_amplitude",
"numpy.arange",
"madpy.checks.check_stats",
"madpy.checks.check_duration_index",
"madpy.checks.check_cc",
"obspy.UTCDateTime",
"madpy.checks.check_window",
"madpy.checks.check_datagaps",
"numpy.array",
"madpy.checks.check_plottype",
"unittest.main"... | [((6909, 6924), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6922, 6924), False, 'import unittest\n'), ((1949, 1979), 'obspy.read', 'obspy.read', (['"""testdata/*.mseed"""'], {}), "('testdata/*.mseed')\n", (1959, 1979), False, 'import obspy\n'), ((2506, 2536), 'obspy.read', 'obspy.read', (['"""testdata/*.mseed"... |
"""
Plot gas, tar, char, water, and water vapor from primary and secondary
reactions based on Blasi / Chan / Liden kinetic schemes for biomass pyrolysis.
This combined scheme is referred to as the Cpc 2016 kinetic scheme. A similar
scheme but without water reaction was proposed in Papadikis 2010 paper.
References:
Bla... | [
"matplotlib.pyplot.grid",
"numpy.ones",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.exp",
"numpy.linspace",
"matplotlib.pyplot.figure",
"numpy.zeros",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.legend"
] | [((913, 948), 'numpy.linspace', 'np.linspace', (['(0)', 'tmax'], {'num': '(tmax / dt)'}), '(0, tmax, num=tmax / dt)\n', (924, 948), True, 'import numpy as np\n'), ((4914, 4926), 'numpy.zeros', 'np.zeros', (['nt'], {}), '(nt)\n', (4922, 4926), True, 'import numpy as np\n'), ((4971, 4983), 'numpy.zeros', 'np.zeros', (['n... |
'''
original implementation credit: https://github.com/openai/baselines
heavily adapted to suit our needs.
'''
import argparse
import tempfile
import os.path as osp
import gym
import logging
from tqdm import tqdm
import tensorflow as tf
import numpy as np
import os
import sys
import glob
file_path = os.path.dirnam... | [
"sys.path.insert",
"matplotlib.pyplot.ylabel",
"tensorflow.reduce_mean",
"numpy.arange",
"contrib.baselines.gail.mlp_policy.MlpPolicy",
"os.path.exists",
"contrib.baselines.common.set_global_seeds",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.close",
"contrib.baselines.common.tf_util.flatgra... | [((476, 504), 'sys.path.insert', 'sys.path.insert', (['(0)', 'src_path'], {}), '(0, src_path)\n', (491, 504), False, 'import sys\n'), ((322, 348), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (338, 348), False, 'import os\n'), ((377, 411), 'os.path.join', 'os.path.join', (['file_path', 'o... |
import glob
import numpy as np
import sys
def group_memory_footprint(memory_list, th_size):
# group similar consecutive entries in the memory list (ts, size)
ts = 0
size_list = [memory_list[0][1]]
group_footprint = []
for i in range(1, len(memory_list)):
if abs(memory_list[i][1] - memory_li... | [
"numpy.mean",
"numpy.array",
"numpy.zeros",
"numpy.savetxt",
"numpy.maximum",
"numpy.loadtxt",
"glob.glob"
] | [((742, 758), 'numpy.zeros', 'np.zeros', (['(n, 2)'], {}), '((n, 2))\n', (750, 758), True, 'import numpy as np\n'), ((1011, 1039), 'glob.glob', 'glob.glob', (["(sys.argv[1] + '*')"], {}), "(sys.argv[1] + '*')\n", (1020, 1039), False, 'import glob\n'), ((1448, 1499), 'numpy.array', 'np.array', (['[[i[0], i[1] / 1024] fo... |
"""Test for hydromt.gis_utils submodule"""
import pytest
import numpy as np
from hydromt import gis_utils as gu
from hydromt.raster import full_from_transform, RasterDataArray
from rasterio.transform import from_origin
def test_crs():
bbox = [3, 51.5, 4, 52] # NL
assert gu.utm_crs(bbox).to_epsg() == 32631
... | [
"hydromt.raster.full_from_transform",
"numpy.ones",
"rasterio.transform.from_origin",
"hydromt.gis_utils.spread2d",
"hydromt.gis_utils.parse_crs",
"hydromt.gis_utils.filter_gdf",
"hydromt.gis_utils.affine_to_coords",
"hydromt.raster.RasterDataArray.from_numpy",
"hydromt.gis_utils.utm_crs",
"numpy.... | [((769, 793), 'rasterio.transform.from_origin', 'from_origin', (['(0)', '(90)', '(1)', '(1)'], {}), '(0, 90, 1, 1)\n', (780, 793), False, 'from rasterio.transform import from_origin\n'), ((830, 867), 'hydromt.gis_utils.affine_to_coords', 'gu.affine_to_coords', (['transform', 'shape'], {}), '(transform, shape)\n', (849,... |
# -*- coding: UTF-8 -*-
import os
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
def show_images(name):
folders = {"A", "b", "c", "d", "e", "f", "g", "h", "i", "j"}
images = []
for folder in folders:
findInFolder = "output/notMNIST_large/" + folder + "/" + name
i... | [
"matplotlib.pyplot.imshow",
"os.path.exists",
"os.listdir",
"PIL.Image.open",
"PIL.Image._show",
"numpy.asarray",
"os.remove",
"matplotlib.pyplot.show"
] | [((397, 415), 'numpy.asarray', 'np.asarray', (['images'], {}), '(images)\n', (407, 415), True, 'import numpy as np\n'), ((451, 467), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (461, 467), False, 'from PIL import Image\n'), ((472, 490), 'PIL.Image._show', 'Image._show', (['image'], {}), '(image)\n', (48... |
import matplotlib.pyplot as plt
import rebalancer
from sp500_data_loader import load_data
import numpy as np
import itertools
import os
from multiprocessing import Process
def interpet_results(assets, rebalance_inv, bah_inv, data, condition, dir):
prices = []
for key in data.keys():
prices.append(data... | [
"matplotlib.pyplot.savefig",
"os.makedirs",
"multiprocessing.Process",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.plot",
"itertools.combinations",
"os.path.isfile",
"sp500_data_loader.load_data",
"os.path.isdir",
"rebalancer.simulate",
"matplotlib.pyplot.axis",
"numpy.shape"
] | [((682, 697), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (690, 697), True, 'import matplotlib.pyplot as plt\n'), ((706, 761), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(dir + assets[0] + '_' + assets[1] + '.png')"], {}), "(dir + assets[0] + '_' + assets[1] + '.png')\n", (717, 761), Tru... |
"""
===============
GTK Spreadsheet
===============
Example of embedding Matplotlib in an application and interacting with a
treeview to store data. Double click on an entry to update plot data.
"""
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
from gi.repository import Gtk, Gdk
from m... | [
"gi.repository.Gtk.TreeView",
"gi.repository.Gtk.main_quit",
"numpy.random.random",
"matplotlib.figure.Figure",
"gi.repository.Gtk.ListStore",
"gi.require_version",
"gi.repository.Gtk.Label",
"matplotlib.backends.backend_gtk3agg.FigureCanvas",
"gi.repository.Gtk.CellRendererText",
"gi.repository.G... | [((212, 244), 'gi.require_version', 'gi.require_version', (['"""Gtk"""', '"""3.0"""'], {}), "('Gtk', '3.0')\n", (230, 244), False, 'import gi\n'), ((245, 277), 'gi.require_version', 'gi.require_version', (['"""Gdk"""', '"""3.0"""'], {}), "('Gdk', '3.0')\n", (263, 277), False, 'import gi\n'), ((2499, 2509), 'gi.reposito... |
import cv2
import numpy as np
def MaxPooling(_img):
img = _img.copy()
result = np.zeros_like(img)
for i in range(img.shape[0]//8):
ind_11 = i * 8
ind_12 = ind_11 + 8
for j in range(img.shape[1]//8):
ind_21 = j * 8
ind_22 = ind_21 + 8
result[ind_11... | [
"cv2.imwrite",
"numpy.zeros_like",
"cv2.imread",
"numpy.max"
] | [((618, 641), 'cv2.imread', 'cv2.imread', (['"""imori.jpg"""'], {}), "('imori.jpg')\n", (628, 641), False, 'import cv2\n'), ((668, 703), 'cv2.imwrite', 'cv2.imwrite', (['"""myans_08.jpg"""', 'result'], {}), "('myans_08.jpg', result)\n", (679, 703), False, 'import cv2\n'), ((88, 106), 'numpy.zeros_like', 'np.zeros_like'... |
import numpy as np
from numpy.testing import assert_equal
import scipy.sparse as sp
import tensorflow as tf
from .math import (sparse_scalar_multiply, sparse_tensor_diag_matmul,
_diag_matmul_py, _diag_matmul_transpose_py)
from .convert import sparse_to_tensor
class MathTest(tf.test.TestCase):
... | [
"numpy.testing.assert_equal",
"numpy.array",
"tensorflow.constant",
"scipy.sparse.coo_matrix",
"tensorflow.sparse_tensor_to_dense"
] | [((406, 422), 'scipy.sparse.coo_matrix', 'sp.coo_matrix', (['a'], {}), '(a)\n', (419, 422), True, 'import scipy.sparse as sp\n'), ((508, 536), 'tensorflow.sparse_tensor_to_dense', 'tf.sparse_tensor_to_dense', (['a'], {}), '(a)\n', (533, 536), True, 'import tensorflow as tf\n'), ((771, 787), 'scipy.sparse.coo_matrix', '... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 22 13:13:06 2021
@author: hossam
"""
from base import BaseTrain
import numpy as np
import matplotlib.pylab as plt
from matplotlib.pyplot import savefig
from scipy.stats import multivariate_normal
class vaeTrainer(BaseTrain):
def __init__(self, ... | [
"numpy.mean",
"matplotlib.pylab.subplots",
"numpy.ones",
"numpy.squeeze",
"numpy.zeros",
"matplotlib.pylab.close"
] | [((5772, 5814), 'numpy.squeeze', 'np.squeeze', (["self.data.test_set_vae['data']"], {}), "(self.data.test_set_vae['data'])\n", (5782, 5814), True, 'import numpy as np\n'), ((5836, 5864), 'numpy.squeeze', 'np.squeeze', (['self.output_test'], {}), '(self.output_test)\n', (5846, 5864), True, 'import numpy as np\n'), ((743... |
import astropy.io.fits as pft
import numpy as np
from astropy.time import Time
import itertools
from astropy.stats import sigma_clipped_stats
from scipy.signal import convolve
def group_image_pairs(file_list, by_next=False, by_exptime=False):
if by_next:
image_pair_lists = [[file_list[2*i], file_list[2*i+... | [
"numpy.mean",
"scipy.signal.convolve",
"numpy.median",
"numpy.ones",
"numpy.where",
"itertools.combinations",
"numpy.stddev",
"astropy.io.fits.open",
"astropy.stats.sigma_clipped_stats"
] | [((1312, 1347), 'scipy.signal.convolve', 'convolve', (['img', 'kernel'], {'mode': '"""valid"""'}), "(img, kernel, mode='valid')\n", (1320, 1347), False, 'from scipy.signal import convolve\n'), ((1004, 1033), 'astropy.stats.sigma_clipped_stats', 'sigma_clipped_stats', (['diff_img'], {}), '(diff_img)\n', (1023, 1033), Fa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 09:36:00 2019
@author: minjie
"""
import SimpleITK as sitk
import numpy as np
from pathlib import Path
import os
import cv2
import pydicom
import h5py
from scipy.ndimage import binary_dilation
fn1 = 'resources/CT/01/data/A_1.mha'
fn2 = 'resour... | [
"numpy.clip",
"pydicom.dcmread",
"numpy.ones",
"pathlib.Path",
"numpy.where",
"SimpleITK.GetArrayFromImage",
"h5py.File",
"numpy.stack",
"numpy.zeros",
"SimpleITK.ReadImage",
"numpy.zeros_like"
] | [((541, 560), 'SimpleITK.ReadImage', 'sitk.ReadImage', (['fn1'], {}), '(fn1)\n', (555, 560), True, 'import SimpleITK as sitk\n'), ((657, 676), 'SimpleITK.ReadImage', 'sitk.ReadImage', (['fn2'], {}), '(fn2)\n', (671, 676), True, 'import SimpleITK as sitk\n'), ((1198, 1252), 'numpy.stack', 'np.stack', (['(labels0, labels... |
import sys
sys.path.append("../modules/")
import numpy as np
import matplotlib.pyplot as plt
from skimage import feature
from utils import conf
if __name__ == "__main__":
filename = conf.dir_data_temp + "slice.npy"
img = np.load(filename)
filename = conf.dir_data_mask + "endocardial_mask.npy"
endoca... | [
"matplotlib.pyplot.figure",
"skimage.feature.canny",
"numpy.load",
"sys.path.append",
"matplotlib.pyplot.show"
] | [((11, 41), 'sys.path.append', 'sys.path.append', (['"""../modules/"""'], {}), "('../modules/')\n", (26, 41), False, 'import sys\n'), ((233, 250), 'numpy.load', 'np.load', (['filename'], {}), '(filename)\n', (240, 250), True, 'import numpy as np\n'), ((333, 350), 'numpy.load', 'np.load', (['filename'], {}), '(filename)... |
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch
class Generator(nn.Module):
def __init__(self, configs, shape):
super(Generator, self).__init__()
self.label_emb = nn.Embedding(configs.n_classes, configs.n_classes)
self.shape = shape
def block(... | [
"numpy.prod",
"torch.nn.Dropout",
"torch.nn.Tanh",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm1d",
"torch.nn.Linear",
"torch.nn.Embedding"
] | [((223, 273), 'torch.nn.Embedding', 'nn.Embedding', (['configs.n_classes', 'configs.n_classes'], {}), '(configs.n_classes, configs.n_classes)\n', (235, 273), True, 'import torch.nn as nn\n'), ((1308, 1358), 'torch.nn.Embedding', 'nn.Embedding', (['configs.n_classes', 'configs.n_classes'], {}), '(configs.n_classes, conf... |
import BotDecidesPos
import numpy as np
class Collision_check:
def __init__(self):
self.m=0.0
self.n=0.0
def load_data(self,bot):
tgx,tgy=bot.getTarget()
mpx,mpy=bot.getPos()
spd=bot.getSpeed()
return spd,mpx,mpy,tgx,tgy
def checkCollisio... | [
"numpy.absolute"
] | [((958, 982), 'numpy.absolute', 'np.absolute', (['(eta1 - eta2)'], {}), '(eta1 - eta2)\n', (969, 982), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x, w, b):
return 1/(1 + np.exp(-x*w+b))
x = np.arange(-5.0, 5.0, 0.1)
y1 = sigmoid(x, 0.5, 0)
y2 = sigmoid(x, 1, 0)
y3 = sigmoid(x, 2, 0)
plt.plot(x, y1, "r", linestyle='--')
plt.plot(x, y2, 'g')
plt.plot(x, y3, 'b', linestyle='--')
plt.plot([0, 0],... | [
"matplotlib.pyplot.plot",
"numpy.exp",
"matplotlib.pyplot.title",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((114, 139), 'numpy.arange', 'np.arange', (['(-5.0)', '(5.0)', '(0.1)'], {}), '(-5.0, 5.0, 0.1)\n', (123, 139), True, 'import numpy as np\n'), ((209, 245), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y1', '"""r"""'], {'linestyle': '"""--"""'}), "(x, y1, 'r', linestyle='--')\n", (217, 245), True, 'import matplotlib.p... |
import numpy as np
from scipy.optimize import fsolve
from scipy.linalg import expm
import matplotlib.pyplot as plt
# Some utilities
# map a vector to a skew symmetric matrix
def skew(x):
return np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])
# map a twist to its adjoint form
def adjoint(x):
r... | [
"numpy.eye",
"numpy.reshape",
"numpy.diag",
"numpy.array",
"numpy.zeros",
"numpy.linalg.inv",
"matplotlib.pyplot.pause",
"numpy.zeros_like",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((199, 263), 'numpy.array', 'np.array', (['[[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]]'], {}), '([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]])\n', (207, 263), True, 'import numpy as np\n'), ((981, 998), 'numpy.zeros', 'np.zeros', (['(N, 12)'], {}), '((N, 12))\n', (989, 998), True, 'import numpy as... |
import numpy as np
from gtsam import SfmTrack
from gtsfm.common.image import Image
import gtsfm.utils.images as image_utils
def test_get_average_point_color():
""" Ensure 3d point color is computed as mean of RGB per 2d measurement."""
# random point; 2d measurements below are dummy locations (not actual pro... | [
"gtsfm.utils.images.get_rescaling_factor_per_axis",
"gtsfm.utils.images.get_downsampling_factor_per_axis",
"numpy.isclose",
"numpy.array",
"numpy.zeros",
"gtsfm.utils.images.get_average_point_color",
"gtsfm.common.image.Image",
"gtsam.SfmTrack"
] | [((351, 370), 'numpy.array', 'np.array', (['[1, 2, 1]'], {}), '([1, 2, 1])\n', (359, 370), True, 'import numpy as np\n'), ((386, 411), 'gtsam.SfmTrack', 'SfmTrack', (['triangulated_pt'], {}), '(triangulated_pt)\n', (394, 411), False, 'from gtsam import SfmTrack\n'), ((578, 617), 'numpy.zeros', 'np.zeros', (['(100, 200,... |
r"""
Difference between magnetic dipole and loop sources
===================================================
In this example we look at the differences between an electric loop loop, which
results in a magnetic source, and a magnetic dipole source.
The derivation of the electromagnetic field in Hunziker et al. (2015)... | [
"numpy.log10",
"empymod.loop",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.yscale",
"numpy.logspace",
"numpy.abs",
"matplotlib.pyplot.gca",
"numpy.size",
"empymod... | [((2839, 2862), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (2852, 2862), True, 'import matplotlib.pyplot as plt\n'), ((3261, 3284), 'numpy.logspace', 'np.logspace', (['(-1)', '(5)', '(301)'], {}), '(-1, 5, 301)\n', (3272, 3284), True, 'import numpy as np\n'), ((3312, 3335), ... |
import numpy as np
import pandas as pd
from sklearn import preprocessing
import math
def load_datasets_feature(filename):
features_df = pd.read_csv(filename, delimiter='\\s*,\\s*', header=0)
return features_df
def load_join_data3(features_df, result_file, histograms_path, num_rows, num_columns):
cols = ... | [
"numpy.dstack",
"numpy.multiply",
"pandas.read_csv",
"math.pow",
"pandas.merge",
"numpy.sum",
"numpy.array",
"sklearn.preprocessing.minmax_scale",
"pandas.DataFrame",
"sklearn.preprocessing.MinMaxScaler"
] | [((142, 196), 'pandas.read_csv', 'pd.read_csv', (['filename'], {'delimiter': '"""\\\\s*,\\\\s*"""', 'header': '(0)'}), "(filename, delimiter='\\\\s*,\\\\s*', header=0)\n", (153, 196), True, 'import pandas as pd\n'), ((501, 573), 'pandas.read_csv', 'pd.read_csv', (['result_file'], {'delimiter': '"""\\\\s*,\\\\s*"""', 'h... |
import os
import numpy as np
import random
from math import isclose
import torch
import matplotlib.pyplot as plt
from modelZoo.DyanOF import OFModel, fista
from torch.autograd import Variable
import torch.nn
def gridRing(N):
# epsilon_low = 0.25
# epsilon_high = 0.15
# rmin = (1 - epsilon_low)
# rmax ... | [
"numpy.logical_and",
"modelZoo.DyanOF.fista",
"numpy.conjugate",
"torch.Tensor",
"numpy.angle",
"torch.matmul",
"numpy.meshgrid",
"numpy.arange"
] | [((967, 996), 'numpy.arange', 'np.arange', (['(-rmax)', 'rmax', 'delta'], {}), '(-rmax, rmax, delta)\n', (976, 996), True, 'import numpy as np\n'), ((1008, 1041), 'numpy.meshgrid', 'np.meshgrid', (['xv', 'xv'], {'sparse': '(False)'}), '(xv, xv, sparse=False)\n', (1019, 1041), True, 'import numpy as np\n'), ((1068, 1134... |
import tqdm
import mediapipe
import requests
import cv2
import numpy as np
import matplotlib
class FullBodyPoseEmbedder(object):
"""Converts 3D pose landmarks into 3D embedding."""
def __init__(self, torso_size_multiplier=2.5):
# Multiplier to apply to the torso to get minimal body size.
se... | [
"numpy.copy",
"numpy.linalg.norm"
] | [((1734, 1752), 'numpy.copy', 'np.copy', (['landmarks'], {}), '(landmarks)\n', (1741, 1752), True, 'import numpy as np\n'), ((2095, 2113), 'numpy.copy', 'np.copy', (['landmarks'], {}), '(landmarks)\n', (2102, 2113), True, 'import numpy as np\n'), ((3729, 3761), 'numpy.linalg.norm', 'np.linalg.norm', (['(shoulders - hip... |
import numpy as np
import math
def GMM(alpha, x, u, conv,dim):
covdet = np.linalg.det(conv + np.eye(dim) * 0.001)
covinv = np.linalg.inv(conv + np.eye(dim) * 0.001)
T1 = 1 / ( (2 * math.pi)**(dim/2) * np.sqrt(covdet))
T2 = np.exp((-0.5) * ((np.transpose(x - u)).dot(covinv).dot(x - u)))
prob = T1 *... | [
"numpy.eye",
"numpy.reshape",
"numpy.sqrt",
"math.log",
"numpy.array",
"numpy.sum",
"numpy.expand_dims",
"numpy.transpose"
] | [((446, 466), 'numpy.expand_dims', 'np.expand_dims', (['i', '(1)'], {}), '(i, 1)\n', (460, 466), True, 'import numpy as np\n'), ((647, 674), 'math.log', 'math.log', (['(all_value + 1e-05)'], {}), '(all_value + 1e-05)\n', (655, 674), False, 'import math\n'), ((215, 230), 'numpy.sqrt', 'np.sqrt', (['covdet'], {}), '(covd... |
# -*- encoding: utf-8 -*-
"""
@Author : zYx.Tom
@Contact : <EMAIL>
@site : https://zhuyuanxiang.github.io
---------------------------
@Software : PyCharm
@Project : deep-learning-with-python-notebooks
@File : ch0604_conv1D.py
@Version : v0.1
@Time : 2019-11-26 11:08
... | [
"keras.layers.MaxPooling1D",
"keras.optimizers.rmsprop",
"keras.datasets.imdb.load_data",
"tools.plot_classes_results",
"matplotlib.pyplot.show",
"matplotlib.pyplot.get_fignums",
"keras.layers.GlobalMaxPooling1D",
"keras.models.Sequential",
"numpy.random.seed",
"winsound.Beep",
"keras.layers.Den... | [((1192, 1277), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)', 'suppress': '(True)', 'threshold': 'np.inf', 'linewidth': '(200)'}), '(precision=3, suppress=True, threshold=np.inf, linewidth=200\n )\n', (1211, 1277), True, 'import numpy as np\n'), ((1343, 1363), 'numpy.random.seed', 'np.ra... |
#! /usr/bin/env python3
"""
Stein PPO: Sample-efficient Policy Optimization with Stein Control Variate
Motivated by the Stein’s identity, Stein PPO extends the previous
control variate methods used in REINFORCE and advantage actor-critic
by introducing more general action-dependent baseline functions.
Details see th... | [
"utils.Scaler",
"numpy.array",
"gym.wrappers.Monitor",
"tensorflow.set_random_seed",
"gym.make",
"numpy.mean",
"numpy.max",
"numpy.random.seed",
"numpy.concatenate",
"numpy.min",
"policy.Policy",
"tb_logger.log",
"value_function.NNValueFunction",
"numpy.squeeze",
"datetime.datetime.utcno... | [((1299, 1316), 'numpy.random.seed', 'np.random.seed', (['i'], {}), '(i)\n', (1313, 1316), True, 'import numpy as np\n'), ((1321, 1335), 'random.seed', 'random.seed', (['i'], {}), '(i)\n', (1332, 1335), False, 'import random\n'), ((1689, 1707), 'gym.make', 'gym.make', (['env_name'], {}), '(env_name)\n', (1697, 1707), F... |
"""
Functions to load and process Ausgrid dataset.
The dataset contains 300 users with their location, PV production and electrical consumption.
The timeline for this dataset is 3 years separated in 3 files.
"""
import os
import pickle
import numpy as np
import pandas as pd
from pandas.tseries.offsets import Day
from... | [
"pickle.dump",
"pandas.MultiIndex",
"pandas.read_csv",
"numpy.arange",
"torch.utils.data.dataloader.DataLoader",
"os.path.join",
"pickle.load",
"numpy.zeros",
"pandas.DataFrame",
"pandas.tseries.offsets.Day",
"os.path.expanduser"
] | [((465, 539), 'os.path.expanduser', 'os.path.expanduser', (['"""~/Documents/Deep_Learning_Resources/datasets/ausgrid"""'], {}), "('~/Documents/Deep_Learning_Resources/datasets/ausgrid')\n", (483, 539), False, 'import os\n'), ((934, 984), 'os.path.join', 'os.path.join', (['DATA_PATH_ROOT', 'FILE_PATH_DICT[year]'], {}), ... |
#!/usr/bin/env python
"""
Estimates the static background in a STORM movie.
The estimate is performed by averaging this might
not be the best choice for movies with a high density
of real localizations.
This may be a good choice if you have a largish
fixed background and a relatively low density of
real localizations... | [
"storm_analysis.sa_library.datareader.inferReader",
"storm_analysis.sa_library.datawriter.DaxWriter",
"argparse.ArgumentParser",
"numpy.zeros",
"storm_analysis.sa_library.parameters.ParametersCommon"
] | [((3756, 3833), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Running average background subtraction"""'}), "(description='Running average background subtraction')\n", (3779, 3833), False, 'import argparse\n'), ((4453, 4490), 'storm_analysis.sa_library.datareader.inferReader', 'dataread... |
import argparse
import ast
import os
import numpy as np
import cv2
parser = argparse.ArgumentParser()
parser.add_argument('OutputDirectory', help='The directory where the generated images will be saved')
parser.add_argument('--numberOfImages', help='The number of generated images. Default: 100', type=int, default=100)... | [
"cv2.imwrite",
"numpy.ones",
"argparse.ArgumentParser",
"ast.literal_eval",
"numpy.random.randint"
] | [((77, 102), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (100, 102), False, 'import argparse\n'), ((895, 927), 'ast.literal_eval', 'ast.literal_eval', (['args.imageSize'], {}), '(args.imageSize)\n', (911, 927), False, 'import ast\n'), ((943, 978), 'ast.literal_eval', 'ast.literal_eval', (['a... |
# Copyright 2021 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.... | [
"numpy.mean",
"numpy.linalg.pinv",
"datasets.utils.file_utils.add_start_docstrings",
"numpy.array",
"numpy.dot",
"numpy.linalg.inv",
"datasets.Value",
"numpy.cov"
] | [((1945, 2030), 'datasets.utils.file_utils.add_start_docstrings', 'datasets.utils.file_utils.add_start_docstrings', (['_DESCRIPTION', '_KWARGS_DESCRIPTION'], {}), '(_DESCRIPTION,\n _KWARGS_DESCRIPTION)\n', (1991, 2030), False, 'import datasets\n'), ((2534, 2545), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (254... |
import numpy as np
import matplotlib.pyplot as plt
from .integrate import Integrate
class Riemann(Integrate):
"""
Compute the Riemann sum of f(x) over the interval [a,b].
Parameters
----------
f : function
A single variable function f(x), ex: lambda x:np.exp(x**2)
"""
def _... | [
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((1479, 1518), 'numpy.linspace', 'np.linspace', (['self.a', 'self.b', '(self.N + 1)'], {}), '(self.a, self.b, self.N + 1)\n', (1490, 1518), True, 'import numpy as np\n'), ((2043, 2082), 'numpy.linspace', 'np.linspace', (['self.a', 'self.b', '(self.N + 1)'], {}), '(self.a, self.b, self.N + 1)\n', (2054, 2082), True, 'i... |
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import utils
from torch.utils.data import Dataset, DataLoader
from net import model
import math
from tqdm import tqdm
import matplotlib.pyplot as plt
import os
from sklearn.preprocessing import StandardScaler
from torch.optim import lr_scheduler
... | [
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"net.model.RNN_modelv1",
"numpy.array",
"torch.nn.MSELoss",
"utils.Setloader",
"torch.cuda.is_available",
"torch.squeeze",
"net.model.train",
"net.model.eval",
"torch.unsqueeze",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"net.model... | [((635, 660), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (658, 660), False, 'import torch\n'), ((876, 967), 'pandas.read_csv', 'pd.read_csv', (['"""D:\\\\dataset\\\\lilium_price\\\\train_data.csv"""'], {'encoding': '"""utf-8"""', 'index_col': '(0)'}), "('D:\\\\dataset\\\\lilium_price\\\\tra... |
import argparse
import numpy as np
import utils.loader as l
def get_arguments():
"""Gets arguments from the command line.
Returns:
A parser with the input arguments.
"""
# Creates the ArgumentParser
parser = argparse.ArgumentParser(
usage='Digitizes a numpy array into interval... | [
"numpy.flip",
"utils.loader.load_npy",
"numpy.unique",
"argparse.ArgumentParser",
"numpy.digitize",
"numpy.linspace",
"utils.loader.save_npy",
"numpy.zeros",
"numpy.bincount"
] | [((243, 347), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'usage': '"""Digitizes a numpy array into intervals in order to create targets."""'}), "(usage=\n 'Digitizes a numpy array into intervals in order to create targets.')\n", (266, 347), False, 'import argparse\n'), ((796, 819), 'utils.loader.loa... |
import numpy as np
import pandas as pd
import tensorflow as tf
tfd = tf.contrib.distributions
def create_german_datasets(batch=64):
def gather_labels(df):
labels = []
for j in range(df.shape[1]):
if type(df[0, j]) is str:
labels.append(np.unique(df[:, j]).tolist())
... | [
"numpy.mean",
"numpy.median",
"numpy.unique",
"pandas.read_csv",
"tensorflow.data.Dataset.from_tensor_slices",
"numpy.zeros",
"numpy.random.seed",
"numpy.arange",
"numpy.random.shuffle"
] | [((1895, 1916), 'numpy.arange', 'np.arange', (['d.shape[0]'], {}), '(d.shape[0])\n', (1904, 1916), True, 'import numpy as np\n'), ((1921, 1938), 'numpy.random.seed', 'np.random.seed', (['(4)'], {}), '(4)\n', (1935, 1938), True, 'import numpy as np\n'), ((1943, 1965), 'numpy.random.shuffle', 'np.random.shuffle', (['idx'... |
import bisect
import math
import operator
from datetime import timedelta
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
import matplotlib.font_manager as font_manager
import matplotlib.patheff... | [
"scipy.ndimage.filters.gaussian_filter",
"numpy.array",
"datetime.timedelta",
"matplotlib.patheffects.withStroke",
"historical_hrrr.historical_hrrr_snow",
"numpy.arange",
"numpy.where",
"nohrsc_plotting.nohrsc_snow",
"plot_cities.get_cities",
"matplotlib.colors.ListedColormap",
"matplotlib.offse... | [((593, 628), 'matplotlib.font_manager.findSystemFonts', 'font_manager.findSystemFonts', (["['.']"], {}), "(['.'])\n", (621, 628), True, 'import matplotlib.font_manager as font_manager\n'), ((1358, 1385), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (1368, 1385), True, ... |
import tensorflow as tf
import numpy as np
import os
import pickle
from utils.symbolic_network import SymbolicNet, MaskedSymbolicNet, SymbolicCell
from utils import functions, regularization, helpers, pretty_print
import argparse
def main(results_dir='results/sho/test', trials=1, learning_rate=1e-2, reg_weight=2e-4, ... | [
"utils.symbolic_network.SymbolicCell",
"tensorflow.shape",
"utils.functions.Square",
"tensorflow.sin",
"utils.functions.Exp",
"os.path.exists",
"argparse.ArgumentParser",
"tensorflow.placeholder",
"tensorflow.Session",
"numpy.asarray",
"json.dumps",
"numpy.stack",
"utils.helpers.batch_genera... | [((795, 821), 'numpy.load', 'np.load', (['"""dataset/sho.npz"""'], {}), "('dataset/sho.npz')\n", (802, 821), True, 'import numpy as np\n'), ((832, 855), 'numpy.asarray', 'np.asarray', (["data['x_d']"], {}), "(data['x_d'])\n", (842, 855), True, 'import numpy as np\n'), ((866, 889), 'numpy.asarray', 'np.asarray', (["data... |
import torch
import torch.utils.data
from torch import nn
from torch.nn import functional as F
from rlkit.pythonplusplus import identity
from rlkit.torch import pytorch_util as ptu
import numpy as np
from rlkit.torch.conv_networks import CNN, DCNN
from rlkit.torch.vae.vae_base import GaussianLatentVAE
imsize48_default... | [
"torch.ones_like",
"torch.nn.functional.mse_loss",
"numpy.ones",
"torch.nn.LSTM",
"numpy.log",
"torch.nn.functional.binary_cross_entropy",
"numpy.zeros",
"torch.nn.Linear",
"rlkit.torch.pytorch_util.ones_like",
"torch.clamp",
"rlkit.torch.pytorch_util.zeros"
] | [((1868, 1902), 'numpy.zeros', 'np.zeros', (['self.representation_size'], {}), '(self.representation_size)\n', (1876, 1902), True, 'import numpy as np\n'), ((1928, 1961), 'numpy.ones', 'np.ones', (['self.representation_size'], {}), '(self.representation_size)\n', (1935, 1961), True, 'import numpy as np\n'), ((2993, 303... |
"""
game.py
Game class which contains the player, target, and all the walls.
"""
from math import cos, sin
import matplotlib.collections as mc
import pylab as plt
from numpy import asarray, pi
from config import Config
from environment.robot import Robot
from utils.dictionary import *
from utils.myutils import load_... | [
"pylab.ylim",
"environment.robot.Robot",
"pylab.arrow",
"utils.myutils.load_pickle",
"config.Config",
"utils.vec2d.Vec2d",
"numpy.asarray",
"pylab.plot",
"matplotlib.collections.LineCollection",
"math.cos",
"pylab.xlim",
"pylab.subplots",
"math.sin",
"utils.myutils.store_pickle"
] | [((7103, 7119), 'environment.robot.Robot', 'Robot', ([], {'game': 'self'}), '(game=self)\n', (7108, 7119), False, 'from environment.robot import Robot\n'), ((8882, 8935), 'utils.myutils.store_pickle', 'store_pickle', (['persist_dict', 'f"""{self.save_path}{self}"""'], {}), "(persist_dict, f'{self.save_path}{self}')\n",... |
import numpy as np
import torch as th
import torch.nn as nn
from rls.nn.mlps import MLP
from rls.nn.represent_nets import RepresentationNetwork
class QattenMixer(nn.Module):
def __init__(self,
n_agents: int,
state_spec,
rep_net_params,
agent_o... | [
"numpy.sqrt",
"torch.nn.ModuleList",
"torch.nn.Linear",
"rls.nn.mlps.MLP",
"torch.no_grad",
"torch.cat",
"rls.nn.represent_nets.RepresentationNetwork"
] | [((714, 787), 'rls.nn.represent_nets.RepresentationNetwork', 'RepresentationNetwork', ([], {'obs_spec': 'state_spec', 'rep_net_params': 'rep_net_params'}), '(obs_spec=state_spec, rep_net_params=rep_net_params)\n', (735, 787), False, 'from rls.nn.represent_nets import RepresentationNetwork\n'), ((1117, 1132), 'torch.nn.... |
import numpy as np
import os
import nibabel as nib
from skimage.transform import resize
from tqdm import tqdm
import matplotlib.pyplot as plt
import SimpleITK as sitk
spacing = {
0: [1.5, 0.8, 0.8],
1: [1.5, 0.8, 0.8],
2: [1.5, 0.8, 0.8],
3: [1.5, 0.8, 0.8],
4: [1.5, 0.8, 0.8],
5: [1.5, 0.8, 0.... | [
"os.path.exists",
"SimpleITK.GetImageFromArray",
"os.makedirs",
"numpy.round",
"os.path.join",
"SimpleITK.GetArrayFromImage",
"numpy.array",
"SimpleITK.ReadImage",
"os.walk"
] | [((445, 462), 'os.walk', 'os.walk', (['ori_path'], {}), '(ori_path)\n', (452, 462), False, 'import os\n'), ((3910, 3938), 'os.path.join', 'os.path.join', (['root1', 'i_dirs1'], {}), '(root1, i_dirs1)\n', (3922, 3938), False, 'import os\n'), ((736, 764), 'os.path.join', 'os.path.join', (['root1', 'i_dirs1'], {}), '(root... |
# Simple single neuron network to model a regression task
from __future__ import print_function
import numpy as np
#np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD,... | [
"numpy.random.rand",
"datetime.datetime.utcnow",
"numpy.random.permutation",
"keras.models.Sequential",
"math.fabs",
"numpy.full",
"numpy.vectorize",
"keras.layers.core.Dense"
] | [((714, 726), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (724, 726), False, 'from keras.models import Sequential\n'), ((5385, 5409), 'numpy.vectorize', 'np.vectorize', (['Chromosome'], {}), '(Chromosome)\n', (5397, 5409), True, 'import numpy as np\n'), ((5455, 5507), 'numpy.full', 'np.full', (['(1, popu... |
from __future__ import print_function, division
from PIL import Image
from torchvision.transforms import ToTensor, ToPILImage, Compose, Normalize
import numpy as np
import random
import tarfile
import io
import os
import pandas as pd
import torch
from torch.utils.data import Dataset
# %% custom dataset
class Places... | [
"numpy.copy",
"numpy.ceil",
"tarfile.open",
"torchvision.transforms.ToPILImage",
"pandas.read_csv",
"io.BytesIO",
"os.path.join",
"random.seed",
"numpy.array",
"numpy.random.randint",
"torch.tensor",
"random.random",
"torchvision.transforms.ToTensor",
"torchvision.transforms.Compose"
] | [((1046, 1089), 'pandas.read_csv', 'pd.read_csv', (['txt_path'], {'sep': '""" """', 'index_col': '(0)'}), "(txt_path, sep=' ', index_col=0)\n", (1057, 1089), True, 'import pandas as pd\n'), ((1255, 1265), 'torchvision.transforms.ToTensor', 'ToTensor', ([], {}), '()\n', (1263, 1265), False, 'from torchvision.transforms ... |
from dsynth.view_datasets.tless import TlessMultiviewDataset
from dsynth import MultiviewWarper
import numpy as np
def test_tless_dataset():
dataset = TlessMultiviewDataset(obj_id=2, unit_test=True)
ibr = MultiviewWarper(dataset)
R = np.reshape(dataset[1].cam_R, (3,3)).astype(np.float32)
t = np.float... | [
"dsynth.MultiviewWarper",
"numpy.reshape",
"numpy.float32",
"dsynth.view_datasets.tless.TlessMultiviewDataset"
] | [((156, 203), 'dsynth.view_datasets.tless.TlessMultiviewDataset', 'TlessMultiviewDataset', ([], {'obj_id': '(2)', 'unit_test': '(True)'}), '(obj_id=2, unit_test=True)\n', (177, 203), False, 'from dsynth.view_datasets.tless import TlessMultiviewDataset\n'), ((214, 238), 'dsynth.MultiviewWarper', 'MultiviewWarper', (['da... |
import types
import sqlite3
from collections import namedtuple
from functools import reduce
import numpy
from glue.lal import LIGOTimeGPS
from glue.ligolw import ligolw, lsctables, table, ilwd
from glue.ligolw.utils import process
def assign_id(row, i):
row.simulation_id = ilwd.ilwdchar("sim_inspiral_table:sim_... | [
"glue.ligolw.ligolw.LIGO_LW",
"glue.ligolw.table.get_next_id",
"collections.namedtuple",
"numpy.sqrt",
"sqlite3.connect",
"numpy.random.random",
"glue.ligolw.utils.write_filename",
"glue.ligolw.table.get_table",
"glue.ligolw.ligolw.Document",
"glue.ligolw.table.RowType",
"numpy.exp",
"numpy.ar... | [((282, 337), 'glue.ligolw.ilwd.ilwdchar', 'ilwd.ilwdchar', (["('sim_inspiral_table:sim_inspiral:%d' % i)"], {}), "('sim_inspiral_table:sim_inspiral:%d' % i)\n", (295, 337), False, 'from glue.ligolw import ligolw, lsctables, table, ilwd\n'), ((2121, 2169), 'numpy.array', 'numpy.array', (['[sampdict[k] for k in keys]', ... |
import numpy as np
import fcl
import torch
# R = np.array([[0.0, -1.0, 0.0],
# [1.0, 0.0, 0.0],
# [0.0, 0.0, 1.0]])
R = np.array([[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0]])
T = np.array([1.0, 1.865, 0])
g1 = fcl.Box(1,2,3)
t1 = fcl.Transform()
o1 = ... | [
"fcl.Cylinder",
"fcl.update",
"matplotlib.pyplot.show",
"fcl.Transform",
"fcl.collide",
"torch.stack",
"fcl.CollisionObject",
"numpy.array",
"matplotlib.pyplot.scatter",
"fcl.CollisionRequest",
"torch.zeros_like",
"fcl.Box",
"torch.linspace",
"fcl.CollisionResult"
] | [((151, 212), 'numpy.array', 'np.array', (['[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]'], {}), '([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])\n', (159, 212), True, 'import numpy as np\n'), ((247, 272), 'numpy.array', 'np.array', (['[1.0, 1.865, 0]'], {}), '([1.0, 1.865, 0])\n', (255, 272), True, 'impor... |
# -*- coding: utf-8 -*-
import librosa.display
import librosa as lb
import os
import numpy as np
import pickle
import matplotlib.pyplot as plt
import time
import multiprocessing
import itertools
import sys
from collections import OrderedDict
from more_itertools import unique_everseen
from scipy.stats import skew
from ... | [
"librosa.feature.poly_features",
"librosa.feature.zero_crossing_rate",
"multiprocessing.cpu_count",
"numpy.array",
"librosa.feature.spectral_centroid",
"librosa.feature.spectral_bandwidth",
"librosa.feature.spectral_contrast",
"librosa.load",
"numpy.arange",
"numpy.mean",
"itertools.repeat",
"... | [((881, 900), 'numpy.array', 'np.array', (['splittime'], {}), '(splittime)\n', (889, 900), True, 'import numpy as np\n'), ((1169, 1188), 'numpy.array', 'np.array', (['splitfreq'], {}), '(splitfreq)\n', (1177, 1188), True, 'import numpy as np\n'), ((7649, 7670), 'librosa.effects.hpss', 'lb.effects.hpss', (['song'], {}),... |
import streamlit as st
from streamlit_yellowbrick import st_yellowbrick
def run_regression():
with st.sidebar.form(key="regression_form"):
regression_visualizers = st.multiselect(
"Choose Regression Visualizers",
[
"Residuals Plot",
"Prediction Erro... | [
"streamlit.checkbox",
"yellowbrick.datasets.load_concrete",
"yellowbrick.regressor.PredictionError",
"yellowbrick.regressor.AlphaSelection",
"streamlit.markdown",
"sklearn.linear_model.LassoCV",
"sklearn.linear_model.Lasso",
"streamlit.beta_columns",
"sklearn.model_selection.train_test_split",
"ye... | [((6089, 6104), 'yellowbrick.datasets.load_concrete', 'load_concrete', ([], {}), '()\n', (6102, 6104), False, 'from yellowbrick.datasets import load_concrete\n'), ((6182, 6236), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': '(42)'}), '(X, y, test_siz... |
import numpy as np
from PIL import Image
from skimage import color
from skimage.feature import hog
from pelops.features.feature_producer import FeatureProducer
class HOGFeatureProducer(FeatureProducer):
def __init__(self, chip_producer, image_size=(224,224), cells=(16, 16), orientations=8, histogram_bins_per_ch... | [
"numpy.histogram",
"numpy.array",
"numpy.concatenate",
"numpy.full",
"skimage.feature.hog"
] | [((907, 972), 'numpy.full', 'np.full', ([], {'shape': '(3 * self.histogram_bins_per_channel)', 'fill_value': '(-1)'}), '(shape=3 * self.histogram_bins_per_channel, fill_value=-1)\n', (914, 972), True, 'import numpy as np\n'), ((1798, 1935), 'skimage.feature.hog', 'hog', (['img'], {'orientations': 'self.orientations', '... |
import numpy as np
arr = np.random.choice([6, 8, 3, 1, 5], p=[0.0, 0.5, 0.2, 0.2, 0.1], size=(100))
print(arr)
arr = np.random.choice([6, 8, 3, 1, 5], p=[0.0, 0.5, 0.2, 0.2, 0.1], size=100)
print(arr)
arr = np.random.choice([6, 8, 3, 1, 5], p=[0.0, 0.5, 0.2, 0.2, 0.1], size=(5, 10))
print(arr)
| [
"numpy.random.choice"
] | [((28, 100), 'numpy.random.choice', 'np.random.choice', (['[6, 8, 3, 1, 5]'], {'p': '[0.0, 0.5, 0.2, 0.2, 0.1]', 'size': '(100)'}), '([6, 8, 3, 1, 5], p=[0.0, 0.5, 0.2, 0.2, 0.1], size=100)\n', (44, 100), True, 'import numpy as np\n'), ((121, 193), 'numpy.random.choice', 'np.random.choice', (['[6, 8, 3, 1, 5]'], {'p': ... |
"""
Example of a simple genetic algorithm based on DeepNEAT
Miikkulainen, Risto, et al. "Evolving deep neural networks."
Artificial Intelligence in the Age of Neural Networks and Brain Computing.
Academic Press, 2019. 293-312.
"""
import time
import traceback
import numpy as np
import... | [
"nord.neural_nets.LocalEvaluator",
"nord.design.metaheuristics.genetics.neat.Innovation",
"numpy.random.choice",
"numpy.argmax",
"nord.utils.assure_reproducibility",
"nord.design.metaheuristics.genetics.neat.Genome",
"traceback.print_exc",
"time.time"
] | [((503, 527), 'nord.utils.assure_reproducibility', 'assure_reproducibility', ([], {}), '()\n', (525, 527), False, 'from nord.utils import assure_reproducibility\n'), ((1248, 1291), 'nord.neural_nets.LocalEvaluator', 'LocalEvaluator', (['torch.optim.Adam', '{}', '(False)'], {}), '(torch.optim.Adam, {}, False)\n', (1262,... |
import pymysql
import pandas as pd
import pickle
import numpy as np
import databaseInfo as db
databaseName = 'root'
databasePasswd = '<PASSWORD>'
def user_info_query(user_id):
conn = pymysql.connect(host=db.databaseAddress, user=db.databaseLoginName, password=db.databasePasswd, database=db.databaseName)
cur =... | [
"pandas.read_sql",
"numpy.zeros",
"pymysql.connect",
"numpy.reshape"
] | [((189, 314), 'pymysql.connect', 'pymysql.connect', ([], {'host': 'db.databaseAddress', 'user': 'db.databaseLoginName', 'password': 'db.databasePasswd', 'database': 'db.databaseName'}), '(host=db.databaseAddress, user=db.databaseLoginName,\n password=db.databasePasswd, database=db.databaseName)\n', (204, 314), False... |
#
# locally sensitive hashing code
#
from collections import defaultdict
import numpy as np
import xxhash
import sys
import pyximport
pyximport.install()
sys.path.insert(0, 'tools')
import simcore as csimcore
# k-shingles: pairs of adjacent k-length substrings (in order)
def shingle(s, k=2):
k = min(len(s), k)
... | [
"sys.path.insert",
"xxhash.xxh64_intdigest",
"pyximport.install",
"numpy.uint64",
"collections.defaultdict"
] | [((136, 155), 'pyximport.install', 'pyximport.install', ([], {}), '()\n', (153, 155), False, 'import pyximport\n'), ((156, 183), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""tools"""'], {}), "(0, 'tools')\n", (171, 183), False, 'import sys\n'), ((469, 494), 'xxhash.xxh64_intdigest', 'xxhash.xxh64_intdigest', (['x... |
"""
File: sample_generator.py
Author: Nrupatunga
Email: <EMAIL>
Github: https://github.com/nrupatunga
Description: Generating samples from single frame
"""
import sys
import cv2
import numpy as np
from loguru import logger
try:
from goturn.helper.BoundingBox import BoundingBox
from goturn.helper.image_proc i... | [
"goturn.helper.image_io._is_pil_image",
"goturn.helper.draw_util.draw.bbox",
"goturn.helper.image_proc.cropPadImage",
"goturn.helper.BoundingBox.BoundingBox",
"numpy.asarray",
"loguru.logger.error",
"goturn.helper.vis_utils.Visualizer",
"cv2.cvtColor",
"sys.exit",
"numpy.concatenate",
"cv2.resiz... | [((498, 564), 'loguru.logger.error', 'logger.error', (['"""Please run $source settings.sh from root directory"""'], {}), "('Please run $source settings.sh from root directory')\n", (510, 564), False, 'from loguru import logger\n'), ((569, 580), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (577, 580), False, 'import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.