_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q256000 | _coeff4 | validation | def _coeff4(N, a0, a1, a2, a3):
"""a common internal function to some window functions with 4 coeffs
For the blackmna harris for instance, the results are identical to octave if N is odd
but not for even values...if n =0 whatever N is, the w(0) must be equal to a0-a1+a2-a3, which
is the case here, but not in octave..."""
if N == | python | {
"resource": ""
} |
q256001 | window_nuttall | validation | def window_nuttall(N):
r"""Nuttall tapering window
:param N: window length
.. math:: w(n) = a_0 - a_1 \cos\left(\frac{2\pi n}{N-1}\right)+ a_2 \cos\left(\frac{4\pi n}{N-1}\right)- a_3 \cos\left(\frac{6\pi n}{N-1}\right)
with :math:`a_0 = 0.355768`, :math:`a_1 = 0.487396`, :math:`a_2=0.144232` and :math:`a_3=0.012604`
.. plot::
:width: 80%
:include-source:
| python | {
"resource": ""
} |
q256002 | window_blackman_nuttall | validation | def window_blackman_nuttall(N):
r"""Blackman Nuttall window
returns a minimum, 4-term Blackman-Harris window. The window is minimum in the sense that its maximum sidelobes are minimized.
The coefficients for this window differ from the Blackman-Harris window coefficients and produce slightly lower sidelobes.
:param N: window length
.. math:: w(n) = a_0 - a_1 \cos\left(\frac{2\pi n}{N-1}\right)+ a_2 \cos\left(\frac{4\pi n}{N-1}\right)- a_3 \cos\left(\frac{6\pi n}{N-1}\right)
with :math:`a_0 = 0.3635819`, :math:`a_1 = 0.4891775`, :math:`a_2=0.1365995` and :math:`0_3=.0106411`
.. plot::
| python | {
"resource": ""
} |
q256003 | window_blackman_harris | validation | def window_blackman_harris(N):
r"""Blackman Harris window
:param N: window length
.. math:: w(n) = a_0 - a_1 \cos\left(\frac{2\pi n}{N-1}\right)+ a_2 \cos\left(\frac{4\pi n}{N-1}\right)- a_3 \cos\left(\frac{6\pi n}{N-1}\right)
=============== =========
coeff value
=============== =========
:math:`a_0` 0.35875
:math:`a_1` 0.48829
:math:`a_2` 0.14128
:math:`a_3` 0.01168
=============== =========
.. plot::
:width: 80%
:include-source:
| python | {
"resource": ""
} |
q256004 | window_bohman | validation | def window_bohman(N):
r"""Bohman tapering window
:param N: window length
.. math:: w(n) = (1-|x|) \cos (\pi |x|) + \frac{1}{\pi} \sin(\pi |x|)
where x is a length N vector of linearly spaced values between
-1 and 1.
.. plot::
:width: 80%
:include-source:
| python | {
"resource": ""
} |
q256005 | window_flattop | validation | def window_flattop(N, mode='symmetric',precision=None):
r"""Flat-top tapering window
Returns symmetric or periodic flat top window.
:param N: window length
:param mode: way the data are normalised. If mode is *symmetric*, then
divide n by N-1. IF mode is *periodic*, divide by N,
to be consistent with octave code.
When using windows for filter design, the *symmetric* mode
should be used (default). When using windows for spectral analysis, the *periodic*
mode should be used. The mathematical form of the flat-top window in the symmetric
case is:
.. math:: w(n) = a_0
- a_1 \cos\left(\frac{2\pi n}{N-1}\right)
+ a_2 \cos\left(\frac{4\pi n}{N-1}\right)
- a_3 \cos\left(\frac{6\pi n}{N-1}\right)
+ a_4 \cos\left(\frac{8\pi n}{N-1}\right)
===== =============
coeff value
===== =============
a0 0.21557895
a1 0.41663158
a2 0.277263158
a3 0.083578947
a4 0.006947368
===== =============
.. plot::
:width: 80%
:include-source:
from spectrum import window_visu
window_visu(64, 'bohman')
| python | {
"resource": ""
} |
q256006 | window_taylor | validation | def window_taylor(N, nbar=4, sll=-30):
"""Taylor tapering window
Taylor windows allows you to make tradeoffs between the
mainlobe width and sidelobe level (sll).
Implemented as described by Carrara, Goodman, and Majewski
in 'Spotlight Synthetic Aperture Radar: Signal Processing Algorithms'
Pages 512-513
:param N: window length
:param float nbar:
:param float sll:
The default values gives equal height
sidelobes (nbar) and maximum sidelobe level (sll).
.. warning:: not implemented
.. seealso:: :func:`create_window`, :class:`Window`
"""
B = 10**(-sll/20)
A = log(B + sqrt(B**2 - 1))/pi
s2 = nbar**2 / (A**2 + (nbar - 0.5)**2)
ma = arange(1,nbar)
def calc_Fm(m):
| python | {
"resource": ""
} |
q256007 | window_riesz | validation | def window_riesz(N):
r"""Riesz tapering window
:param N: window length
.. math:: w(n) = 1 - \left| \frac{n}{N/2} \right|^2
with :math:`-N/2 \leq n \leq N/2`.
.. plot::
:width: 80%
:include-source:
from spectrum import window_visu
| python | {
"resource": ""
} |
q256008 | window_riemann | validation | def window_riemann(N):
r"""Riemann tapering window
:param int N: window length
.. math:: w(n) = 1 - \left| \frac{n}{N/2} \right|^2
with :math:`-N/2 \leq n \leq N/2`.
.. plot::
:width: 80%
:include-source:
from spectrum import window_visu
| python | {
"resource": ""
} |
q256009 | window_poisson | validation | def window_poisson(N, alpha=2):
r"""Poisson tapering window
:param int N: window length
.. math:: w(n) = \exp^{-\alpha \frac{|n|}{N/2} }
with :math:`-N/2 \leq n \leq N/2`.
.. plot::
:width: 80%
:include-source:
from spectrum import window_visu
window_visu(64, 'poisson')
| python | {
"resource": ""
} |
q256010 | window_poisson_hanning | validation | def window_poisson_hanning(N, alpha=2):
r"""Hann-Poisson tapering window
This window is constructed as the product of the Hanning and Poisson
windows. The parameter **alpha** is the Poisson parameter.
:param int N: window length
:param float alpha: parameter of the poisson window
.. plot::
:width: 80%
:include-source:
| python | {
"resource": ""
} |
q256011 | window_cauchy | validation | def window_cauchy(N, alpha=3):
r"""Cauchy tapering window
:param int N: window length
:param float alpha: parameter of the poisson window
.. math:: w(n) = \frac{1}{1+\left(\frac{\alpha*n}{N/2}\right)**2}
.. plot::
:width: 80%
:include-source:
from spectrum import window_visu
window_visu(64, 'cauchy', alpha=3) | python | {
"resource": ""
} |
q256012 | Window.compute_response | validation | def compute_response(self, **kargs):
"""Compute the window data frequency response
:param norm: True by default. normalised the frequency data.
:param int NFFT: total length of the final data sets( 2048 by default.
if less than data length, then NFFT is set to the data length*2).
The response is stored in :attr:`response`.
.. note:: Units are dB (20 log10) since we plot the frequency response)
"""
from numpy.fft import fft, fftshift
norm = kargs.get('norm', self.norm)
# do some padding. Default is max(2048, data.len*2)
NFFT = kargs.get('NFFT', 2048)
if NFFT < len(self.data):
| python | {
"resource": ""
} |
q256013 | Window.plot_frequencies | validation | def plot_frequencies(self, mindB=None, maxdB=None, norm=True):
"""Plot the window in the frequency domain
:param mindB: change the default lower y bound
:param maxdB: change the default upper lower bound
:param bool norm: if True, normalise the frequency response.
.. plot::
:width: 80%
:include-source:
from spectrum.window import Window
w = Window(64, name='hamming')
w.plot_frequencies()
"""
from pylab import plot, title, xlim, grid, ylim, xlabel, ylabel
# recompute the response
self.compute_response(norm=norm)
plot(self.frequencies, | python | {
"resource": ""
} |
q256014 | Window.plot_window | validation | def plot_window(self):
"""Plot the window in the time domain
.. plot::
:width: 80%
:include-source:
from spectrum.window import Window
w = Window(64, name='hamming')
| python | {
"resource": ""
} |
q256015 | Window.plot_time_freq | validation | def plot_time_freq(self, mindB=-100, maxdB=None, norm=True,
yaxis_label_position="right"):
"""Plotting method to plot both time and frequency domain results.
See :meth:`plot_frequencies` for the optional arguments.
.. plot::
:width: 80%
:include-source:
from spectrum.window import Window
w = Window(64, name='hamming')
w.plot_time_freq()
"""
from pylab import subplot, gca
subplot(1, 2, 1)
| python | {
"resource": ""
} |
q256016 | TOEPLITZ | validation | def TOEPLITZ(T0, TC, TR, Z):
"""solve the general toeplitz linear equations
Solve TX=Z
:param T0: zero lag value
:param TC: r1 to rN
:param TR: r1 to rN
returns X
requires 3M^2+M operations instead of M^3 with gaussian elimination
.. warning:: not used right now
"""
assert len(TC)>0
assert len(TC)==len(TR)
M = len(TC)
X = numpy.zeros(M+1,dtype=complex)
A = numpy.zeros(M,dtype=complex)
B = numpy.zeros(M,dtype=complex)
P = T0
if P == 0: raise ValueError("P must be different from zero")
if P == 0: raise ValueError("P must be different from zero")
X[0] = Z[0]/T0
for k in range(0, M):
save1 = TC[k]
save2 = TR[k]
beta = X[0]*TC[k]
if k == 0:
temp1 = -save1 / P
temp2 = -save2 / P
else:
for j in range(0, k):
save1 = save1 + A[j] * TC[k-j-1]
save2 = | python | {
"resource": ""
} |
q256017 | HERMTOEP | validation | def HERMTOEP(T0, T, Z):
"""solve Tx=Z by a variation of Levinson algorithm where T
is a complex hermitian toeplitz matrix
:param T0: zero lag value
:param T: r1 to rN
:return: X
used by eigen PSD method
"""
assert len(T)>0
M = len(T)
X = numpy.zeros(M+1,dtype=complex)
A = numpy.zeros(M,dtype=complex)
P = T0
if P == 0: raise ValueError("P must be different from zero")
X[0] = Z[0]/T0
for k in range(0, M):
save = T[k]
beta = X[0]*T[k]
if k == 0:
temp = -save / P
else:
for j in range(0, k):
save = save + A[j] * T[k-j-1]
beta = beta + X[j+1] * T[k-j-1]
temp = -save / P
P = P * (1. - (temp.real**2+temp.imag**2))
if P <= 0:
raise ValueError("singular matrix")
A[k] = temp
alpha = (Z[k+1]-beta)/P
| python | {
"resource": ""
} |
q256018 | get_short_module_name | validation | def get_short_module_name(module_name, obj_name):
""" Get the shortest possible module name """
parts = module_name.split('.')
short_name = module_name
for i in range(len(parts) - 1, 0, -1):
short_name = '.'.join(parts[:i])
try:
exec('from | python | {
"resource": ""
} |
q256019 | identify_names | validation | def identify_names(code):
"""Builds a codeobj summary by identifying and resolving used names
>>> code = '''
... from a.b import c
... import d as e
... print(c)
... e.HelloWorld().f.g
... '''
>>> for name, o in sorted(identify_names(code).items()):
... print(name, o['name'], o['module'], o['module_short'])
c c a.b a.b
e.HelloWorld HelloWorld d d
"""
finder = NameFinder()
finder.visit(ast.parse(code))
example_code_obj = {}
for name, full_name in finder.get_mapping():
# name is as written in file (e.g. np.asarray)
# full_name includes resolved import path (e.g. numpy.asarray)
| python | {
"resource": ""
} |
q256020 | _thumbnail_div | validation | def _thumbnail_div(full_dir, fname, snippet, is_backref=False):
"""Generates RST to place a thumbnail in a gallery"""
thumb = os.path.join(full_dir, 'images', 'thumb',
| python | {
"resource": ""
} |
q256021 | modcovar | validation | def modcovar(x, order):
"""Simple and fast implementation of the covariance AR estimate
This code is 10 times faster than :func:`modcovar_marple` and more importantly
only 10 lines of code, compared to a 200 loc for :func:`modcovar_marple`
:param X: Array of complex data samples
:param int order: Order of linear prediction model
:return:
* P - Real linear prediction variance at order IP
* A - Array of complex linear prediction coefficients
.. plot::
:include-source:
:width: 80%
from spectrum import modcovar, marple_data, arma2psd, cshift
from pylab import log10, linspace, axis, plot
a, p = modcovar(marple_data, 15)
PSD = arma2psd(a)
PSD = cshift(PSD, len(PSD)/2) # switch positive and negative freq
plot(linspace(-0.5, 0.5, 4096), 10*log10(PSD/max(PSD)))
axis([-0.5,0.5,-60,0])
.. seealso:: :class:`~spectrum.modcovar.pmodcovar`
:validation: the AR parameters are the same as those | python | {
"resource": ""
} |
q256022 | aryule | validation | def aryule(X, order, norm='biased', allow_singularity=True):
r"""Compute AR coefficients using Yule-Walker method
:param X: Array of complex data values, X(1) to X(N)
:param int order: Order of autoregressive process to be fitted (integer)
:param str norm: Use a biased or unbiased correlation.
:param bool allow_singularity:
:return:
* AR coefficients (complex)
* variance of white noise (Real)
* reflection coefficients for use in lattice filter
.. rubric:: Description:
The Yule-Walker method returns the polynomial A corresponding to the
AR parametric signal model estimate of vector X using the Yule-Walker
(autocorrelation) method. The autocorrelation may be computed using a
**biased** or **unbiased** estimation. In practice, the biased estimate of
the autocorrelation is used for the unknown true autocorrelation. Indeed,
an unbiased estimate may result in nonpositive-definite autocorrelation
matrix.
So, a biased estimate leads to a stable AR filter.
The following matrix form represents the Yule-Walker equations. The are
solved by means of the Levinson-Durbin recursion:
.. math::
\left( \begin{array}{cccc}
r(1) & r(2)^* & \dots & r(n)^*\\
r(2) & r(1)^* & \dots & r(n-1)^*\\
\dots & \dots & \dots & \dots\\
r(n) & \dots & r(2) & r(1) \end{array} \right)
\left( \begin{array}{cccc}
a(2)\\
a(3) \\
\dots \\
a(n+1) \end{array} \right)
=
\left( \begin{array}{cccc}
-r(2)\\
-r(3) \\
\dots \\
-r(n+1) \end{array} \right)
The outputs consists of the AR coefficients, the estimated variance of the
white noise process, and the reflection coefficients. These outputs can be
used to estimate the optimal order by using :mod:`~spectrum.criteria`.
.. rubric:: Examples:
From a known AR process or order 4, we estimate those AR parameters using
the aryule function.
.. doctest::
>>> from scipy.signal import lfilter
>>> from spectrum import *
>>> from numpy.random import randn
>>> A =[1, -2.7607, 3.8106, -2.6535, 0.9238]
>>> noise = randn(1, 1024)
>>> y = lfilter([1], A, noise);
| python | {
"resource": ""
} |
q256023 | LEVINSON | validation | def LEVINSON(r, order=None, allow_singularity=False):
r"""Levinson-Durbin recursion.
Find the coefficients of a length(r)-1 order autoregressive linear process
:param r: autocorrelation sequence of length N + 1 (first element being the zero-lag autocorrelation)
:param order: requested order of the autoregressive coefficients. default is N.
:param allow_singularity: false by default. Other implementations may be True (e.g., octave)
:return:
* the `N+1` autoregressive coefficients :math:`A=(1, a_1...a_N)`
* the prediction errors
* the `N` reflections coefficients values
This algorithm solves the set of complex linear simultaneous equations
using Levinson algorithm.
.. math::
\bold{T}_M \left( \begin{array}{c} 1 \\ \bold{a}_M \end{array} \right) =
\left( \begin{array}{c} \rho_M \\ \bold{0}_M \end{array} \right)
where :math:`\bold{T}_M` is a Hermitian Toeplitz matrix with elements
:math:`T_0, T_1, \dots ,T_M`.
.. note:: Solving this equations by Gaussian elimination would
require :math:`M^3` operations whereas the levinson algorithm
requires :math:`M^2+M` additions and :math:`M^2+M` multiplications.
This is equivalent to solve the following symmetric Toeplitz system of
linear equations
.. math::
\left( \begin{array}{cccc}
r_1 & r_2^* & \dots & r_{n}^*\\
r_2 & r_1^* & \dots & r_{n-1}^*\\
\dots & \dots & \dots & \dots\\
r_n & \dots & r_2 & r_1 \end{array} \right)
\left( \begin{array}{cccc}
a_2\\
a_3 \\
\dots \\
a_{N+1} \end{array} \right)
=
\left( \begin{array}{cccc}
-r_2\\
-r_3 \\
\dots \\
-r_{N+1} \end{array} \right)
where :math:`r = (r_1 ... r_{N+1})` is the input autocorrelation vector, and
:math:`r_i^*` denotes the complex conjugate of :math:`r_i`. The input r is typically
a vector of autocorrelation coefficients where lag 0 is the first
element :math:`r_1`.
.. doctest::
>>> import numpy; from spectrum import LEVINSON
>>> T = numpy.array([3., -2+0.5j, .7-1j])
>>> a, e, k = LEVINSON(T)
"""
#from numpy import isrealobj
T0 = numpy.real(r[0])
T = r[1:]
M = len(T)
if order is None:
M = len(T)
else:
assert order <= M, 'order | python | {
"resource": ""
} |
q256024 | rlevinson | validation | def rlevinson(a, efinal):
"""computes the autocorrelation coefficients, R based
on the prediction polynomial A and the final prediction error Efinal,
using the stepdown algorithm.
Works for real or complex data
:param a:
:param efinal:
:return:
* R, the autocorrelation
* U prediction coefficient
* kr reflection coefficients
* e errors
A should be a minimum phase polynomial and A(1) is assumed to be unity.
:returns: (P+1) by (P+1) upper triangular matrix, U,
that holds the i'th order prediction polynomials
Ai, i=1:P, where P is the order of the input
polynomial, A.
[ 1 a1(1)* a2(2)* ..... aP(P) * ]
[ 0 1 a2(1)* ..... aP(P-1)* ]
U = [ .................................]
[ 0 0 0 ..... 1 ]
from which the i'th order prediction polynomial can be extracted
using Ai=U(i+1:-1:1,i+1)'. The first row of U contains the
conjugates of the reflection coefficients, and the K's may be
extracted using, K=conj(U(1,2:end)).
.. todo:: remove the conjugate when data is real data, clean up the code
test and doc.
"""
a = numpy.array(a)
realdata = numpy.isrealobj(a)
assert a[0] == 1, 'First coefficient of the prediction polynomial must be unity'
p = len(a)
if p < 2:
raise ValueError('Polynomial should have at least two coefficients')
if realdata == True:
U = numpy.zeros((p, p)) # This matrix will have the prediction
# polynomials of orders 1:p
else:
U = numpy.zeros((p, p), dtype=complex)
U[:, p-1] = numpy.conj(a[-1::-1]) # Prediction coefficients of order p
p = p -1
e = numpy.zeros(p)
# First we find the prediction coefficients of smaller orders and form the
# Matrix U
# Initialize the step down
e[-1] = efinal # Prediction error of order p
# Step down
for k in range(p-1, 0, -1):
[a, e[k-1]] = levdown(a, e[k])
U[:, k] = numpy.concatenate((numpy.conj(a[-1::-1].transpose()) ,
| python | {
"resource": ""
} |
q256025 | levdown | validation | def levdown(anxt, enxt=None):
"""One step backward Levinson recursion
:param anxt:
:param enxt:
:return:
* acur the P'th order prediction polynomial based on the P+1'th order prediction polynomial, anxt.
* ecur the the P'th order prediction error based on the P+1'th order prediction error, enxt.
.. * knxt the P+1'th order reflection coefficient.
"""
#% Some preliminaries first
#if nargout>=2 & nargin<2
# raise ValueError('Insufficient number of input arguments');
if anxt[0] != 1:
raise ValueError('At least one of the reflection coefficients is equal to one.')
anxt = anxt[1:] # Drop the leading 1, it is not needed
# in the | python | {
"resource": ""
} |
q256026 | levup | validation | def levup(acur, knxt, ecur=None):
"""LEVUP One step forward Levinson recursion
:param acur:
:param knxt:
:return:
* anxt the P+1'th order prediction polynomial based on the P'th order prediction polynomial, acur, and the
P+1'th order reflection coefficient, Knxt.
* enxt the P+1'th order prediction prediction error, based on the P'th order prediction error, ecur.
:References: P. Stoica R. Moses, Introduction to Spectral Analysis Prentice Hall, N.J., 1997, Chapter 3.
"""
if acur[0] != 1:
raise ValueError('At least one of the reflection coefficients is equal to one.')
acur = acur[1:] # Drop the leading 1, it is not needed
# Matrix formulation from Stoica | python | {
"resource": ""
} |
q256027 | arcovar | validation | def arcovar(x, order):
r"""Simple and fast implementation of the covariance AR estimate
This code is 10 times faster than :func:`arcovar_marple` and more importantly
only 10 lines of code, compared to a 200 loc for :func:`arcovar_marple`
:param array X: Array of complex data samples
:param int oder: Order of linear prediction model
:return:
* a - Array of complex forward linear prediction coefficients
* e - error
The covariance method fits a Pth order autoregressive (AR) model to the
input signal, which is assumed to be the output of
an AR system driven by white noise. This method minimizes the forward
prediction error in the least-squares sense. The output vector
contains the normalized estimate of the AR system parameters
The white noise input variance estimate is also returned.
If is the power spectral density of y(n), then:
.. math:: \frac{e}{\left| A(e^{jw}) \right|^2} = \frac{e}{\left| 1+\sum_{k-1}^P a(k)e^{-jwk}\right|^2}
Because the method characterizes the input data using an all-pole model,
the correct choice of the model order p is important.
.. plot::
:width: 80%
:include-source:
from spectrum import arcovar, marple_data, arma2psd
from pylab import plot, log10, linspace, axis
ar_values, error = arcovar(marple_data, 15)
psd = arma2psd(ar_values, sides='centerdc')
plot(linspace(-0.5, 0.5, len(psd)), 10*log10(psd/max(psd)))
axis([-0.5, 0.5, -60, 0])
| python | {
"resource": ""
} |
q256028 | lpc | validation | def lpc(x, N=None):
"""Linear Predictor Coefficients.
:param x:
:param int N: default is length(X) - 1
:Details:
Finds the coefficients :math:`A=(1, a(2), \dots a(N+1))`, of an Nth order
forward linear predictor that predicts the current value value of the
real-valued time series x based on past samples:
.. math:: \hat{x}(n) = -a(2)*x(n-1) - a(3)*x(n-2) - ... - a(N+1)*x(n-N)
such that the sum of the squares of the errors
.. math:: err(n) = X(n) - Xp(n)
is minimized. This function uses the Levinson-Durbin recursion to
solve the normal equations that arise from the least-squares formulation.
.. seealso:: :func:`levinson`, :func:`aryule`, :func:`prony`, :func:`stmcb`
.. todo:: matrix case, references
:Example:
::
from scipy.signal import lfilter
noise = randn(50000,1); % Normalized white Gaussian noise
x = filter([1], [1 1/2 1/3 1/4], noise)
x = x[45904:50000]
x.reshape(4096, 1)
x = x[0]
Compute the predictor coefficients, estimated signal, prediction error, and autocorrelation sequence of the prediction error:
1.00000 + 0.00000i 0.51711 - 0.00000i 0.33908 - 0.00000i 0.24410 - 0.00000i
::
| python | {
"resource": ""
} |
q256029 | pascal | validation | def pascal(n):
"""Return Pascal matrix
:param int n: size of the matrix
.. doctest::
>>> from spectrum import pascal
>>> pascal(6)
array([[ 1., 1., 1., 1., 1., 1.],
[ 1., 2., 3., 4., 5., 6.],
[ 1., 3., 6., 10., 15., 21.],
[ 1., 4., 10., 20., 35., 56.],
[ 1., 5., 15., 35., 70., 126.],
[ 1., 6., 21., 56., 126., | python | {
"resource": ""
} |
q256030 | csvd | validation | def csvd(A):
"""SVD decomposition using numpy.linalg.svd
:param A: a M by N matrix
:return:
* U, a M by M matrix
* S the N eigen values
* V a N by N matrix
See :func:`numpy.linalg.svd` for a detailed documentation.
| python | {
"resource": ""
} |
q256031 | compatible_staticpath | validation | def compatible_staticpath(path):
"""
Try to return a path to static the static files compatible all
the way back to Django 1.2. If anyone has a cleaner or better
way to do this let me know!
"""
if VERSION >= (1, 10):
# Since Django 1.10, forms.Media automatically invoke static
# lazily on the path if it is relative.
return path
try:
# >= 1.4
from django.templatetags.static import static
return static(path)
except ImportError:
pass
try: | python | {
"resource": ""
} |
q256032 | main | validation | def main(argv=None):
"""Main command line interface."""
if argv is None:
argv = sys.argv[1:]
| python | {
"resource": ""
} |
q256033 | CommandLineTool.pass_from_pipe | validation | def pass_from_pipe(cls):
"""Return password from pipe if not on TTY, else False.
"""
is_pipe | python | {
"resource": ""
} |
q256034 | get_all_keyring | validation | def get_all_keyring():
"""
Return a list of all implemented keyrings that can be constructed without
parameters.
"""
_load_plugins()
viable_classes = KeyringBackend.get_viable_backends()
| python | {
"resource": ""
} |
q256035 | KeyringBackend.name | validation | def name(cls):
"""
The keyring name, suitable for display.
The name is derived from module and class name.
"""
| python | {
"resource": ""
} |
q256036 | KeyringBackend.get_credential | validation | def get_credential(self, service, username):
"""Gets the username and password for the service.
Returns a Credential instance.
The *username* argument is optional and may be omitted by
the caller or ignored by the backend. Callers must use the
| python | {
"resource": ""
} |
q256037 | DBusKeyring.delete_password | validation | def delete_password(self, service, username):
"""Delete the password for the username of the service.
"""
if not self.connected(service):
# the user pressed "cancel" when prompted to | python | {
"resource": ""
} |
q256038 | EnvironCredential._get_env | validation | def _get_env(self, env_var):
"""Helper to read an environment variable
"""
value = os.environ.get(env_var)
if not value:
| python | {
"resource": ""
} |
q256039 | Keyring.get_preferred_collection | validation | def get_preferred_collection(self):
"""If self.preferred_collection contains a D-Bus path,
the collection at that address is returned. Otherwise,
the default collection is returned.
"""
bus = secretstorage.dbus_init()
try:
if hasattr(self, 'preferred_collection'):
collection = secretstorage.Collection(
bus, self.preferred_collection)
else:
collection = secretstorage.get_default_collection(bus)
except exceptions.SecretStorageException as e:
| python | {
"resource": ""
} |
q256040 | ChainerBackend.backends | validation | def backends(cls):
"""
Discover all keyrings for chaining.
"""
allowed = (
keyring
for keyring in filter(backend._limit, backend.get_all_keyring())
if not isinstance(keyring, | python | {
"resource": ""
} |
q256041 | set_keyring | validation | def set_keyring(keyring):
"""Set current keyring backend.
"""
global _keyring_backend
if not isinstance(keyring, backend.KeyringBackend):
| python | {
"resource": ""
} |
q256042 | disable | validation | def disable():
"""
Configure the null keyring as the default.
"""
root = platform.config_root()
try:
os.makedirs(root)
except OSError:
pass
filename = os.path.join(root, 'keyringrc.cfg')
if os.path.exists(filename):
msg | python | {
"resource": ""
} |
q256043 | init_backend | validation | def init_backend(limit=None):
"""
Load a keyring specified in the config file or infer the best available.
Limit, if supplied, should be a callable taking a backend and returning
True if that backend should be included for consideration.
"""
# save the limit for the chainer to honor
backend._limit = limit
# get all keyrings | python | {
"resource": ""
} |
q256044 | _load_keyring_class | validation | def _load_keyring_class(keyring_name):
"""
Load the keyring class indicated by name.
These popular names are tested to ensure their presence.
>>> popular_names = [
... 'keyring.backends.Windows.WinVaultKeyring',
... 'keyring.backends.OS_X.Keyring',
... 'keyring.backends.kwallet.DBusKeyring',
... 'keyring.backends.SecretService.Keyring',
... ]
>>> list(map(_load_keyring_class, popular_names))
[...]
These | python | {
"resource": ""
} |
q256045 | load_config | validation | def load_config():
"""Load a keyring using the config file in the config root."""
filename = 'keyringrc.cfg'
keyring_cfg = os.path.join(platform.config_root(), filename)
if not os.path.exists(keyring_cfg):
return
config = configparser.RawConfigParser()
config.read(keyring_cfg)
_load_keyring_path(config)
# load the keyring class name, and then | python | {
"resource": ""
} |
q256046 | _data_root_Linux | validation | def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = | python | {
"resource": ""
} |
q256047 | _check_old_config_root | validation | def _check_old_config_root():
"""
Prior versions of keyring would search for the config
in XDG_DATA_HOME, but should probably have been
searching for config in XDG_CONFIG_HOME. If the
config exists in the former but not in the latter,
raise a RuntimeError to force the change.
"""
# disable the check - once is enough and avoids infinite loop
| python | {
"resource": ""
} |
q256048 | _config_root_Linux | validation | def _config_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine config
location.
"""
_check_old_config_root()
fallback = os.path.expanduser('~/.local/share')
| python | {
"resource": ""
} |
q256049 | make_formatter | validation | def make_formatter(format_name):
"""Returns a callable that outputs the data. Defaults to print."""
if "json" in format_name:
from json import dumps
import datetime
def jsonhandler(obj): obj.isoformat() if isinstance(obj, (datetime.datetime, datetime.date)) else obj
if format_name == "prettyjson":
def jsondumps(data): return dumps(data, default=jsonhandler, indent=2, separators=(',', ': '))
else:
def jsondumps(data): return dumps(data, default=jsonhandler)
def jsonify(data):
if isinstance(data, dict):
print(jsondumps(data))
| python | {
"resource": ""
} |
q256050 | argparser | validation | def argparser():
"""Constructs the ArgumentParser for the CLI"""
parser = ArgumentParser(prog='pynetgear')
parser.add_argument("--format", choices=['json', 'prettyjson', 'py'], default='prettyjson')
router_args = parser.add_argument_group("router connection config")
router_args.add_argument("--host", help="Hostname for the router")
router_args.add_argument("--user", help="Account for login")
router_args.add_argument("--port", help="Port exposed on the router")
router_args.add_argument("--login-v2", help="Force the use of the cookie-based authentication",
dest="force_login_v2", default=False, action="store_true")
router_args.add_argument(
"--password",
help="Not required with a wired connection." +
"Optionally, set the PYNETGEAR_PASSWORD environment variable")
router_args.add_argument(
"--url", help="Overrides host:port and ssl with url to router")
router_args.add_argument("--no-ssl",
dest="ssl", default=True,
action="store_false",
help="Connect with https")
subparsers = parser.add_subparsers(
description="Runs subcommand | python | {
"resource": ""
} |
q256051 | run_subcommand | validation | def run_subcommand(netgear, args):
"""Runs the subcommand configured in args on the netgear session"""
subcommand = args.subcommand
if subcommand == "block_device" or subcommand == "allow_device":
return netgear.allow_block_device(args.mac_addr, BLOCK if subcommand == "block_device" else ALLOW)
if subcommand == "attached_devices":
if args.verbose:
| python | {
"resource": ""
} |
q256052 | main | validation | def main():
"""Scan for devices and print results."""
args = argparser().parse_args(sys.argv[1:])
password = os.environ.get('PYNETGEAR_PASSWORD') or args.password
netgear = Netgear(password, args.host, args.user, args.port, args.ssl, args.url, args.force_login_v2)
results = run_subcommand(netgear, args)
| python | {
"resource": ""
} |
q256053 | autodetect_url | validation | def autodetect_url():
"""
Try to autodetect the base URL of the router SOAP service.
Returns None if it can't be found.
"""
for url in ["http://routerlogin.net:5000", "https://routerlogin.net",
"http://routerlogin.net"]:
try:
r = requests.get(url + "/soap/server_sa/",
headers=_get_soap_headers("Test:1", "test"),
| python | {
"resource": ""
} |
q256054 | _xml_get | validation | def _xml_get(e, name):
"""
Returns the value of the subnode "name" of element e.
Returns None if the subnode doesn't exist
"""
| python | {
"resource": ""
} |
q256055 | _convert | validation | def _convert(value, to_type, default=None):
"""Convert value to to_type, returns default if fails."""
try:
return default if value is | python | {
"resource": ""
} |
q256056 | Netgear.login | validation | def login(self):
"""
Login to the router.
Will be called automatically by other actions.
| python | {
"resource": ""
} |
q256057 | Netgear.get_attached_devices_2 | validation | def get_attached_devices_2(self):
"""
Return list of connected devices to the router with details.
This call is slower and probably heavier on the router load.
Returns None if error occurred.
"""
_LOGGER.info("Get attached devices 2")
success, response = self._make_request(SERVICE_DEVICE_INFO,
"GetAttachDevice2")
if not success:
return None
success, devices_node = _find_node(
response.text,
".//GetAttachDevice2Response/NewAttachDevice")
if not success:
return None
xml_devices = devices_node.findall("Device")
devices = []
for d in xml_devices:
ip = _xml_get(d, 'IP')
name = _xml_get(d, 'Name')
mac = _xml_get(d, 'MAC')
signal = _convert(_xml_get(d, 'SignalStrength'), int)
link_type = _xml_get(d, 'ConnectionType')
link_rate = _xml_get(d, | python | {
"resource": ""
} |
q256058 | Netgear.get_traffic_meter | validation | def get_traffic_meter(self):
"""
Return dict of traffic meter stats.
Returns None if error occurred.
"""
_LOGGER.info("Get traffic meter")
def parse_text(text):
"""
there are three kinds of values in the returned data
This function parses the different values and returns
(total, avg), timedelta or a plain float
"""
def tofloats(lst): return (float(t) for t in lst)
try:
if "/" in text: # "6.19/0.88" total/avg
return tuple(tofloats(text.split('/')))
elif ":" in text: # 11:14 hr:mn
hour, mins = tofloats(text.split(':'))
return timedelta(hours=hour, minutes=mins)
else:
return float(text)
| python | {
"resource": ""
} |
q256059 | Netgear.config_finish | validation | def config_finish(self):
"""
End of a configuration session.
Tells the router we're done managing admin functionality.
"""
_LOGGER.info("Config finish")
if not self.config_started:
return True
success, | python | {
"resource": ""
} |
q256060 | Netgear._make_request | validation | def _make_request(self, service, method, params=None, body="",
need_auth=True):
"""Make an API request to the router."""
# If we have no cookie (v2) or never called login before (v1)
# and we need auth, the request will fail for sure.
if need_auth and not self.cookie:
if not self.login():
return False, None
headers = self._get_headers(service, method, need_auth)
if not body:
if not params:
params = ""
if isinstance(params, dict):
_map = params
params = ""
for k in _map:
params += "<" + k + ">" + _map[k] + "</" + k + ">\n"
body = CALL_BODY.format(service=SERVICE_PREFIX + service,
method=method, params=params)
message = SOAP_REQUEST.format(session_id=SESSION_ID, body=body)
try:
response = requests.post(self.soap_url, headers=headers,
data=message, timeout=30, verify=False)
if need_auth and _is_unauthorized_response(response):
# let's discard the cookie because it probably expired (v2)
# or the IP-bound (?) session expired (v1)
| python | {
"resource": ""
} |
q256061 | ip2long | validation | def ip2long(ip):
"""
Wrapper function for IPv4 and IPv6 converters.
:arg ip: IPv4 or IPv6 address
"""
try:
return int(binascii.hexlify(socket.inet_aton(ip)), 16)
| python | {
"resource": ""
} |
q256062 | GeoIP._seek_country | validation | def _seek_country(self, ipnum):
"""
Using the record length and appropriate start points, seek to the
country that corresponds to the converted IP address integer.
Return offset of record.
:arg ipnum: Result of ip2long conversion
"""
try:
offset = 0
seek_depth = 127 if len(str(ipnum)) > 10 else 31
for depth in range(seek_depth, -1, -1):
if self._flags & const.MEMORY_CACHE:
startIndex = 2 * self._recordLength * offset
endIndex = startIndex + (2 * self._recordLength)
buf = self._memory[startIndex:endIndex]
else:
startIndex = 2 * self._recordLength * offset
readLength = 2 * self._recordLength
try:
self._lock.acquire()
self._fp.seek(startIndex, os.SEEK_SET)
buf = self._fp.read(readLength)
finally:
self._lock.release()
if PY3 and type(buf) is bytes:
buf = buf.decode(ENCODING)
x = [0, 0]
for i in range(2):
for j in range(self._recordLength):
byte = buf[self._recordLength * i + j] | python | {
"resource": ""
} |
q256063 | GeoIP._get_region | validation | def _get_region(self, ipnum):
"""
Seek and return the region information.
Returns dict containing country_code and region_code.
:arg ipnum: Result of ip2long conversion
"""
region_code = None
country_code = None
seek_country = self._seek_country(ipnum)
def get_region_code(offset):
region1 = chr(offset // 26 + 65)
region2 = chr(offset % 26 + 65)
return ''.join([region1, region2])
if self._databaseType == const.REGION_EDITION_REV0:
seek_region = seek_country - const.STATE_BEGIN_REV0
if seek_region >= 1000:
country_code = 'US'
region_code = get_region_code(seek_region - 1000)
else:
country_code = const.COUNTRY_CODES[seek_region]
elif self._databaseType == const.REGION_EDITION_REV1:
seek_region = seek_country - const.STATE_BEGIN_REV1
if seek_region < const.US_OFFSET:
pass
elif seek_region < const.CANADA_OFFSET:
country_code = 'US'
| python | {
"resource": ""
} |
q256064 | GeoIP._get_record | validation | def _get_record(self, ipnum):
"""
Populate location dict for converted IP.
Returns dict with numerous location properties.
:arg ipnum: Result of ip2long conversion
"""
seek_country = self._seek_country(ipnum)
if seek_country == self._databaseSegments:
return {}
read_length = (2 * self._recordLength - 1) * self._databaseSegments
try:
self._lock.acquire()
self._fp.seek(seek_country + read_length, os.SEEK_SET)
buf = self._fp.read(const.FULL_RECORD_LENGTH)
finally:
self._lock.release()
if PY3 and type(buf) is bytes:
buf = buf.decode(ENCODING)
record = {
'dma_code': 0,
'area_code': 0,
'metro_code': None,
'postal_code': None
}
latitude = 0
longitude = 0
char = ord(buf[0])
record['country_code'] = const.COUNTRY_CODES[char]
record['country_code3'] = const.COUNTRY_CODES3[char]
record['country_name'] = const.COUNTRY_NAMES[char]
record['continent'] = const.CONTINENT_NAMES[char]
def read_data(buf, pos):
cur = pos
while buf[cur] != '\0':
cur += 1
return cur, buf[pos:cur] if cur > pos else None
offset, record['region_code'] = read_data(buf, 1)
offset, record['city'] = read_data(buf, offset + 1)
| python | {
"resource": ""
} |
q256065 | GeoIP._gethostbyname | validation | def _gethostbyname(self, hostname):
"""
Hostname lookup method, supports both IPv4 and IPv6.
"""
if self._databaseType in const.IPV6_EDITIONS:
response = socket.getaddrinfo(hostname, 0, socket.AF_INET6)
| python | {
"resource": ""
} |
q256066 | GeoIP.id_by_name | validation | def id_by_name(self, hostname):
"""
Returns the database ID for specified hostname.
The id might be useful as array index. 0 is unknown.
:arg hostname: | python | {
"resource": ""
} |
q256067 | GeoIP.id_by_addr | validation | def id_by_addr(self, addr):
"""
Returns the database ID for specified address.
The ID might be useful as array index. 0 is unknown.
:arg addr: IPv4 or IPv6 address (eg. 203.0.113.30)
"""
if self._databaseType in (const.PROXY_EDITION, const.NETSPEED_EDITION_REV1, const.NETSPEED_EDITION_REV1_V6):
raise GeoIPError('Invalid database type; this database is not supported')
ipv = 6 if addr.find(':') >= 0 else 4
if ipv == 4 | python | {
"resource": ""
} |
q256068 | GeoIP.netspeed_by_addr | validation | def netspeed_by_addr(self, addr):
"""
Returns NetSpeed name from address.
:arg addr: IP address (e.g. 203.0.113.30)
"""
if self._databaseType == const.NETSPEED_EDITION:
return const.NETSPEED_NAMES[self.id_by_addr(addr)]
elif self._databaseType in (const.NETSPEED_EDITION_REV1,
| python | {
"resource": ""
} |
q256069 | GeoIP.netspeed_by_name | validation | def netspeed_by_name(self, hostname):
"""
Returns NetSpeed name from hostname. Can be Unknown, Dial-up,
| python | {
"resource": ""
} |
q256070 | GeoIP.country_name_by_addr | validation | def country_name_by_addr(self, addr):
"""
Returns full country name for specified IP address.
:arg addr: IP address (e.g. 203.0.113.30)
"""
VALID_EDITIONS = (const.COUNTRY_EDITION, const.COUNTRY_EDITION_V6)
if self._databaseType in VALID_EDITIONS:
country_id = self.id_by_addr(addr)
return const.COUNTRY_NAMES[country_id]
| python | {
"resource": ""
} |
q256071 | GeoIP.country_name_by_name | validation | def country_name_by_name(self, hostname):
"""
Returns full country name for specified hostname.
| python | {
"resource": ""
} |
q256072 | GeoIP.org_by_addr | validation | def org_by_addr(self, addr):
"""
Returns Organization, ISP, or ASNum name for given IP address.
:arg addr: IP address (e.g. 203.0.113.30)
"""
valid = (const.ORG_EDITION, const.ISP_EDITION,
const.ASNUM_EDITION, const.ASNUM_EDITION_V6)
if self._databaseType not in valid:
| python | {
"resource": ""
} |
q256073 | GeoIP.org_by_name | validation | def org_by_name(self, hostname):
"""
Returns Organization, ISP, or ASNum name for given hostname.
:arg hostname: Hostname (e.g. example.com)
| python | {
"resource": ""
} |
q256074 | time_zone_by_country_and_region | validation | def time_zone_by_country_and_region(country_code, region_code=None):
"""
Returns time zone from country and region code.
:arg country_code: Country code
:arg region_code: Region code
"""
| python | {
"resource": ""
} |
q256075 | BaseCompressor.compress | validation | def compress(self, filename):
"""Compress a file, only if needed."""
compressed_filename = self.get_compressed_filename(filename)
| python | {
"resource": ""
} |
q256076 | BaseCompressor.get_compressed_filename | validation | def get_compressed_filename(self, filename):
"""If the given filename should be compressed, returns the
compressed filename.
A file can be compressed if:
- It is a whitelisted extension
- The compressed file does not exist
- The compressed file exists by is older than the file itself
Otherwise, it returns False.
"""
if not os.path.splitext(filename)[1][1:] in self.suffixes_to_compress:
return False
file_stats = None
compressed_stats = None
compressed_filename = '{}.{}'.format(filename, self.suffix)
try:
file_stats | python | {
"resource": ""
} |
q256077 | copy | validation | def copy(src, dst, symlink=False, rellink=False):
"""Copy or symlink the file."""
func = os.symlink if symlink else shutil.copy2
if symlink and os.path.lexists(dst):
os.remove(dst)
| python | {
"resource": ""
} |
q256078 | url_from_path | validation | def url_from_path(path):
"""Transform path to url, converting backslashes to slashes if needed."""
if os.sep != '/':
| python | {
"resource": ""
} |
q256079 | read_markdown | validation | def read_markdown(filename):
"""Reads markdown file, converts output and fetches title and meta-data for
further processing.
"""
global MD
# Use utf-8-sig codec to remove BOM if it is present. This is only possible
# this way prior to feeding the text to the markdown parser (which would
# also default to pure utf-8)
with open(filename, 'r', encoding='utf-8-sig') as f:
text = f.read()
if MD is None:
MD = Markdown(extensions=['markdown.extensions.meta',
'markdown.extensions.tables'],
output_format='html5')
else:
MD.reset() | python | {
"resource": ""
} |
q256080 | load_exif | validation | def load_exif(album):
"""Loads the exif data of all images in an album from cache"""
if not hasattr(album.gallery, "exifCache"):
_restore_cache(album.gallery)
| python | {
"resource": ""
} |
q256081 | _restore_cache | validation | def _restore_cache(gallery):
"""Restores the exif data cache from the cache file"""
cachePath = os.path.join(gallery.settings["destination"], ".exif_cache")
try:
if os.path.exists(cachePath):
with open(cachePath, "rb") as cacheFile:
gallery.exifCache = pickle.load(cacheFile)
| python | {
"resource": ""
} |
q256082 | save_cache | validation | def save_cache(gallery):
"""Stores the exif data of all images in the gallery"""
if hasattr(gallery, "exifCache"):
cache = gallery.exifCache
else:
cache = gallery.exifCache = {}
for album in gallery.albums.values():
for image in album.images:
cache[os.path.join(image.path, image.filename)] = image.exif
| python | {
"resource": ""
} |
q256083 | filter_nomedia | validation | def filter_nomedia(album, settings=None):
"""Removes all filtered Media and subdirs from an Album"""
nomediapath = os.path.join(album.src_path, ".nomedia")
if os.path.isfile(nomediapath):
if os.path.getsize(nomediapath) == 0:
logger.info("Ignoring album '%s' because of present 0-byte "
".nomedia file", album.name)
# subdirs have been added to the gallery already, remove them
# there, too
_remove_albums_with_subdirs(album.gallery.albums, [album.path])
try:
os.rmdir(album.dst_path)
except OSError as e:
# directory was created and populated with images in a
# previous run => keep it
pass
# cannot set albums => empty subdirs so that no albums are
# generated
album.subdirs = []
album.medias = []
else:
with open(nomediapath, "r") as nomediaFile:
| python | {
"resource": ""
} |
q256084 | build | validation | def build(source, destination, debug, verbose, force, config, theme, title,
ncpu):
"""Run sigal to process a directory.
If provided, 'source', 'destination' and 'theme' will override the
corresponding values from the settings file.
"""
level = ((debug and logging.DEBUG) or (verbose and logging.INFO) or
logging.WARNING)
init_logging(__name__, level=level)
logger = logging.getLogger(__name__)
if not os.path.isfile(config):
logger.error("Settings file not found: %s", config)
sys.exit(1)
start_time = time.time()
settings = read_settings(config)
for key in ('source', 'destination', 'theme'):
arg = locals()[key]
if arg is not None:
settings[key] = os.path.abspath(arg)
logger.info("%12s : %s", key.capitalize(), settings[key])
if not settings['source'] or not os.path.isdir(settings['source']):
logger.error("Input directory not found: %s", settings['source'])
sys.exit(1)
# on windows os.path.relpath raises a ValueError if the two paths are on
# different drives, in that case we just ignore the exception as the two
# paths are anyway not relative
relative_check = True
try:
relative_check = os.path.relpath(settings['destination'],
settings['source']).startswith('..')
except ValueError:
pass
if not relative_check:
logger.error("Output directory should be outside of the input "
| python | {
"resource": ""
} |
q256085 | serve | validation | def serve(destination, port, config):
"""Run a simple web server."""
if os.path.exists(destination):
pass
elif os.path.exists(config):
settings = read_settings(config)
destination = settings.get('destination')
if not os.path.exists(destination):
sys.stderr.write("The '{}' directory doesn't exist, maybe try "
"building first?\n".format(destination))
sys.exit(1)
else:
sys.stderr.write("The {destination} directory doesn't exist "
"and the config file ({config}) could not be read.\n"
| python | {
"resource": ""
} |
q256086 | set_meta | validation | def set_meta(target, keys, overwrite=False):
"""Write metadata keys to .md file.
TARGET can be a media file or an album directory. KEYS are key/value pairs.
Ex, to set the title of test.jpg to "My test image":
sigal set_meta test.jpg title "My test image"
"""
if not os.path.exists(target):
sys.stderr.write("The target {} does not exist.\n".format(target))
sys.exit(1)
if len(keys) < 2 or len(keys) % 2 > 0:
sys.stderr.write("Need an even number of arguments.\n")
sys.exit(1)
if os.path.isdir(target):
descfile = os.path.join(target, 'index.md')
else:
descfile = os.path.splitext(target)[0] + '.md'
if os.path.exists(descfile) and not overwrite:
sys.stderr.write("Description file '{}' already exists. | python | {
"resource": ""
} |
q256087 | generate_image | validation | def generate_image(source, outname, settings, options=None):
"""Image processor, rotate and resize the image.
:param source: path to an image
:param outname: output filename
:param settings: settings dict
:param options: dict with PIL options (quality, optimize, progressive)
"""
logger = logging.getLogger(__name__)
if settings['use_orig'] or source.endswith('.gif'):
utils.copy(source, outname, symlink=settings['orig_link'])
return
img = _read_image(source)
original_format = img.format
if settings['copy_exif_data'] and settings['autorotate_images']:
logger.warning("The 'autorotate_images' and 'copy_exif_data' settings "
"are not compatible because Sigal can't save the "
"modified Orientation tag.")
# Preserve EXIF data
if settings['copy_exif_data'] and _has_exif_tags(img):
if options is not None:
options = deepcopy(options)
else:
options = {}
options['exif'] = img.info['exif']
# Rotate the img, and catch IOError when PIL fails to read EXIF
if settings['autorotate_images']:
try:
img = Transpose().process(img)
except (IOError, IndexError):
pass
# Resize the image
if settings['img_processor']:
try:
logger.debug('Processor: %s', settings['img_processor']) | python | {
"resource": ""
} |
q256088 | generate_thumbnail | validation | def generate_thumbnail(source, outname, box, fit=True, options=None,
thumb_fit_centering=(0.5, 0.5)):
"""Create a thumbnail image."""
logger = logging.getLogger(__name__)
img = _read_image(source)
original_format = img.format
| python | {
"resource": ""
} |
q256089 | get_exif_data | validation | def get_exif_data(filename):
"""Return a dict with the raw EXIF data."""
logger = logging.getLogger(__name__)
img = _read_image(filename)
try:
exif = img._getexif() or {}
except ZeroDivisionError:
logger.warning('Failed to read EXIF data.')
return None
data = {TAGS.get(tag, tag): value for tag, value in exif.items()}
if 'GPSInfo' in data:
try:
data['GPSInfo'] = {GPSTAGS.get(tag, tag): value
| python | {
"resource": ""
} |
q256090 | get_iptc_data | validation | def get_iptc_data(filename):
"""Return a dict with the raw IPTC data."""
logger = logging.getLogger(__name__)
iptc_data = {}
raw_iptc = {}
# PILs IptcImagePlugin issues a SyntaxError in certain circumstances
# with malformed metadata, see PIL/IptcImagePlugin.py", line 71.
# ( https://github.com/python-pillow/Pillow/blob/9dd0348be2751beb2c617e32ff9985aa2f92ae5f/src/PIL/IptcImagePlugin.py#L71 )
try:
img = _read_image(filename)
raw_iptc = IptcImagePlugin.getiptcinfo(img)
except SyntaxError:
logger.info('IPTC Error in %s', filename)
# IPTC fields are catalogued in:
# https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata
# 2:05 is the IPTC title property
if raw_iptc and (2, 5) in raw_iptc:
iptc_data["title"] = raw_iptc[(2, 5)].decode('utf-8', errors='replace')
# 2:120 is | python | {
"resource": ""
} |
q256091 | get_exif_tags | validation | def get_exif_tags(data, datetime_format='%c'):
"""Make a simplified version with common tags from raw EXIF data."""
logger = logging.getLogger(__name__)
simple = {}
for tag in ('Model', 'Make', 'LensModel'):
if tag in data:
if isinstance(data[tag], tuple):
simple[tag] = data[tag][0].strip()
else:
simple[tag] = data[tag].strip()
if 'FNumber' in data:
fnumber = data['FNumber']
try:
simple['fstop'] = float(fnumber[0]) / fnumber[1]
except Exception:
logger.debug('Skipped invalid FNumber: %r', fnumber, exc_info=True)
if 'FocalLength' in data:
focal = data['FocalLength']
try:
simple['focal'] = round(float(focal[0]) / focal[1])
except Exception:
logger.debug('Skipped invalid FocalLength: %r', focal,
exc_info=True)
if 'ExposureTime' in data:
exptime = data['ExposureTime']
if isinstance(exptime, tuple):
try:
simple['exposure'] = str(fractions.Fraction(exptime[0],
| python | {
"resource": ""
} |
q256092 | Album.create_output_directories | validation | def create_output_directories(self):
"""Create output directories for thumbnails and original images."""
check_or_create_dir(self.dst_path)
if self.medias:
check_or_create_dir(join(self.dst_path,
| python | {
"resource": ""
} |
q256093 | Album.url | validation | def url(self):
"""URL of the album, relative to its parent."""
url | python | {
"resource": ""
} |
q256094 | Album.thumbnail | validation | def thumbnail(self):
"""Path to the thumbnail of the album."""
if self._thumbnail:
# stop if it is already set
return self._thumbnail
# Test the thumbnail from the Markdown file.
thumbnail = self.meta.get('thumbnail', [''])[0]
if thumbnail and isfile(join(self.src_path, thumbnail)):
self._thumbnail = url_from_path(join(
self.name, get_thumb(self.settings, thumbnail)))
self.logger.debug("Thumbnail for %r : %s", self, self._thumbnail)
return self._thumbnail
else:
# find and return the first landscape image
for f in self.medias:
ext = splitext(f.filename)[1]
if ext.lower() in self.settings['img_extensions']:
# Use f.size if available as it is quicker (in cache), but
# fallback to the size of src_path if dst_path is missing
size = f.size
if size is None:
size = get_size(f.src_path)
if size['width'] > size['height']:
self._thumbnail = (url_quote(self.name) + '/' +
f.thumbnail)
self.logger.debug(
"Use 1st landscape image as thumbnail for %r : %s",
self, self._thumbnail)
return self._thumbnail
# else simply return the 1st media file
if not self._thumbnail and self.medias:
for media in self.medias:
if media.thumbnail is not None:
| python | {
"resource": ""
} |
q256095 | Album.zip | validation | def zip(self):
"""Make a ZIP archive with all media files and return its path.
If the ``zip_gallery`` setting is set,it contains the location of a zip
archive with all original images of the corresponding directory.
"""
zip_gallery = self.settings['zip_gallery']
if zip_gallery and len(self) > 0:
zip_gallery = zip_gallery.format(album=self)
archive_path = join(self.dst_path, zip_gallery)
if (self.settings.get('zip_skip_if_exists', False) and
isfile(archive_path)):
self.logger.debug("Archive %s already created, passing",
archive_path)
return zip_gallery
archive = zipfile.ZipFile(archive_path, 'w', allowZip64=True)
attr = ('src_path' if self.settings['zip_media_format'] == 'orig'
| python | {
"resource": ""
} |
q256096 | Gallery.get_albums | validation | def get_albums(self, path):
"""Return the list of all sub-directories of path."""
for name in self.albums[path].subdirs:
| python | {
"resource": ""
} |
q256097 | Gallery.build | validation | def build(self, force=False):
"Create the image gallery"
if not self.albums:
self.logger.warning("No albums found.")
return
def log_func(x):
# 63 is the total length of progressbar, label, percentage, etc
available_length = get_terminal_size()[0] - 64
if x and available_length > 10:
return x.name[:available_length]
else:
return ""
try:
with progressbar(self.albums.values(), label="Collecting files",
item_show_func=log_func, show_eta=False,
file=self.progressbar_target) as albums:
media_list = [f for album in albums
for f in self.process_dir(album, force=force)]
except KeyboardInterrupt:
sys.exit('Interrupted')
bar_opt = {'label': "Processing files",
'show_pos': True,
'file': self.progressbar_target}
failed_files = []
if self.pool:
try:
with progressbar(length=len(media_list), **bar_opt) as bar:
for res in self.pool.imap_unordered(worker, media_list):
if res:
failed_files.append(res)
bar.update(1)
self.pool.close()
self.pool.join()
except KeyboardInterrupt:
self.pool.terminate()
sys.exit('Interrupted')
except pickle.PicklingError:
self.logger.critical(
"Failed to process files with the multiprocessing feature."
" This can be caused by some module import or object "
"defined in the settings file, which can't be serialized.",
exc_info=True)
sys.exit('Abort')
else:
with progressbar(media_list, **bar_opt) as medias:
for media_item in medias:
res = process_file(media_item) | python | {
"resource": ""
} |
q256098 | Gallery.process_dir | validation | def process_dir(self, album, force=False):
"""Process a list of images in a directory."""
for f in album:
if isfile(f.dst_path) and not force:
self.logger.info("%s exists - skipping", f.filename)
self.stats[f.type + '_skipped'] += 1
| python | {
"resource": ""
} |
q256099 | reduce_opacity | validation | def reduce_opacity(im, opacity):
"""Returns an image with reduced opacity."""
assert opacity >= 0 and opacity <= 1
if im.mode != 'RGBA': | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.