_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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... | 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 :ma... | 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 sidelobe... | 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
=============== =... | 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:
from spectru... | 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 ... | 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'
Pa... | 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
window_visu(64, 'riesz')
..... | 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
window_visu(64, 'riesz')... | 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, 'po... | 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::
... | 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_v... | 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).
... | 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::
... | 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')
w.plot_window()
"""
from pylab import plot, xlim, grid, tit... | 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:
... | 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
"""
... | 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... | 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 %s import %s' % (short_name, obj_nam... | 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[... | 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',
'sphx_glr_%s_thumb.png' % fname[:-3])
ref_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')
templ... | 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 ... | 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.
:par... | 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 aut... | 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... | 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 er... | 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... | 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 o... | 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 ... | 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., 1... | 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.
Should return the same as in [Marple]_ , CSVD routine.
... | 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
#... | python | {
"resource": ""
} |
q256032 | main | validation | def main(argv=None):
"""Main command line interface."""
if argv is None:
argv = sys.argv[1:]
cli = CommandLineTool()
return cli.run(argv) | 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 = not sys.stdin.isatty()
return is_pipe and cls.strip_last_newline(sys.stdin.read()) | 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()
rings = util.suppress_exceptions(viable_classes, exceptions=TypeError)
return list(rings) | python | {
"resource": ""
} |
q256035 | KeyringBackend.name | validation | def name(cls):
"""
The keyring name, suitable for display.
The name is derived from module and class name.
"""
parent, sep, mod_name = cls.__module__.rpartition('.')
mod_name = mod_name.replace('_', ' ')
return ' '.join([mod_name, cls.__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
returned username.
"""
... | 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 unlock their keyring.
raise PasswordDeleteError("Cancelled by user")
if not self.... | 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:
raise ValueError('Missing environment variable:%s' % env_var)
return 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_collectio... | 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, ChainerBackend)
and keyring.priority > 0
)
return... | python | {
"resource": ""
} |
q256041 | set_keyring | validation | def set_keyring(keyring):
"""Set current keyring backend.
"""
global _keyring_backend
if not isinstance(keyring, backend.KeyringBackend):
raise TypeError("The keyring must be a subclass of KeyringBackend")
_keyring_backend = keyring | 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 = "Refusing to overwrite {filename}".format(... | 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... | 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.kwal... | 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)
_l... | 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 = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring') | 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.
"""
# disab... | 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')
key = 'XDG_CONFIG_HOME'
root = os.environ.get(key, None) or fallback
return os.path.join(root, 'python_ke... | 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_na... | 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("--ho... | 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)
... | 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... | 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_... | 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
"""
r = e.find(name)
if r is not None:
return r.text
return None | 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 None else to_type(value)
except ValueError:
# If value could not be converted
return default | python | {
"resource": ""
} |
q256056 | Netgear.login | validation | def login(self):
"""
Login to the router.
Will be called automatically by other actions.
"""
if not self.force_login_v2:
v1_result = self.login_v1()
if v1_result:
return v1_result
return self.login_v2() | 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._... | 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 fun... | 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, _ = self._make_request(
SERVICE_DEVIC... | 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.cooki... | 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)
except socket.error:
return int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, 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
... | 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)
... | 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:
... | 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)
family, socktype, proto, canonname, sockaddr = response[0]
... | 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: Hostname to get ID from.
"""
addr = self._gethostbyname(hostname)
return self.id_by_addr(addr) | 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.NE... | 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.NETSP... | python | {
"resource": ""
} |
q256069 | GeoIP.netspeed_by_name | validation | def netspeed_by_name(self, hostname):
"""
Returns NetSpeed name from hostname. Can be Unknown, Dial-up,
Cable, or Corporate.
:arg hostname: Hostname (e.g. example.com)
"""
addr = self._gethostbyname(hostname)
return self.netspeed_by_addr(addr) | 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 ... | python | {
"resource": ""
} |
q256071 | GeoIP.country_name_by_name | validation | def country_name_by_name(self, hostname):
"""
Returns full country name for specified hostname.
:arg hostname: Hostname (e.g. example.com)
"""
addr = self._gethostbyname(hostname)
return self.country_name_by_addr(addr) | 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._databaseTyp... | 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)
"""
addr = self._gethostbyname(hostname)
return self.org_by_addr(addr) | 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
"""
timezone = country_dict.get(country_code)
if not timezone:
return None
if isinstance(timezo... | python | {
"resource": ""
} |
q256075 | BaseCompressor.compress | validation | def compress(self, filename):
"""Compress a file, only if needed."""
compressed_filename = self.get_compressed_filename(filename)
if not compressed_filename:
return
self.do_compress(filename, compressed_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 t... | 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)
if rellink: # relative symlink from dst
func(os.path.relpath(src, os.path.dirname(dst)), dst)
else:
... | 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 != '/':
path = '/'.join(path.split(os.sep))
return quote(path) | 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
# al... | 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)
cache = album.gallery.exifCache
for media in album.medias:
if media.type == "image":
key = os.path.join(media.path, ... | 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(cacheFi... | 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(imag... | 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 "
... | 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 l... | 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("... | 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):
... | 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 = ... | 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
if fit:
img = ImageOps.fit(img, box, PILI... | 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.ge... | 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://gith... | 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[ta... | 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,
self.settings['thumb_dir']))
if self.medi... | python | {
"resource": ""
} |
q256093 | Album.url | validation | def url(self):
"""URL of the album, relative to its parent."""
url = self.name.encode('utf-8')
return url_quote(url) + '/' + self.url_ext | 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(jo... | 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... | 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:
subdir = os.path.normpath(join(path, name))
yield subdir, self.albums[subdir]
for subname, album in self.get_albums(subdir):
yield... | 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]... | 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
else:
... | 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':
im = im.convert('RGBA')
else:
im = im.copy()
alpha = im.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
im.putalpha(alph... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.