id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
18,117
import json import os from dataclasses import dataclass import numpy as np import pyarrow as pa import datasets from utils import get_duration SPEED_TEST_N_EXAMPLES = 100_000_000_000 SPEED_TEST_CHUNK_SIZE = 10_000 RESULTS_FILE_PATH = os.path.join(RESULTS_BASEPATH, "results", RESULTS_FILENAME.replace(".py", ".json")) de...
null
18,118
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration SPEED_TEST_N_EXAMPLES = 50_000 SMALL_TEST = 5_000 RESULTS_FILE_PATH = os.path.join(RESULTS_BASEPATH, "results", RESULTS_FILENAME.replace(".py", ".json")) def read(dataset: datasets.Dataset, length): for i ...
null
18,119
import json import sys def format_json_to_md(input_json_file, output_md_file): with open(input_json_file, encoding="utf-8") as f: results = json.load(f) output_md = ["<details>", "<summary>Show updated benchmarks!</summary>", " "] for benchmark_name in sorted(results): benchmark_res = res...
null
18,120
import argparse import re import packaging.version def global_version_update(version): """Update the version in all needed files.""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(fname, version, pattern) def get_version(): """Reads the current version in the __init__.""" wi...
Do all the necessary pre-release steps.
18,121
import argparse import re import packaging.version def global_version_update(version): """Update the version in all needed files.""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(fname, version, pattern) def get_version(): """Reads the current version in the __init__.""" wi...
Do all the necesarry post-release steps.
18,122
import os def amiiDump(f): pagelist = [] uidlist = [] try: amiibin = open(f, "rb") pagenumber = 0 while amiibin: # Read the bin 4 bytes at a time chunk = amiibin.read(4) if not chunk: break # Convert binary to non-ASCII...
null
18,123
import os template1 = """Filetype: Flipper NFC device Version: 2 # Nfc device type can be UID, Mifare Ultralight, Bank card Device type: NTAG215 # UID, ATQA and SAK are common for all formats""" template2 ="""ATQA: 44 00 SAK: 00 # Mifare Ultralight specific data Signature: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0...
null
18,134
import os import sys import inspect sys.path.insert(0, os.path.abspath("..")) gh_url = "https://github.com/ddbourgin/numpy-ml" def linkcode_resolve(domain, info): if domain != "py": return None module = info.get("module", None) fullname = info.get("fullname", None) if not module or not fullna...
null
18,135
import numpy as np The provided code snippet includes necessary dependencies for implementing the `_sigmoid` function. Write a Python function `def _sigmoid(x)` to solve the following problem: The logistic sigmoid function Here is the function: def _sigmoid(x): """The logistic sigmoid function""" return 1 / ...
The logistic sigmoid function
18,136
import numpy as np from .dt import DecisionTree from .losses import MSELoss, CrossEntropyLoss def to_one_hot(labels, n_classes=None): if labels.ndim > 1: raise ValueError("labels must have dimension 1, but got {}".format(labels.ndim)) N = labels.size n_cols = np.max(labels) + 1 if n_classes is Non...
null
18,137
import numpy as np The provided code snippet includes necessary dependencies for implementing the `mse` function. Write a Python function `def mse(y)` to solve the following problem: Mean squared error for decision tree (ie., mean) predictions Here is the function: def mse(y): """ Mean squared error for deci...
Mean squared error for decision tree (ie., mean) predictions
18,138
import numpy as np The provided code snippet includes necessary dependencies for implementing the `entropy` function. Write a Python function `def entropy(y)` to solve the following problem: Entropy of a label sequence Here is the function: def entropy(y): """ Entropy of a label sequence """ hist = n...
Entropy of a label sequence
18,139
import numpy as np The provided code snippet includes necessary dependencies for implementing the `gini` function. Write a Python function `def gini(y)` to solve the following problem: Gini impurity (local entropy) of a label sequence Here is the function: def gini(y): """ Gini impurity (local entropy) of a ...
Gini impurity (local entropy) of a label sequence
18,140
import numpy as np from .dt import DecisionTree def bootstrap_sample(X, Y): N, M = X.shape idxs = np.random.choice(N, N, replace=True) return X[idxs], Y[idxs]
null
18,141
import numpy as np from matplotlib import pyplot as plt import seaborn as sns from hmmlearn.hmm import MultinomialHMM as MHMM from numpy_ml.hmm import MultinomialHMM def generate_training_data(params, n_steps=500, n_examples=15): hmm = MultinomialHMM(A=params["A"], B=params["B"], pi=params["pi"]) # generate a n...
null
18,142
import gym from numpy_ml.rl_models.trainer import Trainer from numpy_ml.rl_models.agents import ( CrossEntropyAgent, MonteCarloAgent, TemporalDifferenceAgent, DynaAgent, ) class Trainer(object): def __init__(self, agent, env): """ An object to facilitate agent training and evaluatio...
null
18,143
import gym from numpy_ml.rl_models.trainer import Trainer from numpy_ml.rl_models.agents import ( CrossEntropyAgent, MonteCarloAgent, TemporalDifferenceAgent, DynaAgent, ) class Trainer(object): def __init__(self, agent, env): """ An object to facilitate agent training and evaluatio...
null
18,144
import gym from numpy_ml.rl_models.trainer import Trainer from numpy_ml.rl_models.agents import ( CrossEntropyAgent, MonteCarloAgent, TemporalDifferenceAgent, DynaAgent, ) class Trainer(object): def __init__(self, agent, env): """ An object to facilitate agent training and evaluatio...
null
18,145
import gym from numpy_ml.rl_models.trainer import Trainer from numpy_ml.rl_models.agents import ( CrossEntropyAgent, MonteCarloAgent, TemporalDifferenceAgent, DynaAgent, ) class Trainer(object): def __init__(self, agent, env): """ An object to facilitate agent training and evaluatio...
null
18,146
import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style("white") sns.set_context("notebook", font_scale=0.7) from numpy_ml.neural_nets.activations import ( Affine, ReLU, LeakyReLU, Tanh, Sigmoid, ELU, Exponential, SELU, HardSigmoid, SoftPlus, ) def...
null
18,147
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from numpy_ml.nonparametric import GPRegression, KNN, KernelRegression from numpy_ml.linear_models.lm import LinearRegression from sklearn.model_selection import train_test_split def random_regression_problem(n_ex, n_in, n_out, d=3, intercept=0, s...
null
18,148
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from numpy_ml.nonparametric import GPRegression, KNN, KernelRegression from numpy_ml.linear_models.lm import LinearRegression from sklearn.model_selection import train_test_split def random_regression_problem(n_ex, n_in, n_out, d=3, intercept=0, s...
null
18,149
import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style("white") sns.set_context("paper", font_scale=0.5) from numpy_ml.nonparametric import GPRegression, KNN, KernelRegression from numpy_ml.linear_models.lm import LinearRegression from sklearn.model_selection import train_test_split def...
null
18,150
import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style("white") sns.set_context("paper", font_scale=0.5) from numpy_ml.nonparametric import GPRegression, KNN, KernelRegression from numpy_ml.linear_models.lm import LinearRegression from sklearn.model_selection import train_test_split def...
null
18,151
import numpy as np from sklearn.model_selection import train_test_split from sklearn.datasets.samples_generator import make_blobs from sklearn.linear_model import LogisticRegression as LogisticRegression_sk from sklearn.datasets import make_regression from sklearn.metrics import zero_one_loss, r2_score import matplotli...
null
18,152
import numpy as np from sklearn.model_selection import train_test_split from sklearn.datasets.samples_generator import make_blobs from sklearn.linear_model import LogisticRegression as LogisticRegression_sk from sklearn.datasets import make_regression from sklearn.metrics import zero_one_loss, r2_score import matplotli...
null
18,153
import numpy as np from sklearn.model_selection import train_test_split from sklearn.datasets.samples_generator import make_blobs from sklearn.linear_model import LogisticRegression as LogisticRegression_sk from sklearn.datasets import make_regression from sklearn.metrics import zero_one_loss, r2_score import matplotli...
null
18,154
import numpy as np from sklearn.model_selection import train_test_split from sklearn.datasets.samples_generator import make_blobs from sklearn.linear_model import LogisticRegression as LogisticRegression_sk from sklearn.datasets import make_regression from sklearn.metrics import zero_one_loss, r2_score import matplotli...
null
18,155
import time import numpy as np import matplotlib.pyplot as plt import seaborn as sns from numpy_ml.neural_nets.schedulers import ( ConstantScheduler, ExponentialScheduler, NoamScheduler, KingScheduler, ) def king_loss_fn(x): if x <= 250: return -0.25 * x + 82.50372665317208 elif 250 < x ...
null
18,156
import numpy as np from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.datasets import make_blobs, make_regression from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import seaborn as sns from numpy_ml.trees import GradientBoostedDecisionTree, DecisionTree, Rand...
null
18,157
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from numpy_ml.ngram import MLENGram, AdditiveNGram, GoodTuringNGram def plot_count_models(GT, N): NC = GT._num_grams_with_count mod = GT._count_models[N] max_n = max(GT.counts[N].values()) emp = [NC(n + 1, N) for n in range(max_n)...
null
18,158
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from numpy_ml.ngram import MLENGram, AdditiveNGram, GoodTuringNGram def compare_probs(fp, N): MLE = MLENGram(N, unk=False, filter_punctuation=False, filter_stopwords=False) MLE.train(fp, encoding="utf-8-sig") add_y, mle_y, gtt_y = []...
null
18,159
import numpy as np import matplotlib.pyplot as plt import seaborn as sns from numpy_ml.ngram import MLENGram, AdditiveNGram, GoodTuringNGram The provided code snippet includes necessary dependencies for implementing the `plot_gt_freqs` function. Write a Python function `def plot_gt_freqs(fp)` to solve the following pr...
Draws a scatterplot of the empirical frequencies of the counted species versus their Simple Good Turing smoothed values, in rank order. Depends on pylab and matplotlib.
18,160
import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style("white") sns.set_context("paper", font_scale=1) from numpy_ml.lda import LDA def generate_corpus(): # Generate some fake data D = 300 T = 10 V = 30 N = np.random.randint(150, 200, size=D) # Create a document-t...
null
18,161
from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.policies import ( EpsilonGreedy, UCB1, ThompsonSampl...
Evaluate an epsilon-greedy policy on a random multinomial bandit problem
18,162
from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.policies import ( EpsilonGreedy, UCB1, ThompsonSampl...
Evaluate the UCB1 policy on a multinomial bandit environment
18,163
from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.policies import ( EpsilonGreedy, UCB1, ThompsonSampl...
Evaluate the ThompsonSamplingBetaBinomial policy on a random Bernoulli multi-armed bandit.
18,164
from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.policies import ( EpsilonGreedy, UCB1, ThompsonSampl...
Plot the linUCB policy on a contextual linear bandit problem
18,165
from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.policies import ( EpsilonGreedy, UCB1, ThompsonSampl...
Plot the UCB1 policy on a graph shortest path problem each edge weight drawn from an independent univariate Gaussian
18,166
from collections import namedtuple import numpy as np from numpy_ml.bandits import ( MultinomialBandit, BernoulliBandit, ShortestPathBandit, ContextualLinearBandit, ) from numpy_ml.bandits.trainer import BanditTrainer from numpy_ml.bandits.policies import ( EpsilonGreedy, UCB1, ThompsonSampl...
Use the BanditTrainer to compare several policies on the same bandit problem
18,167
import warnings from itertools import product from collections import defaultdict import numpy as np from numpy_ml.utils.testing import DependencyWarning from numpy_ml.rl_models.tiles.tiles3 import tiles, IHT class IHT: "Structure to handle collisions" def __init__(self, sizeval): self.size = sizeval ...
Return a function to encode the continous observations generated by `env` in terms of a collection of `n_tilings` overlapping tilings (each with dimension `grid_size`) of the state space. Arguments --------- env : ``gym.wrappers.time_limit.TimeLimit`` instance An openAI environment. n_tilings : int The number of overla...
18,168
import warnings from itertools import product from collections import defaultdict import numpy as np from numpy_ml.utils.testing import DependencyWarning from numpy_ml.rl_models.tiles.tiles3 import tiles, IHT try: import gym except ModuleNotFoundError: fstr = ( "Agents in `numpy_ml.rl_models` use the Op...
List all valid OpenAI ``gym`` environment ids
18,169
import warnings from itertools import product from collections import defaultdict import numpy as np from numpy_ml.utils.testing import DependencyWarning from numpy_ml.rl_models.tiles.tiles3 import tiles, IHT NO_PD = False try: import gym except ModuleNotFoundError: fstr = ( "Agents in `numpy_ml.rl_mode...
Return a pandas DataFrame of the environment IDs.
18,170
from math import floor from itertools import zip_longest def hashcoords(coordinates, m, readonly=False): if type(m) == IHT: return m.getindex(tuple(coordinates), readonly) if type(m) == int: return basehash(tuple(coordinates)) % m if m == None: return coordinates The provided code s...
returns num-tilings tile indices corresponding to the floats and ints, wrapping some floats
18,171
import warnings import os.path as op from collections import defaultdict import numpy as np from numpy_ml.utils.testing import DependencyWarning The provided code snippet includes necessary dependencies for implementing the `get_scriptdir` function. Write a Python function `def get_scriptdir()` to solve the following ...
Return the directory containing the `trainer.py` script
18,172
import warnings import os.path as op from collections import defaultdict import numpy as np from numpy_ml.utils.testing import DependencyWarning The provided code snippet includes necessary dependencies for implementing the `mse` function. Write a Python function `def mse(bandit, policy)` to solve the following proble...
Computes the mean squared error between a policy's estimates of the expected arm payouts and the true expected payouts.
18,173
import warnings import os.path as op from collections import defaultdict import numpy as np from numpy_ml.utils.testing import DependencyWarning The provided code snippet includes necessary dependencies for implementing the `smooth` function. Write a Python function `def smooth(prev, cur, weight)` to solve the followi...
r""" Compute a simple weighted average of the previous and current value. Notes ----- The smoothed value at timestep `t`, :math:`\tilde{X}_t` is calculated as .. math:: \tilde{X}_t = \epsilon \tilde{X}_{t-1} + (1 - \epsilon) X_t where :math:`X_t` is the value at timestep `t`, :math:`\tilde{X}_{t-1}` is the value of the...
18,174
import numpy as np from scipy.special import digamma, polygamma, gammaln The provided code snippet includes necessary dependencies for implementing the `dg` function. Write a Python function `def dg(gamma, d, t)` to solve the following problem: E[log X_t] where X_t ~ Dir Here is the function: def dg(gamma, d, t): ...
E[log X_t] where X_t ~ Dir
18,175
import numpy as np from numpy.lib.stride_tricks import as_strided from ..utils.windows import WindowInitializer def nn_interpolate_2D(X, x, y): """ Estimates of the pixel values at the coordinates (x, y) in `X` using a nearest neighbor interpolation strategy. Notes ----- Assumes the current entr...
Resample each image (or similar grid-based 2D signal) in a batch to `new_dim` using the specified resampling strategy. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, in_rows, in_cols, in_channels)` An input image volume new_dim : 2-tuple of `(out_rows, out_cols)` The dimension to resampl...
18,176
import numpy as np from numpy.lib.stride_tricks import as_strided from ..utils.windows import WindowInitializer The provided code snippet includes necessary dependencies for implementing the `nn_interpolate_1D` function. Write a Python function `def nn_interpolate_1D(X, t)` to solve the following problem: Estimates of...
Estimates of the signal values at `X[t]` using a nearest neighbor interpolation strategy. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(in_length, in_channels)` An input image sampled along an integer `in_length` t : list of length `k` A list of coordinates for the samples we wish to generate...
18,177
import numpy as np from numpy.lib.stride_tricks import as_strided from ..utils.windows import WindowInitializer The provided code snippet includes necessary dependencies for implementing the `__DCT2` function. Write a Python function `def __DCT2(frame)` to solve the following problem: Currently broken Here is the fun...
Currently broken
18,178
import numpy as np from numpy.lib.stride_tricks import as_strided from ..utils.windows import WindowInitializer The provided code snippet includes necessary dependencies for implementing the `autocorrelate1D` function. Write a Python function `def autocorrelate1D(x)` to solve the following problem: Autocorrelate a 1D ...
Autocorrelate a 1D signal `x` with itself. Notes ----- The `k` th term in the 1 dimensional autocorrelation is .. math:: a_k = \sum_n x_{n + k} x_n NB. This is a naive :math:`O(N^2)` implementation. For a faster :math:`O(N \log N)` approach using the FFT, see [1]. References ---------- .. [1] https://en.wikipedia.org/w...
18,179
import numpy as np from numpy.lib.stride_tricks import as_strided from ..utils.windows import WindowInitializer def DCT(frame, orthonormal=True): """ A naive :math:`O(N^2)` implementation of the 1D discrete cosine transform-II (DCT-II). Notes ----- For a signal :math:`\mathbf{x} = [x_1, \ldots, ...
Compute the Mel-frequency cepstral coefficients (MFCC) for a signal. Notes ----- Computing MFCC features proceeds in the following stages: 1. Convert the signal into overlapping frames and apply a window fn 2. Compute the power spectrum at each frame 3. Apply the mel filterbank to the power spectra to get mel filterban...
18,180
import re import heapq import os.path as op from collections import Counter, OrderedDict, defaultdict import numpy as np The provided code snippet includes necessary dependencies for implementing the `ngrams` function. Write a Python function `def ngrams(sequence, N)` to solve the following problem: Return all `N`-gra...
Return all `N`-grams of the elements in `sequence`
18,181
import re import heapq import os.path as op from collections import Counter, OrderedDict, defaultdict import numpy as np def remove_stop_words(words): """Remove stop words from a list of word strings""" return [w for w in words if w.lower() not in _STOP_WORDS] def strip_punctuation(line): """Remove punctuat...
Split a string at any whitespace characters, optionally removing punctuation and stop-words in the process.
18,182
import re import heapq import os.path as op from collections import Counter, OrderedDict, defaultdict import numpy as np def tokenize_words( line, lowercase=True, filter_stopwords=True, filter_punctuation=True, **kwargs, ): """ Split a string into individual words, optionally removing punctuation and st...
Split a string into individual words, optionally removing punctuation and stop-words in the process. Translate each word into a list of bytes.
18,183
import re import heapq import os.path as op from collections import Counter, OrderedDict, defaultdict import numpy as np _PUNC_BYTE_REGEX = re.compile( r"(33|34|35|36|37|38|39|40|41|42|43|44|45|" r"46|47|58|59|60|61|62|63|64|91|92|93|94|" r"95|96|123|124|125|126)", ) The provided code snippet includes nece...
Convert the characters in `line` to a collection of bytes. Each byte is represented in decimal as an integer between 0 and 255. Parameters ---------- line : str The string to tokenize. encoding : str The encoding scheme for the characters in `line`. Default is `'utf-8'`. splitter : {'punctuation', None} If `'punctuatio...
18,184
import re import heapq import os.path as op from collections import Counter, OrderedDict, defaultdict import numpy as np The provided code snippet includes necessary dependencies for implementing the `bytes_to_chars` function. Write a Python function `def bytes_to_chars(byte_list, encoding="utf-8")` to solve the follo...
Decode bytes (represented as an integer between 0 and 255) to characters in the specified encoding.
18,185
import re import heapq import os.path as op from collections import Counter, OrderedDict, defaultdict import numpy as np def strip_punctuation(line): """Remove punctuation from a string""" return line.translate(_PUNC_TABLE).strip() The provided code snippet includes necessary dependencies for implementing the ...
Split a string into individual characters, optionally removing punctuation and stop-words in the process.
18,186
import json import hashlib import warnings import numpy as np The provided code snippet includes necessary dependencies for implementing the `minibatch` function. Write a Python function `def minibatch(X, batchsize=256, shuffle=True)` to solve the following problem: Compute the minibatch indices for a training dataset...
Compute the minibatch indices for a training dataset. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, \*)` The dataset to divide into minibatches. Assumes the first dimension represents the number of training examples. batchsize : int The desired size of each minibatch. Note, however, that i...
18,187
from abc import ABC, abstractmethod import numpy as np class Dropout(WrapperBase): def __init__(self, wrapped_layer, p): """ A dropout regularization wrapper. Notes ----- During training, a dropout layer zeroes each element of the layer input with probability `p` and ...
Initialize the layer wrappers in `wrapper_list` and return a wrapped `layer` object. Parameters ---------- layer : :doc:`Layer <numpy_ml.neural_nets.layers>` instance The base layer object to apply the wrappers to. wrappers : list of dicts A list of parameter dictionaries for a the wrapper objects. The wrappers are ini...
18,188
from copy import deepcopy from abc import ABC, abstractmethod import numpy as np from math import erf The provided code snippet includes necessary dependencies for implementing the `gaussian_cdf` function. Write a Python function `def gaussian_cdf(x, mean, var)` to solve the following problem: Compute the probability ...
Compute the probability that a random draw from a 1D Gaussian with mean `mean` and variance `var` is less than or equal to `x`.
18,189
import numpy as np The provided code snippet includes necessary dependencies for implementing the `minibatch` function. Write a Python function `def minibatch(X, batchsize=256, shuffle=True)` to solve the following problem: Compute the minibatch indices for a training dataset. Parameters ---------- X : :py:class:`ndar...
Compute the minibatch indices for a training dataset. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, \*)` The dataset to divide into minibatches. Assumes the first dimension represents the number of training examples. batchsize : int The desired size of each minibatch. Note, however, that i...
18,190
import numpy as np def pad1D(X, pad, kernel_width=None, stride=None, dilation=0): """ Zero-pad a 3D input volume `X` along the second dimension. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, l_in, in_ch)` Input volume. Padding is applied to `l_in`. pad : ...
Compute the dimension of the output volume for the specified convolution. Parameters ---------- X_shape : 3-tuple or 4-tuple The dimensions of the input volume to the convolution. If 3-tuple, entries are expected to be (`n_ex`, `in_length`, `in_ch`). If 4-tuple, entries are expected to be (`n_ex`, `in_rows`, `in_cols`,...
18,191
import numpy as np def _im2col_indices(X_shape, fr, fc, p, s, d=0): """ Helper function that computes indices into X in prep for columnization in :func:`im2col`. Code extended from Andrej Karpathy's `im2col.py` """ pr1, pr2, pc1, pc2 = p n_ex, n_in, in_rows, in_cols = X_shape # adjust ef...
Take columns of a 2D matrix and rearrange them into the blocks/windows of a 4D image volume. Notes ----- A NumPy reimagining of MATLAB's ``col2im`` 'sliding' function. Code extended from Andrej Karpathy's ``im2col.py``. Parameters ---------- X_col : :py:class:`ndarray <numpy.ndarray>` of shape `(Q, Z)` The columnized v...
18,192
import numpy as np def pad1D(X, pad, kernel_width=None, stride=None, dilation=0): """ Zero-pad a 3D input volume `X` along the second dimension. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, l_in, in_ch)` Input volume. Padding is applied to `l_in`. pad : ...
A faster (but more memory intensive) implementation of a 1D "convolution" (technically, cross-correlation) of input `X` with a collection of kernels in `W`. Notes ----- Relies on the :func:`im2col` function to perform the convolution as a single matrix multiplication. For a helpful diagram, see Pete Warden's 2015 blogp...
18,193
import numpy as np def calc_pad_dims_2D(X_shape, out_dim, kernel_shape, stride, dilation=0): """ Compute the padding necessary to ensure that convolving `X` with a 2D kernel of shape `kernel_shape` and stride `stride` produces outputs with dimension `out_dim`. Parameters ---------- X_shape :...
Perform a "deconvolution" (more accurately, a transposed convolution) of an input volume `X` with a weight kernel `W`, incorporating stride, pad, and dilation. Notes ----- Rather than using the transpose of the convolution matrix, this approach uses a direct convolution with zero padding, which, while conceptually stra...
18,194
import numpy as np def pad2D(X, pad, kernel_shape=None, stride=None, dilation=0): """ Zero-pad a 4D input volume `X` along the second and third dimensions. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, in_rows, in_cols, in_ch)` Input volume. Padding is applie...
A slow but more straightforward implementation of a 2D "convolution" (technically, cross-correlation) of input `X` with a collection of kernels `W`. Notes ----- This implementation uses ``for`` loops and direct indexing to perform the convolution. As a result, it is slower than the vectorized :func:`conv2D` function th...
18,195
import numpy as np def calc_fan(weight_shape): """ Compute the fan-in and fan-out for a weight matrix/volume. Parameters ---------- weight_shape : tuple The dimensions of the weight matrix/volume. The final 2 entries must be `in_ch`, `out_ch`. Returns ------- fan_in : int...
Initializes network weights `W` with using the He uniform initialization strategy. Notes ----- The He uniform initializations trategy initializes thew eights in `W` using draws from Uniform(-b, b) where .. math:: b = \sqrt{\\frac{6}{\\text{fan_in}}} Developed for deep networks with ReLU nonlinearities. Parameters -----...
18,196
import numpy as np def calc_fan(weight_shape): """ Compute the fan-in and fan-out for a weight matrix/volume. Parameters ---------- weight_shape : tuple The dimensions of the weight matrix/volume. The final 2 entries must be `in_ch`, `out_ch`. Returns ------- fan_in : int...
Initialize network weights `W` using the He normal initialization strategy. Notes ----- The He normal initialization strategy initializes the weights in `W` using draws from TruncatedNormal(0, b) where the variance `b` is .. math:: b = \\frac{2}{\\text{fan_in}} He normal initialization was originally developed for deep...
18,197
import numpy as np def calc_fan(weight_shape): """ Compute the fan-in and fan-out for a weight matrix/volume. Parameters ---------- weight_shape : tuple The dimensions of the weight matrix/volume. The final 2 entries must be `in_ch`, `out_ch`. Returns ------- fan_in : int...
Initialize network weights `W` using the Glorot uniform initialization strategy. Notes ----- The Glorot uniform initialization strategy initializes weights using draws from ``Uniform(-b, b)`` where: .. math:: b = \\text{gain} \sqrt{\\frac{6}{\\text{fan_in} + \\text{fan_out}}} The motivation for Glorot uniform initializ...
18,198
import numpy as np def calc_fan(weight_shape): """ Compute the fan-in and fan-out for a weight matrix/volume. Parameters ---------- weight_shape : tuple The dimensions of the weight matrix/volume. The final 2 entries must be `in_ch`, `out_ch`. Returns ------- fan_in : int...
Initialize network weights `W` using the Glorot normal initialization strategy. Notes ----- The Glorot normal initializaiton initializes weights with draws from TruncatedNormal(0, b) where the variance `b` is .. math:: b = \\frac{2 \\text{gain}^2}{\\text{fan_in} + \\text{fan_out}} The motivation for Glorot normal initi...
18,199
import numpy as np def generalized_cosine(window_len, coefs, symmetric=False): """ The generalized cosine family of window functions. Notes ----- The generalized cosine window is a simple weighted sum of cosine terms. For :math:`n \in \{0, \ldots, \\text{window_len} \}`: .. math:: \\...
The Blackman-Harris window. Notes ----- The Blackman-Harris window is an instance of the more general class of cosine-sum windows where `K=3`. Additional coefficients extend the Hamming window to further minimize the magnitude of the nearest side-lobe in the frequency response. .. math:: \\text{bh}(n) = a_0 - a_1 \cos\...
18,200
import numpy as np def generalized_cosine(window_len, coefs, symmetric=False): """ The generalized cosine family of window functions. Notes ----- The generalized cosine window is a simple weighted sum of cosine terms. For :math:`n \in \{0, \ldots, \\text{window_len} \}`: .. math:: \\...
The Hamming window. Notes ----- The Hamming window is an instance of the more general class of cosine-sum windows where `K=1` and :math:`a_0 = 0.54`. Coefficients selected to minimize the magnitude of the nearest side-lobe in the frequency response. .. math:: \\text{hamming}(n) = 0.54 - 0.46 \cos\left(\\frac{2 \pi n}{\...
18,201
import numpy as np def generalized_cosine(window_len, coefs, symmetric=False): """ The generalized cosine family of window functions. Notes ----- The generalized cosine window is a simple weighted sum of cosine terms. For :math:`n \in \{0, \ldots, \\text{window_len} \}`: .. math:: \\...
The Hann window. Notes ----- The Hann window is an instance of the more general class of cosine-sum windows where `K=1` and :math:`a_0` = 0.5. Unlike the Hamming window, the end points of the Hann window touch zero. .. math:: \\text{hann}(n) = 0.5 - 0.5 \cos\left(\\frac{2 \pi n}{\\text{window_len} - 1}\\right) Paramete...
18,202
import numpy as np The provided code snippet includes necessary dependencies for implementing the `euclidean` function. Write a Python function `def euclidean(x, y)` to solve the following problem: Compute the Euclidean (`L2`) distance between two real vectors Notes ----- The Euclidean distance between two vectors **x...
Compute the Euclidean (`L2`) distance between two real vectors Notes ----- The Euclidean distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \sqrt{ \sum_i (x_i - y_i)^2 } Parameters ---------- x,y : :py:class:`ndarray <numpy.ndarray>` s of shape `(N,)` The two vectors to compute the di...
18,203
import numpy as np The provided code snippet includes necessary dependencies for implementing the `manhattan` function. Write a Python function `def manhattan(x, y)` to solve the following problem: Compute the Manhattan (`L1`) distance between two real vectors Notes ----- The Manhattan distance between two vectors **x...
Compute the Manhattan (`L1`) distance between two real vectors Notes ----- The Manhattan distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \sum_i |x_i - y_i| Parameters ---------- x,y : :py:class:`ndarray <numpy.ndarray>` s of shape `(N,)` The two vectors to compute the distance betw...
18,204
import numpy as np The provided code snippet includes necessary dependencies for implementing the `chebyshev` function. Write a Python function `def chebyshev(x, y)` to solve the following problem: Compute the Chebyshev (:math:`L_\infty`) distance between two real vectors Notes ----- The Chebyshev distance between two...
Compute the Chebyshev (:math:`L_\infty`) distance between two real vectors Notes ----- The Chebyshev distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \max_i |x_i - y_i| Parameters ---------- x,y : :py:class:`ndarray <numpy.ndarray>` s of shape `(N,)` The two vectors to compute the d...
18,205
import numpy as np The provided code snippet includes necessary dependencies for implementing the `minkowski` function. Write a Python function `def minkowski(x, y, p)` to solve the following problem: Compute the Minkowski-`p` distance between two real vectors. Notes ----- The Minkowski-`p` distance between two vector...
Compute the Minkowski-`p` distance between two real vectors. Notes ----- The Minkowski-`p` distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \left( \sum_i |x_i - y_i|^p \\right)^{1/p} Parameters ---------- x,y : :py:class:`ndarray <numpy.ndarray>` s of shape `(N,)` The two vectors to...
18,206
import numpy as np The provided code snippet includes necessary dependencies for implementing the `hamming` function. Write a Python function `def hamming(x, y)` to solve the following problem: Compute the Hamming distance between two integer-valued vectors. Notes ----- The Hamming distance between two vectors **x** a...
Compute the Hamming distance between two integer-valued vectors. Notes ----- The Hamming distance between two vectors **x** and **y** is .. math:: d(\mathbf{x}, \mathbf{y}) = \\frac{1}{N} \sum_i \mathbb{1}_{x_i \\neq y_i} Parameters ---------- x,y : :py:class:`ndarray <numpy.ndarray>` s of shape `(N,)` The two vectors ...
18,207
import numpy as np The provided code snippet includes necessary dependencies for implementing the `logsumexp` function. Write a Python function `def logsumexp(log_probs, axis=None)` to solve the following problem: Redefine scipy.special.logsumexp see: http://bayesjumping.net/log-sum-exp-trick/ Here is the function: ...
Redefine scipy.special.logsumexp see: http://bayesjumping.net/log-sum-exp-trick/
18,208
import numpy as np The provided code snippet includes necessary dependencies for implementing the `log_gaussian_pdf` function. Write a Python function `def log_gaussian_pdf(x_i, mu, sigma)` to solve the following problem: Compute log N(x_i | mu, sigma) Here is the function: def log_gaussian_pdf(x_i, mu, sigma): ...
Compute log N(x_i | mu, sigma)
18,209
import re from abc import ABC, abstractmethod import numpy as np def kernel_checks(X, Y): X = X.reshape(-1, 1) if X.ndim == 1 else X Y = X if Y is None else Y Y = Y.reshape(-1, 1) if Y.ndim == 1 else Y assert X.ndim == 2, "X must have 2 dimensions, but got {}".format(X.ndim) assert Y.ndim == 2, "Y...
null
18,210
import re from abc import ABC, abstractmethod import numpy as np The provided code snippet includes necessary dependencies for implementing the `pairwise_l2_distances` function. Write a Python function `def pairwise_l2_distances(X, Y)` to solve the following problem: A fast, vectorized way to compute pairwise l2 dista...
A fast, vectorized way to compute pairwise l2 distances between rows in `X` and `Y`. Notes ----- An entry of the pairwise Euclidean distance matrix for two vectors is .. math:: d[i, j] &= \sqrt{(x_i - y_i) @ (x_i - y_i)} \\\\ &= \sqrt{sum (x_i - y_j)^2} \\\\ &= \sqrt{sum (x_i)^2 - 2 x_i y_j + (y_j)^2} The code below co...
18,211
import ssl import sys from gzip import GzipFile from json import JSONDecoder from time import time from urllib.request import Request, urlopen HOST = 'translate.googleapis.com' TESTIP_FORMAT = 'https://{}/translate_a/single?client=gtx&sl=en&tl=fr&q=a' def _build_request(ip, host=HOST, testip_format=TESTIP_FORMAT): def ...
null
18,212
import ssl import sys from gzip import GzipFile from json import JSONDecoder from time import time from urllib.request import Request, urlopen def _build_request(ip, host=HOST, testip_format=TESTIP_FORMAT): url = testip_format.format(f'[{ip}]' if ':' in ip else ip) request = Request(url) request.add_header(...
null
18,213
import ssl import sys from gzip import GzipFile from json import JSONDecoder from time import time from urllib.request import Request, urlopen def time_repr(secs): return f'{secs*1000:.0f}ms' if secs < 0.9995 else f'{secs:.2f}s'
null
18,214
import ssl import sys from gzip import GzipFile from json import JSONDecoder from time import time from urllib.request import Request, urlopen HOST = 'translate.googleapis.com' def dns_query(name=HOST, server='1.1.1.1', type='A', path='/dns-query'): # https://github.com/stamparm/python-doh/blob/master/client.py ...
null
18,215
import ssl import sys from gzip import GzipFile from json import JSONDecoder from time import time from urllib.request import Request, urlopen def read_url(url, timeout=3.5): request = Request(url) request.add_header('Accept-Encoding', 'gzip') with urlopen(request, timeout=timeout) as response: # H...
null
18,216
from PySide6 import QtCore qt_resource_data = b"\ \x00\x00\x08@\ \x89\ PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\ \x00\x000\x00\x00\x000\x08\x06\x00\x00\x00W\x02\xf9\x87\ \x00\x00\x08\x07IDATh\x81\xed\x99[lT\xc7\ \x19\xc7\x7f3s\xce\xae\xbdxms\xb1]\xdb\x5cJ\ L[\xdc\xa4P\xc4\x1d\xdbA\xe1b\x9aJTJ+\ \x15\x94\x87\xcaBM\xd...
null
18,217
from PySide6 import QtCore qt_resource_data = b"\ \x00\x00\x08@\ \x89\ PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\ \x00\x000\x00\x00\x000\x08\x06\x00\x00\x00W\x02\xf9\x87\ \x00\x00\x08\x07IDATh\x81\xed\x99[lT\xc7\ \x19\xc7\x7f3s\xce\xae\xbdxms\xb1]\xdb\x5cJ\ L[\xdc\xa4P\xc4\x1d\xdbA\xe1b\x9aJTJ+\ \x15\x94\x87\xcaBM\xd...
null
18,218
from io import StringIO from json import loads from glob import glob from pathlib import Path from pytablewriter import MarkdownTableWriter def print_md_table(settings) -> MarkdownTableWriter: writer = MarkdownTableWriter( headers=["Setting", "Default", "Context", "Multiple", "Description"], value_...
null
18,219
from io import StringIO from json import loads from glob import glob from pathlib import Path from pytablewriter import MarkdownTableWriter def stream_support(support) -> str: md = "STREAM support " if support == "no": md += ":x:" elif support == "yes": md += ":white_check_mark:" else: ...
null
18,220
The provided code snippet includes necessary dependencies for implementing the `toc` function. Write a Python function `def toc(obj)` to solve the following problem: main routine Here is the function: def toc(obj): """ main routine """ print """ import libinjection def lookup(state, stype, keyword): k...
main routine
18,221
The provided code snippet includes necessary dependencies for implementing the `toc` function. Write a Python function `def toc(obj)` to solve the following problem: main routine Here is the function: def toc(obj): """ main routine """ print("""<?php function lookup($state, $stype, $keyword) { $keyword...
main routine
18,222
import sys The provided code snippet includes necessary dependencies for implementing the `toc` function. Write a Python function `def toc(obj)` to solve the following problem: main routine Here is the function: def toc(obj): """ main routine """ print(""" #ifndef LIBINJECTION_SQLI_DATA_H #define LIBINJECTI...
main routine
18,223
import subprocess RMAP = { '1': '1', 'f': 'convert', '&': 'and', 'v': '@version', 'n': 'aname', 's': "\"1\"", '(': '(', ')': ')', 'o': '*', 'E': 'select', 'U': 'union', 'k': "JOIN", 't': 'binary', ',': ',', ';': ';', 'c': ' -- comment', 'T': 'DROP', ...
main code, expects to be run in main libinjection/src directory and hardwires "fingerprints.txt" as input file
18,224
KEYWORDS = { '_BIG5': 't', '_DEC8': 't', '_CP850': 't', '_HP8': 't', '_KOI8R': 't', '_LATIN1': 't', '_LATIN2': 't', '_SWE7': 't', '_ASCII': 't', '_UJIS': 't', '_SJIS': 't', '_HEBREW': 't', '_TIS620': 't', '_EUCKR': 't', '_KOI8U': 't', '_GB2312': 't', '_GREEK': 't', '_CP1250': 't', '_GBK': 't', '_LATIN5': 't', '_ARMSCII...
generates a JSON file, sorted keys
18,225
The provided code snippet includes necessary dependencies for implementing the `toc` function. Write a Python function `def toc(obj)` to solve the following problem: main routine Here is the function: def toc(obj): """ main routine """ if False: print 'fingerprints = {' for fp in sorted(obj...
main routine
18,226
The provided code snippet includes necessary dependencies for implementing the `make_lua_table` function. Write a Python function `def make_lua_table(obj)` to solve the following problem: Generates table. Fingerprints don't contain any special chars so they don't need to be escaped. The output may be sorted but it is...
Generates table. Fingerprints don't contain any special chars so they don't need to be escaped. The output may be sorted but it is not required.