code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import os
import pathlib
from glob import glob
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
from tensorflow.keras import Model
from tensorflow.keras.layers import *
from tensorflow.keras.preprocessing... | [
"sklearn.preprocessing.LabelBinarizer",
"numpy.random.seed",
"numpy.sum",
"pathlib.Path.home",
"sklearn.model_selection.train_test_split",
"tensorflow.keras.Model",
"numpy.random.randint",
"numpy.array",
"glob.glob"
] | [((2177, 2197), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (2191, 2197), True, 'import numpy as np\n'), ((2695, 2751), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)', 'random_state': 'SEED'}), '(X, y, test_size=0.2, random_state=SEED)\n', (2711... |
from PIL import Image
import numpy as np
import komm as komm
class CorectionCodes:
def __init__(self,bits):
"""Load data from file and get size and pixel data (as 'image_bits')
"""
self.image_bits = bits
def bits_trippling_1(self):
"""Function which return trippled bits in ord... | [
"komm.BCHCode",
"numpy.append",
"numpy.array",
"numpy.reshape",
"komm.SingleParityCheckCode",
"komm.HammingCode",
"numpy.concatenate",
"numpy.repeat"
] | [((360, 385), 'numpy.array', 'np.array', (['self.image_bits'], {}), '(self.image_bits)\n', (368, 385), True, 'import numpy as np\n'), ((425, 443), 'numpy.repeat', 'np.repeat', (['bits', '(3)'], {}), '(bits, 3)\n', (434, 443), True, 'import numpy as np\n'), ((613, 638), 'numpy.array', 'np.array', (['self.image_bits'], {... |
import numpy as np
import torch
from itertools import product
from functools import reduce
from operator import add
from Data.data_utils import new_node_by_val
def iter_input(input_seq):
if isinstance(input_seq, list):
for s in input_seq:
yield [s]
else:
batch_size = input_seq.shap... | [
"numpy.argmax",
"numpy.zeros",
"numpy.ones",
"numpy.take",
"itertools.product",
"functools.reduce"
] | [((620, 661), 'numpy.zeros', 'np.zeros', (['[max_len, beam_size]'], {'dtype': 'int'}), '([max_len, beam_size], dtype=int)\n', (628, 661), True, 'import numpy as np\n'), ((785, 826), 'numpy.zeros', 'np.zeros', (['[max_len, beam_size]'], {'dtype': 'int'}), '([max_len, beam_size], dtype=int)\n', (793, 826), True, 'import ... |
import numpy as np
import matplotlib.pyplot as plt
from parser_xyz import XYZParser
def parse_average_velocity(file):
parsed_data = XYZParser(file)
average_velocities = []
time = []
for iteration in parsed_data.get_output():
velocities = []
time.append(iteration[0].get_time_passed())
... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"numpy.average",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"parser_xyz.XYZParser",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tight_layout"
] | [((1578, 1639), 'matplotlib.pyplot.plot', 'plt.plot', (['time_1', 'average_velocities_1'], {'label': '"""48 partículas"""'}), "(time_1, average_velocities_1, label='48 partículas')\n", (1586, 1639), True, 'import matplotlib.pyplot as plt\n'), ((1640, 1702), 'matplotlib.pyplot.plot', 'plt.plot', (['time_2', 'average_vel... |
"""
v.e.s.
To make FPC predictions
MIT License
Copyright (c) 2020 <NAME>
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 right... | [
"numpy.save",
"pandas.read_csv",
"torch.manual_seed",
"torch.load",
"sklearn.preprocessing.MinMaxScaler",
"numpy.zeros",
"os.path.getsize",
"time.sleep",
"os.path.isfile",
"numpy.array",
"random.seed",
"torch.nn.Linear",
"torch.zeros",
"torch.nn.LSTM",
"torch.no_grad",
"torch.from_nump... | [((1425, 1445), 'torch.manual_seed', 'torch.manual_seed', (['(3)'], {}), '(3)\n', (1442, 1445), False, 'import torch\n'), ((1447, 1461), 'random.seed', 'random.seed', (['(3)'], {}), '(3)\n', (1458, 1461), False, 'import random\n'), ((1699, 1715), 'numpy.array', 'np.array', (['dfinal'], {}), '(dfinal)\n', (1707, 1715), ... |
import numpy as np
from scipy import linalg
def monte_carlo_sample(mu: np.ndarray, r: np.ndarray, t=1):
"""
creates a monte carlo sample from the mean and covariance
:param mu: distribution mean
:param r: distribution covariance
:param t: number of samples to generate
:return:
"""
p = ... | [
"scipy.linalg.cholesky",
"numpy.size",
"numpy.random.randn"
] | [((320, 333), 'numpy.size', 'np.size', (['r', '(0)'], {}), '(r, 0)\n', (327, 333), True, 'import numpy as np\n'), ((345, 375), 'scipy.linalg.cholesky', 'linalg.cholesky', (['r'], {'lower': '(True)'}), '(r, lower=True)\n', (360, 375), False, 'from scipy import linalg\n'), ((386, 407), 'numpy.random.randn', 'np.random.ra... |
import json
import os
import random
import bottle
import time
from api import ping_response, start_response, move_response, end_response
from Queue import Queue
from copy import deepcopy as copy
import numpy as np
from collections import defaultdict
class Loc:
def __init__(self,x,y):
self.x = x
... | [
"copy.deepcopy",
"api.ping_response",
"Queue.Queue",
"bottle.default_app",
"bottle.static_file",
"numpy.zeros",
"bottle.route",
"collections.defaultdict",
"numpy.sort",
"api.start_response",
"api.move_response",
"api.end_response",
"os.getenv",
"bottle.post"
] | [((6463, 6480), 'bottle.route', 'bottle.route', (['"""/"""'], {}), "('/')\n", (6475, 6480), False, 'import bottle\n'), ((6643, 6678), 'bottle.route', 'bottle.route', (['"""/static/<path:path>"""'], {}), "('/static/<path:path>')\n", (6655, 6678), False, 'import bottle\n'), ((6922, 6942), 'bottle.post', 'bottle.post', ([... |
import time
from datetime import timedelta
from enum import Enum, auto
from threading import Thread
from typing import List, Optional, Union, Dict, Tuple
import numpy as np
import RPi.GPIO as gpio
from rpi.gpio import Component
from rpi.gpio.ic_chips import ShiftRegister
class LED(Component):
"""
LED.
""... | [
"threading.Thread",
"RPi.GPIO.setup",
"numpy.zeros",
"time.sleep",
"RPi.GPIO.PWM",
"numpy.array",
"enum.auto",
"RPi.GPIO.output",
"numpy.all"
] | [((23339, 23566), 'numpy.array', 'np.array', (['[[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 0, 0, 0, 1, 0], [1, 0, 1, 0, 0, 1, 0, \n 1], [1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 1, 0, 0, 1, 0, 1], [0, 1, 0, 1, 1,\n 0, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0]]'], {}), '([[0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 0, 0, 0,... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | [
"numpy.sum",
"numpy.empty",
"numpy.zeros",
"numpy.argpartition",
"numpy.array",
"collections.namedtuple",
"numpy.nanmean"
] | [((6163, 6253), 'collections.namedtuple', 'collections.namedtuple', (['"""ObjectClassifyEvalMetrics"""', "['average_precisions', 'mean_ap']"], {}), "('ObjectClassifyEvalMetrics', ['average_precisions',\n 'mean_ap'])\n", (6185, 6253), False, 'import collections\n'), ((6674, 6711), 'numpy.empty', 'np.empty', (['self.n... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import numpy as np
import tensorflow as tf
from matplotlib import pyplot as plt
import scipy.sparse as sp
import GCN
import utils
import AFGSM
direct_attack = True # dicrect attack or indirect attack
perturb_features = True # whether perturb features
dataset = 'cora... | [
"numpy.random.seed",
"numpy.abs",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.arange",
"numpy.random.randint",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.tight_layout",
"AFGSM.AFGSM",
"matplotlib.pyplot.show",
"utils.preprocess_graph",
"matplotlib.pyplot.ylim",... | [((785, 827), 'utils.largest_connected_components', 'utils.largest_connected_components', (['_A_obs'], {}), '(_A_obs)\n', (819, 827), False, 'import utils\n'), ((1270, 1300), 'utils.preprocess_graph', 'utils.preprocess_graph', (['_A_obs'], {}), '(_A_obs)\n', (1292, 1300), False, 'import utils\n'), ((1574, 1594), 'numpy... |
"""
audio model config
"""
import numpy as np
import mfcc.feature_extractor as feature_extractor
class ModelAudio(object):
"""
modelAudio
"""
def __init__(self, configs, use_gpu=1):
self.use_gpu = use_gpu
self.audio_fps = configs.COMMON.fps
self.audio_feat_scale = configs.TSN... | [
"numpy.fromstring",
"mfcc.feature_extractor.wav_to_example"
] | [((490, 545), 'mfcc.feature_extractor.wav_to_example', 'feature_extractor.wav_to_example', (['wav_data', 'sample_rate'], {}), '(wav_data, sample_rate)\n', (522, 545), True, 'import mfcc.feature_extractor as feature_extractor\n'), ((890, 929), 'numpy.fromstring', 'np.fromstring', (['pcm_data'], {'dtype': 'np.int16'}), '... |
# -*- coding: utf-8 -*-
import numpy as np
import sys
import pickle
import os
import sknw
from time import sleep
from skimage.measure import find_contours
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
def show_progress_bar(progress, message='Progress'):
s... | [
"sys.stdout.write",
"pickle.dump",
"matplotlib.pyplot.figure",
"pickle.load",
"sys.stdout.flush",
"skimage.measure.find_contours",
"numpy.linalg.norm",
"os.path.join",
"os.path.exists",
"numpy.max",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylim",
"numpy.roll",
"time.sleep",
"sknw.bui... | [((319, 341), 'sys.stdout.write', 'sys.stdout.write', (["'\\r'"], {}), "('\\r')\n", (335, 341), False, 'import sys\n'), ((389, 468), 'sys.stdout.write', 'sys.stdout.write', (["((message + ': [%-20s] %d%%') % ('=' * progress, 5 * progress))"], {}), "((message + ': [%-20s] %d%%') % ('=' * progress, 5 * progress))\n", (40... |
import numpy as np
import os
import random
import torch
from data.datamgr import SetDataManager, SimpleDataManager
from options import parse_args, get_resume_file, load_warmup_state
from methods.LFTNet import LFTNet
from datasets import cifar100_few_shot
import ipdb
def cycle(iterable):
while True:
for x in iter... | [
"numpy.random.seed",
"os.makedirs",
"os.path.isdir",
"random.sample",
"datasets.cifar100_few_shot.SimpleDataManager",
"options.load_warmup_state",
"options.parse_args",
"options.get_resume_file",
"data.datamgr.SetDataManager",
"data.datamgr.SimpleDataManager",
"datasets.cifar100_few_shot.SetData... | [((1860, 1878), 'numpy.random.seed', 'np.random.seed', (['(10)'], {}), '(10)\n', (1874, 1878), True, 'import numpy as np\n'), ((1910, 1929), 'options.parse_args', 'parse_args', (['"""train"""'], {}), "('train')\n", (1920, 1929), False, 'from options import parse_args, get_resume_file, load_warmup_state\n'), ((2604, 266... |
"""
Handle time and time intervals.
"""
from functools import reduce
import operator as op
import numpy as np
from roto import arrays
def select_from(t, intervals):
"""Index for selecting time intervals from a time array.
Arguments:
t -- time array from which times are selected
intervals -- list o... | [
"numpy.zeros_like",
"numpy.ones_like",
"numpy.ceil",
"numpy.logical_and",
"roto.arrays.find_groups",
"numpy.diff",
"roto.arrays.merge_adjacent_groups"
] | [((1511, 1546), 'roto.arrays.find_groups', 'arrays.find_groups', (['ix'], {'min_size': 'sz'}), '(ix, min_size=sz)\n', (1529, 1546), False, 'from roto import arrays\n'), ((530, 551), 'numpy.zeros_like', 'np.zeros_like', (['t', '"""?"""'], {}), "(t, '?')\n", (543, 551), True, 'import numpy as np\n'), ((1434, 1454), 'nump... |
import os
from tqdm import tqdm
import json
import open3d as o3d
import numpy as np
def load_car_models(car_model_dir):
car_model_dict = {}
for car_name in tqdm(os.listdir(car_model_dir)):
with open(os.path.join(car_model_dir, car_name)) as json_file:
car_model_dict[car_name[:-5]] = json.l... | [
"json.load",
"os.path.join",
"open3d.utility.Vector3iVector",
"numpy.asarray",
"open3d.geometry.TriangleMesh",
"numpy.array",
"open3d.utility.Vector3dVector",
"os.listdir"
] | [((171, 196), 'os.listdir', 'os.listdir', (['car_model_dir'], {}), '(car_model_dir)\n', (181, 196), False, 'import os\n'), ((564, 595), 'numpy.array', 'np.array', (["car_model['vertices']"], {}), "(car_model['vertices'])\n", (572, 595), True, 'import numpy as np\n'), ((653, 681), 'numpy.array', 'np.array', (["car_model... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import ads
import sys
import time
import numpy as np
import pickle
import shutil
import requests
import unicodedata as ud
if sys.version_info[0] > 2:
input_line = input
else:
input_line = raw... | [
"unicodedata.normalize",
"os.path.dirname",
"time.sleep",
"os.path.isfile",
"ads.ExportQuery",
"ads.SearchQuery",
"shutil.copy",
"os.path.join",
"numpy.unique"
] | [((665, 709), 'os.path.join', 'os.path.join', (['self.here', '"""my_library.pickle"""'], {}), "(self.here, 'my_library.pickle')\n", (677, 709), False, 'import os\n'), ((734, 775), 'os.path.join', 'os.path.join', (['self.here', '"""my_library.bib"""'], {}), "(self.here, 'my_library.bib')\n", (746, 775), False, 'import o... |
#!/usr/bin/env python
# coding: utf-8
# # Feature extraction
#
# ## Install Packages
# In[1]:
get_ipython().run_cell_magic('capture', '', '!pip install forgi\n!yes Y |conda install -c bioconda viennarna')
# ## Library Imports
# In[2]:
import os, math, random
from collections import Counter
import RNA
import... | [
"matplotlib.pyplot.title",
"numpy.load",
"RNA.fold_compound",
"seaborn.heatmap",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"forgi.visual.mplotlib.plot_rna",
"RNA.fold",
"pandas.DataFrame",
"numpy.zeros_like",
"numpy.max",
"numpy.triu_indices_from",
"collections.Counter",
"matplotlib.p... | [((665, 711), 'pandas.read_json', 'pd.read_json', (['f"""{path}/train.json"""'], {'lines': '(True)'}), "(f'{path}/train.json', lines=True)\n", (677, 711), True, 'import pandas as pd\n'), ((721, 766), 'pandas.read_json', 'pd.read_json', (['f"""{path}/test.json"""'], {'lines': '(True)'}), "(f'{path}/test.json', lines=Tru... |
simulationMode = False
if not simulationMode:
import TensorflowProcessingModule as TPM
from imutils.video.pivideostream import PiVideoStream
import MathModule as MM
import math, time, copy
import cv2
import numpy as np
from multiprocessing import Process, RawValue, RawArray
#program sluzacy do analizy obraz... | [
"MathModule.clamp",
"cv2.getPerspectiveTransform",
"multiprocessing.RawValue",
"cv2.imshow",
"numpy.round",
"cv2.warpPerspective",
"cv2.cvtColor",
"imutils.video.pivideostream.PiVideoStream",
"numpy.int32",
"cv2.resize",
"multiprocessing.RawArray",
"MathModule.lerp",
"numpy.size",
"cv2.cir... | [((1044, 1062), 'multiprocessing.RawValue', 'RawValue', (['"""f"""', '(0.0)'], {}), "('f', 0.0)\n", (1052, 1062), False, 'from multiprocessing import Process, RawValue, RawArray\n'), ((1087, 1105), 'multiprocessing.RawValue', 'RawValue', (['"""f"""', '(0.0)'], {}), "('f', 0.0)\n", (1095, 1105), False, 'from multiproces... |
#!/usr/bin/env python
"""
Copyright 2018, <NAME>, HKUST.
Numpy utils.
"""
import os
from math import cos, sin, pi
import random
import numpy as np
import tensorflow as tf
from tools.common import Notify
FLAGS = tf.compat.v1.app.flags.FLAGS
class EndPoints(object):
def __init__(self, endpoints, config):
... | [
"numpy.stack",
"numpy.random.uniform",
"json.load",
"cv2.getPerspectiveTransform",
"numpy.zeros",
"os.path.exists",
"numpy.ones",
"numpy.sin",
"numpy.array",
"numpy.reshape",
"numpy.random.normal",
"numpy.cos",
"numpy.sqrt"
] | [((2681, 2708), 'os.path.exists', 'os.path.exists', (['config_path'], {}), '(config_path)\n', (2695, 2708), False, 'import os\n'), ((3100, 3164), 'numpy.array', 'np.array', (['[[-1, 1], [1, 1], [-1, -1], [1, -1]]'], {'dtype': 'np.float32'}), '([[-1, 1], [1, 1], [-1, -1], [1, -1]], dtype=np.float32)\n', (3108, 3164), Tr... |
import os
import subprocess
import numpy as np
np.random.seed(123)
import torch
torch.manual_seed(123)
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
MODEL_PATH = "../model/age_est_model.pt"
DATAPATH = "../data/"
class twoHiddenNet(nn.Module):
def __init__(self, ... | [
"torch.nn.MSELoss",
"numpy.load",
"numpy.random.seed",
"os.remove",
"numpy.save",
"torch.manual_seed",
"torch.nn.init.xavier_uniform",
"subprocess.call",
"torch.nn.Linear",
"torch.from_numpy"
] | [((48, 67), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (62, 67), True, 'import numpy as np\n'), ((82, 104), 'torch.manual_seed', 'torch.manual_seed', (['(123)'], {}), '(123)\n', (99, 104), False, 'import torch\n'), ((1117, 1148), 'numpy.load', 'np.load', (["(DATAPATH + 'train.npy')"], {}), "(DAT... |
import numpy as np
from OpenGL.GL import *
from mgl2d.graphics.drawable import Drawable
from mgl2d.graphics.shader import Shader
from mgl2d.math.matrix4 import Matrix4
from mgl2d.math.vector2 import Vector2
class QuadDrawable(Drawable):
_default_shader = None
def __init__(self, x=0.0, y=0.0, scale_x=1, scal... | [
"mgl2d.math.matrix4.Matrix4",
"mgl2d.math.matrix4.Matrix4.translate",
"mgl2d.graphics.shader.Shader",
"mgl2d.math.vector2.Vector2",
"numpy.array"
] | [((442, 455), 'mgl2d.math.vector2.Vector2', 'Vector2', (['(0)', '(0)'], {}), '(0, 0)\n', (449, 455), False, 'from mgl2d.math.vector2 import Vector2\n'), ((481, 490), 'mgl2d.math.matrix4.Matrix4', 'Matrix4', ([], {}), '()\n', (488, 490), False, 'from mgl2d.math.matrix4 import Matrix4\n'), ((700, 764), 'numpy.array', 'np... |
from __future__ import print_function
import itertools
import numpy as np
import sys
sys.path.append('..')
from lib_inhomogeneous_gutzwiller import Gutzwiller
def test_lattice_definition_2D():
xy = np.empty(2, dtype=np.int32)
for L in [2, 3, 10, 11]:
G = Gutzwiller(D=2, L=L)
for i_site in ran... | [
"sys.path.append",
"numpy.empty",
"lib_inhomogeneous_gutzwiller.Gutzwiller"
] | [((86, 107), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (101, 107), False, 'import sys\n'), ((205, 232), 'numpy.empty', 'np.empty', (['(2)'], {'dtype': 'np.int32'}), '(2, dtype=np.int32)\n', (213, 232), True, 'import numpy as np\n'), ((274, 294), 'lib_inhomogeneous_gutzwiller.Gutzwiller', 'Gu... |
#-*- coding: utf8
'''Unit tests for the dist module'''
from __future__ import division, print_function
from math import sqrt
from numpy.testing import *
from pyksc import dist
import unittest
import numpy as np
class TestDist(unittest.TestCase):
def test_shift_roll(self):
array = np.array([])
... | [
"unittest.main",
"pyksc.dist.inner_prod",
"math.sqrt",
"pyksc.dist.dist_all",
"pyksc.dist.dist",
"pyksc.dist.shift",
"pyksc.dist.sqsum",
"numpy.array",
"pyksc.dist.shift_dist"
] | [((8135, 8150), 'unittest.main', 'unittest.main', ([], {}), '()\n', (8148, 8150), False, 'import unittest\n'), ((299, 311), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (307, 311), True, 'import numpy as np\n'), ((648, 663), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (656, 663), True, 'import numpy ... |
import baselines.common.tf_util as U
import pickle
import tensorflow as tf
import gym
import numpy as np
import cvxopt as cvx
import cvxpy
import cdd
cvx.solvers.options['show_progress'] = False
# ============== Class Definitions for
# 1.) Region
# 2.) HPolytope
# 3.) Polytope Tree
class Region(object):
def... | [
"numpy.abs",
"cdd.Matrix",
"tensorflow.get_collection",
"tensorflow.variables_initializer",
"numpy.ones",
"numpy.mean",
"numpy.linalg.norm",
"numpy.inner",
"cvxopt.solvers.lp",
"numpy.copy",
"numpy.random.randn",
"tensorflow.variable_scope",
"cvxopt.matrix",
"cdd.Polyhedron",
"numpy.mod"... | [((20797, 20836), 'numpy.concatenate', 'np.concatenate', (['(state, action)'], {'axis': '(0)'}), '((state, action), axis=0)\n', (20811, 20836), True, 'import numpy as np\n'), ((21613, 21646), 'numpy.concatenate', 'np.concatenate', (['(Ap, Ap_)'], {'axis': '(0)'}), '((Ap, Ap_), axis=0)\n', (21627, 21646), True, 'import ... |
"""
Copyright (c) 2020 <NAME>
All rights reserved.
@author <NAME> <<EMAIL>>
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
"""Parser for the MovieLens dataset found on
http://files.grouplens.org/datasets/movielens/ml-100k.zip"""
fr... | [
"pandas.read_csv",
"pandas.Timestamp",
"numpy.random.seed",
"argparse.ArgumentParser"
] | [((520, 538), 'pandas.Timestamp', 'pd.Timestamp', (['date'], {}), '(date)\n', (532, 538), True, 'import pandas as pd\n'), ((624, 720), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Parse csv dataset: select columns + sort."""'}), "(description=\n 'Parse csv dataset: ... |
import numpy as np
from matplotlib import pyplot as plt
import fnmatch, os, glob
import Preprocessing
from load import get_image
class Result:
def __init__(self, order, images, text):
self.order = order
self.images = images
self.text = text
def show(self):
titles = ['Original... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"Preprocessing.tesseract",
"os.path.dirname",
"matplotlib.pyplot.imshow",
"numpy.zeros",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.text",
"matplotlib.pyplot.gca",
"glob.glob",
"load.get_image",
"matplotlib.pyplot.xticks",
"os.listdir"... | [((1903, 1937), 'Preprocessing.tesseract', 'Preprocessing.tesseract', (['images[4]'], {}), '(images[4])\n', (1926, 1937), False, 'import Preprocessing\n'), ((2574, 2599), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2589, 2599), False, 'import fnmatch, os, glob\n'), ((2995, 3026), 'glob.gl... |
"""Authors: <NAME> and <NAME>."""
import numpy as np
from pathlib import Path
from hdf5storage import loadmat # scipy.io loadmat doesn't support >= v7.3 matlab files
import pandas as pd
from nwb_conversion_tools.basedatainterface import BaseDataInterface
from nwb_conversion_tools.utils.conversion_tools import (
c... | [
"nwb_conversion_tools.utils.conversion_tools.get_module",
"pandas.read_csv",
"hdmf.backends.hdf5.h5_utils.H5DataIO",
"nwb_conversion_tools.utils.conversion_tools.check_regular_timestamps",
"pathlib.Path",
"numpy.array",
"pynwb.behavior.Position"
] | [((1321, 1358), 'pathlib.Path', 'Path', (["self.source_data['folder_path']"], {}), "(self.source_data['folder_path'])\n", (1325, 1358), False, 'from pathlib import Path\n'), ((1675, 1712), 'pandas.read_csv', 'pd.read_csv', (['take_file_path'], {'header': '(5)'}), '(take_file_path, header=5)\n', (1686, 1712), True, 'imp... |
import numpy as np
import imageio
import os, shutil
import yaml
from typing import Dict, Text
from dannce.engine.data import io
from dannce import (
_param_defaults_dannce,
_param_defaults_shared,
_param_defaults_com,
)
import warnings
def grab_predict_label3d_file(defaultdir=""):
"""
Finds the pa... | [
"dannce.engine.data.io.load_camnames",
"os.makedirs",
"os.path.exists",
"numpy.max",
"yaml.safe_load",
"imageio.get_reader",
"shutil.copyfile",
"warnings.warn",
"os.path.join",
"os.listdir"
] | [((384, 413), 'os.path.join', 'os.path.join', (['"""."""', 'defaultdir'], {}), "('.', defaultdir)\n", (396, 413), False, 'import os, shutil\n'), ((434, 452), 'os.listdir', 'os.listdir', (['def_ep'], {}), '(def_ep)\n', (444, 452), False, 'import os, shutil\n'), ((1538, 1591), 'os.path.join', 'os.path.join', (["params['v... |
from torchkit import flows, nn as nn_, utils
from torch import optim, nn
from torch.autograd import Variable
import torch
import os
from scipy.spatial.distance import pdist, squareform
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
from torch.nn.parameter import Para... | [
"matplotlib.pyplot.title",
"pickle.dump",
"matplotlib.pyplot.figure",
"pickle.load",
"scipy.spatial.distance.pdist",
"torchkit.nn.sigmoid_",
"matplotlib.pyplot.tight_layout",
"os.path.join",
"torch.ones",
"matplotlib.pyplot.close",
"os.path.exists",
"torch.sin",
"torch.FloatTensor",
"torch... | [((456, 468), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (466, 468), True, 'import matplotlib.pyplot as plt\n'), ((555, 583), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""f"""'], {'fontsize': '(15)'}), "('f', fontsize=15)\n", (565, 583), True, 'import matplotlib.pyplot as plt\n'), ((623, 662), 'matp... |
# coding: utf-8
# In[105]:
from pypokerengine.utils.game_state_utils import restore_game_state, attach_hole_card, attach_hole_card_from_deck
from pypokerengine.players import BasePokerPlayer
from pypokerengine.api.emulator import Emulator
from pypokerengine.engine.card import Card
from pypokerengine.utils.card_util... | [
"numpy.load",
"numpy.sum",
"pypokerengine.utils.card_utils.gen_cards",
"numpy.ones",
"numpy.argsort",
"pypokerengine.utils.game_state_utils.restore_game_state",
"numpy.mean",
"pypokerengine.api.emulator.Emulator",
"numpy.random.normal",
"numpy.exp",
"pypokerengine.utils.game_state_utils.attach_h... | [((1886, 1896), 'pypokerengine.api.emulator.Emulator', 'Emulator', ([], {}), '()\n', (1894, 1896), False, 'from pypokerengine.api.emulator import Emulator\n'), ((2034, 2088), 'numpy.array', 'np.array', (['[0.1, 1, 2, 3, 7, 14, 28, 56, 112, 224, 448]'], {}), '([0.1, 1, 2, 3, 7, 14, 28, 56, 112, 224, 448])\n', (2042, 208... |
# -*- coding: utf-8 -*-
"""Functions for Genius environment.
- Author: <NAME>
- Contact: <EMAIL>
"""
import gym
from gym import spaces
import numpy as np
_LOWEST_VALUE = np.float32(0.0)
_HIGHEST_VALUE = np.float32(1.0)
def _get_observation_space() -> spaces.Box:
high = np.concatenate(
[
np.a... | [
"numpy.array",
"numpy.float32",
"gym.spaces.Discrete",
"gym.spaces.Box"
] | [((172, 187), 'numpy.float32', 'np.float32', (['(0.0)'], {}), '(0.0)\n', (182, 187), True, 'import numpy as np\n'), ((205, 220), 'numpy.float32', 'np.float32', (['(1.0)'], {}), '(1.0)\n', (215, 220), True, 'import numpy as np\n'), ((625, 710), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '_LOWEST_VALUE', 'high': '_HIGH... |
import numpy as np
import pandas as pd
import scipy
def time_length_matrix(sm):
# pathfinder
sm.step_road_pathfinder(all_or_nothing=True)
# length per road type
los = sm.car_los[['origin', 'destination', 'time', 'link_path', 'ntlegs']]
ztr_length = sm.zone_to_road.set_index(['a', 'b'])['distance'... | [
"numpy.dot",
"scipy.optimize.minimize",
"pandas.Series"
] | [((2846, 2891), 'scipy.optimize.minimize', 'scipy.optimize.minimize', (['J', 'x0'], {'bounds': 'bounds'}), '(J, x0, bounds=bounds)\n', (2869, 2891), False, 'import scipy\n'), ((3374, 3471), 'pandas.Series', 'pd.Series', (['{classe: [(1 / x) for x in speed_bounds[classe]][::-1] for classe in\n road_classes}'], {}), '... |
# Copyright 2008-2021 pydicom authors. See LICENSE file for details.
"""Benchmarks for the pixel data utilities."""
import numpy as np
from pydicom import dcmread
from pydicom.data import get_testdata_file
from pydicom.pixel_data_handlers.util import convert_color_space
# 32/32, 3 sample/pixel, 2 frame
EXPL_32_3_2F... | [
"pydicom.pixel_data_handlers.util.convert_color_space",
"pydicom.dcmread",
"pydicom.data.get_testdata_file",
"numpy.ones"
] | [((323, 367), 'pydicom.data.get_testdata_file', 'get_testdata_file', (['"""SC_rgb_32bit_2frame.dcm"""'], {}), "('SC_rgb_32bit_2frame.dcm')\n", (340, 367), False, 'from pydicom.data import get_testdata_file\n'), ((783, 827), 'numpy.ones', 'np.ones', (['(10, 1024, 1024, 3)'], {'dtype': 'np.uint8'}), '((10, 1024, 1024, 3)... |
"""
Generate a large batch of samples from a super resolution model, given a batch
of samples from a regular model from image_sample.py.
Simple shortcircuiting kwarg indirection
"""
import argparse
import os
from pprint import pprint
import blobfile as bf
import numpy as np
import torch as th
import torch.distributed... | [
"numpy.load",
"guided_diffusion.script_util.sr_create_model_and_diffusion",
"argparse.ArgumentParser",
"blobfile.BlobFile",
"guided_diffusion.dist_util.setup_dist",
"torch.distributed.all_gather",
"torch.distributed.get_world_size",
"guided_diffusion.script_util.add_dict_to_argparser",
"guided_diffu... | [((1918, 1955), 'guided_diffusion.script_util.sr_create_model_and_diffusion', 'sr_create_model_and_diffusion', ([], {}), '(**args)\n', (1947, 1955), False, 'from guided_diffusion.script_util import sr_model_and_diffusion_defaults, sr_create_model_and_diffusion, args_to_dict, add_dict_to_argparser\n'), ((2056, 2095), 't... |
import copy
import sys
import numpy as np
from numpy import sqrt,log,pi,cos,arctan
import scipy.optimize
import scipy as sp
import pandas as pd
from matplotlib import pylab as pl
#pl.rc('text', usetex=True) # Support greek letters in plot legend
from crackclosuresim2 import inverse_closure,crackopening_from_tensile_... | [
"matplotlib.pylab.savefig",
"matplotlib.pylab.show",
"numpy.argmax",
"pandas.read_csv",
"crackclosuresim2.crackopening_from_tensile_closure",
"numpy.zeros",
"matplotlib.pylab.ylabel",
"crackclosuresim2.soft_closure.soft_closure_plots",
"matplotlib.pylab.plot",
"numpy.array",
"matplotlib.pylab.xl... | [((1117, 1232), 'pandas.read_csv', 'pd.read_csv', (['"""0000-C18-AFVT-018J_optical_collect_optical_data_dic_closureprofile_closurestress_side1.csv"""'], {}), "(\n '0000-C18-AFVT-018J_optical_collect_optical_data_dic_closureprofile_closurestress_side1.csv'\n )\n", (1128, 1232), True, 'import pandas as pd\n'), ((20... |
import random
import time
import uuid
import tempfile
import os
from copy import copy
from socket import gethostname
import numpy as np
import pickle
from ml_collections import ConfigDict
import wandb
import torch
class Timer(object):
def __init__(self):
self._time = None
def __enter__(self):
... | [
"wandb.log",
"numpy.random.uniform",
"pickle.dump",
"uuid.uuid4",
"numpy.random.seed",
"os.makedirs",
"torch.manual_seed",
"ml_collections.ConfigDict",
"copy.copy",
"time.time",
"socket.gethostname",
"torch.cuda.manual_seed_all",
"tempfile.mkdtemp",
"random.seed",
"wandb.Settings",
"os... | [((3503, 3523), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (3517, 3523), True, 'import numpy as np\n'), ((3528, 3560), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (3554, 3560), False, 'import torch\n'), ((3565, 3588), 'torch.manual_seed', 'torch.manual... |
import string
import datetime
import random
import numpy as np
from PIL import Image, ImageDraw
from peewee import (BooleanField, CharField, CompositeKey, DateTimeField, FloatField,
ForeignKeyField, IntegerField, Model, SqliteDatabase)
database = SqliteDatabase(None)
class BaseModel(Model):
... | [
"PIL.Image.new",
"peewee.FloatField",
"numpy.deg2rad",
"peewee.DateTimeField",
"peewee.CompositeKey",
"random.choice",
"peewee.IntegerField",
"peewee.CharField",
"peewee.ForeignKeyField",
"peewee.SqliteDatabase",
"numpy.min",
"numpy.sin",
"numpy.cos",
"peewee.BooleanField",
"PIL.ImageDra... | [((270, 290), 'peewee.SqliteDatabase', 'SqliteDatabase', (['None'], {}), '(None)\n', (284, 290), False, 'from peewee import BooleanField, CharField, CompositeKey, DateTimeField, FloatField, ForeignKeyField, IntegerField, Model, SqliteDatabase\n'), ((331, 375), 'peewee.DateTimeField', 'DateTimeField', ([], {'default': '... |
import logging
import json
import datetime
import pandas as pd
import numpy as np
from collections import Counter, OrderedDict
from math import log2, ceil
logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S', level=logging.INFO)
def regional_analysis(df, region):
"""
regional an... | [
"json.dump",
"logging.basicConfig",
"numpy.datetime_as_string",
"datetime.date",
"logging.info",
"pandas.to_datetime",
"datetime.timedelta",
"collections.OrderedDict"
] | [((156, 265), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(message)s"""', 'datefmt': '"""%d-%b-%y %H:%M:%S"""', 'level': 'logging.INFO'}), "(format='%(asctime)s - %(message)s', datefmt=\n '%d-%b-%y %H:%M:%S', level=logging.INFO)\n", (175, 265), False, 'import logging\n'), ((796, ... |
# -*- coding: utf-8 -*-
"""Tests for the pyflwdir.upscael module."""
import pytest
from affine import Affine
import time
import numpy as np
import os
# local
from pyflwdir import upscale, core_d8, core, streams, basins
from test_core import test_data
# # large test data
# flwdir = np.fromfile(r"./data/d8.bin", dtype... | [
"numpy.uint32",
"pyflwdir.streams.upstream_area",
"numpy.multiply",
"pyflwdir.core.loop_indices",
"os.path.dirname",
"pyflwdir.core_d8.from_array",
"pyflwdir.upscale.map_effare",
"numpy.argsort",
"pyflwdir.core.pit_indices",
"pyflwdir.upscale.map_celledge",
"numpy.arange",
"pytest.mark.paramet... | [((572, 591), 'numpy.uint32', 'np.uint32', (['core._mv'], {}), '(core._mv)\n', (581, 591), True, 'import numpy as np\n'), ((692, 717), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (707, 717), False, 'import os\n'), ((815, 858), 'pyflwdir.core_d8.from_array', 'core_d8.from_array', (['flwdir'... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 11:35:13 2021
@author: hoss3301
"""
import os,sys
sys.path.append('../')
import h5py as hp
import matplotlib.pyplot as plt
from TrialsOfNeuralVocalRecon.tools.calculate_intelligibility import find_intel
from TrialsOfNeuralVocalRecon.tools.utils.losses import *
import ... | [
"sys.path.append",
"h5py.File",
"numpy.save",
"tensorflow.keras.models.load_model",
"os.path.realpath",
"numpy.shape",
"TrialsOfNeuralVocalRecon.tools.calculate_intelligibility.find_intel",
"os.path.join",
"numpy.concatenate",
"numpy.repeat"
] | [((101, 123), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (116, 123), False, 'import os, sys\n'), ((912, 963), 'os.path.join', 'os.path.join', (["*[DATADIR, 'Normalized', time_folder]"], {}), "(*[DATADIR, 'Normalized', time_folder])\n", (924, 963), False, 'import os, sys\n'), ((973, 1012), '... |
#%%
import numpy as np
import pandas as pd
import tqdm
# From the SI of Li 2014, Cell, hard-code the growth rates.
growth_rate = np.log(2) / (150 / 60)
# Load the data quantifying absolute protein synthesis rates.
counts = pd.read_csv('../../../data/taniguchi2010_raw_data/taniguchi2010_counts.csv')
counts = counts[['... | [
"pandas.DataFrame",
"numpy.log",
"pandas.read_csv",
"numpy.exp",
"pandas.concat"
] | [((225, 301), 'pandas.read_csv', 'pd.read_csv', (['"""../../../data/taniguchi2010_raw_data/taniguchi2010_counts.csv"""'], {}), "('../../../data/taniguchi2010_raw_data/taniguchi2010_counts.csv')\n", (236, 301), True, 'import pandas as pd\n'), ((424, 478), 'pandas.read_csv', 'pd.read_csv', (['"""../../../data/ecoli_genel... |
from nose.tools import (raises, assert_raises, assert_true,
assert_equal, assert_not_equal, assert_almost_equal)
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from deepjets.preprocessing import zoom_image, pixel_edges
def test_zoom():
edges =... | [
"deepjets.preprocessing.pixel_edges",
"deepjets.preprocessing.zoom_image",
"nose.tools.assert_equal",
"nose.tools.assert_raises",
"numpy.random.normal",
"numpy.testing.assert_array_almost_equal"
] | [((321, 385), 'deepjets.preprocessing.pixel_edges', 'pixel_edges', ([], {'jet_size': '(1)', 'pixel_size': '(0.1, 0.1)', 'border_size': '(0.25)'}), '(jet_size=1, pixel_size=(0.1, 0.1), border_size=0.25)\n', (332, 385), False, 'from deepjets.preprocessing import zoom_image, pixel_edges\n'), ((390, 425), 'nose.tools.asser... |
# EEG preprocessing
import numpy as np
import scipy.signal
def lr_assymetry_pfl(channels, band="alpha"):
# asymmetry between left-right prefrontal areas alpha waves, most related to emotional state, and approach withdrawal
# Prefrontal Cortex, Emotion, and Approach/Withdrawal Motivation
# <NAME>, <NAME>, <NAME>, <N... | [
"numpy.absolute",
"numpy.kaiser",
"numpy.sum",
"numpy.fft.fft",
"numpy.square",
"numpy.zeros",
"numpy.mean",
"numpy.array",
"numpy.sin",
"numpy.linspace",
"numpy.convolve"
] | [((2480, 2493), 'numpy.array', 'np.array', (['eeg'], {}), '(eeg)\n', (2488, 2493), True, 'import numpy as np\n'), ((2749, 2762), 'numpy.fft.fft', 'np.fft.fft', (['y'], {}), '(y)\n', (2759, 2762), True, 'import numpy as np\n'), ((3540, 3574), 'numpy.fft.fft', 'np.fft.fft', (['alpha[M / 2:L + M / 2]'], {}), '(alpha[M / 2... |
from layers.makeup_dataframe import merge_initialized_table
from libs.extensions import Extension
import pandas as pd
import numpy as np
class Yjzt(Extension):
"""预警状态"""
"""
计算公式:
当同比或环比的绝对值超过20%即为告警,绝对值超过10%即为异常,否则为平稳
"""
def __init__(self, apis_copy, apis, *args, **kwargs):
# 执... | [
"pandas.DataFrame",
"libs.extensions.Extension.groupby_and_sum",
"pandas.merge",
"layers.makeup_dataframe.merge_initialized_table",
"numpy.int32"
] | [((1614, 1674), 'libs.extensions.Extension.groupby_and_sum', 'Extension.groupby_and_sum', (['self.db_results[0][0]', 'self.value'], {}), '(self.db_results[0][0], self.value)\n', (1639, 1674), False, 'from libs.extensions import Extension\n'), ((1707, 1767), 'libs.extensions.Extension.groupby_and_sum', 'Extension.groupb... |
import shutil
import os
import fire
import gdal
import numpy as np
import cv2
from tqdm import tqdm
from osgeo import ogr
from scipy import ndimage as ndi
from skimage import measure
from skimage.morphology import dilation, square, watershed
from scipy.ndimage import binary_erosion
from multiprocessing.pool import Pool... | [
"os.mkdir",
"numpy.sum",
"shutil.rmtree",
"os.path.join",
"skimage.measure.regionprops",
"numpy.zeros_like",
"gdal.RasterizeLayer",
"gdal.GetDriverByName",
"os.path.exists",
"numpy.max",
"multiprocessing.pool.Pool",
"skimage.morphology.watershed",
"skimage.morphology.square",
"os.listdir",... | [((535, 562), 'skimage.measure.regionprops', 'measure.regionprops', (['labels'], {}), '(labels)\n', (554, 562), False, 'from skimage import measure\n'), ((575, 610), 'numpy.zeros_like', 'np.zeros_like', (['labels'], {'dtype': '"""bool"""'}), "(labels, dtype='bool')\n", (588, 610), True, 'import numpy as np\n'), ((1379,... |
# -*- coding: utf-8 -*-
"""
Enunciado:
Compare assintoticamente o tempo de execução (apresente dados, tabelas e
gráficos) dos algoritmos de ordenação:
Inserção; BubbleSort; e Seleção.
Em seguida, responda os seguintes questionamentos.
a. Qual desses algoritmos é o mais eficiente?
b. ... | [
"numpy.load",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.grid"
] | [((2312, 2339), 'numpy.load', 'np.load', (['"""./IS_results.npy"""'], {}), "('./IS_results.npy')\n", (2319, 2339), True, 'import numpy as np\n'), ((2349, 2376), 'numpy.load', 'np.load', (['"""./ns_results.npy"""'], {}), "('./ns_results.npy')\n", (2356, 2376), True, 'import numpy as np\n'), ((2397, 2424), 'numpy.load', ... |
# Copyright 2019 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | [
"numpy.absolute",
"numpy.trace",
"numpy.abs",
"scipy.linalg.polar",
"numpy.angle",
"numpy.allclose",
"collections.defaultdict",
"numpy.isclose",
"numpy.linalg.svd",
"numpy.sin",
"numpy.exp",
"numpy.arange",
"scipy.linalg.schur",
"numpy.diag",
"numpy.conjugate",
"numpy.round",
"numpy.... | [((1926, 1945), 'numpy.real_if_close', 'np.real_if_close', (['N'], {}), '(N)\n', (1942, 1945), True, 'import numpy as np\n'), ((1954, 1971), 'numpy.allclose', 'np.allclose', (['N', '(0)'], {}), '(N, 0)\n', (1965, 1971), True, 'import numpy as np\n'), ((2019, 2034), 'numpy.isrealobj', 'np.isrealobj', (['N'], {}), '(N)\n... |
import numpy as np
from bayesian.linear._classifier import Classifier
class VariationalClassifier(Classifier):
r"""
### Prior distribution of model parameter
$$
\begin{aligned}
p({\alpha}|a_0,b_0) &= {\rm Gam}(\alpha|a_0, b_0)\\
p({\boldsymbol w}|\alpha)
&= \mathcal{N}({\boldsymbol ... | [
"numpy.random.uniform",
"numpy.sum",
"numpy.tanh",
"numpy.copy",
"numpy.asarray",
"numpy.allclose",
"numpy.linalg.inv",
"numpy.eye"
] | [((1719, 1732), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (1729, 1732), True, 'import numpy as np\n'), ((1866, 1898), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'n'}), '(-1, 1, size=n)\n', (1883, 1898), True, 'import numpy as np\n'), ((1913, 1922), 'numpy.eye', 'np.eye', (['d'], ... |
# coding: utf-8
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import os
from keras.models import load_model
a = np.random.rand(64,64,3) * 255
im_out = Image.fromarray(a.astype('uint8')).convert('RGB')
fig, axs = plt.subplots(5, 5)
cnt = 0
for i in range(5):
for j in range(5):
... | [
"keras.models.load_model",
"numpy.random.rand",
"matplotlib.pyplot.subplots",
"os.chdir"
] | [((243, 261), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(5)', '(5)'], {}), '(5, 5)\n', (255, 261), True, 'import matplotlib.pyplot as plt\n'), ((510, 524), 'os.chdir', 'os.chdir', (['""".."""'], {}), "('..')\n", (518, 524), False, 'import os\n'), ((531, 580), 'keras.models.load_model', 'load_model', (['"""final_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Built-in imports
import warnings
import itertools
# 3rd party imports
import numpy as np
import xarray as xr
# Local imports
from .feeps_pitch_angles import feeps_pitch_angles
from .feeps_active_eyes import feeps_active_eyes
__author__ = "<NAME>"
__email__ = "<EMAIL>"... | [
"warnings.simplefilter",
"numpy.logical_and",
"numpy.zeros",
"numpy.isnan",
"numpy.min",
"numpy.max",
"numpy.arange",
"xarray.DataArray",
"warnings.catch_warnings",
"numpy.where",
"numpy.nanmean"
] | [((5991, 6079), 'xarray.DataArray', 'xr.DataArray', (['pa_flux'], {'coords': '[time, pa_labels]', 'dims': "['time', 'theta']", 'attrs': 'attrs'}), "(pa_flux, coords=[time, pa_labels], dims=['time', 'theta'],\n attrs=attrs)\n", (6003, 6079), True, 'import xarray as xr\n'), ((1097, 1109), 'numpy.arange', 'np.arange', ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 19 23:09:56 2020
@author: jose
"""
#%% Please dont read the code below
### This legit breaks most of the code standards I believe in
#Getting data from dataset
import h5py
import numpy as np
#%% This section is dedicated to getting the... | [
"numpy.full",
"h5py.File",
"numpy.linspace"
] | [((712, 755), 'h5py.File', 'h5py.File', (['(dataset_location + filename)', '"""r"""'], {}), "(dataset_location + filename, 'r')\n", (721, 755), False, 'import h5py\n'), ((4440, 4490), 'numpy.full', 'np.full', (['(1, 150)', '(walking_speed * delta_time_left)'], {}), '((1, 150), walking_speed * delta_time_left)\n', (4447... |
import numpy as np
from pyspark.sql import DataFrame
from pyspark.ml.linalg import DenseVector, DenseMatrix
from pyspark.ml.classification import LogisticRegression, LogisticRegressionModel, \
BinaryLogisticRegressionTrainingSummary
class LogitRegression:
@staticmethod
def __build_model_parameters(**karg... | [
"numpy.sort",
"pyspark.ml.classification.LogisticRegression"
] | [((3295, 4334), 'pyspark.ml.classification.LogisticRegression', 'LogisticRegression', ([], {'featuresCol': "config_params['features_col']", 'labelCol': "config_params['label_col']", 'maxIter': "config_params['max_iter']", 'predictionCol': "config_params['prediction_col']", 'regParam': "config_params['reg_param']", 'ela... |
import argparse
import itertools
import os
from enum import Enum
from types import SimpleNamespace
from typing import List
import numpy
import torch
import torchtext
from robustcode.analysis.graph import AstTree
from robustcode.analysis.graph import TypeScriptGraphAnalyzer
from robustcode.datasets.dataset import Conf... | [
"robustcode.models.modules.rnn.deeptyper.DeepTyperEdgesFieldsGenerator",
"robustcode.dedup.fastsim.compute_similar_files",
"robustcode.dedup.fastsim.hash_file_tokens",
"argparse.ArgumentParser",
"os.path.join",
"robustcode.util.misc.Logger.end_scope",
"numpy.flatnonzero",
"robustcode.models.modules.dg... | [((1261, 1286), 'robustcode.analysis.graph.TypeScriptGraphAnalyzer', 'TypeScriptGraphAnalyzer', ([], {}), '()\n', (1284, 1286), False, 'from robustcode.analysis.graph import TypeScriptGraphAnalyzer\n'), ((2470, 2534), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""DeepTyper AST Dataset"""'], {'add_help': '... |
# AMFinder - amfinder_calc.py
#
# MIT License
# Copyright (c) 2021 <NAME>, <NAME>
#
# 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
# rig... | [
"copy.deepcopy",
"matplotlib.pyplot.show",
"tensorflow.random.uniform",
"tensorflow.argmax",
"tensorflow.maximum",
"tensorflow.math.reduce_max",
"tensorflow.reduce_mean",
"matplotlib.pyplot.matshow",
"numpy.clip",
"numpy.array",
"tensorflow.GradientTape",
"tensorflow.squeeze",
"tensorflow.ke... | [((1590, 1623), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['filter_activation'], {}), '(filter_activation)\n', (1604, 1623), True, 'import tensorflow as tf\n'), ((1927, 1954), 'tensorflow.math.l2_normalize', 'tf.math.l2_normalize', (['grads'], {}), '(grads)\n', (1947, 1954), True, 'import tensorflow as tf\n'), ((225... |
from abc import ABC, abstractmethod
from dataclasses import dataclass
import numpy as np
@dataclass
class NormalInverseWishart:
"""A normal-inverse Wishart distribution."""
mu0: np.ndarray
Phi: np.ndarray
N_mean: float
N_covar: float
def posterior(self, emp_mean: np.ndarray, emp_covar: np.nd... | [
"numpy.zeros",
"numpy.einsum"
] | [((1556, 1570), 'numpy.zeros', 'np.zeros', (['(d,)'], {}), '((d,))\n', (1564, 1570), True, 'import numpy as np\n'), ((1589, 1605), 'numpy.zeros', 'np.zeros', (['(d, d)'], {}), '((d, d))\n', (1597, 1605), True, 'import numpy as np\n'), ((884, 946), 'numpy.einsum', 'np.einsum', (['"""i,j->ij"""', '(emp_mean - self.mu0)',... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os, copy
import numpy as np
from astropy.table import Table
from astropy.coordinates import SkyCoord
from sklearn.neighbors import KDTree
from .utils import ra_dec_to_xyz, angular_dist_to_euclidean_dist
... | [
"copy.deepcopy",
"numpy.asarray",
"sklearn.neighbors.KDTree",
"astropy.coordinates.SkyCoord",
"astropy.table.Table.read"
] | [((1467, 1485), 'numpy.asarray', 'np.asarray', (['coords'], {}), '(coords)\n', (1477, 1485), True, 'import numpy as np\n'), ((2626, 2645), 'copy.deepcopy', 'copy.deepcopy', (['self'], {}), '(self)\n', (2639, 2645), False, 'import os, copy\n'), ((560, 589), 'astropy.table.Table.read', 'Table.read', (['fn'], {'format': '... |
"""
Test developed by <NAME>, Max Planck Institute for Intelligent Systems, Tuebingen, Germany, March-2020
It shows that working with sparse matrices it's much faster, this can be noticed for Adjacency matrices of size ~10^4
"""
import scipy.sparse
import numpy as np
import networkx as nx
import timeit
from SpringRank... | [
"networkx.to_scipy_sparse_matrix",
"numpy.allclose",
"networkx.scale_free_graph",
"SpringRank.SpringRank",
"timeit.timeit",
"numpy.random.rand"
] | [((513, 574), 'SpringRank.SpringRank', 'SpringRank', (['B'], {'alpha': 'alpha', 'verbose': 'verbose', 'force_dense': '(True)'}), '(B, alpha=alpha, verbose=verbose, force_dense=True)\n', (523, 574), False, 'from SpringRank import SpringRank\n'), ((589, 632), 'SpringRank.SpringRank', 'SpringRank', (['A'], {'alpha': 'alph... |
# Extensions: not included in the prototype
import numpy as np
import numba as nb
import scipy.sparse as sp
from .tron import tron
from sklearn.utils.extmath import safe_sparse_dot
from .extmath import csr_gemm
from .steps import l2_loss_valj
def b_step_tron_valj(b, Y, X, C_B):
"""Compute current value the b-... | [
"numpy.minimum",
"numpy.maximum",
"scipy.sparse.issparse",
"numpy.linalg.norm",
"numpy.dot"
] | [((483, 497), 'scipy.sparse.issparse', 'sp.issparse', (['Y'], {}), '(Y)\n', (494, 497), True, 'import scipy.sparse as sp\n'), ((954, 968), 'scipy.sparse.issparse', 'sp.issparse', (['Y'], {}), '(Y)\n', (965, 968), True, 'import scipy.sparse as sp\n'), ((1586, 1600), 'scipy.sparse.issparse', 'sp.issparse', (['Y'], {}), '... |
import numpy as np
import os
import cv2
import random
import pickle
DIRECTORY = 'dataset'
CATEGORIES = ['mask_off', 'mask_on']
IMAGE_SIZE = 50
trainingData = []
featureSet = []
labelSet = []
def createTrainingData():
for category in CATEGORIES:
pathToCategories = os.path.join(DIRECTORY, category)
... | [
"pickle.dump",
"random.shuffle",
"numpy.array",
"os.path.join",
"os.listdir",
"cv2.resize"
] | [((1137, 1171), 'pickle.dump', 'pickle.dump', (['featureSet', 'pickleOut'], {}), '(featureSet, pickleOut)\n', (1148, 1171), False, 'import pickle\n'), ((1233, 1265), 'pickle.dump', 'pickle.dump', (['labelSet', 'pickleOut'], {}), '(labelSet, pickleOut)\n', (1244, 1265), False, 'import pickle\n'), ((286, 319), 'os.path.j... |
import os
import numpy as np
import pandas as pd
from models import GANBase
from modules.plot import get_plot
from modules.utils import dump
class _2DGANBase(GANBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def gen_sample_images(self, dataset, basename, batch_size=64... | [
"modules.plot.get_plot",
"os.path.join",
"numpy.arange",
"numpy.expand_dims"
] | [((415, 447), 'os.path.join', 'os.path.join', (['self.dir', 'basename'], {}), '(self.dir, basename)\n', (427, 447), False, 'import os\n'), ((577, 615), 'modules.plot.get_plot', 'get_plot', (['path', '[x, x_gen]', "('b', 'g')"], {}), "(path, [x, x_gen], ('b', 'g'))\n", (585, 615), False, 'from modules.plot import get_pl... |
from typing import Any, Optional, Union
from .base_data_module import BaseDataModule
from dataclasses import dataclass
from .processor import get_dataset, processors
from torch.utils.data import DataLoader
from transformers import AutoTokenizer
from transformers.file_utils import PaddingStrategy
from transformers.toke... | [
"transformers.AutoTokenizer.from_pretrained",
"numpy.concatenate"
] | [((4712, 4771), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['self.args.model_name_or_path'], {}), '(self.args.model_name_or_path)\n', (4741, 4771), False, 'from transformers import AutoTokenizer\n'), ((6677, 6736), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pr... |
"""
Copyright 2018-2019 CS Systèmes d'Information
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... | [
"ikats.core.resource.api.IkatsApi.ts.create",
"ikats.core.library.exception.IkatsException",
"ikats.core.resource.api.IkatsApi.ts.inherit",
"ikats.algo.ts_cut.cut_ds_multiprocessing",
"ikats.core.library.spark.ScManager.stop",
"time.time",
"ikats.core.resource.api.IkatsApi.md.read",
"ikats.core.resour... | [((900, 927), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (917, 927), False, 'import logging\n'), ((3454, 3482), 'ikats.core.resource.api.IkatsApi.md.read', 'IkatsApi.md.read', (['tsuid_list'], {}), '(tsuid_list)\n', (3470, 3482), False, 'from ikats.core.resource.api import IkatsApi\n'... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as scn; scn.set()
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris
dataset = load_iris()
X = dataset["data"]
y = dataset["target"]
features = np.array(["sepallength","sepalwidth","petallength","petalwidth"])
... | [
"pandas.DataFrame",
"sklearn.datasets.load_iris",
"matplotlib.pyplot.show",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.figure",
"numpy.array",
"seaborn.set"
] | [((94, 103), 'seaborn.set', 'scn.set', ([], {}), '()\n', (101, 103), True, 'import seaborn as scn\n'), ((189, 200), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (198, 200), False, 'from sklearn.datasets import load_iris\n'), ((254, 322), 'numpy.array', 'np.array', (["['sepallength', 'sepalwidth', 'petal... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 20:59:05 2019
@author: ben
"""
import glob
import re
import pointCollection as pc
import matplotlib.pyplot as plt
import numpy as np
thedir='/Volumes/ice2/ben/ATL14_test/IS2/z03xlooser_dt10xlooser_80km'
W_ctr=4.e4
MOG=pc.grid.data().from_geot... | [
"pointCollection.grid.data",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.array",
"matplotlib.pyplot.gca",
"glob.glob",
"matplotlib.pyplot.gcf",
"re.compile"
] | [((371, 383), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (381, 383), True, 'import matplotlib.pyplot as plt\n'), ((734, 763), 'glob.glob', 'glob.glob', (["(thedir + '/*/*.h5')"], {}), "(thedir + '/*/*.h5')\n", (743, 763), False, 'import glob\n'), ((296, 310), 'pointCollection.grid.data', 'pc.grid.data'... |
from __future__ import generators, division, absolute_import, with_statement, print_function, unicode_literals
import os
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import keras
import keras.backend as K
import time
from keras.utils import plot_model
from keras.models import Model
from ke... | [
"keras.backend.set_floatx",
"keras.backend.set_image_data_format",
"numpy.random.randint",
"numpy.arange",
"keras.backend.pow",
"os.path.join",
"tensorflow.Summary",
"keras.layers.GlobalAveragePooling2D",
"keras.callbacks.ReduceLROnPlateau",
"numpy.random.shuffle",
"keras.Model",
"numpy.square... | [((878, 918), 'keras.backend.set_image_data_format', 'K.set_image_data_format', (['"""channels_last"""'], {}), "('channels_last')\n", (901, 918), True, 'import keras.backend as K\n'), ((919, 942), 'keras.backend.set_floatx', 'K.set_floatx', (['"""float32"""'], {}), "('float32')\n", (931, 942), True, 'import keras.backe... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [
"mindspore.context.set_context",
"mindspore.nn.Tanh",
"mindspore.nn.CellList",
"mindspore.common.tensor.Tensor",
"mindspore.ops.operations.Less",
"numpy.random.random",
"mindspore.ops.operations.Zeros"
] | [((2754, 2852), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.GRAPH_MODE', 'save_graphs': '(False)', 'save_graphs_path': '"""./graph_ir"""'}), "(mode=context.GRAPH_MODE, save_graphs=False,\n save_graphs_path='./graph_ir')\n", (2773, 2852), False, 'from mindspore import context\n'), (... |
from collections import deque
import pandas as pd
import torch
import numpy as np
from tqdm import tqdm
def check_cuda(gpu_idx = 0):
# Check if CUDA is available
use_cuda = torch.cuda.is_available()
if use_cuda and gpu_idx is not "cpu":
print('CUDA is available! Training on GPU ...')
devi... | [
"numpy.zeros_like",
"numpy.mean",
"torch.cuda.is_available",
"pandas.Series",
"torch.device",
"torch.cuda.get_device_name",
"collections.deque"
] | [((183, 208), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (206, 208), False, 'import torch\n'), ((1957, 1974), 'collections.deque', 'deque', ([], {'maxlen': '(100)'}), '(maxlen=100)\n', (1962, 1974), False, 'from collections import deque\n'), ((3391, 3412), 'numpy.zeros_like', 'np.zeros_like... |
from .modelmanager import Model
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.feature_selection import SelectKBest, SelectPercentile, SelectFpr
from sklearn.feature_selection import chi2, f_classif, mutual_info_classif
from yell... | [
"sklearn.model_selection.GridSearchCV",
"sklearn.model_selection.cross_val_score",
"yellowbrick.target.ClassBalance",
"yellowbrick.model_selection.ValidationCurve",
"numpy.mean",
"yellowbrick.style.set_palette",
"yellowbrick.classifier.ClassificationReport",
"numpy.std",
"yellowbrick.model_selection... | [((1065, 1086), 'yellowbrick.style.set_palette', 'set_palette', (['"""paired"""'], {}), "('paired')\n", (1076, 1086), False, 'from yellowbrick.style import set_palette\n'), ((2638, 2650), 'yellowbrick.features.rfecv.RFECV', 'RFECV', (['model'], {}), '(model)\n', (2643, 2650), False, 'from yellowbrick.features.rfecv imp... |
import tensorflow as tf
import numpy as np
import ssd_mobilenet_v1 as ssd
from PIL import Image
import os
import pdb
def load_model(sess,CKPT,var_list=None):
if not var_list:
loader = tf.train.Saver()
else:
loader = tf.train.Saver(var_list)
loader.restore(sess,CKPT)
def main():
# set ... | [
"os.path.join",
"tensorflow.train.Saver",
"tensorflow.global_variables_initializer",
"tensorflow.get_collection",
"tensorflow.device",
"tensorflow.Session",
"numpy.expand_dims",
"PIL.Image.open",
"tensorflow.placeholder",
"numpy.array",
"pdb.set_trace",
"tensorflow.Graph",
"tensorflow.get_de... | [((381, 430), 'os.path.join', 'os.path.join', (['"""ckpt"""', '"""mobilenet_v1_1.0_224.ckpt"""'], {}), "('ckpt', 'mobilenet_v1_1.0_224.ckpt')\n", (393, 430), False, 'import os\n'), ((589, 599), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (597, 599), True, 'import tensorflow as tf\n'), ((198, 214), 'tensorflow.tra... |
"""
In this file the optimizers are defined that can be
used to optimize the parameters of layers.
"""
# Standard libraries
from abc import ABC, abstractmethod
import json
# Third-party libraries
import numpy as np
class Optimizer(ABC):
"""
This is a base class for optimizers
used with the recurrent lay... | [
"json.dump",
"json.load",
"numpy.array",
"numpy.sqrt"
] | [((6141, 6161), 'json.dump', 'json.dump', (['obj', 'file'], {}), '(obj, file)\n', (6150, 6161), False, 'import json\n'), ((6320, 6335), 'json.load', 'json.load', (['file'], {}), '(file)\n', (6329, 6335), False, 'import json\n'), ((4374, 4403), 'numpy.sqrt', 'np.sqrt', (['self.cache[layer][0]'], {}), '(self.cache[layer]... |
#!/usr/bin/env python
import RNA
import random
from numpy import zeros
import dask.dataframe as dd
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('Folding test')
class FoldingTest():
def __init__(self, n=1000):
'''
initiate test class,
n = how many random... | [
"logging.basicConfig",
"random.shuffle",
"numpy.zeros",
"pandas.read_excel",
"RNA.fold",
"logging.getLogger"
] | [((115, 154), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (134, 154), False, 'import logging\n'), ((164, 197), 'logging.getLogger', 'logging.getLogger', (['"""Folding test"""'], {}), "('Folding test')\n", (181, 197), False, 'import logging\n'), ((404, 417), '... |
#!/usr/bin/env python
import roslib; roslib.load_manifest('hanse_wallfollowing')
import rospy
import smach
import smach_ros
import numpy
import math
import sys
from rospy.numpy_msg import numpy_msg
from dynamic_reconfigure.server import Server
from hanse_wallfollowing.cfg import WallFollowingConfig
from hanse_wallfollo... | [
"geometry_msgs.msg.Vector3",
"rospy.Subscriber",
"math.asin",
"math.atan2",
"rospy.ServiceProxy",
"numpy.clip",
"std_msgs.msg.Float64",
"rospy.get_name",
"roslib.load_manifest",
"rospy.Duration",
"rospy.is_shutdown",
"rospy.init_node",
"rospy.wait_for_service",
"smach_ros.IntrospectionServ... | [((37, 80), 'roslib.load_manifest', 'roslib.load_manifest', (['"""hanse_wallfollowing"""'], {}), "('hanse_wallfollowing')\n", (57, 80), False, 'import roslib\n'), ((7137, 7169), 'rospy.init_node', 'rospy.init_node', (['"""wallfollowing"""'], {}), "('wallfollowing')\n", (7152, 7169), False, 'import rospy\n'), ((7220, 72... |
from sklearn.datasets import load_boston
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression
import numpy as np
import pandas as pd
boston_dataset = load_boston()
data = pd.DataFrame(data=boston_dataset.data,columns=boston_dataset.feature_names)
# data.head()
features = da... | [
"pandas.DataFrame",
"numpy.log",
"numpy.median",
"sklearn.linear_model.LinearRegression",
"sklearn.datasets.load_boston",
"numpy.around",
"sklearn.metrics.mean_squared_error",
"numpy.sqrt"
] | [((196, 209), 'sklearn.datasets.load_boston', 'load_boston', ([], {}), '()\n', (207, 209), False, 'from sklearn.datasets import load_boston\n'), ((217, 293), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'boston_dataset.data', 'columns': 'boston_dataset.feature_names'}), '(data=boston_dataset.data, columns=boston_d... |
import csv
import os
import numpy as np
import tensorflow as tf
import definitions
import keras
from keras.models import load_model
from pretrained_models import pretrained_tf
import eran.read_net_file
import clone_graph
PRETRAINED_NETS =['VGG16', 'VGG19', 'ResNet18', 'ResNet50', 'AlexNet',
'DenseNe... | [
"numpy.argmax",
"tensorflow.reshape",
"tensorflow.logging.set_verbosity",
"tensorflow.train.latest_checkpoint",
"pretrained_models.pretrained_tf.keras_pretrained_model",
"os.path.join",
"numpy.prod",
"os.path.dirname",
"tensorflow.linalg.norm",
"tensorflow.placeholder",
"tensorflow.random.normal... | [((3016, 3040), 'os.path.dirname', 'os.path.dirname', (['netname'], {}), '(netname)\n', (3031, 3040), False, 'import os\n'), ((3072, 3097), 'os.path.splitext', 'os.path.splitext', (['netname'], {}), '(netname)\n', (3088, 3097), False, 'import os\n'), ((971, 995), 'tensorflow.get_default_session', 'tf.get_default_sessio... |
import chainer
from chainer import cuda
import chainer.functions as F
import chainer.links as L
import numpy as np
from crop import crop
class RAM(chainer.Chain):
def __init__(
self, g_size=8, n_steps=6, n_scales=1, var=0.03, use_lstm=False
):
d_glm = 128
d_core = 256
super(RAM... | [
"chainer.functions.mean_squared_error",
"chainer.Variable",
"numpy.random.uniform",
"chainer.functions.softmax_cross_entropy",
"numpy.power",
"chainer.functions.sum",
"numpy.sqrt",
"chainer.functions.average_pooling_2d",
"chainer.functions.concat",
"numpy.array",
"chainer.functions.reshape",
"... | [((2368, 2397), 'chainer.functions.softmax_cross_entropy', 'F.softmax_cross_entropy', (['y', 't'], {}), '(y, t)\n', (2391, 2397), True, 'import chainer.functions as F\n'), ((2459, 2475), 'chainer.functions.accuracy', 'F.accuracy', (['y', 't'], {}), '(y, t)\n', (2469, 2475), True, 'import chainer.functions as F\n'), ((3... |
# -*- coding: utf-8 -*-
import numpy as np
from inclusion import Polyhedron
import pandas as pd
class Configuration:
'''
Provides methods for configuring the geometrical and topological parameters of the mesostructure.
'''
def __init__(self,vf_max_assembly=0.3, average_shape=False):
... | [
"pandas.read_csv",
"numpy.shape",
"inclusion.Polyhedron",
"numpy.array"
] | [((3093, 3114), 'pandas.read_csv', 'pd.read_csv', (['conf_csv'], {}), '(conf_csv)\n', (3104, 3114), True, 'import pandas as pd\n'), ((3154, 3168), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (3162, 3168), True, 'import numpy as np\n'), ((3383, 3404), 'numpy.array', 'np.array', (['conf_values'], {}), '(conf_v... |
# Add a numpy array of points to a mesh.
#
import numpy as np
import pyvista
points = np.random.random((10, 3))
pl = pyvista.Plotter()
actor = pl.add_points(points, render_points_as_spheres=True,
point_size=100.0)
pl.show()
| [
"numpy.random.random",
"pyvista.Plotter"
] | [((86, 111), 'numpy.random.random', 'np.random.random', (['(10, 3)'], {}), '((10, 3))\n', (102, 111), True, 'import numpy as np\n'), ((117, 134), 'pyvista.Plotter', 'pyvista.Plotter', ([], {}), '()\n', (132, 134), False, 'import pyvista\n')] |
"""Summarizing functions for DiviK result.
_summary.py
Copyright 2019 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by appl... | [
"logging.debug",
"numpy.sum",
"numpy.unique",
"matplotlib.pyplot.axis",
"networkx.draw_networkx",
"divik.core.DivikResult",
"numpy.max",
"networkx.spring_layout",
"networkx.get_node_attributes",
"networkx.DiGraph",
"networkx.spectral_layout",
"numpy.sqrt"
] | [((3207, 3219), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (3217, 3219), True, 'import networkx as nx\n'), ((3384, 3421), 'networkx.get_node_attributes', 'nx.get_node_attributes', (['graph', '"""size"""'], {}), "(graph, 'size')\n", (3406, 3421), True, 'import networkx as nx\n'), ((3959, 3984), 'networkx.spectr... |
"""
Description of program
"""
import numpy as np
from scipy.odr import odrpack as odr
from scipy.odr import models
from scipy import interpolate
from astropy.table import Table as table
from astropy.io import fits
import matplotlib.pyplot as plt
# ======================================================================... | [
"numpy.nansum",
"numpy.sum",
"numpy.isnan",
"numpy.array",
"scipy.interpolate.splev",
"scipy.interpolate.splrep",
"numpy.sqrt"
] | [((1555, 1584), 'scipy.interpolate.splrep', 'interpolate.splrep', (['x', 'y'], {'s': '(0)'}), '(x, y, s=0)\n', (1573, 1584), False, 'from scipy import interpolate\n'), ((2702, 2732), 'numpy.sum', 'np.sum', (['(((y1 - y2) / ey1) ** 2)'], {}), '(((y1 - y2) / ey1) ** 2)\n', (2708, 2732), True, 'import numpy as np\n'), ((3... |
import torch
import torch.nn as nn
import numpy as np
from torch.distributions.gamma import Gamma
from torch.distributions.normal import Normal
from .helpers import my_softplus, grid_helper
from .kernels import RBF, meanzeroRBF, addint_2D_kernel_decomposition, addint_kernel_diag
# class for GP-regression with input... | [
"torch.eye",
"torch.sqrt",
"torch.cat",
"torch.mm",
"torch.isnan",
"torch.ones",
"torch.diag",
"torch.distributions.gamma.Gamma",
"torch.zeros",
"torch.log",
"torch.nn.Parameter",
"torch.triangular_solve",
"torch.zeros_like",
"torch.cholesky_inverse",
"torch.pow",
"torch.sum",
"numpy... | [((3944, 3962), 'torch.sqrt', 'torch.sqrt', (['sigma2'], {}), '(sigma2)\n', (3954, 3962), False, 'import torch\n'), ((4141, 4161), 'torch.cholesky', 'torch.cholesky', (['K_uu'], {}), '(K_uu)\n', (4155, 4161), False, 'import torch\n'), ((4304, 4321), 'torch.cholesky', 'torch.cholesky', (['B'], {}), '(B)\n', (4318, 4321)... |
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from mpi4py import MPI
import time
import datasets as DS
from lessmpi import LESSRegressor
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
split_size = 0.1
random_state = 1234
df = np.array(DS.energy('... | [
"datasets.energy",
"sklearn.model_selection.train_test_split",
"lessmpi.LESSRegressor",
"numpy.empty",
"time.time"
] | [((309, 333), 'datasets.energy', 'DS.energy', (['"""./datasets/"""'], {}), "('./datasets/')\n", (318, 333), True, 'import datasets as DS\n'), ((418, 489), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': 'split_size', 'random_state': 'random_state'}), '(X, y, test_size=split_si... |
import typing
import sys
import numpy as np
import numba as nb
@nb.njit((nb.i8[:], ), cache=True)
def solve(a: np.ndarray) -> typing.NoReturn:
n = len(a)
b = np.full(n, -1, np.int64)
s = 0
for i in np.argsort(a, kind='mergesort')[::-1]:
d = 0
p = i
for j in range(n):
... | [
"numpy.full",
"numpy.argsort",
"numba.njit",
"sys.stdin.readline"
] | [((70, 102), 'numba.njit', 'nb.njit', (['(nb.i8[:],)'], {'cache': '(True)'}), '((nb.i8[:],), cache=True)\n', (77, 102), True, 'import numba as nb\n'), ((172, 196), 'numpy.full', 'np.full', (['n', '(-1)', 'np.int64'], {}), '(n, -1, np.int64)\n', (179, 196), True, 'import numpy as np\n'), ((220, 251), 'numpy.argsort', 'n... |
import os
import pdb
import copy
import numpy as np
from collections import OrderedDict, defaultdict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from src.model import building_blocks
from src.model.virtual_network import VirtualNetwork
from src.model.virtual_... | [
"src.utils.io_utils.write_json",
"src.utils.accumulator.Accumulator",
"torch.cat",
"src.utils.io_utils.check_and_create_dir",
"os.path.join",
"src.utils.utils.get_value_from_dict",
"src.utils.net_utils.get_data",
"src.model.building_blocks.StackedAttention",
"src.utils.io_utils.open_hdf5",
"src.ut... | [((787, 855), 'src.utils.utils.get_value_from_dict', 'utils.get_value_from_dict', (["config['model']", '"""base_model_type"""', '"""san"""'], {}), "(config['model'], 'base_model_type', 'san')\n", (812, 855), False, 'from src.utils import accumulator, utils, io_utils, vis_utils, net_utils\n'), ((886, 921), 'src.experime... |
from datetime import datetime, timedelta
import cv2
import numpy as np
from CVUtil import frameToBitmap, jpegToFrame
def MakeComposite( tsJpgs, leftToRight, pixelsPerSec, scale, highQuality=False ):
if not tsJpgs:
return None, None, None
# Create a composite at full size, then rescale at the end.
tsFirst = tsJp... | [
"numpy.full",
"CVUtil.frameToBitmap",
"CVUtil.jpegToFrame",
"cv2.resize"
] | [((403, 428), 'CVUtil.jpegToFrame', 'jpegToFrame', (['tsJpgs[0][1]'], {}), '(tsJpgs[0][1])\n', (414, 428), False, 'from CVUtil import frameToBitmap, jpegToFrame\n'), ((907, 963), 'numpy.full', 'np.full', (['(heightPhoto, widthComposite, 3)', '(211)', 'np.uint8'], {}), '((heightPhoto, widthComposite, 3), 211, np.uint8)\... |
import numpy as np
def np_color_to_gray(image: np.ndarray):
gray_image = image.dot([0.07, 0.72, 0.21])
gray_image = np.min(gray_image, 255).astype(np.uint8)
return gray_image
| [
"numpy.min"
] | [((126, 149), 'numpy.min', 'np.min', (['gray_image', '(255)'], {}), '(gray_image, 255)\n', (132, 149), True, 'import numpy as np\n')] |
""" Davidson iterative diagonalization """
import numpy as np
def davidson(hamiltonian, num_roots=3, convergence=1e-6):
"""
Return the lowest several eigenvalues and associated eigenvectors of a real (M x M) symmetric
matrix using the Davidson iterative diagonalization method.
Returns two objects, a 1... | [
"numpy.random.seed",
"numpy.copy",
"numpy.random.randn",
"numpy.allclose",
"numpy.linalg.qr",
"numpy.zeros",
"time.time",
"numpy.linalg.eigh",
"numpy.arange",
"numpy.linalg.norm",
"numpy.dot",
"numpy.eye",
"numpy.diag"
] | [((1229, 1266), 'numpy.eye', 'np.eye', (['dim_hamiltonian', 'dim_subspace'], {}), '(dim_hamiltonian, dim_subspace)\n', (1235, 1266), True, 'import numpy as np\n'), ((4315, 4326), 'time.time', 'time.time', ([], {}), '()\n', (4324, 4326), False, 'import time\n'), ((4331, 4348), 'numpy.random.seed', 'np.random.seed', (['(... |
import os.path as osp
import json
import numpy as np
import math
from datetime import datetime
from pprint import pprint
from scipy.misc import imread, imresize
import matplotlib.pyplot as plt
class Story_in_Sequence:
def __init__(self, images_dir, annotations_dir, splits=None):
"""
The vist_dir s... | [
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"os.path.join",
"matplotlib.pyplot.figure",
"datetime.datetime.strptime",
"numpy.tile",
"scipy.misc.imresize",
"datetime.datetime.now",
"scipy.misc.imread"
] | [((4698, 4714), 'scipy.misc.imread', 'imread', (['img_file'], {}), '(img_file)\n', (4704, 4714), False, 'from scipy.misc import imread, imresize\n'), ((4853, 4886), 'scipy.misc.imresize', 'imresize', (['img_content', '(224, 224)'], {}), '(img_content, (224, 224))\n', (4861, 4886), False, 'from scipy.misc import imread,... |
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
import netCDF4 as nc
import os
import glob
import fnmatch
from collections import namedtuple, OrderedDict
import scipy.io as sio
from scipy import interpolate, signal
from pyproj import Proj,transform
import sys
sys.path.append('/ocean/s... | [
"sys.path.append",
"netCDF4.Dataset",
"gsw.spiciness0",
"gsw.SA_from_SP",
"numpy.ma.masked_values",
"numpy.empty",
"numpy.empty_like",
"gsw.CT_from_pt",
"numpy.mean",
"numpy.arange",
"collections.namedtuple",
"gsw.density.rho",
"glob.glob"
] | [((295, 345), 'sys.path.append', 'sys.path.append', (['"""/ocean/ssahu/CANYONS/wcvi/grid/"""'], {}), "('/ocean/ssahu/CANYONS/wcvi/grid/')\n", (310, 345), False, 'import sys\n'), ((711, 816), 'netCDF4.Dataset', 'nc.Dataset', (['"""/data/mdunphy/NEP036-N30-OUT/INV/Bathymetry_EastCoast_NEMO_R036_GEBCO_corr_v14.nc"""'], {}... |
import numpy as np
from inference import infer_interactions
def build_diffusion_from_expt(params, state_means):
"""
steadystate_samples: of the form STATE_DIM x NUM_TRAJ
"""
# setup
D = np.zeros((params.dim, params.dim))
# fill in matrix
for idx in xrange(params.dim):
if idx < par... | [
"numpy.zeros",
"inference.infer_interactions",
"numpy.mean",
"numpy.eye",
"numpy.cov"
] | [((209, 243), 'numpy.zeros', 'np.zeros', (['(params.dim, params.dim)'], {}), '((params.dim, params.dim))\n', (217, 243), True, 'import numpy as np\n'), ((618, 636), 'numpy.eye', 'np.eye', (['params.dim'], {}), '(params.dim)\n', (624, 636), True, 'import numpy as np\n'), ((907, 934), 'numpy.cov', 'np.cov', (['steadystat... |
######## Webcam Object Detection Using Tensorflow-trained Classifier #########
#
# Author: <NAME>
# Date: 10/27/19
# Description:
# This program uses a TensorFlow Lite model to perform object detection on a live webcam
# feed. It draws boxes and scores around the objects of interest in each frame from the
# webcam. To ... | [
"argparse.ArgumentParser",
"cv2.VideoWriter_fourcc",
"socket.socket",
"cv2.getTickCount",
"cv2.rectangle",
"RPi.GPIO.output",
"os.path.join",
"RPi.GPIO.cleanup",
"cv2.getTickFrequency",
"RPi.GPIO.setup",
"cv2.cvtColor",
"os.path.exists",
"tensorflow.lite.python.interpreter.load_delegate",
... | [((1524, 1549), 'multiprocessing.Manager', 'multiprocessing.Manager', ([], {}), '()\n', (1547, 1549), False, 'import multiprocessing\n'), ((3117, 3132), 'socket.socket', 'socket.socket', ([], {}), '()\n', (3130, 3132), False, 'import socket\n'), ((13363, 13388), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([]... |
import numpy as np
from sc3nb.sc_objects.buffer import Buffer
from tests.conftest import SCBaseTest
class BufferTest(SCBaseTest):
__test__ = True
def setUp(self) -> None:
self.buffer = Buffer()
def test_load_data(self):
bufdata = np.random.rand(30000, 1)
self.buffer.load_data(b... | [
"numpy.random.rand",
"sc3nb.sc_objects.buffer.Buffer"
] | [((206, 214), 'sc3nb.sc_objects.buffer.Buffer', 'Buffer', ([], {}), '()\n', (212, 214), False, 'from sc3nb.sc_objects.buffer import Buffer\n'), ((264, 288), 'numpy.random.rand', 'np.random.rand', (['(30000)', '(1)'], {}), '(30000, 1)\n', (278, 288), True, 'import numpy as np\n')] |
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems Inc.
# 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.o... | [
"threading.Thread.__init__",
"imgworker.decode_list",
"os.path.join",
"neon.util.persist.deserialize",
"numpy.eye",
"neon.util.batch_writer.BatchWriter",
"numpy.zeros",
"os.path.exists",
"neon.util.batch_writer.BatchWriterImagenet",
"neon.util.param.opt_param",
"numpy.squeeze",
"sys.exit",
"... | [((1044, 1071), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1061, 1071), False, 'import logging\n'), ((1306, 1327), 'threading.Thread.__init__', 'Thread.__init__', (['self'], {}), '(self)\n', (1321, 1327), False, 'from threading import Thread\n'), ((1859, 1922), 'numpy.zeros', 'np.zer... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Load true values
#test_df = pd.read_csv("Sparse_parity_test.csv", header=None).to_numpy()
test_df = np.load("data/sparse_parity_test.npy")
y = test_df[:, -1]
ofpreds1k = np.load("output/of_sparse_parity_preds_1000.npy")
ofpreds5k = np.load("out... | [
"matplotlib.pyplot.title",
"numpy.load",
"numpy.sum",
"numpy.log",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlabel"
] | [((175, 213), 'numpy.load', 'np.load', (['"""data/sparse_parity_test.npy"""'], {}), "('data/sparse_parity_test.npy')\n", (182, 213), True, 'import numpy as np\n'), ((246, 295), 'numpy.load', 'np.load', (['"""output/of_sparse_parity_preds_1000.npy"""'], {}), "('output/of_sparse_parity_preds_1000.npy')\n", (253, 295), Tr... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.optim as optim
import numpy as np
class stAdvAttack:
def __init__(self, model, args):
self.model = model
self.args = args
super(stAdvAttack, self).__init__()
def... | [
"csv.reader",
"torchvision.transforms.Normalize",
"torch.optim.LBFGSB",
"torch.nn.functional.grid_sample",
"torchvision.transforms.Scale",
"requests.get",
"torch.zeros",
"torch.mean",
"opt_imagenet.parse_opt",
"torch.clamp",
"torch.cuda.is_available",
"torch.max",
"torch.sum",
"torch.from_... | [((3148, 3170), 'PIL.Image.open', 'Image.open', (['image_name'], {}), '(image_name)\n', (3158, 3170), False, 'from PIL import Image\n'), ((3615, 3626), 'opt_imagenet.parse_opt', 'parse_opt', ([], {}), '()\n', (3624, 3626), False, 'from opt_imagenet import parse_opt\n'), ((3699, 3724), 'torch.cuda.is_available', 'torch.... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 10 04:24:07 2021
@author: Saif
"""
from sklearn.datasets import load_files
from keras.utils import np_utils
import numpy as np
from glob import glob
from collections import Counter
import matplotlib.pyplot as plt
from keras.preprocessing import image ... | [
"keras.models.load_model",
"keras.preprocessing.image.img_to_array",
"keras.preprocessing.image.load_img",
"numpy.expand_dims"
] | [((543, 609), 'keras.models.load_model', 'load_model', (['"""saved_models/weights.best.with_augmentation_new.hdf5"""'], {}), "('saved_models/weights.best.with_augmentation_new.hdf5')\n", (553, 609), False, 'from keras.models import load_model\n'), ((656, 712), 'keras.preprocessing.image.load_img', 'load_img', (['img_pa... |
import os
import numpy as np
from pymatbridge import Matlab
from sklearn.metrics import precision_recall_curve, roc_curve
from sklearn.metrics import auc
class KBMF:
def __init__(self, num_factors=10):
self.num_factors = num_factors
def fix_model(self, W, intMat, drugMat, targetMat, seed=None):
... | [
"sklearn.metrics.roc_curve",
"pymatbridge.Matlab",
"sklearn.metrics.precision_recall_curve",
"sklearn.metrics.auc",
"numpy.array",
"os.sep.join"
] | [((438, 446), 'pymatbridge.Matlab', 'Matlab', ([], {}), '()\n', (444, 446), False, 'from pymatbridge import Matlab\n'), ((978, 997), 'numpy.array', 'np.array', (['test_data'], {}), '(test_data)\n', (986, 997), True, 'import numpy as np\n'), ((1189, 1231), 'sklearn.metrics.precision_recall_curve', 'precision_recall_curv... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
from model.test import test_net, im_detect
from model.config import cfg, cfg_from_file, cfg_from_list
from datasets.factory import get_imdb
import argparse
import pprint
import time, os, sys
... | [
"argparse.ArgumentParser",
"tensorflow.ConfigProto",
"nets.vgg16.vgg16",
"os.path.join",
"numpy.max",
"tensorflow.train.Saver",
"os.path.basename",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"numpy.hstack",
"numpy.min",
"nets.resnet_v1.resnetv1",
"model.test.im_detect",... | [((578, 644), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test a Faster R-CNN network"""'}), "(description='Test a Faster R-CNN network')\n", (601, 644), False, 'import argparse\n'), ((1837, 1894), 'cv2.polylines', 'cv2.polylines', (['img', '[pts]', '(True)', '(255, 0, 0)'], {'thickne... |
import numpy as np
from .matrix import MatrixTransformer
class DiagonalMatrixTransformer(MatrixTransformer):
def __init__(self):
pass
def individual_size(self, input_dim):
return input_dim
def fit(self, X, y, flat_weights):
self.input_dim = X.shape[1]
if self.input_dim !... | [
"numpy.diag"
] | [((526, 547), 'numpy.diag', 'np.diag', (['flat_weights'], {}), '(flat_weights)\n', (533, 547), True, 'import numpy as np\n')] |
from __future__ import annotations
from pathlib import Path
from typing import Tuple, Union
import cv2
import numpy as np
import skimage.color
import skimage.io
import skimage.transform
import bsmu.vision.core.converters.image as image_converter
class DnnModelParams:
def __init__(self,
path: P... | [
"numpy.stack",
"numpy.dstack",
"numpy.copy",
"numpy.median",
"cv2.flip",
"numpy.mean",
"bsmu.vision.core.converters.image.normalized_uint8",
"cv2.convertScaleAbs",
"cv2.dnn.blobFromImages",
"numpy.squeeze",
"bsmu.vision.core.converters.image.normalized",
"cv2.imshow",
"numpy.var",
"cv2.res... | [((1572, 1610), 'cv2.imshow', 'cv2.imshow', (['f"""Image"""', 'image[..., ::-1]'], {}), "(f'Image', image[..., ::-1])\n", (1582, 1610), False, 'import cv2\n'), ((5657, 5670), 'numpy.copy', 'np.copy', (['conv'], {}), '(conv)\n', (5664, 5670), True, 'import numpy as np\n'), ((5797, 5817), 'numpy.mean', 'np.mean', (['cam'... |
import numpy as np
from itertools import chain
from mdft_nn.mdft import MDFT, get_time_based_dft_dist, get_preference_based_dft_dist
from mdft_nn.helpers.distances import hotaling_S
from max_ent.algorithms import rl as RL
class System2Solver:
def __init__(self):
super()
def policy(self, modelSelf, state, w=[1... | [
"mdft_nn.mdft.MDFT",
"numpy.argmax",
"mdft_nn.helpers.distances.hotaling_S",
"numpy.zeros",
"mdft_nn.mdft.get_preference_based_dft_dist",
"numpy.array",
"numpy.concatenate"
] | [((1284, 1327), 'numpy.concatenate', 'np.concatenate', (['[r[:, None], c[:, None]]', '(1)'], {}), '([r[:, None], c[:, None]], 1)\n', (1298, 1327), True, 'import numpy as np\n'), ((1334, 1362), 'mdft_nn.helpers.distances.hotaling_S', 'hotaling_S', (['M', '(0.01)', '(0.01)', '(2)'], {}), '(M, 0.01, 0.01, 2)\n', (1344, 13... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.