INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Parse the BSER packet | def _loads(self, response):
""" Parse the BSER packet """
return bser.loads(
response,
True,
value_encoding=encoding.get_local_encoding(),
value_errors=encoding.default_local_errors,
) |
Receive the response to a request made to the Watchman service. | async def receive_bilateral_response(self):
"""Receive the response to a request made to the Watchman service."""
self._check_receive_loop()
resp = await self.bilateral_response_queue.get()
self._check_error(resp)
return resp |
Send a query to the Watchman service and return the response. | async def query(self, *args):
"""Send a query to the Watchman service and return the response."""
self._check_receive_loop()
try:
await self.connection.send(args)
return await self.receive_bilateral_response()
except CommandError as ex:
ex.setCommand(... |
Perform a server capability check. | async def capability_check(self, optional=None, required=None):
"""Perform a server capability check."""
self._check_receive_loop()
# If the returned response is an error, self.query will raise an error
await self.query(
"version", {"optional": optional or [], "required": re... |
Retrieve the data associated with a named subscription | async def get_subscription(self, name, root):
""" Retrieve the data associated with a named subscription
Returns None if there is no data associated with `name`
If root is not None, then only return the subscription
data that matches both root and name. When used in this way,
... |
Get one log from the log queue. | async def pop_log(self):
"""Get one log from the log queue."""
self._check_receive_loop()
res = self.log_queue.get()
self._check_error(res)
return res |
Close the underlying connection. | def close(self):
"""Close the underlying connection."""
self._closed = True
if self.receive_task:
self.receive_task.cancel()
if self.connection:
self.connection.close() |
Schedules the receive loop to run on the given loop. | def enable_receiving(self, loop=None):
"""Schedules the receive loop to run on the given loop."""
self.receive_task = asyncio.ensure_future(self._receive_loop(), loop=loop)
def do_if_done(fut):
try:
fut.result()
except asyncio.CancelledError:
... |
Create a new AIOClient using Unix transport and BSER Codec connecting to the specified socket. If the specified socket is None then resolve the socket path automatically. | async def from_socket(cls, sockname: typing.Optional[str] = None) -> "AIOClient":
"""Create a new AIOClient using Unix transport and BSER Codec
connecting to the specified socket. If the specified socket is None,
then resolve the socket path automatically.
This method also schedules the... |
Receive the response to a request made to the Watchman service. | async def _receive_loop(self):
"""Receive the response to a request made to the Watchman service.
Note that when trying to receive a PDU from the Watchman service,
we might get a unilateral response to a subscription or log, so these
are processed and queued up for later retrieval. This... |
expand a win32 error code into a human readable message | def _win32_strerror(err):
""" expand a win32 error code into a human readable message """
# FormatMessage will allocate memory and assign it here
buf = ctypes.c_char_p()
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS,
... |
Windows 7 and earlier does not support GetOverlappedResultEx. The alternative is to use GetOverlappedResult and wait for read or write operation to complete. This is done be using CreateEvent and WaitForSingleObjectEx. CreateEvent WaitForSingleObjectEx and GetOverlappedResult are all part of Windows API since WindowsXP... | def _get_overlapped_result_ex_impl(pipe, olap, nbytes, millis, alertable):
""" Windows 7 and earlier does not support GetOverlappedResultEx. The
alternative is to use GetOverlappedResult and wait for read or write
operation to complete. This is done be using CreateEvent and
WaitForSingleObjectEx. Create... |
read a line Maintains its own buffer callers of the transport should not mix calls to readBytes and readLine. | def readLine(self):
""" read a line
Maintains its own buffer, callers of the transport should not mix
calls to readBytes and readLine.
"""
if self.buf is None:
self.buf = []
# Buffer may already have a line if we've received unilateral
# response(s) f... |
A read can block for an unbounded amount of time even if the kernel reports that the pipe handle is signalled so we need to always perform our reads asynchronously | def readBytes(self, size):
""" A read can block for an unbounded amount of time, even if the
kernel reports that the pipe handle is signalled, so we need to
always perform our reads asynchronously
"""
# try to satisfy the read from any buffered data
if self._iobu... |
establish transport connection | def _connect(self):
""" establish transport connection """
if self.recvConn:
if self.pid != os.getpid():
raise UseAfterFork(
"do not re-use a connection after fork; open a new client instead"
)
return
if self.sockpath ... |
receive the next PDU from the watchman service | def receive(self):
""" receive the next PDU from the watchman service
If the client has activated subscriptions or logs then
this PDU may be a unilateral PDU sent by the service to
inform the client of a log event or subscription change.
It may also simply be the response porti... |
Retrieve buffered log data | def getLog(self, remove=True):
""" Retrieve buffered log data
If remove is true the data will be removed from the buffer.
Otherwise it will be left in the buffer
"""
res = self.logs
if remove:
self.logs = []
return res |
Retrieve the data associated with a named subscription | def getSubscription(self, name, remove=True, root=None):
""" Retrieve the data associated with a named subscription
If remove is True (the default), the subscription data is removed
from the buffer. Otherwise the data is returned but left in
the buffer.
Returns None if there i... |
Send a query to the watchman service and return the response | def query(self, *args):
""" Send a query to the watchman service and return the response
This call will block until the response is returned.
If any unilateral responses are sent by the service in between
the request-response they will be buffered up in the client object
and NOT... |
Perform a server capability check | def capabilityCheck(self, optional=None, required=None):
""" Perform a server capability check """
res = self.query(
"version", {"optional": optional or [], "required": required or []}
)
if not self._hasprop(res, "capabilities"):
# Server doesn't support capabili... |
Read bytes from a file - like object | def _read_bytes(fp, buf):
"""Read bytes from a file-like object
@param fp: File-like object that implements read(int)
@type fp: file
@param buf: Buffer to read into
@type buf: bytes
@return: buf
"""
# Do the first read without resizing the input buffer
offset = 0
remaining = ... |
Deserialize a BSER - encoded blob. | def load(fp, mutable=True, value_encoding=None, value_errors=None):
"""Deserialize a BSER-encoded blob.
@param fp: The file-object to deserialize.
@type file:
@param mutable: Whether to return mutable results.
@type mutable: bool
@param value_encoding: Optional codec to use to decode values. ... |
Returns a path to the Docker context directory. See parse_args. py. | def make_docker_context(
get_steps_fn, github_project, opts=None, default_context_dir=None
):
'''
Returns a path to the Docker context directory. See parse_args.py.
Helper for making a command-line utility that writes your project's
Dockerfile and associated data into a (temporary) directory. Your... |
Log some system diagnostics before/ after setup for ease of debugging | def diagnostics(self):
'Log some system diagnostics before/after setup for ease of debugging'
# The builder's repr is not used in a command to avoid pointlessly
# invalidating Docker's build cache.
return self.step('Diagnostics', [
self.comment('Builder {0}'.format(repr(self)... |
This helper lets Facebook - internal CI special - cases FB projects | def fb_github_project_workdir(self, project_and_path, github_org='facebook'):
'This helper lets Facebook-internal CI special-cases FB projects'
project, path = project_and_path.split('/', 1)
return self.github_project_workdir(github_org + '/' + project, path) |
Functions that perform Gaussian process regression. cov_func has signature ( cov_params x x ) | def make_gp_funs(cov_func, num_cov_params):
"""Functions that perform Gaussian process regression.
cov_func has signature (cov_params, x, x')"""
def unpack_kernel_params(params):
mean = params[0]
cov_params = params[2:]
noise_scale = np.exp(params[1]) + 0.0001
ret... |
Flags that a function is linear wrt all args | def def_linear(fun):
"""Flags that a function is linear wrt all args"""
defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:
fun(*subval(args, argnum, g), **kwargs)) |
Project the velocity field to be approximately mass - conserving using a few iterations of Gauss - Seidel. | def project(vx, vy):
"""Project the velocity field to be approximately mass-conserving,
using a few iterations of Gauss-Seidel."""
p = np.zeros(vx.shape)
h = 1.0/vx.shape[0]
div = -0.5 * h * (np.roll(vx, -1, axis=0) - np.roll(vx, 1, axis=0)
+ np.roll(vy, -1, axis=1) - np.roll(... |
Wraps a function so that its gradient can be specified and its invocation can be recorded. For examples see the docs. | def primitive(f_raw):
"""
Wraps a function so that its gradient can be specified and its invocation
can be recorded. For examples, see the docs."""
@wraps(f_raw)
def f_wrapped(*args, **kwargs):
boxed_args, trace, node_constructor = find_top_boxed_args(args)
if boxed_args:
... |
Numerically stable log ( sum ( exp ( x ))) also defined in scipy. misc | def logsumexp(x):
"""Numerically stable log(sum(exp(x))), also defined in scipy.misc"""
max_x = np.max(x)
return max_x + np.log(np.sum(np.exp(x - max_x))) |
Build a ( weights biases ) tuples for all layers. | def init_net_params(scale, layer_sizes, rs=npr.RandomState(0)):
"""Build a (weights, biases) tuples for all layers."""
return [(scale * rs.randn(m, n), # weight matrix
scale * rs.randn(n)) # bias vector
for m, n in zip(layer_sizes[:-1], layer_sizes[1:])] |
Loads a text file and turns each line into an encoded sequence. | def build_dataset(filename, max_lines=-1):
"""Loads a text file, and turns each line into an encoded sequence."""
encodings = dict(list(map(reversed, enumerate(string.printable))))
digitize = lambda char: encodings[char] if char in encodings else len(encodings)
encode_line = lambda line: np.array(list(m... |
Project the velocity field to be approximately mass - conserving using a few iterations of Gauss - Seidel. | def project(vx, vy, occlusion):
"""Project the velocity field to be approximately mass-conserving,
using a few iterations of Gauss-Seidel."""
p = np.zeros(vx.shape)
div = -0.5 * (np.roll(vx, -1, axis=1) - np.roll(vx, 1, axis=1)
+ np.roll(vy, -1, axis=0) - np.roll(vy, 1, axis=0))
d... |
Move field f according to x and y velocities ( u and v ) using an implicit Euler integrator. | def advect(f, vx, vy):
"""Move field f according to x and y velocities (u and v)
using an implicit Euler integrator."""
rows, cols = f.shape
cell_xs, cell_ys = np.meshgrid(np.arange(cols), np.arange(rows))
center_xs = (cell_xs - vx).ravel()
center_ys = (cell_ys - vy).ravel()
# Compute in... |
Takes an optimizer that operates on flat 1D numpy arrays and returns a wrapped version that handles trees of nested containers ( lists/ tuples/ dicts ) with arrays/ scalars at the leaves. | def unflatten_optimizer(optimize):
"""Takes an optimizer that operates on flat 1D numpy arrays and returns a
wrapped version that handles trees of nested containers (lists/tuples/dicts)
with arrays/scalars at the leaves."""
@wraps(optimize)
def _optimize(grad, x0, callback=None, *args, **kwargs):
... |
Stochastic gradient descent with momentum. grad () must have signature grad ( x i ) where i is the iteration number. | def sgd(grad, x, callback=None, num_iters=200, step_size=0.1, mass=0.9):
"""Stochastic gradient descent with momentum.
grad() must have signature grad(x, i), where i is the iteration number."""
velocity = np.zeros(len(x))
for i in range(num_iters):
g = grad(x, i)
if callback: callback(x,... |
Root mean squared prop: See Adagrad paper for details. | def rmsprop(grad, x, callback=None, num_iters=100,
step_size=0.1, gamma=0.9, eps=10**-8):
"""Root mean squared prop: See Adagrad paper for details."""
avg_sq_grad = np.ones(len(x))
for i in range(num_iters):
g = grad(x, i)
if callback: callback(x, i, g)
avg_sq_grad = avg_... |
Adam as described in http:// arxiv. org/ pdf/ 1412. 6980. pdf. It s basically RMSprop with momentum and some correction terms. | def adam(grad, x, callback=None, num_iters=100,
step_size=0.001, b1=0.9, b2=0.999, eps=10**-8):
"""Adam as described in http://arxiv.org/pdf/1412.6980.pdf.
It's basically RMSprop with momentum and some correction terms."""
m = np.zeros(len(x))
v = np.zeros(len(x))
for i in range(num_iters):... |
These functions implement independent component analysis. | def make_ica_funs(observed_dimension, latent_dimension):
"""These functions implement independent component analysis.
The model is:
latents are drawn i.i.d. for each data point from a product of student-ts.
weights are the same across all datapoints.
each data = latents * weghts + noise."""
de... |
Implements a deep neural network for classification. params is a list of ( weights bias ) tuples. inputs is an ( N x D ) matrix. returns normalized class log - probabilities. | def neural_net_predict(params, inputs):
"""Implements a deep neural network for classification.
params is a list of (weights, bias) tuples.
inputs is an (N x D) matrix.
returns normalized class log-probabilities."""
for W, b in params:
outputs = np.dot(inputs, W) + b
inputs ... |
Computes l2 norm of params by flattening them into a vector. | def l2_norm(params):
"""Computes l2 norm of params by flattening them into a vector."""
flattened, _ = flatten(params)
return np.dot(flattened, flattened) |
These functions implement a standard multi - layer perceptron vectorized over both training examples and weight samples. | def make_nn_funs(layer_sizes, L2_reg, noise_variance, nonlinearity=np.tanh):
"""These functions implement a standard multi-layer perceptron,
vectorized over both training examples and weight samples."""
shapes = list(zip(layer_sizes[:-1], layer_sizes[1:]))
num_weights = sum((m+1)*n for m, n in shapes)
... |
Params is a list of ( weights bias ) tuples. inputs is an ( N x D ) matrix. | def neural_net_predict(params, inputs):
"""Params is a list of (weights, bias) tuples.
inputs is an (N x D) matrix."""
inpW, inpb = params[0]
inputs = relu(np.dot(inputs, inpW) + inpb)
for W, b in params[1:-1]:
outputs = batch_normalize(np.dot(inputs, W) + b)
inputs = relu(outputs... |
Adam modified to do minimiax optimization for instance to help with training generative adversarial networks. | def adam_minimax(grad_both, init_params_max, init_params_min, callback=None, num_iters=100,
step_size_max=0.001, step_size_min=0.001, b1=0.9, b2=0.999, eps=10**-8):
"""Adam modified to do minimiax optimization, for instance to help with
training generative adversarial networks."""
x_max, unflatten... |
Returns a function that computes the sum of each column of the Jacobian of fun in one pass. If the Jacobian is diagonal then this is the diagonal of the Jacobian. | def elementwise_grad(fun, x):
"""
Returns a function that computes the sum of each column of the Jacobian of
`fun`, in one pass. If the Jacobian is diagonal, then this is the diagonal
of the Jacobian.
"""
vjp, ans = _make_vjp(fun, x)
if vspace(ans).iscomplex:
raise TypeError("Element... |
Returns a function which computes the Jacobian of fun with respect to positional argument number argnum which must be a scalar or array. Unlike grad it is not restricted to scalar - output functions but also it cannot take derivatives with respect to some argument types ( like lists or dicts ). If the input to fun has ... | def jacobian(fun, x):
"""
Returns a function which computes the Jacobian of `fun` with respect to
positional argument number `argnum`, which must be a scalar or array. Unlike
`grad` it is not restricted to scalar-output functions, but also it cannot
take derivatives with respect to some argument typ... |
Takes gradients with respect to a named argument. Doesn t work on * args or ** kwargs. | def grad_named(fun, argname):
'''Takes gradients with respect to a named argument.
Doesn't work on *args or **kwargs.'''
arg_index = getargspec(fun).args.index(argname)
return grad(fun, arg_index) |
Builds a function that returns the exact Hessian - tensor product. The returned function has arguments ( * args tensor ** kwargs ) and for vectors takes roughly 4x as long to evaluate as the original function. | def hessian_tensor_product(fun, argnum=0):
"""Builds a function that returns the exact Hessian-tensor product.
The returned function has arguments (*args, tensor, **kwargs), and for
vectors takes roughly 4x as long to evaluate as the original function."""
fun_grad = grad(fun, argnum)
def vector_dot_... |
Builds a function that returns the exact tensor - Jacobian product that is the Jacobian matrix left - multiplied by tensor. The returned function has arguments ( * args tensor ** kwargs ). | def tensor_jacobian_product(fun, argnum=0):
"""Builds a function that returns the exact tensor-Jacobian product, that
is the Jacobian matrix left-multiplied by tensor. The returned function
has arguments (*args, tensor, **kwargs)."""
def vector_dot_fun(*args, **kwargs):
args, vector = args[:-1],... |
Builds a function for evaluating the Jacobian - vector product at a point. Roughly 1. 5x more FLOPs than forward - mode plus memory requirements that scale with the number of primitives applied in the evaluation of f as well as other overheads. See j - towns. github. io/ 2017/ 06/ 12/ A - new - trick. html. | def make_jvp_reversemode(fun, x):
"""Builds a function for evaluating the Jacobian-vector product at a
point. Roughly 1.5x more FLOPs than forward-mode, plus memory requirements
that scale with the number of primitives applied in the evaluation of f, as
well as other overheads. See j-towns.github.io/201... |
Builds a function for evaluating generalized - Gauss - Newton - vector products at a point. Slightly more expensive than mixed - mode. | def make_ggnvp(f, g=lambda x: 1./2*np.sum(x**2, axis=-1), f_argnum=0):
"""Builds a function for evaluating generalized-Gauss-Newton-vector products
at a point. Slightly more expensive than mixed-mode."""
@unary_to_nary
def _make_ggnvp(f, x):
f_vjp, f_x = _make_vjp(f, x)
g_hvp, grad_g_x =... |
Returns a function that returns both value and gradient. Suitable for use in scipy. optimize | def value_and_grad(fun, x):
"""Returns a function that returns both value and gradient. Suitable for use
in scipy.optimize"""
vjp, ans = _make_vjp(fun, x)
if not vspace(ans).size == 1:
raise TypeError("value_and_grad only applies to real scalar-output "
"functions. Try ja... |
Builds a function that returns the gradient of the first output and the ( unmodified ) second output of a function that returns two outputs. | def grad_and_aux(fun, x):
"""Builds a function that returns the gradient of the first output and the
(unmodified) second output of a function that returns two outputs."""
vjp, (ans, aux) = _make_vjp(lambda x: atuple(fun(x)), x)
return vjp((vspace(ans).ones(), vspace(aux).zeros())), aux |
Takes gradients wrt all arguments simultaneously | def multigrad_dict(fun):
"Takes gradients wrt all arguments simultaneously,"
"returns a dict mapping 'argname' to 'gradval'"
import funcsigs
sig = funcsigs.signature(fun)
def select(preds, lst):
idx = lambda item: next(
(i for i, pred in enumerate(preds) if pred(item)), len(pre... |
Returns a checkpointed version of fun where intermediate values computed during the forward pass of fun are discarded and then recomputed for the backward pass. Useful to save memory effectively trading off time and memory. See e. g. arxiv. org/ abs/ 1604. 06174. | def checkpoint(fun):
"""Returns a checkpointed version of `fun`, where intermediate values
computed during the forward pass of `fun` are discarded and then recomputed
for the backward pass. Useful to save memory, effectively trading off time
and memory. See e.g. arxiv.org/abs/1604.06174.
"""
def... |
Converts an ASCII string to a one - of - k encoding. | def string_to_one_hot(string, maxchar):
"""Converts an ASCII string to a one-of-k encoding."""
ascii = np.array([ord(c) for c in string]).T
return np.array(ascii[:,None] == np.arange(maxchar)[None, :], dtype=int) |
Loads a text file and turns each line into an encoded sequence. | def build_dataset(filename, sequence_length, alphabet_size, max_lines=-1):
"""Loads a text file, and turns each line into an encoded sequence."""
with open(filename) as f:
content = f.readlines()
content = content[:max_lines]
content = [line for line in content if len(line) > 2] # Remove blank... |
Build a list of ( weights biases ) tuples one for each layer. | def init_nn_params(scale, layer_sizes, rs=npr.RandomState(0)):
"""Build a list of (weights, biases) tuples, one for each layer."""
return [(rs.randn(insize, outsize) * scale, # weight matrix
rs.randn(outsize) * scale) # bias vector
for insize, outsize in zip(layer_sizes[:-1]... |
make the compression factors and compute the normalization for irfft and rfft. | def make_rfft_factors(axes, resshape, facshape, normshape, norm):
""" make the compression factors and compute the normalization
for irfft and rfft.
"""
N = 1.0
for n in normshape: N = N * n
# inplace modification is fine because we produce a constant
# which doesn't go into autograd.
... |
Provides a stochastic estimate of the variational lower bound for any variational family and model density. | def variational_lower_bound(params, t, logprob, sampler, log_density,
num_samples, rs):
"""Provides a stochastic estimate of the variational lower bound,
for any variational family and model density."""
samples = sampler(params, num_samples, rs)
log_qs = log_density(params... |
Gradient for eigenvalues and vectors of a symmetric matrix. | def grad_eigh(ans, x, UPLO='L'):
"""Gradient for eigenvalues and vectors of a symmetric matrix."""
N = x.shape[-1]
w, v = ans # Eigenvalues, eigenvectors.
def vjp(g):
wg, vg = g # Gradient w.r.t. eigenvalues, eigenvectors.
w_repeated = anp.repeat(w[..., anp.newaxis]... |
Implements http:// arxiv. org/ abs/ 1401. 0118 and uses the local reparameterization trick from http:// arxiv. org/ abs/ 1506. 02557 | def black_box_variational_inference(logprob, D, num_samples):
"""Implements http://arxiv.org/abs/1401.0118, and uses the
local reparameterization trick from http://arxiv.org/abs/1506.02557"""
def unpack_params(params):
# Variational dist is a diagonal Gaussian.
mean, log_std = params[:D], p... |
Returns the array g repeated along axis to fit vector space vs. Also returns the number of repetitions of the array. | def repeat_to_match_shape(g, shape, dtype, axis, keepdims):
"""Returns the array g repeated along axis to fit vector space vs.
Also returns the number of repetitions of the array."""
if shape == ():
return g, 1
axis = list(axis) if isinstance(axis, tuple) else axis
new_shape = onp.array(sha... |
Images should be a ( N_images x pixels ) matrix. | def plot_images(images, ax, ims_per_row=5, padding=5, digit_dimensions=(28, 28),
cmap=matplotlib.cm.binary, vmin=None, vmax=None):
"""Images should be a (N_images x pixels) matrix."""
N_images = images.shape[0]
N_rows = (N_images - 1) // ims_per_row + 1
pad_value = np.min(images.ravel())... |
Based on code by Ryan P. Adams. | def make_pinwheel(radial_std, tangential_std, num_classes, num_per_class, rate,
rs=npr.RandomState(0)):
"""Based on code by Ryan P. Adams."""
rads = np.linspace(0, 2*np.pi, num_classes, endpoint=False)
features = rs.randn(num_classes*num_per_class, 2) \
* np.array([radial_std, tan... |
Borrowed from http:// blog. dkbza. org/ 2007/ 05/ scanning - data - for - entropy - anomalies. html | def shannon_entropy(data, iterator):
"""
Borrowed from http://blog.dkbza.org/2007/05/scanning-data-for-entropy-anomalies.html
"""
if not data:
return 0
entropy = 0
for x in iterator:
p_x = float(data.count(x))/len(data)
if p_x > 0:
entropy += - p_x*math.log(p_... |
Serialize a list of subtitles according to the SRT format with optional time padding. | def srt_formatter(subtitles, padding_before=0, padding_after=0):
"""
Serialize a list of subtitles according to the SRT format, with optional time padding.
"""
sub_rip_file = pysrt.SubRipFile()
for i, ((start, end), text) in enumerate(subtitles, start=1):
item = pysrt.SubRipItem()
it... |
Serialize a list of subtitles according to the VTT format with optional time padding. | def vtt_formatter(subtitles, padding_before=0, padding_after=0):
"""
Serialize a list of subtitles according to the VTT format, with optional time padding.
"""
text = srt_formatter(subtitles, padding_before, padding_after)
text = 'WEBVTT\n\n' + text.replace(',', '.')
return text |
Serialize a list of subtitles as a JSON blob. | def json_formatter(subtitles):
"""
Serialize a list of subtitles as a JSON blob.
"""
subtitle_dicts = [
{
'start': start,
'end': end,
'content': text,
}
for ((start, end), text)
in subtitles
]
return json.dumps(subtitle_dicts) |
Calculate the given percentile of arr. | def percentile(arr, percent):
"""
Calculate the given percentile of arr.
"""
arr = sorted(arr)
index = (len(arr) - 1) * percent
floor = math.floor(index)
ceil = math.ceil(index)
if floor == ceil:
return arr[int(index)]
low_value = arr[int(floor)] * (ceil - index)
high_val... |
Extract audio from an input file to a temporary WAV file. | def extract_audio(filename, channels=1, rate=16000):
"""
Extract audio from an input file to a temporary WAV file.
"""
temp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
if not os.path.isfile(filename):
print("The given file does not exist: {}".format(filename))
raise Ex... |
Perform voice activity detection on a given audio file. | def find_speech_regions(filename, frame_width=4096, min_region_size=0.5, max_region_size=6): # pylint: disable=too-many-locals
"""
Perform voice activity detection on a given audio file.
"""
reader = wave.open(filename)
sample_width = reader.getsampwidth()
rate = reader.getframerate()
n_chan... |
Given an input audio/ video file generate subtitles in the specified language and format. | def generate_subtitles( # pylint: disable=too-many-locals,too-many-arguments
source_path,
output=None,
concurrency=DEFAULT_CONCURRENCY,
src_language=DEFAULT_SRC_LANGUAGE,
dst_language=DEFAULT_DST_LANGUAGE,
subtitle_file_format=DEFAULT_SUBTITLE_FORMAT,
api_key=None... |
Check that the CLI arguments passed to autosub are valid. | def validate(args):
"""
Check that the CLI arguments passed to autosub are valid.
"""
if args.format not in FORMATTERS:
print(
"Subtitle format not supported. "
"Run with --list-formats to see all supported formats."
)
return False
if args.src_languag... |
Run autosub as a command - line program. | def main():
"""
Run autosub as a command-line program.
"""
parser = argparse.ArgumentParser()
parser.add_argument('source_path', help="Path to the video or audio file to subtitle",
nargs='?')
parser.add_argument('-C', '--concurrency', help="Number of concurrent API reques... |
Plugin interface to pyls linter. | def lint(cls, document, is_saved, flags=''):
"""Plugin interface to pyls linter.
Args:
document: The document to be linted.
is_saved: Whether or not the file has been saved to disk.
flags: Additional flags to pass to pylint. Not exposed to
pyls_lint, ... |
Ensure builtins appear at the bottom. Description is of format <type >: <module >. <item > | def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
# If its 'hidden', put it next last
prefix = 'z{}' if definition.name.startswith('_') else 'a{}'
return prefix.format(definition.name) |
Settings are constructed from a few sources: | def settings(self, document_path=None):
"""Settings are constructed from a few sources:
1. User settings, found in user's home directory
2. Plugin settings, reported by PyLS plugins
3. LSP settings, given to us from didChangeConfiguration
4. Project settings, fou... |
Recursively merge the given settings into the current settings. | def update(self, settings):
"""Recursively merge the given settings into the current settings."""
self.settings.cache_clear()
self._settings = settings
log.info("Updated settings to %s", self._settings)
self._update_disabled_plugins() |
Return a managed document if - present else create one pointing at disk. | def get_document(self, doc_uri):
"""Return a managed document if-present, else create one pointing at disk.
See https://github.com/Microsoft/language-server-protocol/issues/177
"""
return self._docs.get(doc_uri) or self._create_document(doc_uri) |
Return the source roots for the given document. | def source_roots(self, document_path):
"""Return the source roots for the given document."""
files = _utils.find_parents(self._root_path, document_path, ['setup.py']) or []
return [os.path.dirname(setup_py) for setup_py in files] |
Apply a change to the document. | def apply_change(self, change):
"""Apply a change to the document."""
text = change['text']
change_range = change.get('range')
if not change_range:
# The whole file has changed
self._source = text
return
start_line = change_range['start']['li... |
Get the word under the cursor returning the start and end positions. | def word_at_position(self, position):
"""Get the word under the cursor returning the start and end positions."""
if position['line'] >= len(self.lines):
return ''
line = self.lines[position['line']]
i = position['character']
# Split word in two
start = line[:... |
Debounce calls to this function until interval_s seconds have passed. | def debounce(interval_s, keyed_by=None):
"""Debounce calls to this function until interval_s seconds have passed."""
def wrapper(func):
timers = {}
lock = threading.Lock()
@functools.wraps(func)
def debounced(*args, **kwargs):
call_args = inspect.getcallargs(func, *a... |
Find files matching the given names relative to the given path. | def find_parents(root, path, names):
"""Find files matching the given names relative to the given path.
Args:
path (str): The file path to start searching up from.
names (List[str]): The file/directory names to look for.
root (str): The directory at which to stop recursing upwards.
... |
Recursively merge dictionary b into dictionary a. | def merge_dicts(dict_a, dict_b):
"""Recursively merge dictionary b into dictionary a.
If override_nones is True, then
"""
def _merge_dicts_(a, b):
for key in set(a.keys()).union(b.keys()):
if key in a and key in b:
if isinstance(a[key], dict) and isinstance(b[key], d... |
Python doc strings come in a number of formats but LSP wants markdown. | def format_docstring(contents):
"""Python doc strings come in a number of formats, but LSP wants markdown.
Until we can find a fast enough way of discovering and parsing each format,
we can do a little better by at least preserving indentation.
"""
contents = contents.replace('\t', u'\u00A0' * 4)
... |
Parse and decode the parts of a URI. | def urlparse(uri):
"""Parse and decode the parts of a URI."""
scheme, netloc, path, params, query, fragment = parse.urlparse(uri)
return (
parse.unquote(scheme),
parse.unquote(netloc),
parse.unquote(path),
parse.unquote(params),
parse.unquote(query),
parse.unq... |
Unparse and encode parts of a URI. | def urlunparse(parts):
"""Unparse and encode parts of a URI."""
scheme, netloc, path, params, query, fragment = parts
# Avoid encoding the windows drive letter colon
if RE_DRIVE_LETTER_PATH.match(path):
quoted_path = path[:3] + parse.quote(path[3:])
else:
quoted_path = parse.quote(p... |
Returns the filesystem path of the given URI. | def to_fs_path(uri):
"""Returns the filesystem path of the given URI.
Will handle UNC paths and normalize windows drive letters to lower-case. Also
uses the platform specific path separator. Will *not* validate the path for
invalid characters and semantics. Will *not* look at the scheme of this URI.
... |
Returns a URI for the given filesystem path. | def from_fs_path(path):
"""Returns a URI for the given filesystem path."""
scheme = 'file'
params, query, fragment = '', '', ''
path, netloc = _normalize_win_path(path)
return urlunparse((scheme, netloc, path, params, query, fragment)) |
Return a URI with the given part ( s ) replaced. | def uri_with(uri, scheme=None, netloc=None, path=None, params=None, query=None, fragment=None):
"""Return a URI with the given part(s) replaced.
Parts are decoded / encoded.
"""
old_scheme, old_netloc, old_path, old_params, old_query, old_fragment = urlparse(uri)
path, _netloc = _normalize_win_path... |
Get message like <filename >: <lineno >: <msg > | def flake(self, message):
""" Get message like <filename>:<lineno>: <msg> """
err_range = {
'start': {'line': message.lineno - 1, 'character': message.col},
'end': {'line': message.lineno - 1, 'character': len(self.lines[message.lineno - 1])},
}
severity = lsp.Di... |
Calls hook_name and returns a list of results from all registered handlers | def _hook(self, hook_name, doc_uri=None, **kwargs):
"""Calls hook_name and returns a list of results from all registered handlers"""
doc = self.workspace.get_document(doc_uri) if doc_uri else None
hook_handlers = self.config.plugin_manager.subset_hook_caller(hook_name, self.config.disabled_plugi... |
Ensure builtins appear at the bottom. Description is of format <type >: <module >. <item > | def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
if definition.name.startswith("_"):
# It's a 'hidden' func, put it next last
return 'z' + definition.name
elif definition.scope == 'builtin':
return 'y' ... |
Return the VSCode type | def _kind(d):
""" Return the VSCode type """
MAP = {
'none': lsp.CompletionItemKind.Value,
'type': lsp.CompletionItemKind.Class,
'tuple': lsp.CompletionItemKind.Class,
'dict': lsp.CompletionItemKind.Class,
'dictionary': lsp.CompletionItemKind.Class,
'function': ls... |
Get an option from a configparser with the given type. | def _get_opt(config, key, option, opt_type):
"""Get an option from a configparser with the given type."""
for opt_key in [option, option.replace('-', '_')]:
if not config.has_option(key, opt_key):
continue
if opt_type == bool:
return config.getbool(key, opt_key)
... |
Set the value in the dictionary at the given path if the value is not None. | def _set_opt(config_dict, path, value):
"""Set the value in the dictionary at the given path if the value is not None."""
if value is None:
return
if '.' not in path:
config_dict[path] = value
return
key, rest = path.split(".", 1)
if key not in config_dict:
config_d... |
Parse the config with the given options. | def parse_config(config, key, options):
"""Parse the config with the given options."""
conf = {}
for source, destination, opt_type in options:
opt_value = _get_opt(config, key, source, opt_type)
if opt_value is not None:
_set_opt(conf, destination, opt_val... |
Construct binary stdio streams ( not text mode ). | def _binary_stdio():
"""Construct binary stdio streams (not text mode).
This seems to be different for Window/Unix Python2/3, so going by:
https://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin
"""
PY3K = sys.version_info >= (3, 0)
if PY3K:
# pylint: disable=no-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.