id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
229,300 | joshspeagle/dynesty | dynesty/nestedsamplers.py | UnitCubeSampler.update_hslice | def update_hslice(self, blob):
"""Update the Hamiltonian slice proposal scale based
on the relative amount of time spent moving vs reflecting."""
nmove, nreflect = blob['nmove'], blob['nreflect']
ncontract = blob.get('ncontract', 0)
fmove = (1. * nmove) / (nmove + nreflect + ncontract + 2)
norm = max(self.fmove, 1. - self.fmove)
self.scale *= math.exp((fmove - self.fmove) / norm) | python | def update_hslice(self, blob):
nmove, nreflect = blob['nmove'], blob['nreflect']
ncontract = blob.get('ncontract', 0)
fmove = (1. * nmove) / (nmove + nreflect + ncontract + 2)
norm = max(self.fmove, 1. - self.fmove)
self.scale *= math.exp((fmove - self.fmove) / norm) | [
"def",
"update_hslice",
"(",
"self",
",",
"blob",
")",
":",
"nmove",
",",
"nreflect",
"=",
"blob",
"[",
"'nmove'",
"]",
",",
"blob",
"[",
"'nreflect'",
"]",
"ncontract",
"=",
"blob",
".",
"get",
"(",
"'ncontract'",
",",
"0",
")",
"fmove",
"=",
"(",
... | Update the Hamiltonian slice proposal scale based
on the relative amount of time spent moving vs reflecting. | [
"Update",
"the",
"Hamiltonian",
"slice",
"proposal",
"scale",
"based",
"on",
"the",
"relative",
"amount",
"of",
"time",
"spent",
"moving",
"vs",
"reflecting",
"."
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/nestedsamplers.py#L216-L224 |
229,301 | joshspeagle/dynesty | dynesty/nestedsamplers.py | SingleEllipsoidSampler.update | def update(self, pointvol):
"""Update the bounding ellipsoid using the current set of
live points."""
# Check if we should use the provided pool for updating.
if self.use_pool_update:
pool = self.pool
else:
pool = None
# Update the ellipsoid.
self.ell.update(self.live_u, pointvol=pointvol, rstate=self.rstate,
bootstrap=self.bootstrap, pool=pool)
if self.enlarge != 1.:
self.ell.scale_to_vol(self.ell.vol * self.enlarge)
return copy.deepcopy(self.ell) | python | def update(self, pointvol):
# Check if we should use the provided pool for updating.
if self.use_pool_update:
pool = self.pool
else:
pool = None
# Update the ellipsoid.
self.ell.update(self.live_u, pointvol=pointvol, rstate=self.rstate,
bootstrap=self.bootstrap, pool=pool)
if self.enlarge != 1.:
self.ell.scale_to_vol(self.ell.vol * self.enlarge)
return copy.deepcopy(self.ell) | [
"def",
"update",
"(",
"self",
",",
"pointvol",
")",
":",
"# Check if we should use the provided pool for updating.",
"if",
"self",
".",
"use_pool_update",
":",
"pool",
"=",
"self",
".",
"pool",
"else",
":",
"pool",
"=",
"None",
"# Update the ellipsoid.",
"self",
"... | Update the bounding ellipsoid using the current set of
live points. | [
"Update",
"the",
"bounding",
"ellipsoid",
"using",
"the",
"current",
"set",
"of",
"live",
"points",
"."
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/nestedsamplers.py#L346-L362 |
229,302 | joshspeagle/dynesty | dynesty/nestedsamplers.py | MultiEllipsoidSampler.update | def update(self, pointvol):
"""Update the bounding ellipsoids using the current set of
live points."""
# Check if we should use the pool for updating.
if self.use_pool_update:
pool = self.pool
else:
pool = None
# Update the bounding ellipsoids.
self.mell.update(self.live_u, pointvol=pointvol,
vol_dec=self.vol_dec, vol_check=self.vol_check,
rstate=self.rstate, bootstrap=self.bootstrap,
pool=pool)
if self.enlarge != 1.:
self.mell.scale_to_vols(self.mell.vols * self.enlarge)
return copy.deepcopy(self.mell) | python | def update(self, pointvol):
# Check if we should use the pool for updating.
if self.use_pool_update:
pool = self.pool
else:
pool = None
# Update the bounding ellipsoids.
self.mell.update(self.live_u, pointvol=pointvol,
vol_dec=self.vol_dec, vol_check=self.vol_check,
rstate=self.rstate, bootstrap=self.bootstrap,
pool=pool)
if self.enlarge != 1.:
self.mell.scale_to_vols(self.mell.vols * self.enlarge)
return copy.deepcopy(self.mell) | [
"def",
"update",
"(",
"self",
",",
"pointvol",
")",
":",
"# Check if we should use the pool for updating.",
"if",
"self",
".",
"use_pool_update",
":",
"pool",
"=",
"self",
".",
"pool",
"else",
":",
"pool",
"=",
"None",
"# Update the bounding ellipsoids.",
"self",
... | Update the bounding ellipsoids using the current set of
live points. | [
"Update",
"the",
"bounding",
"ellipsoids",
"using",
"the",
"current",
"set",
"of",
"live",
"points",
"."
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/nestedsamplers.py#L550-L568 |
229,303 | joshspeagle/dynesty | dynesty/nestedsamplers.py | RadFriendsSampler.update | def update(self, pointvol):
"""Update the N-sphere radii using the current set of live points."""
# Initialize a K-D Tree to assist nearest neighbor searches.
if self.use_kdtree:
kdtree = spatial.KDTree(self.live_u)
else:
kdtree = None
# Check if we should use the provided pool for updating.
if self.use_pool_update:
pool = self.pool
else:
pool = None
# Update the N-spheres.
self.radfriends.update(self.live_u, pointvol=pointvol,
rstate=self.rstate, bootstrap=self.bootstrap,
pool=pool, kdtree=kdtree)
if self.enlarge != 1.:
self.radfriends.scale_to_vol(self.radfriends.vol_ball *
self.enlarge)
return copy.deepcopy(self.radfriends) | python | def update(self, pointvol):
# Initialize a K-D Tree to assist nearest neighbor searches.
if self.use_kdtree:
kdtree = spatial.KDTree(self.live_u)
else:
kdtree = None
# Check if we should use the provided pool for updating.
if self.use_pool_update:
pool = self.pool
else:
pool = None
# Update the N-spheres.
self.radfriends.update(self.live_u, pointvol=pointvol,
rstate=self.rstate, bootstrap=self.bootstrap,
pool=pool, kdtree=kdtree)
if self.enlarge != 1.:
self.radfriends.scale_to_vol(self.radfriends.vol_ball *
self.enlarge)
return copy.deepcopy(self.radfriends) | [
"def",
"update",
"(",
"self",
",",
"pointvol",
")",
":",
"# Initialize a K-D Tree to assist nearest neighbor searches.",
"if",
"self",
".",
"use_kdtree",
":",
"kdtree",
"=",
"spatial",
".",
"KDTree",
"(",
"self",
".",
"live_u",
")",
"else",
":",
"kdtree",
"=",
... | Update the N-sphere radii using the current set of live points. | [
"Update",
"the",
"N",
"-",
"sphere",
"radii",
"using",
"the",
"current",
"set",
"of",
"live",
"points",
"."
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/nestedsamplers.py#L788-L811 |
229,304 | joshspeagle/dynesty | dynesty/results.py | Results.summary | def summary(self):
"""Return a formatted string giving a quick summary
of the results."""
res = ("nlive: {:d}\n"
"niter: {:d}\n"
"ncall: {:d}\n"
"eff(%): {:6.3f}\n"
"logz: {:6.3f} +/- {:6.3f}"
.format(self.nlive, self.niter, sum(self.ncall),
self.eff, self.logz[-1], self.logzerr[-1]))
print('Summary\n=======\n'+res) | python | def summary(self):
res = ("nlive: {:d}\n"
"niter: {:d}\n"
"ncall: {:d}\n"
"eff(%): {:6.3f}\n"
"logz: {:6.3f} +/- {:6.3f}"
.format(self.nlive, self.niter, sum(self.ncall),
self.eff, self.logz[-1], self.logzerr[-1]))
print('Summary\n=======\n'+res) | [
"def",
"summary",
"(",
"self",
")",
":",
"res",
"=",
"(",
"\"nlive: {:d}\\n\"",
"\"niter: {:d}\\n\"",
"\"ncall: {:d}\\n\"",
"\"eff(%): {:6.3f}\\n\"",
"\"logz: {:6.3f} +/- {:6.3f}\"",
".",
"format",
"(",
"self",
".",
"nlive",
",",
"self",
".",
"niter",
",",
"sum",
... | Return a formatted string giving a quick summary
of the results. | [
"Return",
"a",
"formatted",
"string",
"giving",
"a",
"quick",
"summary",
"of",
"the",
"results",
"."
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/results.py#L161-L173 |
229,305 | joshspeagle/dynesty | dynesty/utils.py | unitcheck | def unitcheck(u, nonperiodic=None):
"""Check whether `u` is inside the unit cube. Given a masked array
`nonperiodic`, also allows periodic boundaries conditions to exceed
the unit cube."""
if nonperiodic is None:
# No periodic boundary conditions provided.
return np.all(u > 0.) and np.all(u < 1.)
else:
# Alternating periodic and non-periodic boundary conditions.
return (np.all(u[nonperiodic] > 0.) and
np.all(u[nonperiodic] < 1.) and
np.all(u[~nonperiodic] > -0.5) and
np.all(u[~nonperiodic] < 1.5)) | python | def unitcheck(u, nonperiodic=None):
if nonperiodic is None:
# No periodic boundary conditions provided.
return np.all(u > 0.) and np.all(u < 1.)
else:
# Alternating periodic and non-periodic boundary conditions.
return (np.all(u[nonperiodic] > 0.) and
np.all(u[nonperiodic] < 1.) and
np.all(u[~nonperiodic] > -0.5) and
np.all(u[~nonperiodic] < 1.5)) | [
"def",
"unitcheck",
"(",
"u",
",",
"nonperiodic",
"=",
"None",
")",
":",
"if",
"nonperiodic",
"is",
"None",
":",
"# No periodic boundary conditions provided.",
"return",
"np",
".",
"all",
"(",
"u",
">",
"0.",
")",
"and",
"np",
".",
"all",
"(",
"u",
"<",
... | Check whether `u` is inside the unit cube. Given a masked array
`nonperiodic`, also allows periodic boundaries conditions to exceed
the unit cube. | [
"Check",
"whether",
"u",
"is",
"inside",
"the",
"unit",
"cube",
".",
"Given",
"a",
"masked",
"array",
"nonperiodic",
"also",
"allows",
"periodic",
"boundaries",
"conditions",
"to",
"exceed",
"the",
"unit",
"cube",
"."
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/utils.py#L29-L42 |
229,306 | joshspeagle/dynesty | dynesty/utils.py | mean_and_cov | def mean_and_cov(samples, weights):
"""
Compute the weighted mean and covariance of the samples.
Parameters
----------
samples : `~numpy.ndarray` with shape (nsamples, ndim)
2-D array containing data samples. This ordering is equivalent to
using `rowvar=False` in `~numpy.cov`.
weights : `~numpy.ndarray` with shape (nsamples,)
1-D array of sample weights.
Returns
-------
mean : `~numpy.ndarray` with shape (ndim,)
Weighted sample mean vector.
cov : `~numpy.ndarray` with shape (ndim, ndim)
Weighted sample covariance matrix.
Notes
-----
Implements the formulae found `here <https://goo.gl/emWFLR>`_.
"""
# Compute the weighted mean.
mean = np.average(samples, weights=weights, axis=0)
# Compute the weighted covariance.
dx = samples - mean
wsum = np.sum(weights)
w2sum = np.sum(weights**2)
cov = wsum / (wsum**2 - w2sum) * np.einsum('i,ij,ik', weights, dx, dx)
return mean, cov | python | def mean_and_cov(samples, weights):
# Compute the weighted mean.
mean = np.average(samples, weights=weights, axis=0)
# Compute the weighted covariance.
dx = samples - mean
wsum = np.sum(weights)
w2sum = np.sum(weights**2)
cov = wsum / (wsum**2 - w2sum) * np.einsum('i,ij,ik', weights, dx, dx)
return mean, cov | [
"def",
"mean_and_cov",
"(",
"samples",
",",
"weights",
")",
":",
"# Compute the weighted mean.",
"mean",
"=",
"np",
".",
"average",
"(",
"samples",
",",
"weights",
"=",
"weights",
",",
"axis",
"=",
"0",
")",
"# Compute the weighted covariance.",
"dx",
"=",
"sa... | Compute the weighted mean and covariance of the samples.
Parameters
----------
samples : `~numpy.ndarray` with shape (nsamples, ndim)
2-D array containing data samples. This ordering is equivalent to
using `rowvar=False` in `~numpy.cov`.
weights : `~numpy.ndarray` with shape (nsamples,)
1-D array of sample weights.
Returns
-------
mean : `~numpy.ndarray` with shape (ndim,)
Weighted sample mean vector.
cov : `~numpy.ndarray` with shape (ndim, ndim)
Weighted sample covariance matrix.
Notes
-----
Implements the formulae found `here <https://goo.gl/emWFLR>`_. | [
"Compute",
"the",
"weighted",
"mean",
"and",
"covariance",
"of",
"the",
"samples",
"."
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/utils.py#L45-L81 |
229,307 | joshspeagle/dynesty | dynesty/utils.py | resample_equal | def resample_equal(samples, weights, rstate=None):
"""
Resample a new set of points from the weighted set of inputs
such that they all have equal weight.
Each input sample appears in the output array either
`floor(weights[i] * nsamples)` or `ceil(weights[i] * nsamples)` times,
with `floor` or `ceil` randomly selected (weighted by proximity).
Parameters
----------
samples : `~numpy.ndarray` with shape (nsamples,)
Set of unequally weighted samples.
weights : `~numpy.ndarray` with shape (nsamples,)
Corresponding weight of each sample.
rstate : `~numpy.random.RandomState`, optional
`~numpy.random.RandomState` instance.
Returns
-------
equal_weight_samples : `~numpy.ndarray` with shape (nsamples,)
New set of samples with equal weights.
Examples
--------
>>> x = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])
>>> w = np.array([0.6, 0.2, 0.15, 0.05])
>>> utils.resample_equal(x, w)
array([[ 1., 1.],
[ 1., 1.],
[ 1., 1.],
[ 3., 3.]])
Notes
-----
Implements the systematic resampling method described in `Hol, Schon, and
Gustafsson (2006) <doi:10.1109/NSSPW.2006.4378824>`_.
"""
if rstate is None:
rstate = np.random
if abs(np.sum(weights) - 1.) > SQRTEPS: # same tol as in np.random.choice.
raise ValueError("Weights do not sum to 1.")
# Make N subdivisions and choose positions with a consistent random offset.
nsamples = len(weights)
positions = (rstate.random() + np.arange(nsamples)) / nsamples
# Resample the data.
idx = np.zeros(nsamples, dtype=np.int)
cumulative_sum = np.cumsum(weights)
i, j = 0, 0
while i < nsamples:
if positions[i] < cumulative_sum[j]:
idx[i] = j
i += 1
else:
j += 1
return samples[idx] | python | def resample_equal(samples, weights, rstate=None):
if rstate is None:
rstate = np.random
if abs(np.sum(weights) - 1.) > SQRTEPS: # same tol as in np.random.choice.
raise ValueError("Weights do not sum to 1.")
# Make N subdivisions and choose positions with a consistent random offset.
nsamples = len(weights)
positions = (rstate.random() + np.arange(nsamples)) / nsamples
# Resample the data.
idx = np.zeros(nsamples, dtype=np.int)
cumulative_sum = np.cumsum(weights)
i, j = 0, 0
while i < nsamples:
if positions[i] < cumulative_sum[j]:
idx[i] = j
i += 1
else:
j += 1
return samples[idx] | [
"def",
"resample_equal",
"(",
"samples",
",",
"weights",
",",
"rstate",
"=",
"None",
")",
":",
"if",
"rstate",
"is",
"None",
":",
"rstate",
"=",
"np",
".",
"random",
"if",
"abs",
"(",
"np",
".",
"sum",
"(",
"weights",
")",
"-",
"1.",
")",
">",
"S... | Resample a new set of points from the weighted set of inputs
such that they all have equal weight.
Each input sample appears in the output array either
`floor(weights[i] * nsamples)` or `ceil(weights[i] * nsamples)` times,
with `floor` or `ceil` randomly selected (weighted by proximity).
Parameters
----------
samples : `~numpy.ndarray` with shape (nsamples,)
Set of unequally weighted samples.
weights : `~numpy.ndarray` with shape (nsamples,)
Corresponding weight of each sample.
rstate : `~numpy.random.RandomState`, optional
`~numpy.random.RandomState` instance.
Returns
-------
equal_weight_samples : `~numpy.ndarray` with shape (nsamples,)
New set of samples with equal weights.
Examples
--------
>>> x = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])
>>> w = np.array([0.6, 0.2, 0.15, 0.05])
>>> utils.resample_equal(x, w)
array([[ 1., 1.],
[ 1., 1.],
[ 1., 1.],
[ 3., 3.]])
Notes
-----
Implements the systematic resampling method described in `Hol, Schon, and
Gustafsson (2006) <doi:10.1109/NSSPW.2006.4378824>`_. | [
"Resample",
"a",
"new",
"set",
"of",
"points",
"from",
"the",
"weighted",
"set",
"of",
"inputs",
"such",
"that",
"they",
"all",
"have",
"equal",
"weight",
"."
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/utils.py#L84-L147 |
229,308 | joshspeagle/dynesty | dynesty/utils.py | _get_nsamps_samples_n | def _get_nsamps_samples_n(res):
""" Helper function for calculating the number of samples
Parameters
----------
res : :class:`~dynesty.results.Results` instance
The :class:`~dynesty.results.Results` instance taken from a previous
nested sampling run.
Returns
-------
nsamps: int
The total number of samples
samples_n: array
Number of live points at a given iteration
"""
try:
# Check if the number of live points explicitly changes.
samples_n = res.samples_n
nsamps = len(samples_n)
except:
# If the number of live points is constant, compute `samples_n`.
niter = res.niter
nlive = res.nlive
nsamps = len(res.logvol)
if nsamps == niter:
samples_n = np.ones(niter, dtype='int') * nlive
elif nsamps == (niter + nlive):
samples_n = np.append(np.ones(niter, dtype='int') * nlive,
np.arange(1, nlive + 1)[::-1])
else:
raise ValueError("Final number of samples differs from number of "
"iterations and number of live points.")
return nsamps, samples_n | python | def _get_nsamps_samples_n(res):
try:
# Check if the number of live points explicitly changes.
samples_n = res.samples_n
nsamps = len(samples_n)
except:
# If the number of live points is constant, compute `samples_n`.
niter = res.niter
nlive = res.nlive
nsamps = len(res.logvol)
if nsamps == niter:
samples_n = np.ones(niter, dtype='int') * nlive
elif nsamps == (niter + nlive):
samples_n = np.append(np.ones(niter, dtype='int') * nlive,
np.arange(1, nlive + 1)[::-1])
else:
raise ValueError("Final number of samples differs from number of "
"iterations and number of live points.")
return nsamps, samples_n | [
"def",
"_get_nsamps_samples_n",
"(",
"res",
")",
":",
"try",
":",
"# Check if the number of live points explicitly changes.",
"samples_n",
"=",
"res",
".",
"samples_n",
"nsamps",
"=",
"len",
"(",
"samples_n",
")",
"except",
":",
"# If the number of live points is constant... | Helper function for calculating the number of samples
Parameters
----------
res : :class:`~dynesty.results.Results` instance
The :class:`~dynesty.results.Results` instance taken from a previous
nested sampling run.
Returns
-------
nsamps: int
The total number of samples
samples_n: array
Number of live points at a given iteration | [
"Helper",
"function",
"for",
"calculating",
"the",
"number",
"of",
"samples"
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/utils.py#L197-L231 |
229,309 | joshspeagle/dynesty | dynesty/utils.py | reweight_run | def reweight_run(res, logp_new, logp_old=None):
"""
Reweight a given run based on a new target distribution.
Parameters
----------
res : :class:`~dynesty.results.Results` instance
The :class:`~dynesty.results.Results` instance taken from a previous
nested sampling run.
logp_new : `~numpy.ndarray` with shape (nsamps,)
New target distribution evaluated at the location of the samples.
logp_old : `~numpy.ndarray` with shape (nsamps,)
Old target distribution evaluated at the location of the samples.
If not provided, the `logl` values from `res` will be used.
Returns
-------
new_res : :class:`~dynesty.results.Results` instance
A new :class:`~dynesty.results.Results` instance with corresponding
weights based on our reweighted samples.
"""
# Extract info.
if logp_old is None:
logp_old = res['logl']
logrwt = logp_new - logp_old # ln(reweight)
logvol = res['logvol']
logl = res['logl']
nsamps = len(logvol)
# Compute weights using quadratic estimator.
h = 0.
logz = -1.e300
loglstar = -1.e300
logzvar = 0.
logvols_pad = np.concatenate(([0.], logvol))
logdvols = misc.logsumexp(a=np.c_[logvols_pad[:-1], logvols_pad[1:]],
axis=1, b=np.c_[np.ones(nsamps),
-np.ones(nsamps)])
logdvols += math.log(0.5)
dlvs = -np.diff(np.append(0., logvol))
saved_logwt, saved_logz, saved_logzvar, saved_h = [], [], [], []
for i in range(nsamps):
loglstar_new = logl[i]
logdvol, dlv = logdvols[i], dlvs[i]
logwt = np.logaddexp(loglstar_new, loglstar) + logdvol + logrwt[i]
logz_new = np.logaddexp(logz, logwt)
try:
lzterm = (math.exp(loglstar - logz_new) * loglstar +
math.exp(loglstar_new - logz_new) * loglstar_new)
except:
lzterm = 0.
h_new = (math.exp(logdvol) * lzterm +
math.exp(logz - logz_new) * (h + logz) -
logz_new)
dh = h_new - h
h = h_new
logz = logz_new
logzvar += dh * dlv
loglstar = loglstar_new
saved_logwt.append(logwt)
saved_logz.append(logz)
saved_logzvar.append(logzvar)
saved_h.append(h)
# Copy results.
new_res = Results([item for item in res.items()])
# Overwrite items with our new estimates.
new_res.logwt = np.array(saved_logwt)
new_res.logz = np.array(saved_logz)
new_res.logzerr = np.sqrt(np.array(saved_logzvar))
new_res.h = np.array(saved_h)
return new_res | python | def reweight_run(res, logp_new, logp_old=None):
# Extract info.
if logp_old is None:
logp_old = res['logl']
logrwt = logp_new - logp_old # ln(reweight)
logvol = res['logvol']
logl = res['logl']
nsamps = len(logvol)
# Compute weights using quadratic estimator.
h = 0.
logz = -1.e300
loglstar = -1.e300
logzvar = 0.
logvols_pad = np.concatenate(([0.], logvol))
logdvols = misc.logsumexp(a=np.c_[logvols_pad[:-1], logvols_pad[1:]],
axis=1, b=np.c_[np.ones(nsamps),
-np.ones(nsamps)])
logdvols += math.log(0.5)
dlvs = -np.diff(np.append(0., logvol))
saved_logwt, saved_logz, saved_logzvar, saved_h = [], [], [], []
for i in range(nsamps):
loglstar_new = logl[i]
logdvol, dlv = logdvols[i], dlvs[i]
logwt = np.logaddexp(loglstar_new, loglstar) + logdvol + logrwt[i]
logz_new = np.logaddexp(logz, logwt)
try:
lzterm = (math.exp(loglstar - logz_new) * loglstar +
math.exp(loglstar_new - logz_new) * loglstar_new)
except:
lzterm = 0.
h_new = (math.exp(logdvol) * lzterm +
math.exp(logz - logz_new) * (h + logz) -
logz_new)
dh = h_new - h
h = h_new
logz = logz_new
logzvar += dh * dlv
loglstar = loglstar_new
saved_logwt.append(logwt)
saved_logz.append(logz)
saved_logzvar.append(logzvar)
saved_h.append(h)
# Copy results.
new_res = Results([item for item in res.items()])
# Overwrite items with our new estimates.
new_res.logwt = np.array(saved_logwt)
new_res.logz = np.array(saved_logz)
new_res.logzerr = np.sqrt(np.array(saved_logzvar))
new_res.h = np.array(saved_h)
return new_res | [
"def",
"reweight_run",
"(",
"res",
",",
"logp_new",
",",
"logp_old",
"=",
"None",
")",
":",
"# Extract info.",
"if",
"logp_old",
"is",
"None",
":",
"logp_old",
"=",
"res",
"[",
"'logl'",
"]",
"logrwt",
"=",
"logp_new",
"-",
"logp_old",
"# ln(reweight)",
"l... | Reweight a given run based on a new target distribution.
Parameters
----------
res : :class:`~dynesty.results.Results` instance
The :class:`~dynesty.results.Results` instance taken from a previous
nested sampling run.
logp_new : `~numpy.ndarray` with shape (nsamps,)
New target distribution evaluated at the location of the samples.
logp_old : `~numpy.ndarray` with shape (nsamps,)
Old target distribution evaluated at the location of the samples.
If not provided, the `logl` values from `res` will be used.
Returns
-------
new_res : :class:`~dynesty.results.Results` instance
A new :class:`~dynesty.results.Results` instance with corresponding
weights based on our reweighted samples. | [
"Reweight",
"a",
"given",
"run",
"based",
"on",
"a",
"new",
"target",
"distribution",
"."
] | 9e482aafeb5cf84bedb896fa6f07a761d917983e | https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/utils.py#L624-L701 |
229,310 | ozgur/python-linkedin | linkedin/utils.py | enum | def enum(enum_type='enum', base_classes=None, methods=None, **attrs):
"""
Generates a enumeration with the given attributes.
"""
# Enumerations can not be initalized as a new instance
def __init__(instance, *args, **kwargs):
raise RuntimeError('%s types can not be initialized.' % enum_type)
if base_classes is None:
base_classes = ()
if methods is None:
methods = {}
base_classes = base_classes + (object,)
for k, v in methods.items():
methods[k] = classmethod(v)
attrs['enums'] = attrs.copy()
methods.update(attrs)
methods['__init__'] = __init__
return type(to_string(enum_type), base_classes, methods) | python | def enum(enum_type='enum', base_classes=None, methods=None, **attrs):
# Enumerations can not be initalized as a new instance
def __init__(instance, *args, **kwargs):
raise RuntimeError('%s types can not be initialized.' % enum_type)
if base_classes is None:
base_classes = ()
if methods is None:
methods = {}
base_classes = base_classes + (object,)
for k, v in methods.items():
methods[k] = classmethod(v)
attrs['enums'] = attrs.copy()
methods.update(attrs)
methods['__init__'] = __init__
return type(to_string(enum_type), base_classes, methods) | [
"def",
"enum",
"(",
"enum_type",
"=",
"'enum'",
",",
"base_classes",
"=",
"None",
",",
"methods",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"# Enumerations can not be initalized as a new instance",
"def",
"__init__",
"(",
"instance",
",",
"*",
"args",
","... | Generates a enumeration with the given attributes. | [
"Generates",
"a",
"enumeration",
"with",
"the",
"given",
"attributes",
"."
] | 9832fd995d6f74f14700bdbeeea3ab39151e737f | https://github.com/ozgur/python-linkedin/blob/9832fd995d6f74f14700bdbeeea3ab39151e737f/linkedin/utils.py#L32-L53 |
229,311 | lingthio/Flask-User | flask_user/email_adapters/sendmail_email_adapter.py | SendmailEmailAdapter.send_email_message | def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
""" Send email message via Flask-Sendmail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text.
"""
if not current_app.testing: # pragma: no cover
# Prepare email message
from flask_sendmail import Message
message = Message(
subject,
recipients=[recipient],
html=html_message,
body=text_message)
# Send email message
self.mail.send(message) | python | def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
if not current_app.testing: # pragma: no cover
# Prepare email message
from flask_sendmail import Message
message = Message(
subject,
recipients=[recipient],
html=html_message,
body=text_message)
# Send email message
self.mail.send(message) | [
"def",
"send_email_message",
"(",
"self",
",",
"recipient",
",",
"subject",
",",
"html_message",
",",
"text_message",
",",
"sender_email",
",",
"sender_name",
")",
":",
"if",
"not",
"current_app",
".",
"testing",
":",
"# pragma: no cover",
"# Prepare email message",... | Send email message via Flask-Sendmail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text. | [
"Send",
"email",
"message",
"via",
"Flask",
"-",
"Sendmail",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_adapters/sendmail_email_adapter.py#L34-L55 |
229,312 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.add_user_role | def add_user_role(self, user, role_name):
"""Associate a role name with a user."""
# For SQL: user.roles is list of pointers to Role objects
if isinstance(self.db_adapter, SQLDbAdapter):
# user.roles is a list of Role IDs
# Get or add role
role = self.db_adapter.find_first_object(self.RoleClass, name=role_name)
if not role:
role = self.RoleClass(name=role_name)
self.db_adapter.add_object(role)
user.roles.append(role)
# For others: user.roles is a list of role names
else:
# user.roles is a list of role names
user.roles.append(role_name) | python | def add_user_role(self, user, role_name):
# For SQL: user.roles is list of pointers to Role objects
if isinstance(self.db_adapter, SQLDbAdapter):
# user.roles is a list of Role IDs
# Get or add role
role = self.db_adapter.find_first_object(self.RoleClass, name=role_name)
if not role:
role = self.RoleClass(name=role_name)
self.db_adapter.add_object(role)
user.roles.append(role)
# For others: user.roles is a list of role names
else:
# user.roles is a list of role names
user.roles.append(role_name) | [
"def",
"add_user_role",
"(",
"self",
",",
"user",
",",
"role_name",
")",
":",
"# For SQL: user.roles is list of pointers to Role objects",
"if",
"isinstance",
"(",
"self",
".",
"db_adapter",
",",
"SQLDbAdapter",
")",
":",
"# user.roles is a list of Role IDs",
"# Get or ad... | Associate a role name with a user. | [
"Associate",
"a",
"role",
"name",
"with",
"a",
"user",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L81-L97 |
229,313 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.find_user_by_username | def find_user_by_username(self, username):
"""Find a User object by username."""
return self.db_adapter.ifind_first_object(self.UserClass, username=username) | python | def find_user_by_username(self, username):
return self.db_adapter.ifind_first_object(self.UserClass, username=username) | [
"def",
"find_user_by_username",
"(",
"self",
",",
"username",
")",
":",
"return",
"self",
".",
"db_adapter",
".",
"ifind_first_object",
"(",
"self",
".",
"UserClass",
",",
"username",
"=",
"username",
")"
] | Find a User object by username. | [
"Find",
"a",
"User",
"object",
"by",
"username",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L136-L138 |
229,314 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.find_user_emails | def find_user_emails(self, user):
"""Find all the UserEmail object belonging to a user."""
user_emails = self.db_adapter.find_objects(self.UserEmailClass, user_id=user.id)
return user_emails | python | def find_user_emails(self, user):
user_emails = self.db_adapter.find_objects(self.UserEmailClass, user_id=user.id)
return user_emails | [
"def",
"find_user_emails",
"(",
"self",
",",
"user",
")",
":",
"user_emails",
"=",
"self",
".",
"db_adapter",
".",
"find_objects",
"(",
"self",
".",
"UserEmailClass",
",",
"user_id",
"=",
"user",
".",
"id",
")",
"return",
"user_emails"
] | Find all the UserEmail object belonging to a user. | [
"Find",
"all",
"the",
"UserEmail",
"object",
"belonging",
"to",
"a",
"user",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L140-L143 |
229,315 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.get_user_and_user_email_by_id | def get_user_and_user_email_by_id(self, user_or_user_email_id):
"""Retrieve the User and UserEmail object by ID."""
if self.UserEmailClass:
user_email = self.db_adapter.get_object(self.UserEmailClass, user_or_user_email_id)
user = user_email.user if user_email else None
else:
user = self.db_adapter.get_object(self.UserClass, user_or_user_email_id)
user_email = user
return (user, user_email) | python | def get_user_and_user_email_by_id(self, user_or_user_email_id):
if self.UserEmailClass:
user_email = self.db_adapter.get_object(self.UserEmailClass, user_or_user_email_id)
user = user_email.user if user_email else None
else:
user = self.db_adapter.get_object(self.UserClass, user_or_user_email_id)
user_email = user
return (user, user_email) | [
"def",
"get_user_and_user_email_by_id",
"(",
"self",
",",
"user_or_user_email_id",
")",
":",
"if",
"self",
".",
"UserEmailClass",
":",
"user_email",
"=",
"self",
".",
"db_adapter",
".",
"get_object",
"(",
"self",
".",
"UserEmailClass",
",",
"user_or_user_email_id",
... | Retrieve the User and UserEmail object by ID. | [
"Retrieve",
"the",
"User",
"and",
"UserEmail",
"object",
"by",
"ID",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L157-L165 |
229,316 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.get_user_and_user_email_by_email | def get_user_and_user_email_by_email(self, email):
"""Retrieve the User and UserEmail object by email address."""
if self.UserEmailClass:
user_email = self.db_adapter.ifind_first_object(self.UserEmailClass, email=email)
user = user_email.user if user_email else None
else:
user = self.db_adapter.ifind_first_object(self.UserClass, email=email)
user_email = user
return (user, user_email) | python | def get_user_and_user_email_by_email(self, email):
if self.UserEmailClass:
user_email = self.db_adapter.ifind_first_object(self.UserEmailClass, email=email)
user = user_email.user if user_email else None
else:
user = self.db_adapter.ifind_first_object(self.UserClass, email=email)
user_email = user
return (user, user_email) | [
"def",
"get_user_and_user_email_by_email",
"(",
"self",
",",
"email",
")",
":",
"if",
"self",
".",
"UserEmailClass",
":",
"user_email",
"=",
"self",
".",
"db_adapter",
".",
"ifind_first_object",
"(",
"self",
".",
"UserEmailClass",
",",
"email",
"=",
"email",
"... | Retrieve the User and UserEmail object by email address. | [
"Retrieve",
"the",
"User",
"and",
"UserEmail",
"object",
"by",
"email",
"address",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L167-L175 |
229,317 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.get_user_by_id | def get_user_by_id(self, id):
"""Retrieve a User object by ID."""
return self.db_adapter.get_object(self.UserClass, id=id) | python | def get_user_by_id(self, id):
return self.db_adapter.get_object(self.UserClass, id=id) | [
"def",
"get_user_by_id",
"(",
"self",
",",
"id",
")",
":",
"return",
"self",
".",
"db_adapter",
".",
"get_object",
"(",
"self",
".",
"UserClass",
",",
"id",
"=",
"id",
")"
] | Retrieve a User object by ID. | [
"Retrieve",
"a",
"User",
"object",
"by",
"ID",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L177-L179 |
229,318 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.get_user_invitation_by_id | def get_user_invitation_by_id(self, id):
"""Retrieve a UserInvitation object by ID."""
return self.db_adapter.get_object(self.UserInvitationClass, id=id) | python | def get_user_invitation_by_id(self, id):
return self.db_adapter.get_object(self.UserInvitationClass, id=id) | [
"def",
"get_user_invitation_by_id",
"(",
"self",
",",
"id",
")",
":",
"return",
"self",
".",
"db_adapter",
".",
"get_object",
"(",
"self",
".",
"UserInvitationClass",
",",
"id",
"=",
"id",
")"
] | Retrieve a UserInvitation object by ID. | [
"Retrieve",
"a",
"UserInvitation",
"object",
"by",
"ID",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L185-L187 |
229,319 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.get_user_roles | def get_user_roles(self, user):
"""Retrieve a list of user role names.
.. note::
Database management methods.
"""
# For SQL: user.roles is list of pointers to Role objects
if isinstance(self.db_adapter, SQLDbAdapter):
# user.roles is a list of Role IDs
user_roles = [role.name for role in user.roles]
# For others: user.roles is a list of role names
else:
# user.roles is a list of role names
user_roles = user.roles
return user_roles | python | def get_user_roles(self, user):
# For SQL: user.roles is list of pointers to Role objects
if isinstance(self.db_adapter, SQLDbAdapter):
# user.roles is a list of Role IDs
user_roles = [role.name for role in user.roles]
# For others: user.roles is a list of role names
else:
# user.roles is a list of role names
user_roles = user.roles
return user_roles | [
"def",
"get_user_roles",
"(",
"self",
",",
"user",
")",
":",
"# For SQL: user.roles is list of pointers to Role objects",
"if",
"isinstance",
"(",
"self",
".",
"db_adapter",
",",
"SQLDbAdapter",
")",
":",
"# user.roles is a list of Role IDs",
"user_roles",
"=",
"[",
"ro... | Retrieve a list of user role names.
.. note::
Database management methods. | [
"Retrieve",
"a",
"list",
"of",
"user",
"role",
"names",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L189-L208 |
229,320 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.save_user_and_user_email | def save_user_and_user_email(self, user, user_email):
"""Save the User and UserEmail object."""
if self.UserEmailClass:
self.db_adapter.save_object(user_email)
self.db_adapter.save_object(user) | python | def save_user_and_user_email(self, user, user_email):
if self.UserEmailClass:
self.db_adapter.save_object(user_email)
self.db_adapter.save_object(user) | [
"def",
"save_user_and_user_email",
"(",
"self",
",",
"user",
",",
"user_email",
")",
":",
"if",
"self",
".",
"UserEmailClass",
":",
"self",
".",
"db_adapter",
".",
"save_object",
"(",
"user_email",
")",
"self",
".",
"db_adapter",
".",
"save_object",
"(",
"us... | Save the User and UserEmail object. | [
"Save",
"the",
"User",
"and",
"UserEmail",
"object",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L214-L218 |
229,321 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.user_has_confirmed_email | def user_has_confirmed_email(self, user):
"""| Return True if user has a confirmed email.
| Return False otherwise."""
if not self.user_manager.USER_ENABLE_EMAIL: return True
if not self.user_manager.USER_ENABLE_CONFIRM_EMAIL: return True
db_adapter = self.db_adapter
# Handle multiple emails per user: Find at least one confirmed email
if self.UserEmailClass:
has_confirmed_email = False
user_emails = db_adapter.find_objects(self.UserEmailClass, user_id=user.id)
for user_email in user_emails:
if user_email.email_confirmed_at:
has_confirmed_email = True
break
# Handle single email per user
else:
has_confirmed_email = True if user.email_confirmed_at else False
return has_confirmed_email | python | def user_has_confirmed_email(self, user):
if not self.user_manager.USER_ENABLE_EMAIL: return True
if not self.user_manager.USER_ENABLE_CONFIRM_EMAIL: return True
db_adapter = self.db_adapter
# Handle multiple emails per user: Find at least one confirmed email
if self.UserEmailClass:
has_confirmed_email = False
user_emails = db_adapter.find_objects(self.UserEmailClass, user_id=user.id)
for user_email in user_emails:
if user_email.email_confirmed_at:
has_confirmed_email = True
break
# Handle single email per user
else:
has_confirmed_email = True if user.email_confirmed_at else False
return has_confirmed_email | [
"def",
"user_has_confirmed_email",
"(",
"self",
",",
"user",
")",
":",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_EMAIL",
":",
"return",
"True",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_CONFIRM_EMAIL",
":",
"return",
"True",
... | | Return True if user has a confirmed email.
| Return False otherwise. | [
"|",
"Return",
"True",
"if",
"user",
"has",
"a",
"confirmed",
"email",
".",
"|",
"Return",
"False",
"otherwise",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L220-L241 |
229,322 | lingthio/Flask-User | flask_user/db_manager.py | DBManager.username_is_available | def username_is_available(self, new_username):
"""Check if ``new_username`` is still available.
| Returns True if ``new_username`` does not exist or belongs to the current user.
| Return False otherwise.
"""
# Return True if new_username equals current user's username
if self.user_manager.call_or_get(current_user.is_authenticated):
if new_username == current_user.username:
return True
# Return True if new_username does not exist,
# Return False otherwise.
return self.find_user_by_username(new_username) == None | python | def username_is_available(self, new_username):
# Return True if new_username equals current user's username
if self.user_manager.call_or_get(current_user.is_authenticated):
if new_username == current_user.username:
return True
# Return True if new_username does not exist,
# Return False otherwise.
return self.find_user_by_username(new_username) == None | [
"def",
"username_is_available",
"(",
"self",
",",
"new_username",
")",
":",
"# Return True if new_username equals current user's username",
"if",
"self",
".",
"user_manager",
".",
"call_or_get",
"(",
"current_user",
".",
"is_authenticated",
")",
":",
"if",
"new_username",... | Check if ``new_username`` is still available.
| Returns True if ``new_username`` does not exist or belongs to the current user.
| Return False otherwise. | [
"Check",
"if",
"new_username",
"is",
"still",
"available",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_manager.py#L243-L257 |
229,323 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.change_password_view | def change_password_view(self):
""" Prompt for old password and new password and change the user's password."""
# Initialize form
form = self.ChangePasswordFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Hash password
new_password = form.new_password.data
password_hash = self.hash_password(new_password)
# Update user.password
current_user.password = password_hash
self.db_manager.save_object(current_user)
self.db_manager.commit()
# Send password_changed email
if self.USER_ENABLE_EMAIL and self.USER_SEND_PASSWORD_CHANGED_EMAIL:
self.email_manager.send_password_changed_email(current_user)
# Send changed_password signal
signals.user_changed_password.send(current_app._get_current_object(), user=current_user)
# Flash a system message
flash(_('Your password has been changed successfully.'), 'success')
# Redirect to 'next' URL
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_CHANGE_PASSWORD_ENDPOINT)
return redirect(safe_next_url)
# Render form
self.prepare_domain_translations()
return render_template(self.USER_CHANGE_PASSWORD_TEMPLATE, form=form) | python | def change_password_view(self):
# Initialize form
form = self.ChangePasswordFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Hash password
new_password = form.new_password.data
password_hash = self.hash_password(new_password)
# Update user.password
current_user.password = password_hash
self.db_manager.save_object(current_user)
self.db_manager.commit()
# Send password_changed email
if self.USER_ENABLE_EMAIL and self.USER_SEND_PASSWORD_CHANGED_EMAIL:
self.email_manager.send_password_changed_email(current_user)
# Send changed_password signal
signals.user_changed_password.send(current_app._get_current_object(), user=current_user)
# Flash a system message
flash(_('Your password has been changed successfully.'), 'success')
# Redirect to 'next' URL
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_CHANGE_PASSWORD_ENDPOINT)
return redirect(safe_next_url)
# Render form
self.prepare_domain_translations()
return render_template(self.USER_CHANGE_PASSWORD_TEMPLATE, form=form) | [
"def",
"change_password_view",
"(",
"self",
")",
":",
"# Initialize form",
"form",
"=",
"self",
".",
"ChangePasswordFormClass",
"(",
"request",
".",
"form",
")",
"# Process valid POST",
"if",
"request",
".",
"method",
"==",
"'POST'",
"and",
"form",
".",
"validat... | Prompt for old password and new password and change the user's password. | [
"Prompt",
"for",
"old",
"password",
"and",
"new",
"password",
"and",
"change",
"the",
"user",
"s",
"password",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L88-L121 |
229,324 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.change_username_view | def change_username_view(self):
""" Prompt for new username and old password and change the user's username."""
# Initialize form
form = self.ChangeUsernameFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Change username
new_username = form.new_username.data
current_user.username=new_username
self.db_manager.save_object(current_user)
self.db_manager.commit()
# Send username_changed email
self.email_manager.send_username_changed_email(current_user)
# Send changed_username signal
signals.user_changed_username.send(current_app._get_current_object(), user=current_user)
# Flash a system message
flash(_("Your username has been changed to '%(username)s'.", username=new_username), 'success')
# Redirect to 'next' URL
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_CHANGE_USERNAME_ENDPOINT)
return redirect(safe_next_url)
# Render form
self.prepare_domain_translations()
return render_template(self.USER_CHANGE_USERNAME_TEMPLATE, form=form) | python | def change_username_view(self):
# Initialize form
form = self.ChangeUsernameFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Change username
new_username = form.new_username.data
current_user.username=new_username
self.db_manager.save_object(current_user)
self.db_manager.commit()
# Send username_changed email
self.email_manager.send_username_changed_email(current_user)
# Send changed_username signal
signals.user_changed_username.send(current_app._get_current_object(), user=current_user)
# Flash a system message
flash(_("Your username has been changed to '%(username)s'.", username=new_username), 'success')
# Redirect to 'next' URL
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_CHANGE_USERNAME_ENDPOINT)
return redirect(safe_next_url)
# Render form
self.prepare_domain_translations()
return render_template(self.USER_CHANGE_USERNAME_TEMPLATE, form=form) | [
"def",
"change_username_view",
"(",
"self",
")",
":",
"# Initialize form",
"form",
"=",
"self",
".",
"ChangeUsernameFormClass",
"(",
"request",
".",
"form",
")",
"# Process valid POST",
"if",
"request",
".",
"method",
"==",
"'POST'",
"and",
"form",
".",
"validat... | Prompt for new username and old password and change the user's username. | [
"Prompt",
"for",
"new",
"username",
"and",
"old",
"password",
"and",
"change",
"the",
"user",
"s",
"username",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L125-L155 |
229,325 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.confirm_email_view | def confirm_email_view(self, token):
""" Verify email confirmation token and activate the user account."""
# Verify token
data_items = self.token_manager.verify_token(
token,
self.USER_CONFIRM_EMAIL_EXPIRATION)
# Retrieve user, user_email by ID
user = None
user_email = None
if data_items:
user, user_email = self.db_manager.get_user_and_user_email_by_id(data_items[0])
if not user or not user_email:
flash(_('Invalid confirmation token.'), 'error')
return redirect(url_for('user.login'))
# Set UserEmail.email_confirmed_at
user_email.email_confirmed_at=datetime.utcnow()
self.db_manager.save_user_and_user_email(user, user_email)
self.db_manager.commit()
# Send confirmed_email signal
signals.user_confirmed_email.send(current_app._get_current_object(), user=user)
# Flash a system message
flash(_('Your email has been confirmed.'), 'success')
# Auto-login after confirm or redirect to login page
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_CONFIRM_ENDPOINT)
if self.USER_AUTO_LOGIN_AFTER_CONFIRM:
return self._do_login_user(user, safe_next_url) # auto-login
else:
return redirect(url_for('user.login') + '?next=' + quote(safe_next_url)) | python | def confirm_email_view(self, token):
# Verify token
data_items = self.token_manager.verify_token(
token,
self.USER_CONFIRM_EMAIL_EXPIRATION)
# Retrieve user, user_email by ID
user = None
user_email = None
if data_items:
user, user_email = self.db_manager.get_user_and_user_email_by_id(data_items[0])
if not user or not user_email:
flash(_('Invalid confirmation token.'), 'error')
return redirect(url_for('user.login'))
# Set UserEmail.email_confirmed_at
user_email.email_confirmed_at=datetime.utcnow()
self.db_manager.save_user_and_user_email(user, user_email)
self.db_manager.commit()
# Send confirmed_email signal
signals.user_confirmed_email.send(current_app._get_current_object(), user=user)
# Flash a system message
flash(_('Your email has been confirmed.'), 'success')
# Auto-login after confirm or redirect to login page
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_CONFIRM_ENDPOINT)
if self.USER_AUTO_LOGIN_AFTER_CONFIRM:
return self._do_login_user(user, safe_next_url) # auto-login
else:
return redirect(url_for('user.login') + '?next=' + quote(safe_next_url)) | [
"def",
"confirm_email_view",
"(",
"self",
",",
"token",
")",
":",
"# Verify token",
"data_items",
"=",
"self",
".",
"token_manager",
".",
"verify_token",
"(",
"token",
",",
"self",
".",
"USER_CONFIRM_EMAIL_EXPIRATION",
")",
"# Retrieve user, user_email by ID",
"user",... | Verify email confirmation token and activate the user account. | [
"Verify",
"email",
"confirmation",
"token",
"and",
"activate",
"the",
"user",
"account",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L158-L191 |
229,326 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.email_action_view | def email_action_view(self, id, action):
""" Perform action 'action' on UserEmail object 'id'
"""
# Retrieve UserEmail by id
user_email = self.db_manager.get_user_email_by_id(id=id)
# Users may only change their own UserEmails
if not user_email or user_email.user_id != current_user.id:
return self.unauthorized_view()
# Delete UserEmail
if action == 'delete':
# Primary UserEmail can not be deleted
if user_email.is_primary:
return self.unauthorized_view()
# Delete UserEmail
self.db_manager.delete_object(user_email)
self.db_manager.commit()
# Set UserEmail.is_primary
elif action == 'make-primary':
# Disable previously primary emails
user_emails = self.db_manager.find_user_emails(current_user)
for other_user_email in user_emails:
if other_user_email.is_primary:
other_user_email.is_primary=False
self.db_manager.save_object(other_user_email)
# Enable current primary email
user_email.is_primary=True
self.db_manager.save_object(user_email)
self.db_manager.commit()
# Send confirm email
elif action == 'confirm':
self._send_confirm_email_email(user_email.user, user_email)
else:
return self.unauthorized_view()
return redirect(url_for('user.manage_emails')) | python | def email_action_view(self, id, action):
# Retrieve UserEmail by id
user_email = self.db_manager.get_user_email_by_id(id=id)
# Users may only change their own UserEmails
if not user_email or user_email.user_id != current_user.id:
return self.unauthorized_view()
# Delete UserEmail
if action == 'delete':
# Primary UserEmail can not be deleted
if user_email.is_primary:
return self.unauthorized_view()
# Delete UserEmail
self.db_manager.delete_object(user_email)
self.db_manager.commit()
# Set UserEmail.is_primary
elif action == 'make-primary':
# Disable previously primary emails
user_emails = self.db_manager.find_user_emails(current_user)
for other_user_email in user_emails:
if other_user_email.is_primary:
other_user_email.is_primary=False
self.db_manager.save_object(other_user_email)
# Enable current primary email
user_email.is_primary=True
self.db_manager.save_object(user_email)
self.db_manager.commit()
# Send confirm email
elif action == 'confirm':
self._send_confirm_email_email(user_email.user, user_email)
else:
return self.unauthorized_view()
return redirect(url_for('user.manage_emails')) | [
"def",
"email_action_view",
"(",
"self",
",",
"id",
",",
"action",
")",
":",
"# Retrieve UserEmail by id",
"user_email",
"=",
"self",
".",
"db_manager",
".",
"get_user_email_by_id",
"(",
"id",
"=",
"id",
")",
"# Users may only change their own UserEmails",
"if",
"no... | Perform action 'action' on UserEmail object 'id' | [
"Perform",
"action",
"action",
"on",
"UserEmail",
"object",
"id"
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L215-L254 |
229,327 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.forgot_password_view | def forgot_password_view(self):
"""Prompt for email and send reset password email."""
# Initialize form
form = self.ForgotPasswordFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Get User and UserEmail by email
email = form.email.data
user, user_email = self.db_manager.get_user_and_user_email_by_email(email)
if user and user_email:
# Send reset_password email
self.email_manager.send_reset_password_email(user, user_email)
# Send forgot_password signal
signals.user_forgot_password.send(current_app._get_current_object(), user=user)
# Flash a system message
flash(_(
"A reset password email has been sent to '%(email)s'. Open that email and follow the instructions to reset your password.",
email=email), 'success')
# Redirect to the login page
return redirect(self._endpoint_url(self.USER_AFTER_FORGOT_PASSWORD_ENDPOINT))
# Render form
self.prepare_domain_translations()
return render_template(self.USER_FORGOT_PASSWORD_TEMPLATE, form=form) | python | def forgot_password_view(self):
# Initialize form
form = self.ForgotPasswordFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Get User and UserEmail by email
email = form.email.data
user, user_email = self.db_manager.get_user_and_user_email_by_email(email)
if user and user_email:
# Send reset_password email
self.email_manager.send_reset_password_email(user, user_email)
# Send forgot_password signal
signals.user_forgot_password.send(current_app._get_current_object(), user=user)
# Flash a system message
flash(_(
"A reset password email has been sent to '%(email)s'. Open that email and follow the instructions to reset your password.",
email=email), 'success')
# Redirect to the login page
return redirect(self._endpoint_url(self.USER_AFTER_FORGOT_PASSWORD_ENDPOINT))
# Render form
self.prepare_domain_translations()
return render_template(self.USER_FORGOT_PASSWORD_TEMPLATE, form=form) | [
"def",
"forgot_password_view",
"(",
"self",
")",
":",
"# Initialize form",
"form",
"=",
"self",
".",
"ForgotPasswordFormClass",
"(",
"request",
".",
"form",
")",
"# Process valid POST",
"if",
"request",
".",
"method",
"==",
"'POST'",
"and",
"form",
".",
"validat... | Prompt for email and send reset password email. | [
"Prompt",
"for",
"email",
"and",
"send",
"reset",
"password",
"email",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L257-L286 |
229,328 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.invite_user_view | def invite_user_view(self):
""" Allows users to send invitations to register an account """
invite_user_form = self.InviteUserFormClass(request.form)
if request.method == 'POST' and invite_user_form.validate():
# Find User and UserEmail by email
email = invite_user_form.email.data
user, user_email = self.db_manager.get_user_and_user_email_by_email(email)
if user:
flash("User with that email has already registered", "error")
return redirect(url_for('user.invite_user'))
# Add UserInvitation
user_invitation = self.db_manager.add_user_invitation(
email=email,
invited_by_user_id=current_user.id)
self.db_manager.commit()
try:
# Send invite_user email
self.email_manager.send_invite_user_email(current_user, user_invitation)
except Exception as e:
# delete new UserInvitation object if send fails
self.db_manager.delete_object(user_invitation)
self.db_manager.commit()
raise
# Send sent_invitation signal
signals \
.user_sent_invitation \
.send(current_app._get_current_object(), user_invitation=user_invitation,
form=invite_user_form)
# Flash a system message
flash(_('Invitation has been sent.'), 'success')
# Redirect
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_INVITE_ENDPOINT)
return redirect(safe_next_url)
self.prepare_domain_translations()
return render_template(self.USER_INVITE_USER_TEMPLATE, form=invite_user_form) | python | def invite_user_view(self):
invite_user_form = self.InviteUserFormClass(request.form)
if request.method == 'POST' and invite_user_form.validate():
# Find User and UserEmail by email
email = invite_user_form.email.data
user, user_email = self.db_manager.get_user_and_user_email_by_email(email)
if user:
flash("User with that email has already registered", "error")
return redirect(url_for('user.invite_user'))
# Add UserInvitation
user_invitation = self.db_manager.add_user_invitation(
email=email,
invited_by_user_id=current_user.id)
self.db_manager.commit()
try:
# Send invite_user email
self.email_manager.send_invite_user_email(current_user, user_invitation)
except Exception as e:
# delete new UserInvitation object if send fails
self.db_manager.delete_object(user_invitation)
self.db_manager.commit()
raise
# Send sent_invitation signal
signals \
.user_sent_invitation \
.send(current_app._get_current_object(), user_invitation=user_invitation,
form=invite_user_form)
# Flash a system message
flash(_('Invitation has been sent.'), 'success')
# Redirect
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_INVITE_ENDPOINT)
return redirect(safe_next_url)
self.prepare_domain_translations()
return render_template(self.USER_INVITE_USER_TEMPLATE, form=invite_user_form) | [
"def",
"invite_user_view",
"(",
"self",
")",
":",
"invite_user_form",
"=",
"self",
".",
"InviteUserFormClass",
"(",
"request",
".",
"form",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
"and",
"invite_user_form",
".",
"validate",
"(",
")",
":",
"# Fin... | Allows users to send invitations to register an account | [
"Allows",
"users",
"to",
"send",
"invitations",
"to",
"register",
"an",
"account"
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L313-L355 |
229,329 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.login_view | def login_view(self):
"""Prepare and process the login form."""
# Authenticate username/email and login authenticated users.
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGIN_ENDPOINT)
safe_reg_next = self._get_safe_next_url('reg_next', self.USER_AFTER_REGISTER_ENDPOINT)
# Immediately redirect already logged in users
if self.call_or_get(current_user.is_authenticated) and self.USER_AUTO_LOGIN_AT_LOGIN:
return redirect(safe_next_url)
# Initialize form
login_form = self.LoginFormClass(request.form) # for login.html
register_form = self.RegisterFormClass() # for login_or_register.html
if request.method != 'POST':
login_form.next.data = register_form.next.data = safe_next_url
login_form.reg_next.data = register_form.reg_next.data = safe_reg_next
# Process valid POST
if request.method == 'POST' and login_form.validate():
# Retrieve User
user = None
user_email = None
if self.USER_ENABLE_USERNAME:
# Find user record by username
user = self.db_manager.find_user_by_username(login_form.username.data)
# Find user record by email (with form.username)
if not user and self.USER_ENABLE_EMAIL:
user, user_email = self.db_manager.get_user_and_user_email_by_email(login_form.username.data)
else:
# Find user by email (with form.email)
user, user_email = self.db_manager.get_user_and_user_email_by_email(login_form.email.data)
if user:
# Log user in
safe_next_url = self.make_safe_url(login_form.next.data)
return self._do_login_user(user, safe_next_url, login_form.remember_me.data)
# Render form
self.prepare_domain_translations()
template_filename = self.USER_LOGIN_AUTH0_TEMPLATE if self.USER_ENABLE_AUTH0 else self.USER_LOGIN_TEMPLATE
return render_template(template_filename,
form=login_form,
login_form=login_form,
register_form=register_form) | python | def login_view(self):
# Authenticate username/email and login authenticated users.
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGIN_ENDPOINT)
safe_reg_next = self._get_safe_next_url('reg_next', self.USER_AFTER_REGISTER_ENDPOINT)
# Immediately redirect already logged in users
if self.call_or_get(current_user.is_authenticated) and self.USER_AUTO_LOGIN_AT_LOGIN:
return redirect(safe_next_url)
# Initialize form
login_form = self.LoginFormClass(request.form) # for login.html
register_form = self.RegisterFormClass() # for login_or_register.html
if request.method != 'POST':
login_form.next.data = register_form.next.data = safe_next_url
login_form.reg_next.data = register_form.reg_next.data = safe_reg_next
# Process valid POST
if request.method == 'POST' and login_form.validate():
# Retrieve User
user = None
user_email = None
if self.USER_ENABLE_USERNAME:
# Find user record by username
user = self.db_manager.find_user_by_username(login_form.username.data)
# Find user record by email (with form.username)
if not user and self.USER_ENABLE_EMAIL:
user, user_email = self.db_manager.get_user_and_user_email_by_email(login_form.username.data)
else:
# Find user by email (with form.email)
user, user_email = self.db_manager.get_user_and_user_email_by_email(login_form.email.data)
if user:
# Log user in
safe_next_url = self.make_safe_url(login_form.next.data)
return self._do_login_user(user, safe_next_url, login_form.remember_me.data)
# Render form
self.prepare_domain_translations()
template_filename = self.USER_LOGIN_AUTH0_TEMPLATE if self.USER_ENABLE_AUTH0 else self.USER_LOGIN_TEMPLATE
return render_template(template_filename,
form=login_form,
login_form=login_form,
register_form=register_form) | [
"def",
"login_view",
"(",
"self",
")",
":",
"# Authenticate username/email and login authenticated users.",
"safe_next_url",
"=",
"self",
".",
"_get_safe_next_url",
"(",
"'next'",
",",
"self",
".",
"USER_AFTER_LOGIN_ENDPOINT",
")",
"safe_reg_next",
"=",
"self",
".",
"_g... | Prepare and process the login form. | [
"Prepare",
"and",
"process",
"the",
"login",
"form",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L358-L404 |
229,330 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.logout_view | def logout_view(self):
"""Process the logout link."""
""" Sign the user out."""
# Send user_logged_out signal
signals.user_logged_out.send(current_app._get_current_object(), user=current_user)
# Use Flask-Login to sign out user
logout_user()
# Flash a system message
flash(_('You have signed out successfully.'), 'success')
# Redirect to logout_next endpoint or '/'
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGOUT_ENDPOINT)
return redirect(safe_next_url) | python | def logout_view(self):
""" Sign the user out."""
# Send user_logged_out signal
signals.user_logged_out.send(current_app._get_current_object(), user=current_user)
# Use Flask-Login to sign out user
logout_user()
# Flash a system message
flash(_('You have signed out successfully.'), 'success')
# Redirect to logout_next endpoint or '/'
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGOUT_ENDPOINT)
return redirect(safe_next_url) | [
"def",
"logout_view",
"(",
"self",
")",
":",
"\"\"\" Sign the user out.\"\"\"",
"# Send user_logged_out signal",
"signals",
".",
"user_logged_out",
".",
"send",
"(",
"current_app",
".",
"_get_current_object",
"(",
")",
",",
"user",
"=",
"current_user",
")",
"# Use Fla... | Process the logout link. | [
"Process",
"the",
"logout",
"link",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L406-L421 |
229,331 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.register_view | def register_view(self):
""" Display registration form and create new User."""
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGIN_ENDPOINT)
safe_reg_next_url = self._get_safe_next_url('reg_next', self.USER_AFTER_REGISTER_ENDPOINT)
# Initialize form
login_form = self.LoginFormClass() # for login_or_register.html
register_form = self.RegisterFormClass(request.form) # for register.html
# invite token used to determine validity of registeree
invite_token = request.values.get("token")
# require invite without a token should disallow the user from registering
if self.USER_REQUIRE_INVITATION and not invite_token:
flash("Registration is invite only", "error")
return redirect(url_for('user.login'))
user_invitation = None
if invite_token and self.db_manager.UserInvitationClass:
data_items = self.token_manager.verify_token(invite_token, self.USER_INVITE_EXPIRATION)
if data_items:
user_invitation_id = data_items[0]
user_invitation = self.db_manager.get_user_invitation_by_id(user_invitation_id)
if not user_invitation:
flash("Invalid invitation token", "error")
return redirect(url_for('user.login'))
register_form.invite_token.data = invite_token
if request.method != 'POST':
login_form.next.data = register_form.next.data = safe_next_url
login_form.reg_next.data = register_form.reg_next.data = safe_reg_next_url
if user_invitation:
register_form.email.data = user_invitation.email
# Process valid POST
if request.method == 'POST' and register_form.validate():
user = self.db_manager.add_user()
register_form.populate_obj(user)
user_email = self.db_manager.add_user_email(user=user, is_primary=True)
register_form.populate_obj(user_email)
# Store password hash instead of password
user.password = self.hash_password(user.password)
# Email confirmation depends on the USER_ENABLE_CONFIRM_EMAIL setting
request_email_confirmation = self.USER_ENABLE_CONFIRM_EMAIL
# Users that register through an invitation, can skip this process
# but only when they register with an email that matches their invitation.
if user_invitation:
if user_invitation.email.lower() == register_form.email.data.lower():
user_email.email_confirmed_at=datetime.utcnow()
request_email_confirmation = False
self.db_manager.save_user_and_user_email(user, user_email)
self.db_manager.commit()
# Send 'registered' email and delete new User object if send fails
if self.USER_SEND_REGISTERED_EMAIL:
try:
# Send 'confirm email' or 'registered' email
self._send_registered_email(user, user_email, request_email_confirmation)
except Exception as e:
# delete new User object if send fails
self.db_manager.delete_object(user)
self.db_manager.commit()
raise
# Send user_registered signal
signals.user_registered.send(current_app._get_current_object(),
user=user,
user_invitation=user_invitation)
# Redirect if USER_ENABLE_CONFIRM_EMAIL is set
if self.USER_ENABLE_CONFIRM_EMAIL and request_email_confirmation:
safe_reg_next_url = self.make_safe_url(register_form.reg_next.data)
return redirect(safe_reg_next_url)
# Auto-login after register or redirect to login page
if 'reg_next' in request.args:
safe_reg_next_url = self.make_safe_url(register_form.reg_next.data)
else:
safe_reg_next_url = self._endpoint_url(self.USER_AFTER_CONFIRM_ENDPOINT)
if self.USER_AUTO_LOGIN_AFTER_REGISTER:
return self._do_login_user(user, safe_reg_next_url) # auto-login
else:
return redirect(url_for('user.login') + '?next=' + quote(safe_reg_next_url)) # redirect to login page
# Render form
self.prepare_domain_translations()
return render_template(self.USER_REGISTER_TEMPLATE,
form=register_form,
login_form=login_form,
register_form=register_form) | python | def register_view(self):
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_LOGIN_ENDPOINT)
safe_reg_next_url = self._get_safe_next_url('reg_next', self.USER_AFTER_REGISTER_ENDPOINT)
# Initialize form
login_form = self.LoginFormClass() # for login_or_register.html
register_form = self.RegisterFormClass(request.form) # for register.html
# invite token used to determine validity of registeree
invite_token = request.values.get("token")
# require invite without a token should disallow the user from registering
if self.USER_REQUIRE_INVITATION and not invite_token:
flash("Registration is invite only", "error")
return redirect(url_for('user.login'))
user_invitation = None
if invite_token and self.db_manager.UserInvitationClass:
data_items = self.token_manager.verify_token(invite_token, self.USER_INVITE_EXPIRATION)
if data_items:
user_invitation_id = data_items[0]
user_invitation = self.db_manager.get_user_invitation_by_id(user_invitation_id)
if not user_invitation:
flash("Invalid invitation token", "error")
return redirect(url_for('user.login'))
register_form.invite_token.data = invite_token
if request.method != 'POST':
login_form.next.data = register_form.next.data = safe_next_url
login_form.reg_next.data = register_form.reg_next.data = safe_reg_next_url
if user_invitation:
register_form.email.data = user_invitation.email
# Process valid POST
if request.method == 'POST' and register_form.validate():
user = self.db_manager.add_user()
register_form.populate_obj(user)
user_email = self.db_manager.add_user_email(user=user, is_primary=True)
register_form.populate_obj(user_email)
# Store password hash instead of password
user.password = self.hash_password(user.password)
# Email confirmation depends on the USER_ENABLE_CONFIRM_EMAIL setting
request_email_confirmation = self.USER_ENABLE_CONFIRM_EMAIL
# Users that register through an invitation, can skip this process
# but only when they register with an email that matches their invitation.
if user_invitation:
if user_invitation.email.lower() == register_form.email.data.lower():
user_email.email_confirmed_at=datetime.utcnow()
request_email_confirmation = False
self.db_manager.save_user_and_user_email(user, user_email)
self.db_manager.commit()
# Send 'registered' email and delete new User object if send fails
if self.USER_SEND_REGISTERED_EMAIL:
try:
# Send 'confirm email' or 'registered' email
self._send_registered_email(user, user_email, request_email_confirmation)
except Exception as e:
# delete new User object if send fails
self.db_manager.delete_object(user)
self.db_manager.commit()
raise
# Send user_registered signal
signals.user_registered.send(current_app._get_current_object(),
user=user,
user_invitation=user_invitation)
# Redirect if USER_ENABLE_CONFIRM_EMAIL is set
if self.USER_ENABLE_CONFIRM_EMAIL and request_email_confirmation:
safe_reg_next_url = self.make_safe_url(register_form.reg_next.data)
return redirect(safe_reg_next_url)
# Auto-login after register or redirect to login page
if 'reg_next' in request.args:
safe_reg_next_url = self.make_safe_url(register_form.reg_next.data)
else:
safe_reg_next_url = self._endpoint_url(self.USER_AFTER_CONFIRM_ENDPOINT)
if self.USER_AUTO_LOGIN_AFTER_REGISTER:
return self._do_login_user(user, safe_reg_next_url) # auto-login
else:
return redirect(url_for('user.login') + '?next=' + quote(safe_reg_next_url)) # redirect to login page
# Render form
self.prepare_domain_translations()
return render_template(self.USER_REGISTER_TEMPLATE,
form=register_form,
login_form=login_form,
register_form=register_form) | [
"def",
"register_view",
"(",
"self",
")",
":",
"safe_next_url",
"=",
"self",
".",
"_get_safe_next_url",
"(",
"'next'",
",",
"self",
".",
"USER_AFTER_LOGIN_ENDPOINT",
")",
"safe_reg_next_url",
"=",
"self",
".",
"_get_safe_next_url",
"(",
"'reg_next'",
",",
"self",
... | Display registration form and create new User. | [
"Display",
"registration",
"form",
"and",
"create",
"new",
"User",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L423-L518 |
229,332 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.resend_email_confirmation_view | def resend_email_confirmation_view(self):
"""Prompt for email and re-send email conformation email."""
# Initialize form
form = self.ResendEmailConfirmationFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Find user by email
email = form.email.data
user, user_email = self.db_manager.get_user_and_user_email_by_email(email)
# Send confirm_email email
if user:
self._send_confirm_email_email(user, user_email)
# Redirect to the login page
return redirect(self._endpoint_url(self.USER_AFTER_RESEND_EMAIL_CONFIRMATION_ENDPOINT))
# Render form
self.prepare_domain_translations()
return render_template(self.USER_RESEND_CONFIRM_EMAIL_TEMPLATE, form=form) | python | def resend_email_confirmation_view(self):
# Initialize form
form = self.ResendEmailConfirmationFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Find user by email
email = form.email.data
user, user_email = self.db_manager.get_user_and_user_email_by_email(email)
# Send confirm_email email
if user:
self._send_confirm_email_email(user, user_email)
# Redirect to the login page
return redirect(self._endpoint_url(self.USER_AFTER_RESEND_EMAIL_CONFIRMATION_ENDPOINT))
# Render form
self.prepare_domain_translations()
return render_template(self.USER_RESEND_CONFIRM_EMAIL_TEMPLATE, form=form) | [
"def",
"resend_email_confirmation_view",
"(",
"self",
")",
":",
"# Initialize form",
"form",
"=",
"self",
".",
"ResendEmailConfirmationFormClass",
"(",
"request",
".",
"form",
")",
"# Process valid POST",
"if",
"request",
".",
"method",
"==",
"'POST'",
"and",
"form"... | Prompt for email and re-send email conformation email. | [
"Prompt",
"for",
"email",
"and",
"re",
"-",
"send",
"email",
"conformation",
"email",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L521-L543 |
229,333 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.reset_password_view | def reset_password_view(self, token):
""" Verify the password reset token, Prompt for new password, and set the user's password."""
# Verify token
if self.call_or_get(current_user.is_authenticated):
logout_user()
data_items = self.token_manager.verify_token(
token,
self.USER_RESET_PASSWORD_EXPIRATION)
user = None
if data_items:
# Get User by user ID
user_id = data_items[0]
user = self.db_manager.get_user_by_id(user_id)
# Mark email as confirmed
user_or_user_email_object = self.db_manager.get_primary_user_email_object(user)
user_or_user_email_object.email_confirmed_at = datetime.utcnow()
self.db_manager.save_object(user_or_user_email_object)
self.db_manager.commit()
if not user:
flash(_('Your reset password token is invalid.'), 'error')
return redirect(self._endpoint_url('user.login'))
# Initialize form
form = self.ResetPasswordFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Change password
password_hash = self.hash_password(form.new_password.data)
user.password=password_hash
self.db_manager.save_object(user)
self.db_manager.commit()
# Send 'password_changed' email
if self.USER_ENABLE_EMAIL and self.USER_SEND_PASSWORD_CHANGED_EMAIL:
self.email_manager.send_password_changed_email(user)
# Send reset_password signal
signals.user_reset_password.send(current_app._get_current_object(), user=user)
# Flash a system message
flash(_("Your password has been reset successfully."), 'success')
# Auto-login after reset password or redirect to login page
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_RESET_PASSWORD_ENDPOINT)
if self.USER_AUTO_LOGIN_AFTER_RESET_PASSWORD:
return self._do_login_user(user, safe_next_url) # auto-login
else:
return redirect(url_for('user.login') + '?next=' + quote(safe_next_url)) # redirect to login page
# Render form
self.prepare_domain_translations()
return render_template(self.USER_RESET_PASSWORD_TEMPLATE, form=form) | python | def reset_password_view(self, token):
# Verify token
if self.call_or_get(current_user.is_authenticated):
logout_user()
data_items = self.token_manager.verify_token(
token,
self.USER_RESET_PASSWORD_EXPIRATION)
user = None
if data_items:
# Get User by user ID
user_id = data_items[0]
user = self.db_manager.get_user_by_id(user_id)
# Mark email as confirmed
user_or_user_email_object = self.db_manager.get_primary_user_email_object(user)
user_or_user_email_object.email_confirmed_at = datetime.utcnow()
self.db_manager.save_object(user_or_user_email_object)
self.db_manager.commit()
if not user:
flash(_('Your reset password token is invalid.'), 'error')
return redirect(self._endpoint_url('user.login'))
# Initialize form
form = self.ResetPasswordFormClass(request.form)
# Process valid POST
if request.method == 'POST' and form.validate():
# Change password
password_hash = self.hash_password(form.new_password.data)
user.password=password_hash
self.db_manager.save_object(user)
self.db_manager.commit()
# Send 'password_changed' email
if self.USER_ENABLE_EMAIL and self.USER_SEND_PASSWORD_CHANGED_EMAIL:
self.email_manager.send_password_changed_email(user)
# Send reset_password signal
signals.user_reset_password.send(current_app._get_current_object(), user=user)
# Flash a system message
flash(_("Your password has been reset successfully."), 'success')
# Auto-login after reset password or redirect to login page
safe_next_url = self._get_safe_next_url('next', self.USER_AFTER_RESET_PASSWORD_ENDPOINT)
if self.USER_AUTO_LOGIN_AFTER_RESET_PASSWORD:
return self._do_login_user(user, safe_next_url) # auto-login
else:
return redirect(url_for('user.login') + '?next=' + quote(safe_next_url)) # redirect to login page
# Render form
self.prepare_domain_translations()
return render_template(self.USER_RESET_PASSWORD_TEMPLATE, form=form) | [
"def",
"reset_password_view",
"(",
"self",
",",
"token",
")",
":",
"# Verify token",
"if",
"self",
".",
"call_or_get",
"(",
"current_user",
".",
"is_authenticated",
")",
":",
"logout_user",
"(",
")",
"data_items",
"=",
"self",
".",
"token_manager",
".",
"verif... | Verify the password reset token, Prompt for new password, and set the user's password. | [
"Verify",
"the",
"password",
"reset",
"token",
"Prompt",
"for",
"new",
"password",
"and",
"set",
"the",
"user",
"s",
"password",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L546-L604 |
229,334 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.unauthenticated_view | def unauthenticated_view(self):
""" Prepare a Flash message and redirect to USER_UNAUTHENTICATED_ENDPOINT"""
# Prepare Flash message
url = request.url
flash(_("You must be signed in to access '%(url)s'.", url=url), 'error')
# Redirect to USER_UNAUTHENTICATED_ENDPOINT
safe_next_url = self.make_safe_url(url)
return redirect(self._endpoint_url(self.USER_UNAUTHENTICATED_ENDPOINT)+'?next='+quote(safe_next_url)) | python | def unauthenticated_view(self):
# Prepare Flash message
url = request.url
flash(_("You must be signed in to access '%(url)s'.", url=url), 'error')
# Redirect to USER_UNAUTHENTICATED_ENDPOINT
safe_next_url = self.make_safe_url(url)
return redirect(self._endpoint_url(self.USER_UNAUTHENTICATED_ENDPOINT)+'?next='+quote(safe_next_url)) | [
"def",
"unauthenticated_view",
"(",
"self",
")",
":",
"# Prepare Flash message",
"url",
"=",
"request",
".",
"url",
"flash",
"(",
"_",
"(",
"\"You must be signed in to access '%(url)s'.\"",
",",
"url",
"=",
"url",
")",
",",
"'error'",
")",
"# Redirect to USER_UNAUTH... | Prepare a Flash message and redirect to USER_UNAUTHENTICATED_ENDPOINT | [
"Prepare",
"a",
"Flash",
"message",
"and",
"redirect",
"to",
"USER_UNAUTHENTICATED_ENDPOINT"
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L606-L614 |
229,335 | lingthio/Flask-User | flask_user/user_manager__views.py | UserManager__Views.unauthorized_view | def unauthorized_view(self):
""" Prepare a Flash message and redirect to USER_UNAUTHORIZED_ENDPOINT"""
# Prepare Flash message
url = request.script_root + request.path
flash(_("You do not have permission to access '%(url)s'.", url=url), 'error')
# Redirect to USER_UNAUTHORIZED_ENDPOINT
return redirect(self._endpoint_url(self.USER_UNAUTHORIZED_ENDPOINT)) | python | def unauthorized_view(self):
# Prepare Flash message
url = request.script_root + request.path
flash(_("You do not have permission to access '%(url)s'.", url=url), 'error')
# Redirect to USER_UNAUTHORIZED_ENDPOINT
return redirect(self._endpoint_url(self.USER_UNAUTHORIZED_ENDPOINT)) | [
"def",
"unauthorized_view",
"(",
"self",
")",
":",
"# Prepare Flash message",
"url",
"=",
"request",
".",
"script_root",
"+",
"request",
".",
"path",
"flash",
"(",
"_",
"(",
"\"You do not have permission to access '%(url)s'.\"",
",",
"url",
"=",
"url",
")",
",",
... | Prepare a Flash message and redirect to USER_UNAUTHORIZED_ENDPOINT | [
"Prepare",
"a",
"Flash",
"message",
"and",
"redirect",
"to",
"USER_UNAUTHORIZED_ENDPOINT"
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__views.py#L617-L624 |
229,336 | lingthio/Flask-User | flask_user/decorators.py | _is_logged_in_with_confirmed_email | def _is_logged_in_with_confirmed_email(user_manager):
"""| Returns True if user is logged in and has a confirmed email address.
| Returns False otherwise.
"""
# User must be logged in
if user_manager.call_or_get(current_user.is_authenticated):
# Is unconfirmed email allowed for this view by @allow_unconfirmed_email?
unconfirmed_email_allowed = \
getattr(g, '_flask_user_allow_unconfirmed_email', False)
# unconfirmed_email_allowed must be True or
# User must have at least one confirmed email address
if unconfirmed_email_allowed or user_manager.db_manager.user_has_confirmed_email(current_user):
return True
return False | python | def _is_logged_in_with_confirmed_email(user_manager):
# User must be logged in
if user_manager.call_or_get(current_user.is_authenticated):
# Is unconfirmed email allowed for this view by @allow_unconfirmed_email?
unconfirmed_email_allowed = \
getattr(g, '_flask_user_allow_unconfirmed_email', False)
# unconfirmed_email_allowed must be True or
# User must have at least one confirmed email address
if unconfirmed_email_allowed or user_manager.db_manager.user_has_confirmed_email(current_user):
return True
return False | [
"def",
"_is_logged_in_with_confirmed_email",
"(",
"user_manager",
")",
":",
"# User must be logged in",
"if",
"user_manager",
".",
"call_or_get",
"(",
"current_user",
".",
"is_authenticated",
")",
":",
"# Is unconfirmed email allowed for this view by @allow_unconfirmed_email?",
"... | | Returns True if user is logged in and has a confirmed email address.
| Returns False otherwise. | [
"|",
"Returns",
"True",
"if",
"user",
"is",
"logged",
"in",
"and",
"has",
"a",
"confirmed",
"email",
"address",
".",
"|",
"Returns",
"False",
"otherwise",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/decorators.py#L12-L27 |
229,337 | lingthio/Flask-User | flask_user/decorators.py | login_required | def login_required(view_function):
""" This decorator ensures that the current user is logged in.
Example::
@route('/member_page')
@login_required
def member_page(): # User must be logged in
...
If USER_ENABLE_EMAIL is True and USER_ENABLE_CONFIRM_EMAIL is True,
this view decorator also ensures that the user has a confirmed email address.
| Calls unauthorized_view() when the user is not logged in
or when the user has not confirmed their email address.
| Calls the decorated view otherwise.
"""
@wraps(view_function) # Tells debuggers that is is a function wrapper
def decorator(*args, **kwargs):
user_manager = current_app.user_manager
# User must be logged in with a confirmed email address
allowed = _is_logged_in_with_confirmed_email(user_manager)
if not allowed:
# Redirect to unauthenticated page
return user_manager.unauthenticated_view()
# It's OK to call the view
return view_function(*args, **kwargs)
return decorator | python | def login_required(view_function):
@wraps(view_function) # Tells debuggers that is is a function wrapper
def decorator(*args, **kwargs):
user_manager = current_app.user_manager
# User must be logged in with a confirmed email address
allowed = _is_logged_in_with_confirmed_email(user_manager)
if not allowed:
# Redirect to unauthenticated page
return user_manager.unauthenticated_view()
# It's OK to call the view
return view_function(*args, **kwargs)
return decorator | [
"def",
"login_required",
"(",
"view_function",
")",
":",
"@",
"wraps",
"(",
"view_function",
")",
"# Tells debuggers that is is a function wrapper",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"user_manager",
"=",
"current_app",
".",
... | This decorator ensures that the current user is logged in.
Example::
@route('/member_page')
@login_required
def member_page(): # User must be logged in
...
If USER_ENABLE_EMAIL is True and USER_ENABLE_CONFIRM_EMAIL is True,
this view decorator also ensures that the user has a confirmed email address.
| Calls unauthorized_view() when the user is not logged in
or when the user has not confirmed their email address.
| Calls the decorated view otherwise. | [
"This",
"decorator",
"ensures",
"that",
"the",
"current",
"user",
"is",
"logged",
"in",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/decorators.py#L30-L60 |
229,338 | lingthio/Flask-User | flask_user/decorators.py | allow_unconfirmed_email | def allow_unconfirmed_email(view_function):
""" This decorator ensures that the user is logged in,
but allows users with or without a confirmed email addresses
to access this particular view.
It works in tandem with the ``USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL=True`` setting.
.. caution::
| Use ``USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL=True`` and
``@allow_unconfirmed_email`` with caution,
as they relax security requirements.
| Make sure that decorated views **never call other views directly**.
Allways use ``redirect()`` to ensure proper view protection.
Example::
@route('/show_promotion')
@allow_unconfirmed_emails
def show_promotion(): # Logged in, with or without
... # confirmed email address
It can also precede the ``@roles_required`` and ``@roles_accepted`` view decorators::
@route('/show_promotion')
@allow_unconfirmed_emails
@roles_required('Visitor')
def show_promotion(): # Logged in, with or without
... # confirmed email address
| Calls unauthorized_view() when the user is not logged in.
| Calls the decorated view otherwise.
"""
@wraps(view_function) # Tells debuggers that is is a function wrapper
def decorator(*args, **kwargs):
# Sets a boolean on the global request context
g._flask_user_allow_unconfirmed_email = True
# Catch exceptions to properly unset boolean on exceptions
try:
user_manager = current_app.user_manager
# User must be logged in with a confirmed email address
allowed = _is_logged_in_with_confirmed_email(user_manager)
if not allowed:
# Redirect to unauthenticated page
return user_manager.unauthenticated_view()
# It's OK to call the view
return view_function(*args, **kwargs)
finally:
# Allways unset the boolean, whether exceptions occurred or not
g._flask_user_allow_unconfirmed_email = False
return decorator | python | def allow_unconfirmed_email(view_function):
@wraps(view_function) # Tells debuggers that is is a function wrapper
def decorator(*args, **kwargs):
# Sets a boolean on the global request context
g._flask_user_allow_unconfirmed_email = True
# Catch exceptions to properly unset boolean on exceptions
try:
user_manager = current_app.user_manager
# User must be logged in with a confirmed email address
allowed = _is_logged_in_with_confirmed_email(user_manager)
if not allowed:
# Redirect to unauthenticated page
return user_manager.unauthenticated_view()
# It's OK to call the view
return view_function(*args, **kwargs)
finally:
# Allways unset the boolean, whether exceptions occurred or not
g._flask_user_allow_unconfirmed_email = False
return decorator | [
"def",
"allow_unconfirmed_email",
"(",
"view_function",
")",
":",
"@",
"wraps",
"(",
"view_function",
")",
"# Tells debuggers that is is a function wrapper",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Sets a boolean on the global request... | This decorator ensures that the user is logged in,
but allows users with or without a confirmed email addresses
to access this particular view.
It works in tandem with the ``USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL=True`` setting.
.. caution::
| Use ``USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL=True`` and
``@allow_unconfirmed_email`` with caution,
as they relax security requirements.
| Make sure that decorated views **never call other views directly**.
Allways use ``redirect()`` to ensure proper view protection.
Example::
@route('/show_promotion')
@allow_unconfirmed_emails
def show_promotion(): # Logged in, with or without
... # confirmed email address
It can also precede the ``@roles_required`` and ``@roles_accepted`` view decorators::
@route('/show_promotion')
@allow_unconfirmed_emails
@roles_required('Visitor')
def show_promotion(): # Logged in, with or without
... # confirmed email address
| Calls unauthorized_view() when the user is not logged in.
| Calls the decorated view otherwise. | [
"This",
"decorator",
"ensures",
"that",
"the",
"user",
"is",
"logged",
"in",
"but",
"allows",
"users",
"with",
"or",
"without",
"a",
"confirmed",
"email",
"addresses",
"to",
"access",
"this",
"particular",
"view",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/decorators.py#L151-L207 |
229,339 | lingthio/Flask-User | flask_user/token_manager.py | TokenManager.verify_token | def verify_token(self, token, expiration_in_seconds=None):
""" Verify token signature, verify token expiration, and decrypt token.
| Returns None if token is expired or invalid.
| Returns a list of strings and integers on success.
Implemented as::
concatenated_str = self.decrypt_string(token, expiration_in_seconds)
data_items = self.decode_data_items(concatenated_str)
return data_items
Example:
::
# Verify that a User with ``user_id`` has a password that ends in ``password_ends_with``.
token_is_valid = False
data_items = token_manager.verify(token, expiration_in_seconds)
if data_items:
user_id = data_items[0]
password_ends_with = data_items[1]
user = user_manager.db_manager.get_user_by_id(user_id)
token_is_valid = user and user.password[-8:]==password_ends_with
"""
from cryptography.fernet import InvalidToken
try:
concatenated_str = self.decrypt_string(token, expiration_in_seconds)
data_items = self.decode_data_items(concatenated_str)
except InvalidToken:
data_items = None
return data_items | python | def verify_token(self, token, expiration_in_seconds=None):
from cryptography.fernet import InvalidToken
try:
concatenated_str = self.decrypt_string(token, expiration_in_seconds)
data_items = self.decode_data_items(concatenated_str)
except InvalidToken:
data_items = None
return data_items | [
"def",
"verify_token",
"(",
"self",
",",
"token",
",",
"expiration_in_seconds",
"=",
"None",
")",
":",
"from",
"cryptography",
".",
"fernet",
"import",
"InvalidToken",
"try",
":",
"concatenated_str",
"=",
"self",
".",
"decrypt_string",
"(",
"token",
",",
"expi... | Verify token signature, verify token expiration, and decrypt token.
| Returns None if token is expired or invalid.
| Returns a list of strings and integers on success.
Implemented as::
concatenated_str = self.decrypt_string(token, expiration_in_seconds)
data_items = self.decode_data_items(concatenated_str)
return data_items
Example:
::
# Verify that a User with ``user_id`` has a password that ends in ``password_ends_with``.
token_is_valid = False
data_items = token_manager.verify(token, expiration_in_seconds)
if data_items:
user_id = data_items[0]
password_ends_with = data_items[1]
user = user_manager.db_manager.get_user_by_id(user_id)
token_is_valid = user and user.password[-8:]==password_ends_with | [
"Verify",
"token",
"signature",
"verify",
"token",
"expiration",
"and",
"decrypt",
"token",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/token_manager.py#L79-L113 |
229,340 | lingthio/Flask-User | flask_user/token_manager.py | TokenManager.encode_data_items | def encode_data_items(self, *args):
""" Encodes a list of integers and strings into a concatenated string.
- encode string items as-is.
- encode integer items as base-64 with a ``'~'`` prefix.
- concatenate encoded items with a ``'|'`` separator.
Example:
``encode_data_items('abc', 123, 'xyz')`` returns ``'abc|~B7|xyz'``
"""
str_list = []
for arg in args:
# encode string items as-is
if isinstance(arg, str):
arg_str = arg
# encode integer items as base-64 strings with a '~' character in front
elif isinstance(arg, int):
arg_str = self.INTEGER_PREFIX + self.encode_int(arg)
# convert other types to string
else:
arg_str = str(arg)
str_list.append(arg_str)
# Concatenate strings with '|' separators
concatenated_str = self.SEPARATOR.join(str_list)
return concatenated_str | python | def encode_data_items(self, *args):
str_list = []
for arg in args:
# encode string items as-is
if isinstance(arg, str):
arg_str = arg
# encode integer items as base-64 strings with a '~' character in front
elif isinstance(arg, int):
arg_str = self.INTEGER_PREFIX + self.encode_int(arg)
# convert other types to string
else:
arg_str = str(arg)
str_list.append(arg_str)
# Concatenate strings with '|' separators
concatenated_str = self.SEPARATOR.join(str_list)
return concatenated_str | [
"def",
"encode_data_items",
"(",
"self",
",",
"*",
"args",
")",
":",
"str_list",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"# encode string items as-is",
"if",
"isinstance",
"(",
"arg",
",",
"str",
")",
":",
"arg_str",
"=",
"arg",
"# encode integer i... | Encodes a list of integers and strings into a concatenated string.
- encode string items as-is.
- encode integer items as base-64 with a ``'~'`` prefix.
- concatenate encoded items with a ``'|'`` separator.
Example:
``encode_data_items('abc', 123, 'xyz')`` returns ``'abc|~B7|xyz'`` | [
"Encodes",
"a",
"list",
"of",
"integers",
"and",
"strings",
"into",
"a",
"concatenated",
"string",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/token_manager.py#L147-L177 |
229,341 | lingthio/Flask-User | flask_user/token_manager.py | TokenManager.decode_data_items | def decode_data_items(self, concatenated_str):
"""Decodes a concatenated string into a list of integers and strings.
Example:
``decode_data_items('abc|~B7|xyz')`` returns ``['abc', 123, 'xyz']``
"""
data_items = []
str_list = concatenated_str.split(self.SEPARATOR)
for str in str_list:
# '~base-64-strings' are decoded into integers.
if len(str)>=1 and str[0]==self.INTEGER_PREFIX:
item = self.decode_int(str[1:])
# Strings are decoded as-is.
else:
item = str
data_items.append(item)
# Return list of data items
return data_items | python | def decode_data_items(self, concatenated_str):
data_items = []
str_list = concatenated_str.split(self.SEPARATOR)
for str in str_list:
# '~base-64-strings' are decoded into integers.
if len(str)>=1 and str[0]==self.INTEGER_PREFIX:
item = self.decode_int(str[1:])
# Strings are decoded as-is.
else:
item = str
data_items.append(item)
# Return list of data items
return data_items | [
"def",
"decode_data_items",
"(",
"self",
",",
"concatenated_str",
")",
":",
"data_items",
"=",
"[",
"]",
"str_list",
"=",
"concatenated_str",
".",
"split",
"(",
"self",
".",
"SEPARATOR",
")",
"for",
"str",
"in",
"str_list",
":",
"# '~base-64-strings' are decoded... | Decodes a concatenated string into a list of integers and strings.
Example:
``decode_data_items('abc|~B7|xyz')`` returns ``['abc', 123, 'xyz']`` | [
"Decodes",
"a",
"concatenated",
"string",
"into",
"a",
"list",
"of",
"integers",
"and",
"strings",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/token_manager.py#L179-L201 |
229,342 | lingthio/Flask-User | flask_user/token_manager.py | TokenManager.encode_int | def encode_int(self, n):
""" Encodes an integer into a short Base64 string.
Example:
``encode_int(123)`` returns ``'B7'``.
"""
str = []
while True:
n, r = divmod(n, self.BASE)
str.append(self.ALPHABET[r])
if n == 0: break
return ''.join(reversed(str)) | python | def encode_int(self, n):
str = []
while True:
n, r = divmod(n, self.BASE)
str.append(self.ALPHABET[r])
if n == 0: break
return ''.join(reversed(str)) | [
"def",
"encode_int",
"(",
"self",
",",
"n",
")",
":",
"str",
"=",
"[",
"]",
"while",
"True",
":",
"n",
",",
"r",
"=",
"divmod",
"(",
"n",
",",
"self",
".",
"BASE",
")",
"str",
".",
"append",
"(",
"self",
".",
"ALPHABET",
"[",
"r",
"]",
")",
... | Encodes an integer into a short Base64 string.
Example:
``encode_int(123)`` returns ``'B7'``. | [
"Encodes",
"an",
"integer",
"into",
"a",
"short",
"Base64",
"string",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/token_manager.py#L203-L214 |
229,343 | lingthio/Flask-User | flask_user/token_manager.py | TokenManager.decode_int | def decode_int(self, str):
""" Decodes a short Base64 string into an integer.
Example:
``decode_int('B7')`` returns ``123``.
"""
n = 0
for c in str:
n = n * self.BASE + self.ALPHABET_REVERSE[c]
return n | python | def decode_int(self, str):
n = 0
for c in str:
n = n * self.BASE + self.ALPHABET_REVERSE[c]
return n | [
"def",
"decode_int",
"(",
"self",
",",
"str",
")",
":",
"n",
"=",
"0",
"for",
"c",
"in",
"str",
":",
"n",
"=",
"n",
"*",
"self",
".",
"BASE",
"+",
"self",
".",
"ALPHABET_REVERSE",
"[",
"c",
"]",
"return",
"n"
] | Decodes a short Base64 string into an integer.
Example:
``decode_int('B7')`` returns ``123``. | [
"Decodes",
"a",
"short",
"Base64",
"string",
"into",
"an",
"integer",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/token_manager.py#L216-L225 |
229,344 | lingthio/Flask-User | flask_user/email_manager.py | EmailManager.send_confirm_email_email | def send_confirm_email_email(self, user, user_email):
"""Send the 'email confirmation' email."""
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_ENABLE_CONFIRM_EMAIL: return
# The confirm_email email is sent to a specific user_email.email or user.email
email = user_email.email if user_email else user.email
# Generate a confirm_email_link
object_id = user_email.id if user_email else user.id
token = self.user_manager.generate_token(object_id)
confirm_email_link = url_for('user.confirm_email', token=token, _external=True)
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_CONFIRM_EMAIL_TEMPLATE,
confirm_email_link=confirm_email_link,
) | python | def send_confirm_email_email(self, user, user_email):
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_ENABLE_CONFIRM_EMAIL: return
# The confirm_email email is sent to a specific user_email.email or user.email
email = user_email.email if user_email else user.email
# Generate a confirm_email_link
object_id = user_email.id if user_email else user.id
token = self.user_manager.generate_token(object_id)
confirm_email_link = url_for('user.confirm_email', token=token, _external=True)
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_CONFIRM_EMAIL_TEMPLATE,
confirm_email_link=confirm_email_link,
) | [
"def",
"send_confirm_email_email",
"(",
"self",
",",
"user",
",",
"user_email",
")",
":",
"# Verify config settings",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_EMAIL",
":",
"return",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_CON... | Send the 'email confirmation' email. | [
"Send",
"the",
"email",
"confirmation",
"email",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_manager.py#L37-L58 |
229,345 | lingthio/Flask-User | flask_user/email_manager.py | EmailManager.send_password_changed_email | def send_password_changed_email(self, user):
"""Send the 'password has changed' notification email."""
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_SEND_PASSWORD_CHANGED_EMAIL: return
# Notification emails are sent to the user's primary email address
user_or_user_email_object = self.user_manager.db_manager.get_primary_user_email_object(user)
email = user_or_user_email_object.email
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_PASSWORD_CHANGED_EMAIL_TEMPLATE,
) | python | def send_password_changed_email(self, user):
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_SEND_PASSWORD_CHANGED_EMAIL: return
# Notification emails are sent to the user's primary email address
user_or_user_email_object = self.user_manager.db_manager.get_primary_user_email_object(user)
email = user_or_user_email_object.email
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_PASSWORD_CHANGED_EMAIL_TEMPLATE,
) | [
"def",
"send_password_changed_email",
"(",
"self",
",",
"user",
")",
":",
"# Verify config settings",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_EMAIL",
":",
"return",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_SEND_PASSWORD_CHANGED_EMAIL",
... | Send the 'password has changed' notification email. | [
"Send",
"the",
"password",
"has",
"changed",
"notification",
"email",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_manager.py#L60-L76 |
229,346 | lingthio/Flask-User | flask_user/email_manager.py | EmailManager.send_reset_password_email | def send_reset_password_email(self, user, user_email):
"""Send the 'reset password' email."""
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
assert self.user_manager.USER_ENABLE_FORGOT_PASSWORD
# The reset_password email is sent to a specific user_email.email or user.email
email = user_email.email if user_email else user.email
# Generate a reset_password_link
token = self.user_manager.generate_token(user.id)
reset_password_link = url_for('user.reset_password', token=token, _external=True)
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_RESET_PASSWORD_EMAIL_TEMPLATE,
reset_password_link=reset_password_link,
) | python | def send_reset_password_email(self, user, user_email):
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
assert self.user_manager.USER_ENABLE_FORGOT_PASSWORD
# The reset_password email is sent to a specific user_email.email or user.email
email = user_email.email if user_email else user.email
# Generate a reset_password_link
token = self.user_manager.generate_token(user.id)
reset_password_link = url_for('user.reset_password', token=token, _external=True)
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_RESET_PASSWORD_EMAIL_TEMPLATE,
reset_password_link=reset_password_link,
) | [
"def",
"send_reset_password_email",
"(",
"self",
",",
"user",
",",
"user_email",
")",
":",
"# Verify config settings",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_EMAIL",
":",
"return",
"assert",
"self",
".",
"user_manager",
".",
"USER_ENABLE_FORGOT_... | Send the 'reset password' email. | [
"Send",
"the",
"reset",
"password",
"email",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_manager.py#L78-L98 |
229,347 | lingthio/Flask-User | flask_user/email_manager.py | EmailManager.send_invite_user_email | def send_invite_user_email(self, user, user_invitation):
"""Send the 'user invitation' email."""
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_ENABLE_INVITE_USER: return
# The user param points to the inviter
# The user_invitation param points to the invitee
invited_by_user = user
# Use the invitation email
email = user_invitation.email
# Create a dummy user object to an empty name for the invitee
user = self.user_manager.db_manager.UserClass(email=email)
# Generate a accept_invitation_link
token = self.user_manager.generate_token(user_invitation.id)
accept_invitation_link = url_for('user.register', token=token, _external=True)
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_INVITE_USER_EMAIL_TEMPLATE,
accept_invitation_link=accept_invitation_link,
invited_by_user=invited_by_user,
) | python | def send_invite_user_email(self, user, user_invitation):
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_ENABLE_INVITE_USER: return
# The user param points to the inviter
# The user_invitation param points to the invitee
invited_by_user = user
# Use the invitation email
email = user_invitation.email
# Create a dummy user object to an empty name for the invitee
user = self.user_manager.db_manager.UserClass(email=email)
# Generate a accept_invitation_link
token = self.user_manager.generate_token(user_invitation.id)
accept_invitation_link = url_for('user.register', token=token, _external=True)
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_INVITE_USER_EMAIL_TEMPLATE,
accept_invitation_link=accept_invitation_link,
invited_by_user=invited_by_user,
) | [
"def",
"send_invite_user_email",
"(",
"self",
",",
"user",
",",
"user_invitation",
")",
":",
"# Verify config settings",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_EMAIL",
":",
"return",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_... | Send the 'user invitation' email. | [
"Send",
"the",
"user",
"invitation",
"email",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_manager.py#L100-L128 |
229,348 | lingthio/Flask-User | flask_user/email_manager.py | EmailManager.send_registered_email | def send_registered_email(self, user, user_email, request_email_confirmation):
"""Send the 'user has registered' notification email."""
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_SEND_REGISTERED_EMAIL: return
# The registered email is sent to a specific user_email.email or user.email
email = user_email.email if user_email else user.email
# Add a request to confirm email if needed
if request_email_confirmation:
# Generate a confirm_email_link
token = self.user_manager.generate_token(user_email.id if user_email else user.id)
confirm_email_link = url_for('user.confirm_email', token=token, _external=True)
else:
confirm_email_link = None
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_REGISTERED_EMAIL_TEMPLATE,
confirm_email_link=confirm_email_link,
) | python | def send_registered_email(self, user, user_email, request_email_confirmation):
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_SEND_REGISTERED_EMAIL: return
# The registered email is sent to a specific user_email.email or user.email
email = user_email.email if user_email else user.email
# Add a request to confirm email if needed
if request_email_confirmation:
# Generate a confirm_email_link
token = self.user_manager.generate_token(user_email.id if user_email else user.id)
confirm_email_link = url_for('user.confirm_email', token=token, _external=True)
else:
confirm_email_link = None
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_REGISTERED_EMAIL_TEMPLATE,
confirm_email_link=confirm_email_link,
) | [
"def",
"send_registered_email",
"(",
"self",
",",
"user",
",",
"user_email",
",",
"request_email_confirmation",
")",
":",
"# Verify config settings",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_EMAIL",
":",
"return",
"if",
"not",
"self",
".",
"user... | Send the 'user has registered' notification email. | [
"Send",
"the",
"user",
"has",
"registered",
"notification",
"email",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_manager.py#L130-L154 |
229,349 | lingthio/Flask-User | flask_user/email_manager.py | EmailManager.send_username_changed_email | def send_username_changed_email(self, user):
"""Send the 'username has changed' notification email."""
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_SEND_USERNAME_CHANGED_EMAIL: return
# Notification emails are sent to the user's primary email address
user_or_user_email_object = self.user_manager.db_manager.get_primary_user_email_object(user)
email = user_or_user_email_object.email
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_USERNAME_CHANGED_EMAIL_TEMPLATE,
) | python | def send_username_changed_email(self, user):
# Verify config settings
if not self.user_manager.USER_ENABLE_EMAIL: return
if not self.user_manager.USER_SEND_USERNAME_CHANGED_EMAIL: return
# Notification emails are sent to the user's primary email address
user_or_user_email_object = self.user_manager.db_manager.get_primary_user_email_object(user)
email = user_or_user_email_object.email
# Render email from templates and send it via the configured EmailAdapter
self._render_and_send_email(
email,
user,
self.user_manager.USER_USERNAME_CHANGED_EMAIL_TEMPLATE,
) | [
"def",
"send_username_changed_email",
"(",
"self",
",",
"user",
")",
":",
"# Verify config settings",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_ENABLE_EMAIL",
":",
"return",
"if",
"not",
"self",
".",
"user_manager",
".",
"USER_SEND_USERNAME_CHANGED_EMAIL",
... | Send the 'username has changed' notification email. | [
"Send",
"the",
"username",
"has",
"changed",
"notification",
"email",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_manager.py#L156-L172 |
229,350 | lingthio/Flask-User | flask_user/user_mixin.py | UserMixin.get_id | def get_id(self):
"""Converts a User ID and parts of a User password hash to a token."""
# This function is used by Flask-Login to store a User ID securely as a browser cookie.
# The last part of the password is included to invalidate tokens when password change.
# user_id and password_ends_with are encrypted, timestamped and signed.
# This function works in tandem with UserMixin.get_user_by_token()
user_manager = current_app.user_manager
user_id = self.id
password_ends_with = '' if user_manager.USER_ENABLE_AUTH0 else self.password[-8:]
user_token = user_manager.generate_token(
user_id, # User ID
password_ends_with, # Last 8 characters of user password
)
# print("UserMixin.get_id: ID:", self.id, "token:", user_token)
return user_token | python | def get_id(self):
# This function is used by Flask-Login to store a User ID securely as a browser cookie.
# The last part of the password is included to invalidate tokens when password change.
# user_id and password_ends_with are encrypted, timestamped and signed.
# This function works in tandem with UserMixin.get_user_by_token()
user_manager = current_app.user_manager
user_id = self.id
password_ends_with = '' if user_manager.USER_ENABLE_AUTH0 else self.password[-8:]
user_token = user_manager.generate_token(
user_id, # User ID
password_ends_with, # Last 8 characters of user password
)
# print("UserMixin.get_id: ID:", self.id, "token:", user_token)
return user_token | [
"def",
"get_id",
"(",
"self",
")",
":",
"# This function is used by Flask-Login to store a User ID securely as a browser cookie.",
"# The last part of the password is included to invalidate tokens when password change.",
"# user_id and password_ends_with are encrypted, timestamped and signed.",
"#... | Converts a User ID and parts of a User password hash to a token. | [
"Converts",
"a",
"User",
"ID",
"and",
"parts",
"of",
"a",
"User",
"password",
"hash",
"to",
"a",
"token",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_mixin.py#L16-L32 |
229,351 | lingthio/Flask-User | flask_user/user_mixin.py | UserMixin.has_roles | def has_roles(self, *requirements):
""" Return True if the user has all of the specified roles. Return False otherwise.
has_roles() accepts a list of requirements:
has_role(requirement1, requirement2, requirement3).
Each requirement is either a role_name, or a tuple_of_role_names.
role_name example: 'manager'
tuple_of_role_names: ('funny', 'witty', 'hilarious')
A role_name-requirement is accepted when the user has this role.
A tuple_of_role_names-requirement is accepted when the user has ONE of these roles.
has_roles() returns true if ALL of the requirements have been accepted.
For example:
has_roles('a', ('b', 'c'), d)
Translates to:
User has role 'a' AND (role 'b' OR role 'c') AND role 'd'"""
# Translates a list of role objects to a list of role_names
user_manager = current_app.user_manager
role_names = user_manager.db_manager.get_user_roles(self)
# has_role() accepts a list of requirements
for requirement in requirements:
if isinstance(requirement, (list, tuple)):
# this is a tuple_of_role_names requirement
tuple_of_role_names = requirement
authorized = False
for role_name in tuple_of_role_names:
if role_name in role_names:
# tuple_of_role_names requirement was met: break out of loop
authorized = True
break
if not authorized:
return False # tuple_of_role_names requirement failed: return False
else:
# this is a role_name requirement
role_name = requirement
# the user must have this role
if not role_name in role_names:
return False # role_name requirement failed: return False
# All requirements have been met: return True
return True | python | def has_roles(self, *requirements):
""" Return True if the user has all of the specified roles. Return False otherwise.
has_roles() accepts a list of requirements:
has_role(requirement1, requirement2, requirement3).
Each requirement is either a role_name, or a tuple_of_role_names.
role_name example: 'manager'
tuple_of_role_names: ('funny', 'witty', 'hilarious')
A role_name-requirement is accepted when the user has this role.
A tuple_of_role_names-requirement is accepted when the user has ONE of these roles.
has_roles() returns true if ALL of the requirements have been accepted.
For example:
has_roles('a', ('b', 'c'), d)
Translates to:
User has role 'a' AND (role 'b' OR role 'c') AND role 'd'"""
# Translates a list of role objects to a list of role_names
user_manager = current_app.user_manager
role_names = user_manager.db_manager.get_user_roles(self)
# has_role() accepts a list of requirements
for requirement in requirements:
if isinstance(requirement, (list, tuple)):
# this is a tuple_of_role_names requirement
tuple_of_role_names = requirement
authorized = False
for role_name in tuple_of_role_names:
if role_name in role_names:
# tuple_of_role_names requirement was met: break out of loop
authorized = True
break
if not authorized:
return False # tuple_of_role_names requirement failed: return False
else:
# this is a role_name requirement
role_name = requirement
# the user must have this role
if not role_name in role_names:
return False # role_name requirement failed: return False
# All requirements have been met: return True
return True | [
"def",
"has_roles",
"(",
"self",
",",
"*",
"requirements",
")",
":",
"# Translates a list of role objects to a list of role_names",
"user_manager",
"=",
"current_app",
".",
"user_manager",
"role_names",
"=",
"user_manager",
".",
"db_manager",
".",
"get_user_roles",
"(",
... | Return True if the user has all of the specified roles. Return False otherwise.
has_roles() accepts a list of requirements:
has_role(requirement1, requirement2, requirement3).
Each requirement is either a role_name, or a tuple_of_role_names.
role_name example: 'manager'
tuple_of_role_names: ('funny', 'witty', 'hilarious')
A role_name-requirement is accepted when the user has this role.
A tuple_of_role_names-requirement is accepted when the user has ONE of these roles.
has_roles() returns true if ALL of the requirements have been accepted.
For example:
has_roles('a', ('b', 'c'), d)
Translates to:
User has role 'a' AND (role 'b' OR role 'c') AND role 'd | [
"Return",
"True",
"if",
"the",
"user",
"has",
"all",
"of",
"the",
"specified",
"roles",
".",
"Return",
"False",
"otherwise",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_mixin.py#L59-L102 |
229,352 | lingthio/Flask-User | flask_user/user_manager__utils.py | UserManager__Utils.email_is_available | def email_is_available(self, new_email):
"""Check if ``new_email`` is available.
| Returns True if ``new_email`` does not exist or belongs to the current user.
| Return False otherwise.
"""
user, user_email = self.db_manager.get_user_and_user_email_by_email(new_email)
return (user == None) | python | def email_is_available(self, new_email):
user, user_email = self.db_manager.get_user_and_user_email_by_email(new_email)
return (user == None) | [
"def",
"email_is_available",
"(",
"self",
",",
"new_email",
")",
":",
"user",
",",
"user_email",
"=",
"self",
".",
"db_manager",
".",
"get_user_and_user_email_by_email",
"(",
"new_email",
")",
"return",
"(",
"user",
"==",
"None",
")"
] | Check if ``new_email`` is available.
| Returns True if ``new_email`` does not exist or belongs to the current user.
| Return False otherwise. | [
"Check",
"if",
"new_email",
"is",
"available",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__utils.py#L36-L44 |
229,353 | lingthio/Flask-User | flask_user/user_manager__utils.py | UserManager__Utils.make_safe_url | def make_safe_url(self, url):
"""Makes a URL safe by removing optional hostname and port.
Example:
| ``make_safe_url('https://hostname:80/path1/path2?q1=v1&q2=v2#fragment')``
| returns ``'/path1/path2?q1=v1&q2=v2#fragment'``
Override this method if you need to allow a list of safe hostnames.
"""
# Split the URL into scheme, netloc, path, query and fragment
parts = list(urlsplit(url))
# Clear scheme and netloc and rebuild URL
parts[0] = '' # Empty scheme
parts[1] = '' # Empty netloc (hostname:port)
safe_url = urlunsplit(parts)
return safe_url | python | def make_safe_url(self, url):
# Split the URL into scheme, netloc, path, query and fragment
parts = list(urlsplit(url))
# Clear scheme and netloc and rebuild URL
parts[0] = '' # Empty scheme
parts[1] = '' # Empty netloc (hostname:port)
safe_url = urlunsplit(parts)
return safe_url | [
"def",
"make_safe_url",
"(",
"self",
",",
"url",
")",
":",
"# Split the URL into scheme, netloc, path, query and fragment",
"parts",
"=",
"list",
"(",
"urlsplit",
"(",
"url",
")",
")",
"# Clear scheme and netloc and rebuild URL",
"parts",
"[",
"0",
"]",
"=",
"''",
"... | Makes a URL safe by removing optional hostname and port.
Example:
| ``make_safe_url('https://hostname:80/path1/path2?q1=v1&q2=v2#fragment')``
| returns ``'/path1/path2?q1=v1&q2=v2#fragment'``
Override this method if you need to allow a list of safe hostnames. | [
"Makes",
"a",
"URL",
"safe",
"by",
"removing",
"optional",
"hostname",
"and",
"port",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager__utils.py#L54-L72 |
229,354 | lingthio/Flask-User | flask_user/user_manager.py | UserManager.password_validator | def password_validator(self, form, field):
"""Ensure that passwords have at least 6 characters with one lowercase letter, one uppercase letter and one number.
Override this method to customize the password validator.
"""
# Convert string to list of characters
password = list(field.data)
password_length = len(password)
# Count lowercase, uppercase and numbers
lowers = uppers = digits = 0
for ch in password:
if ch.islower(): lowers += 1
if ch.isupper(): uppers += 1
if ch.isdigit(): digits += 1
# Password must have one lowercase letter, one uppercase letter and one digit
is_valid = password_length >= 6 and lowers and uppers and digits
if not is_valid:
raise ValidationError(
_('Password must have at least 6 characters with one lowercase letter, one uppercase letter and one number')) | python | def password_validator(self, form, field):
# Convert string to list of characters
password = list(field.data)
password_length = len(password)
# Count lowercase, uppercase and numbers
lowers = uppers = digits = 0
for ch in password:
if ch.islower(): lowers += 1
if ch.isupper(): uppers += 1
if ch.isdigit(): digits += 1
# Password must have one lowercase letter, one uppercase letter and one digit
is_valid = password_length >= 6 and lowers and uppers and digits
if not is_valid:
raise ValidationError(
_('Password must have at least 6 characters with one lowercase letter, one uppercase letter and one number')) | [
"def",
"password_validator",
"(",
"self",
",",
"form",
",",
"field",
")",
":",
"# Convert string to list of characters",
"password",
"=",
"list",
"(",
"field",
".",
"data",
")",
"password_length",
"=",
"len",
"(",
"password",
")",
"# Count lowercase, uppercase and n... | Ensure that passwords have at least 6 characters with one lowercase letter, one uppercase letter and one number.
Override this method to customize the password validator. | [
"Ensure",
"that",
"passwords",
"have",
"at",
"least",
"6",
"characters",
"with",
"one",
"lowercase",
"letter",
"one",
"uppercase",
"letter",
"and",
"one",
"number",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager.py#L229-L250 |
229,355 | lingthio/Flask-User | flask_user/user_manager.py | UserManager.username_validator | def username_validator(self, form, field):
"""Ensure that Usernames contains at least 3 alphanumeric characters.
Override this method to customize the username validator.
"""
username = field.data
if len(username) < 3:
raise ValidationError(
_('Username must be at least 3 characters long'))
valid_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._'
chars = list(username)
for char in chars:
if char not in valid_chars:
raise ValidationError(
_("Username may only contain letters, numbers, '-', '.' and '_'")) | python | def username_validator(self, form, field):
username = field.data
if len(username) < 3:
raise ValidationError(
_('Username must be at least 3 characters long'))
valid_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._'
chars = list(username)
for char in chars:
if char not in valid_chars:
raise ValidationError(
_("Username may only contain letters, numbers, '-', '.' and '_'")) | [
"def",
"username_validator",
"(",
"self",
",",
"form",
",",
"field",
")",
":",
"username",
"=",
"field",
".",
"data",
"if",
"len",
"(",
"username",
")",
"<",
"3",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'Username must be at least 3 characters long'",
... | Ensure that Usernames contains at least 3 alphanumeric characters.
Override this method to customize the username validator. | [
"Ensure",
"that",
"Usernames",
"contains",
"at",
"least",
"3",
"alphanumeric",
"characters",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager.py#L258-L272 |
229,356 | lingthio/Flask-User | flask_user/user_manager.py | UserManager._check_settings | def _check_settings(self, app):
"""Verify required settings. Produce a helpful error messages for incorrect settings."""
# Check for invalid settings
# --------------------------
# Check self.UserInvitationClass and USER_ENABLE_INVITE_USER
if self.USER_ENABLE_INVITE_USER and not self.UserInvitationClass:
raise ConfigError(
'UserInvitationClass is missing while USER_ENABLE_INVITE_USER is True.' \
' Specify UserInvitationClass with UserManager(app, db, User, UserInvitationClass=...' \
' or set USER_ENABLE_INVITE_USER=False.')
# Check for deprecated settings
# -----------------------------
# Check for deprecated USER_ENABLE_CONFIRM_EMAIL
setting = app.config.get('USER_ENABLE_LOGIN_WITHOUT_CONFIRM_EMAIL', None)
if setting is not None:
print(
'Deprecation warning: USER_ENABLE_LOGIN_WITHOUT_CONFIRM_EMAIL'\
' will be deprecated.' \
' It has been replaced by USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL.'\
' Please change this as soon as possible.')
self.USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL = setting
# Check for deprecated USER_ENABLE_RETYPE_PASSWORD
setting = app.config.get('USER_ENABLE_RETYPE_PASSWORD', None)
if setting is not None:
print(
'Deprecation warning: USER_ENABLE_RETYPE_PASSWORD'\
' will be deprecated.' \
' It has been replaced with USER_REQUIRE_RETYPE_PASSWORD.'\
' Please change this as soon as possible.')
self.USER_REQUIRE_RETYPE_PASSWORD = setting
# Check for deprecated USER_SHOW_USERNAME_EMAIL_DOES_NOT_EXIST
setting = app.config.get('USER_SHOW_USERNAME_EMAIL_DOES_NOT_EXIST', None)
if setting is not None:
print(
'Deprecation warning: USER_SHOW_USERNAME_EMAIL_DOES_NOT_EXIST' \
' will be deprecated.' \
' It has been replaced with USER_SHOW_USERNAME_DOES_NOT_EXIST'
' and USER_SHOW_EMAIL_DOES_NOT_EXIST.'
' Please change this as soon as possible.')
self.USER_SHOW_USERNAME_DOES_NOT_EXIST = setting
self.USER_SHOW_EMAIL_DOES_NOT_EXIST = setting
# Check for deprecated USER_PASSWORD_HASH
setting = app.config.get('USER_PASSWORD_HASH', None)
if setting is not None:
print(
"Deprecation warning: USER_PASSWORD_HASH=<string>"\
" will be deprecated."\
" It has been replaced with USER_PASSLIB_CRYPTCONTEXT_SCHEMES=<list>."
" Please change USER_PASSWORD_HASH='something' to"\
" USER_PASSLIB_CRYPTCONTEXT_SCHEMES=['something'] as soon as possible.")
self.USER_PASSLIB_CRYPTCONTEXT_SCHEMES = [setting]
# Check that USER_EMAIL_SENDER_EMAIL is set when USER_ENABLE_EMAIL is True
if not self.USER_EMAIL_SENDER_EMAIL and self.USER_ENABLE_EMAIL:
raise ConfigError(
'USER_EMAIL_SENDER_EMAIL is missing while USER_ENABLE_EMAIL is True.'\
' specify USER_EMAIL_SENDER_EMAIL (and USER_EMAIL_SENDER_NAME) or set USER_ENABLE_EMAIL to False.')
# Disable settings that rely on a feature setting that's not enabled
# ------------------------------------------------------------------
# USER_ENABLE_REGISTER=True must have USER_ENABLE_USERNAME=True or USER_ENABLE_EMAIL=True.
if not self.USER_ENABLE_USERNAME and not self.USER_ENABLE_EMAIL:
self.USER_ENABLE_REGISTER = False
# Settings that depend on USER_ENABLE_EMAIL
if not self.USER_ENABLE_EMAIL:
self.USER_ENABLE_CONFIRM_EMAIL = False
self.USER_ENABLE_MULTIPLE_EMAILS = False
self.USER_ENABLE_FORGOT_PASSWORD = False
self.USER_SEND_PASSWORD_CHANGED_EMAIL = False
self.USER_SEND_REGISTERED_EMAIL = False
self.USER_SEND_USERNAME_CHANGED_EMAIL = False
self.USER_REQUIRE_INVITATION = False
# Settings that depend on USER_ENABLE_USERNAME
if not self.USER_ENABLE_USERNAME:
self.USER_ENABLE_CHANGE_USERNAME = False | python | def _check_settings(self, app):
# Check for invalid settings
# --------------------------
# Check self.UserInvitationClass and USER_ENABLE_INVITE_USER
if self.USER_ENABLE_INVITE_USER and not self.UserInvitationClass:
raise ConfigError(
'UserInvitationClass is missing while USER_ENABLE_INVITE_USER is True.' \
' Specify UserInvitationClass with UserManager(app, db, User, UserInvitationClass=...' \
' or set USER_ENABLE_INVITE_USER=False.')
# Check for deprecated settings
# -----------------------------
# Check for deprecated USER_ENABLE_CONFIRM_EMAIL
setting = app.config.get('USER_ENABLE_LOGIN_WITHOUT_CONFIRM_EMAIL', None)
if setting is not None:
print(
'Deprecation warning: USER_ENABLE_LOGIN_WITHOUT_CONFIRM_EMAIL'\
' will be deprecated.' \
' It has been replaced by USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL.'\
' Please change this as soon as possible.')
self.USER_ALLOW_LOGIN_WITHOUT_CONFIRMED_EMAIL = setting
# Check for deprecated USER_ENABLE_RETYPE_PASSWORD
setting = app.config.get('USER_ENABLE_RETYPE_PASSWORD', None)
if setting is not None:
print(
'Deprecation warning: USER_ENABLE_RETYPE_PASSWORD'\
' will be deprecated.' \
' It has been replaced with USER_REQUIRE_RETYPE_PASSWORD.'\
' Please change this as soon as possible.')
self.USER_REQUIRE_RETYPE_PASSWORD = setting
# Check for deprecated USER_SHOW_USERNAME_EMAIL_DOES_NOT_EXIST
setting = app.config.get('USER_SHOW_USERNAME_EMAIL_DOES_NOT_EXIST', None)
if setting is not None:
print(
'Deprecation warning: USER_SHOW_USERNAME_EMAIL_DOES_NOT_EXIST' \
' will be deprecated.' \
' It has been replaced with USER_SHOW_USERNAME_DOES_NOT_EXIST'
' and USER_SHOW_EMAIL_DOES_NOT_EXIST.'
' Please change this as soon as possible.')
self.USER_SHOW_USERNAME_DOES_NOT_EXIST = setting
self.USER_SHOW_EMAIL_DOES_NOT_EXIST = setting
# Check for deprecated USER_PASSWORD_HASH
setting = app.config.get('USER_PASSWORD_HASH', None)
if setting is not None:
print(
"Deprecation warning: USER_PASSWORD_HASH=<string>"\
" will be deprecated."\
" It has been replaced with USER_PASSLIB_CRYPTCONTEXT_SCHEMES=<list>."
" Please change USER_PASSWORD_HASH='something' to"\
" USER_PASSLIB_CRYPTCONTEXT_SCHEMES=['something'] as soon as possible.")
self.USER_PASSLIB_CRYPTCONTEXT_SCHEMES = [setting]
# Check that USER_EMAIL_SENDER_EMAIL is set when USER_ENABLE_EMAIL is True
if not self.USER_EMAIL_SENDER_EMAIL and self.USER_ENABLE_EMAIL:
raise ConfigError(
'USER_EMAIL_SENDER_EMAIL is missing while USER_ENABLE_EMAIL is True.'\
' specify USER_EMAIL_SENDER_EMAIL (and USER_EMAIL_SENDER_NAME) or set USER_ENABLE_EMAIL to False.')
# Disable settings that rely on a feature setting that's not enabled
# ------------------------------------------------------------------
# USER_ENABLE_REGISTER=True must have USER_ENABLE_USERNAME=True or USER_ENABLE_EMAIL=True.
if not self.USER_ENABLE_USERNAME and not self.USER_ENABLE_EMAIL:
self.USER_ENABLE_REGISTER = False
# Settings that depend on USER_ENABLE_EMAIL
if not self.USER_ENABLE_EMAIL:
self.USER_ENABLE_CONFIRM_EMAIL = False
self.USER_ENABLE_MULTIPLE_EMAILS = False
self.USER_ENABLE_FORGOT_PASSWORD = False
self.USER_SEND_PASSWORD_CHANGED_EMAIL = False
self.USER_SEND_REGISTERED_EMAIL = False
self.USER_SEND_USERNAME_CHANGED_EMAIL = False
self.USER_REQUIRE_INVITATION = False
# Settings that depend on USER_ENABLE_USERNAME
if not self.USER_ENABLE_USERNAME:
self.USER_ENABLE_CHANGE_USERNAME = False | [
"def",
"_check_settings",
"(",
"self",
",",
"app",
")",
":",
"# Check for invalid settings",
"# --------------------------",
"# Check self.UserInvitationClass and USER_ENABLE_INVITE_USER",
"if",
"self",
".",
"USER_ENABLE_INVITE_USER",
"and",
"not",
"self",
".",
"UserInvitationC... | Verify required settings. Produce a helpful error messages for incorrect settings. | [
"Verify",
"required",
"settings",
".",
"Produce",
"a",
"helpful",
"error",
"messages",
"for",
"incorrect",
"settings",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/user_manager.py#L282-L366 |
229,357 | lingthio/Flask-User | flask_user/db_adapters/mongo_db_adapter.py | MongoDbAdapter.drop_all_tables | def drop_all_tables(self):
"""Drop all document collections of the database.
.. warning:: ALL DATA WILL BE LOST. Use only for automated testing.
"""
# Retrieve database name from application config
app = self.db.app
mongo_settings = app.config['MONGODB_SETTINGS']
database_name = mongo_settings['db']
# Flask-MongoEngine is built on MongoEngine, which is built on PyMongo.
# To drop database collections, we need to access the PyMongo Database object,
# which is stored in the PyMongo MongoClient object,
# which is stored in app.extensions['mongoengine'][self]['conn']
py_mongo_mongo_client = app.extensions['mongoengine'][self.db]['conn']
py_mongo_database = py_mongo_mongo_client[database_name]
# Use the PyMongo Database object
for collection_name in py_mongo_database.collection_names():
py_mongo_database.drop_collection(collection_name) | python | def drop_all_tables(self):
# Retrieve database name from application config
app = self.db.app
mongo_settings = app.config['MONGODB_SETTINGS']
database_name = mongo_settings['db']
# Flask-MongoEngine is built on MongoEngine, which is built on PyMongo.
# To drop database collections, we need to access the PyMongo Database object,
# which is stored in the PyMongo MongoClient object,
# which is stored in app.extensions['mongoengine'][self]['conn']
py_mongo_mongo_client = app.extensions['mongoengine'][self.db]['conn']
py_mongo_database = py_mongo_mongo_client[database_name]
# Use the PyMongo Database object
for collection_name in py_mongo_database.collection_names():
py_mongo_database.drop_collection(collection_name) | [
"def",
"drop_all_tables",
"(",
"self",
")",
":",
"# Retrieve database name from application config",
"app",
"=",
"self",
".",
"db",
".",
"app",
"mongo_settings",
"=",
"app",
".",
"config",
"[",
"'MONGODB_SETTINGS'",
"]",
"database_name",
"=",
"mongo_settings",
"[",
... | Drop all document collections of the database.
.. warning:: ALL DATA WILL BE LOST. Use only for automated testing. | [
"Drop",
"all",
"document",
"collections",
"of",
"the",
"database",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_adapters/mongo_db_adapter.py#L113-L133 |
229,358 | lingthio/Flask-User | flask_user/db_adapters/dynamo_db_adapter.py | DynamoDbAdapter.add_object | def add_object(self, object):
"""Add object to db session. Only for session-centric object-database mappers."""
if object.id is None:
object.get_id()
self.db.engine.save(object) | python | def add_object(self, object):
if object.id is None:
object.get_id()
self.db.engine.save(object) | [
"def",
"add_object",
"(",
"self",
",",
"object",
")",
":",
"if",
"object",
".",
"id",
"is",
"None",
":",
"object",
".",
"get_id",
"(",
")",
"self",
".",
"db",
".",
"engine",
".",
"save",
"(",
"object",
")"
] | Add object to db session. Only for session-centric object-database mappers. | [
"Add",
"object",
"to",
"db",
"session",
".",
"Only",
"for",
"session",
"-",
"centric",
"object",
"-",
"database",
"mappers",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_adapters/dynamo_db_adapter.py#L33-L37 |
229,359 | lingthio/Flask-User | flask_user/db_adapters/dynamo_db_adapter.py | DynamoDbAdapter.delete_object | def delete_object(self, object):
""" Delete object specified by ``object``. """
#pdb.set_trace()
self.db.engine.delete_key(object)#, userid='abc123', id='1')
print('dynamo.delete_object(%s)' % object) | python | def delete_object(self, object):
#pdb.set_trace()
self.db.engine.delete_key(object)#, userid='abc123', id='1')
print('dynamo.delete_object(%s)' % object) | [
"def",
"delete_object",
"(",
"self",
",",
"object",
")",
":",
"#pdb.set_trace()",
"self",
".",
"db",
".",
"engine",
".",
"delete_key",
"(",
"object",
")",
"#, userid='abc123', id='1')",
"print",
"(",
"'dynamo.delete_object(%s)'",
"%",
"object",
")"
] | Delete object specified by ``object``. | [
"Delete",
"object",
"specified",
"by",
"object",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_adapters/dynamo_db_adapter.py#L114-L118 |
229,360 | lingthio/Flask-User | flask_user/forms.py | unique_username_validator | def unique_username_validator(form, field):
""" Ensure that Username is unique. This validator may NOT be customized."""
user_manager = current_app.user_manager
if not user_manager.db_manager.username_is_available(field.data):
raise ValidationError(_('This Username is already in use. Please try another one.')) | python | def unique_username_validator(form, field):
user_manager = current_app.user_manager
if not user_manager.db_manager.username_is_available(field.data):
raise ValidationError(_('This Username is already in use. Please try another one.')) | [
"def",
"unique_username_validator",
"(",
"form",
",",
"field",
")",
":",
"user_manager",
"=",
"current_app",
".",
"user_manager",
"if",
"not",
"user_manager",
".",
"db_manager",
".",
"username_is_available",
"(",
"field",
".",
"data",
")",
":",
"raise",
"Validat... | Ensure that Username is unique. This validator may NOT be customized. | [
"Ensure",
"that",
"Username",
"is",
"unique",
".",
"This",
"validator",
"may",
"NOT",
"be",
"customized",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/forms.py#L37-L41 |
229,361 | lingthio/Flask-User | flask_user/forms.py | unique_email_validator | def unique_email_validator(form, field):
""" Username must be unique. This validator may NOT be customized."""
user_manager = current_app.user_manager
if not user_manager.email_is_available(field.data):
raise ValidationError(_('This Email is already in use. Please try another one.')) | python | def unique_email_validator(form, field):
user_manager = current_app.user_manager
if not user_manager.email_is_available(field.data):
raise ValidationError(_('This Email is already in use. Please try another one.')) | [
"def",
"unique_email_validator",
"(",
"form",
",",
"field",
")",
":",
"user_manager",
"=",
"current_app",
".",
"user_manager",
"if",
"not",
"user_manager",
".",
"email_is_available",
"(",
"field",
".",
"data",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(... | Username must be unique. This validator may NOT be customized. | [
"Username",
"must",
"be",
"unique",
".",
"This",
"validator",
"may",
"NOT",
"be",
"customized",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/forms.py#L44-L48 |
229,362 | lingthio/Flask-User | flask_user/email_adapters/smtp_email_adapter.py | SMTPEmailAdapter.send_email_message | def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
""" Send email message via Flask-Mail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text.
"""
# Construct sender from sender_name and sender_email
sender = '"%s" <%s>' % (sender_name, sender_email) if sender_name else sender_email
# Send email via SMTP except when we're testing
if not current_app.testing: # pragma: no cover
try:
# Prepare email message
from flask_mail import Message
message = Message(
subject,
sender=sender,
recipients=[recipient],
html=html_message,
body=text_message)
# Send email message
self.mail.send(message)
# Print helpful error messages on exceptions
except (socket.gaierror, socket.error) as e:
raise EmailError('SMTP Connection error: Check your MAIL_SERVER and MAIL_PORT settings.')
except smtplib.SMTPAuthenticationError:
raise EmailError('SMTP Authentication error: Check your MAIL_USERNAME and MAIL_PASSWORD settings.') | python | def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
# Construct sender from sender_name and sender_email
sender = '"%s" <%s>' % (sender_name, sender_email) if sender_name else sender_email
# Send email via SMTP except when we're testing
if not current_app.testing: # pragma: no cover
try:
# Prepare email message
from flask_mail import Message
message = Message(
subject,
sender=sender,
recipients=[recipient],
html=html_message,
body=text_message)
# Send email message
self.mail.send(message)
# Print helpful error messages on exceptions
except (socket.gaierror, socket.error) as e:
raise EmailError('SMTP Connection error: Check your MAIL_SERVER and MAIL_PORT settings.')
except smtplib.SMTPAuthenticationError:
raise EmailError('SMTP Authentication error: Check your MAIL_USERNAME and MAIL_PASSWORD settings.') | [
"def",
"send_email_message",
"(",
"self",
",",
"recipient",
",",
"subject",
",",
"html_message",
",",
"text_message",
",",
"sender_email",
",",
"sender_name",
")",
":",
"# Construct sender from sender_name and sender_email",
"sender",
"=",
"'\"%s\" <%s>'",
"%",
"(",
"... | Send email message via Flask-Mail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text. | [
"Send",
"email",
"message",
"via",
"Flask",
"-",
"Mail",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_adapters/smtp_email_adapter.py#L38-L70 |
229,363 | lingthio/Flask-User | flask_user/password_manager.py | PasswordManager.verify_password | def verify_password(self, password, password_hash):
"""Verify plaintext ``password`` against ``hashed password``.
Args:
password(str): Plaintext password that the user types in.
password_hash(str): Password hash generated by a previous call to ``hash_password()``.
Returns:
| True when ``password`` matches ``password_hash``.
| False otherwise.
Example:
::
if verify_password('mypassword', user.password):
login_user(user)
"""
# Print deprecation warning if called with (password, user) instead of (password, user.password)
if isinstance(password_hash, self.user_manager.db_manager.UserClass):
print(
'Deprecation warning: verify_password(password, user) has been changed'\
' to: verify_password(password, password_hash). The user param will be deprecated.'\
' Please change your call with verify_password(password, user) into'\
' a call with verify_password(password, user.password)'
' as soon as possible.')
password_hash = password_hash.password # effectively user.password
# Use passlib's CryptContext to verify a password
return self.password_crypt_context.verify(password, password_hash) | python | def verify_password(self, password, password_hash):
# Print deprecation warning if called with (password, user) instead of (password, user.password)
if isinstance(password_hash, self.user_manager.db_manager.UserClass):
print(
'Deprecation warning: verify_password(password, user) has been changed'\
' to: verify_password(password, password_hash). The user param will be deprecated.'\
' Please change your call with verify_password(password, user) into'\
' a call with verify_password(password, user.password)'
' as soon as possible.')
password_hash = password_hash.password # effectively user.password
# Use passlib's CryptContext to verify a password
return self.password_crypt_context.verify(password, password_hash) | [
"def",
"verify_password",
"(",
"self",
",",
"password",
",",
"password_hash",
")",
":",
"# Print deprecation warning if called with (password, user) instead of (password, user.password)",
"if",
"isinstance",
"(",
"password_hash",
",",
"self",
".",
"user_manager",
".",
"db_man... | Verify plaintext ``password`` against ``hashed password``.
Args:
password(str): Plaintext password that the user types in.
password_hash(str): Password hash generated by a previous call to ``hash_password()``.
Returns:
| True when ``password`` matches ``password_hash``.
| False otherwise.
Example:
::
if verify_password('mypassword', user.password):
login_user(user) | [
"Verify",
"plaintext",
"password",
"against",
"hashed",
"password",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/password_manager.py#L55-L83 |
229,364 | lingthio/Flask-User | flask_user/email_adapters/sendgrid_email_adapter.py | SendgridEmailAdapter.send_email_message | def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
""" Send email message via sendgrid-python.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text.
"""
if not current_app.testing: # pragma: no cover
try:
# Prepare Sendgrid helper objects
from sendgrid.helpers.mail import Email, Content, Substitution, Mail
from_email = Email(sender_email, sender_name)
to_email = Email(recipient)
text_content = Content('text/plain', text_message)
html_content = Content('text/html', html_message)
# Prepare Sendgrid Mail object
# Note: RFC 1341: text must be first, followed by html
mail = Mail(from_email, subject, to_email, text_content)
mail.add_content(html_content)
# Send mail via the Sendgrid API
response = self.sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)
except ImportError:
raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE)
except Exception as e:
print(e)
print(e.body)
raise | python | def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
if not current_app.testing: # pragma: no cover
try:
# Prepare Sendgrid helper objects
from sendgrid.helpers.mail import Email, Content, Substitution, Mail
from_email = Email(sender_email, sender_name)
to_email = Email(recipient)
text_content = Content('text/plain', text_message)
html_content = Content('text/html', html_message)
# Prepare Sendgrid Mail object
# Note: RFC 1341: text must be first, followed by html
mail = Mail(from_email, subject, to_email, text_content)
mail.add_content(html_content)
# Send mail via the Sendgrid API
response = self.sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)
except ImportError:
raise ConfigError(SENDGRID_IMPORT_ERROR_MESSAGE)
except Exception as e:
print(e)
print(e.body)
raise | [
"def",
"send_email_message",
"(",
"self",
",",
"recipient",
",",
"subject",
",",
"html_message",
",",
"text_message",
",",
"sender_email",
",",
"sender_name",
")",
":",
"if",
"not",
"current_app",
".",
"testing",
":",
"# pragma: no cover",
"try",
":",
"# Prepare... | Send email message via sendgrid-python.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text. | [
"Send",
"email",
"message",
"via",
"sendgrid",
"-",
"python",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/email_adapters/sendgrid_email_adapter.py#L40-L72 |
229,365 | lingthio/Flask-User | flask_user/db_adapters/pynamo_db_adapter.py | PynamoDbAdapter.create_all_tables | def create_all_tables(self):
"""Create database tables for all known database data-models."""
for klass in self.__get_classes():
if not klass.exists():
klass.create_table(read_capacity_units=1, write_capacity_units=1, wait=True) | python | def create_all_tables(self):
for klass in self.__get_classes():
if not klass.exists():
klass.create_table(read_capacity_units=1, write_capacity_units=1, wait=True) | [
"def",
"create_all_tables",
"(",
"self",
")",
":",
"for",
"klass",
"in",
"self",
".",
"__get_classes",
"(",
")",
":",
"if",
"not",
"klass",
".",
"exists",
"(",
")",
":",
"klass",
".",
"create_table",
"(",
"read_capacity_units",
"=",
"1",
",",
"write_capa... | Create database tables for all known database data-models. | [
"Create",
"database",
"tables",
"for",
"all",
"known",
"database",
"data",
"-",
"models",
"."
] | a379fa0a281789618c484b459cb41236779b95b1 | https://github.com/lingthio/Flask-User/blob/a379fa0a281789618c484b459cb41236779b95b1/flask_user/db_adapters/pynamo_db_adapter.py#L134-L138 |
229,366 | ericmjl/nxviz | nxviz/plots.py | BasePlot.draw | def draw(self):
"""
Draws the Plot to screen.
If there is a continuous datatype for the nodes, it will be reflected
in self.sm being constructed (in `compute_node_colors`). It will then
automatically add in a colorbar to the plot and scale the plot axes
accordingly.
"""
self.draw_nodes()
self.draw_edges()
# note that self.groups only exists on condition
# that group_label_position was given!
if hasattr(self, "groups") and self.groups:
self.draw_group_labels()
logging.debug("DRAW: {0}".format(self.sm))
if self.sm:
self.figure.subplots_adjust(right=0.8)
cax = self.figure.add_axes([0.85, 0.2, 0.05, 0.6])
self.figure.colorbar(self.sm, cax=cax)
self.ax.relim()
self.ax.autoscale_view()
self.ax.set_aspect("equal") | python | def draw(self):
self.draw_nodes()
self.draw_edges()
# note that self.groups only exists on condition
# that group_label_position was given!
if hasattr(self, "groups") and self.groups:
self.draw_group_labels()
logging.debug("DRAW: {0}".format(self.sm))
if self.sm:
self.figure.subplots_adjust(right=0.8)
cax = self.figure.add_axes([0.85, 0.2, 0.05, 0.6])
self.figure.colorbar(self.sm, cax=cax)
self.ax.relim()
self.ax.autoscale_view()
self.ax.set_aspect("equal") | [
"def",
"draw",
"(",
"self",
")",
":",
"self",
".",
"draw_nodes",
"(",
")",
"self",
".",
"draw_edges",
"(",
")",
"# note that self.groups only exists on condition",
"# that group_label_position was given!",
"if",
"hasattr",
"(",
"self",
",",
"\"groups\"",
")",
"and",... | Draws the Plot to screen.
If there is a continuous datatype for the nodes, it will be reflected
in self.sm being constructed (in `compute_node_colors`). It will then
automatically add in a colorbar to the plot and scale the plot axes
accordingly. | [
"Draws",
"the",
"Plot",
"to",
"screen",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L237-L259 |
229,367 | ericmjl/nxviz | nxviz/plots.py | BasePlot.compute_node_colors | def compute_node_colors(self):
"""Compute the node colors. Also computes the colorbar."""
data = [self.graph.node[n][self.node_color] for n in self.nodes]
if self.group_order == "alphabetically":
data_reduced = sorted(list(set(data)))
elif self.group_order == "default":
data_reduced = list(unique_everseen(data))
dtype = infer_data_type(data)
n_grps = num_discrete_groups(data)
if dtype == "categorical" or dtype == "ordinal":
if n_grps <= 8:
cmap = get_cmap(
cmaps["Accent_{0}".format(n_grps)].mpl_colormap
)
else:
cmap = n_group_colorpallet(n_grps)
elif dtype == "continuous" and not is_data_diverging(data):
cmap = get_cmap(cmaps["continuous"].mpl_colormap)
elif dtype == "continuous" and is_data_diverging(data):
cmap = get_cmap(cmaps["diverging"].mpl_colormap)
for d in data:
idx = data_reduced.index(d) / n_grps
self.node_colors.append(cmap(idx))
# Add colorbar if required.ListedColormap
logging.debug("length of data_reduced: {0}".format(len(data_reduced)))
logging.debug("dtype: {0}".format(dtype))
if len(data_reduced) > 1 and dtype == "continuous":
self.sm = plt.cm.ScalarMappable(
cmap=cmap,
norm=plt.Normalize(
vmin=min(data_reduced),
vmax=max(data_reduced), # noqa # noqa
),
)
self.sm._A = [] | python | def compute_node_colors(self):
data = [self.graph.node[n][self.node_color] for n in self.nodes]
if self.group_order == "alphabetically":
data_reduced = sorted(list(set(data)))
elif self.group_order == "default":
data_reduced = list(unique_everseen(data))
dtype = infer_data_type(data)
n_grps = num_discrete_groups(data)
if dtype == "categorical" or dtype == "ordinal":
if n_grps <= 8:
cmap = get_cmap(
cmaps["Accent_{0}".format(n_grps)].mpl_colormap
)
else:
cmap = n_group_colorpallet(n_grps)
elif dtype == "continuous" and not is_data_diverging(data):
cmap = get_cmap(cmaps["continuous"].mpl_colormap)
elif dtype == "continuous" and is_data_diverging(data):
cmap = get_cmap(cmaps["diverging"].mpl_colormap)
for d in data:
idx = data_reduced.index(d) / n_grps
self.node_colors.append(cmap(idx))
# Add colorbar if required.ListedColormap
logging.debug("length of data_reduced: {0}".format(len(data_reduced)))
logging.debug("dtype: {0}".format(dtype))
if len(data_reduced) > 1 and dtype == "continuous":
self.sm = plt.cm.ScalarMappable(
cmap=cmap,
norm=plt.Normalize(
vmin=min(data_reduced),
vmax=max(data_reduced), # noqa # noqa
),
)
self.sm._A = [] | [
"def",
"compute_node_colors",
"(",
"self",
")",
":",
"data",
"=",
"[",
"self",
".",
"graph",
".",
"node",
"[",
"n",
"]",
"[",
"self",
".",
"node_color",
"]",
"for",
"n",
"in",
"self",
".",
"nodes",
"]",
"if",
"self",
".",
"group_order",
"==",
"\"al... | Compute the node colors. Also computes the colorbar. | [
"Compute",
"the",
"node",
"colors",
".",
"Also",
"computes",
"the",
"colorbar",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L261-L300 |
229,368 | ericmjl/nxviz | nxviz/plots.py | BasePlot.compute_group_colors | def compute_group_colors(self):
"""Computes the group colors according to node colors"""
seen = set()
self.group_label_color = [
x for x in self.node_colors if not (x in seen or seen.add(x))
] | python | def compute_group_colors(self):
seen = set()
self.group_label_color = [
x for x in self.node_colors if not (x in seen or seen.add(x))
] | [
"def",
"compute_group_colors",
"(",
"self",
")",
":",
"seen",
"=",
"set",
"(",
")",
"self",
".",
"group_label_color",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"node_colors",
"if",
"not",
"(",
"x",
"in",
"seen",
"or",
"seen",
".",
"add",
"(",
"... | Computes the group colors according to node colors | [
"Computes",
"the",
"group",
"colors",
"according",
"to",
"node",
"colors"
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L302-L307 |
229,369 | ericmjl/nxviz | nxviz/plots.py | BasePlot.compute_edge_colors | def compute_edge_colors(self):
"""Compute the edge colors."""
data = [self.graph.edges[n][self.edge_color] for n in self.edges]
data_reduced = sorted(list(set(data)))
dtype = infer_data_type(data)
n_grps = num_discrete_groups(data)
if dtype == "categorical" or dtype == "ordinal":
if n_grps <= 8:
cmap = get_cmap(
cmaps["Accent_{0}".format(n_grps)].mpl_colormap
)
else:
cmap = n_group_colorpallet(n_grps)
elif dtype == "continuous" and not is_data_diverging(data):
cmap = get_cmap(cmaps["weights"])
for d in data:
idx = data_reduced.index(d) / n_grps
self.edge_colors.append(cmap(idx))
# Add colorbar if required.
logging.debug("length of data_reduced: {0}".format(len(data_reduced)))
logging.debug("dtype: {0}".format(dtype))
if len(data_reduced) > 1 and dtype == "continuous":
self.sm = plt.cm.ScalarMappable(
cmap=cmap,
norm=plt.Normalize(
vmin=min(data_reduced),
vmax=max(data_reduced), # noqa # noqa
),
)
self.sm._A = [] | python | def compute_edge_colors(self):
data = [self.graph.edges[n][self.edge_color] for n in self.edges]
data_reduced = sorted(list(set(data)))
dtype = infer_data_type(data)
n_grps = num_discrete_groups(data)
if dtype == "categorical" or dtype == "ordinal":
if n_grps <= 8:
cmap = get_cmap(
cmaps["Accent_{0}".format(n_grps)].mpl_colormap
)
else:
cmap = n_group_colorpallet(n_grps)
elif dtype == "continuous" and not is_data_diverging(data):
cmap = get_cmap(cmaps["weights"])
for d in data:
idx = data_reduced.index(d) / n_grps
self.edge_colors.append(cmap(idx))
# Add colorbar if required.
logging.debug("length of data_reduced: {0}".format(len(data_reduced)))
logging.debug("dtype: {0}".format(dtype))
if len(data_reduced) > 1 and dtype == "continuous":
self.sm = plt.cm.ScalarMappable(
cmap=cmap,
norm=plt.Normalize(
vmin=min(data_reduced),
vmax=max(data_reduced), # noqa # noqa
),
)
self.sm._A = [] | [
"def",
"compute_edge_colors",
"(",
"self",
")",
":",
"data",
"=",
"[",
"self",
".",
"graph",
".",
"edges",
"[",
"n",
"]",
"[",
"self",
".",
"edge_color",
"]",
"for",
"n",
"in",
"self",
".",
"edges",
"]",
"data_reduced",
"=",
"sorted",
"(",
"list",
... | Compute the edge colors. | [
"Compute",
"the",
"edge",
"colors",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L309-L340 |
229,370 | ericmjl/nxviz | nxviz/plots.py | BasePlot.compute_node_sizes | def compute_node_sizes(self):
"""Compute the node sizes."""
if type(self.node_size) is str:
nodes = self.graph.nodes
self.node_sizes = [nodes[n][self.node_size] for n in self.nodes]
else:
self.node_sizes = self.node_size | python | def compute_node_sizes(self):
if type(self.node_size) is str:
nodes = self.graph.nodes
self.node_sizes = [nodes[n][self.node_size] for n in self.nodes]
else:
self.node_sizes = self.node_size | [
"def",
"compute_node_sizes",
"(",
"self",
")",
":",
"if",
"type",
"(",
"self",
".",
"node_size",
")",
"is",
"str",
":",
"nodes",
"=",
"self",
".",
"graph",
".",
"nodes",
"self",
".",
"node_sizes",
"=",
"[",
"nodes",
"[",
"n",
"]",
"[",
"self",
".",... | Compute the node sizes. | [
"Compute",
"the",
"node",
"sizes",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L342-L348 |
229,371 | ericmjl/nxviz | nxviz/plots.py | BasePlot.compute_edge_widths | def compute_edge_widths(self):
"""Compute the edge widths."""
if type(self.edge_width) is str:
edges = self.graph.edges
self.edge_widths = [edges[n][self.edge_width] for n in self.edges]
else:
self.edge_widths = self.edge_width | python | def compute_edge_widths(self):
if type(self.edge_width) is str:
edges = self.graph.edges
self.edge_widths = [edges[n][self.edge_width] for n in self.edges]
else:
self.edge_widths = self.edge_width | [
"def",
"compute_edge_widths",
"(",
"self",
")",
":",
"if",
"type",
"(",
"self",
".",
"edge_width",
")",
"is",
"str",
":",
"edges",
"=",
"self",
".",
"graph",
".",
"edges",
"self",
".",
"edge_widths",
"=",
"[",
"edges",
"[",
"n",
"]",
"[",
"self",
"... | Compute the edge widths. | [
"Compute",
"the",
"edge",
"widths",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L350-L356 |
229,372 | ericmjl/nxviz | nxviz/plots.py | BasePlot.group_and_sort_nodes | def group_and_sort_nodes(self):
"""
Groups and then sorts the nodes according to the criteria passed into
the Plot constructor.
"""
if self.node_grouping and not self.node_order:
if self.group_order == "alphabetically":
self.nodes = [
n
for n, d in sorted(
self.graph.nodes(data=True),
key=lambda x: x[1][self.node_grouping],
)
]
elif self.group_order == "default":
grp = [
d[self.node_grouping]
for _, d in self.graph.nodes(data=True)
]
grp_name = list(unique_everseen(grp))
nodes = []
for key in grp_name:
nodes.extend(
[
n
for n, d in self.graph.nodes(data=True)
if key in d.values()
]
)
self.nodes = nodes
elif self.node_order and not self.node_grouping:
self.nodes = [
n
for n, _ in sorted(
self.graph.nodes(data=True),
key=lambda x: x[1][self.node_order],
)
]
elif self.node_grouping and self.node_order:
if self.group_order == "alphabetically":
self.nodes = [
n
for n, d in sorted(
self.graph.nodes(data=True),
key=lambda x: (
x[1][self.node_grouping],
x[1][self.node_order],
),
)
]
elif self.group_order == "default":
grp = [
d[self.node_grouping]
for _, d in self.graph.nodes(data=True)
]
grp_name = list(unique_everseen(grp))
nodes = []
for key in grp_name:
nodes.extend(
[
n
for n, d in sorted(
self.graph.nodes(data=True),
key=lambda x: x[1][self.node_order],
)
if key in d.values()
]
)
self.nodes = nodes | python | def group_and_sort_nodes(self):
if self.node_grouping and not self.node_order:
if self.group_order == "alphabetically":
self.nodes = [
n
for n, d in sorted(
self.graph.nodes(data=True),
key=lambda x: x[1][self.node_grouping],
)
]
elif self.group_order == "default":
grp = [
d[self.node_grouping]
for _, d in self.graph.nodes(data=True)
]
grp_name = list(unique_everseen(grp))
nodes = []
for key in grp_name:
nodes.extend(
[
n
for n, d in self.graph.nodes(data=True)
if key in d.values()
]
)
self.nodes = nodes
elif self.node_order and not self.node_grouping:
self.nodes = [
n
for n, _ in sorted(
self.graph.nodes(data=True),
key=lambda x: x[1][self.node_order],
)
]
elif self.node_grouping and self.node_order:
if self.group_order == "alphabetically":
self.nodes = [
n
for n, d in sorted(
self.graph.nodes(data=True),
key=lambda x: (
x[1][self.node_grouping],
x[1][self.node_order],
),
)
]
elif self.group_order == "default":
grp = [
d[self.node_grouping]
for _, d in self.graph.nodes(data=True)
]
grp_name = list(unique_everseen(grp))
nodes = []
for key in grp_name:
nodes.extend(
[
n
for n, d in sorted(
self.graph.nodes(data=True),
key=lambda x: x[1][self.node_order],
)
if key in d.values()
]
)
self.nodes = nodes | [
"def",
"group_and_sort_nodes",
"(",
"self",
")",
":",
"if",
"self",
".",
"node_grouping",
"and",
"not",
"self",
".",
"node_order",
":",
"if",
"self",
".",
"group_order",
"==",
"\"alphabetically\"",
":",
"self",
".",
"nodes",
"=",
"[",
"n",
"for",
"n",
",... | Groups and then sorts the nodes according to the criteria passed into
the Plot constructor. | [
"Groups",
"and",
"then",
"sorts",
"the",
"nodes",
"according",
"to",
"the",
"criteria",
"passed",
"into",
"the",
"Plot",
"constructor",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L408-L479 |
229,373 | ericmjl/nxviz | nxviz/plots.py | CircosPlot.compute_group_label_positions | def compute_group_label_positions(self):
"""
Computes the x,y positions of the group labels.
"""
assert self.group_label_position in ["beginning", "middle", "end"]
data = [self.graph.node[n][self.node_grouping] for n in self.nodes]
node_length = len(data)
groups = items_in_groups(data)
edge_of_plot = self.plot_radius + self.nodeprops["radius"]
# The 1.02 serves as padding
radius = 1.02 * edge_of_plot + self.group_label_offset
xs = []
ys = []
has = []
vas = []
node_idcs = np.cumsum(list(groups.values()))
node_idcs = np.insert(node_idcs, 0, 0)
if self.group_label_position == "beginning":
for idx in node_idcs[:-1]:
x, y = get_cartesian(
r=radius, theta=group_theta(node_length, idx)
)
ha, va = text_alignment(x, y)
xs.append(x)
ys.append(y)
has.append(ha)
vas.append(va)
elif self.group_label_position == "middle":
node_idcs = node_idcs.reshape(len(node_idcs), 1)
node_idcs = np.concatenate((node_idcs[:-1], node_idcs[1:]), axis=1)
for idx in node_idcs:
theta1 = group_theta(node_length, idx[0])
theta2 = group_theta(node_length, idx[1] - 1)
x, y = get_cartesian(r=radius, theta=(theta1 + theta2) / 2)
ha, va = text_alignment(x, y)
xs.append(x)
ys.append(y)
has.append(ha)
vas.append(va)
elif self.group_label_position == "end":
for idx in node_idcs[1::]:
x, y = get_cartesian(
r=radius, theta=group_theta(node_length, idx - 1)
)
ha, va = text_alignment(x, y)
xs.append(x)
ys.append(y)
has.append(ha)
vas.append(va)
self.group_label_coords = {"x": xs, "y": ys}
self.group_label_aligns = {"has": has, "vas": vas}
self.groups = groups.keys() | python | def compute_group_label_positions(self):
assert self.group_label_position in ["beginning", "middle", "end"]
data = [self.graph.node[n][self.node_grouping] for n in self.nodes]
node_length = len(data)
groups = items_in_groups(data)
edge_of_plot = self.plot_radius + self.nodeprops["radius"]
# The 1.02 serves as padding
radius = 1.02 * edge_of_plot + self.group_label_offset
xs = []
ys = []
has = []
vas = []
node_idcs = np.cumsum(list(groups.values()))
node_idcs = np.insert(node_idcs, 0, 0)
if self.group_label_position == "beginning":
for idx in node_idcs[:-1]:
x, y = get_cartesian(
r=radius, theta=group_theta(node_length, idx)
)
ha, va = text_alignment(x, y)
xs.append(x)
ys.append(y)
has.append(ha)
vas.append(va)
elif self.group_label_position == "middle":
node_idcs = node_idcs.reshape(len(node_idcs), 1)
node_idcs = np.concatenate((node_idcs[:-1], node_idcs[1:]), axis=1)
for idx in node_idcs:
theta1 = group_theta(node_length, idx[0])
theta2 = group_theta(node_length, idx[1] - 1)
x, y = get_cartesian(r=radius, theta=(theta1 + theta2) / 2)
ha, va = text_alignment(x, y)
xs.append(x)
ys.append(y)
has.append(ha)
vas.append(va)
elif self.group_label_position == "end":
for idx in node_idcs[1::]:
x, y = get_cartesian(
r=radius, theta=group_theta(node_length, idx - 1)
)
ha, va = text_alignment(x, y)
xs.append(x)
ys.append(y)
has.append(ha)
vas.append(va)
self.group_label_coords = {"x": xs, "y": ys}
self.group_label_aligns = {"has": has, "vas": vas}
self.groups = groups.keys() | [
"def",
"compute_group_label_positions",
"(",
"self",
")",
":",
"assert",
"self",
".",
"group_label_position",
"in",
"[",
"\"beginning\"",
",",
"\"middle\"",
",",
"\"end\"",
"]",
"data",
"=",
"[",
"self",
".",
"graph",
".",
"node",
"[",
"n",
"]",
"[",
"self... | Computes the x,y positions of the group labels. | [
"Computes",
"the",
"x",
"y",
"positions",
"of",
"the",
"group",
"labels",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L520-L575 |
229,374 | ericmjl/nxviz | nxviz/plots.py | CircosPlot.compute_node_positions | def compute_node_positions(self):
"""
Uses the get_cartesian function to compute the positions of each node
in the Circos plot.
"""
xs = []
ys = []
node_r = self.nodeprops["radius"]
radius = circos_radius(n_nodes=len(self.graph.nodes()), node_r=node_r)
self.plot_radius = radius
self.nodeprops["linewidth"] = radius * 0.01
for node in self.nodes:
x, y = get_cartesian(r=radius, theta=node_theta(self.nodes, node))
xs.append(x)
ys.append(y)
self.node_coords = {"x": xs, "y": ys} | python | def compute_node_positions(self):
xs = []
ys = []
node_r = self.nodeprops["radius"]
radius = circos_radius(n_nodes=len(self.graph.nodes()), node_r=node_r)
self.plot_radius = radius
self.nodeprops["linewidth"] = radius * 0.01
for node in self.nodes:
x, y = get_cartesian(r=radius, theta=node_theta(self.nodes, node))
xs.append(x)
ys.append(y)
self.node_coords = {"x": xs, "y": ys} | [
"def",
"compute_node_positions",
"(",
"self",
")",
":",
"xs",
"=",
"[",
"]",
"ys",
"=",
"[",
"]",
"node_r",
"=",
"self",
".",
"nodeprops",
"[",
"\"radius\"",
"]",
"radius",
"=",
"circos_radius",
"(",
"n_nodes",
"=",
"len",
"(",
"self",
".",
"graph",
... | Uses the get_cartesian function to compute the positions of each node
in the Circos plot. | [
"Uses",
"the",
"get_cartesian",
"function",
"to",
"compute",
"the",
"positions",
"of",
"each",
"node",
"in",
"the",
"Circos",
"plot",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L577-L592 |
229,375 | ericmjl/nxviz | nxviz/plots.py | CircosPlot.compute_node_label_positions | def compute_node_label_positions(self):
"""
Uses the get_cartesian function to compute the positions of each node
label in the Circos plot.
This method is always called after the compute_node_positions
method, so that the plot_radius is pre-computed.
This will also add a new attribute, `node_label_rotation` to the object
which contains the rotation angles for each of the nodes. Together with
the node coordinates this can be used to add additional annotations
with rotated text.
"""
self.init_node_label_meta()
for node in self.nodes:
# Define radius 'radius' and circumference 'theta'
theta = node_theta(self.nodes, node)
# multiplication factor 1.02 moved below
radius = self.plot_radius + self.nodeprops["radius"]
# Coordinates of text inside nodes
if self.node_label_layout == "numbers":
radius_adjustment = 1.0 - (1.0 / radius)
else:
radius_adjustment = 1.02
x, y = get_cartesian(r=radius * radius_adjustment, theta=theta)
# ----- For numbered nodes -----
# Node label x-axis coordinate
tx, _ = get_cartesian(r=radius, theta=theta)
# Create the quasi-circular positioning on the x axis
tx *= 1 - np.log(np.cos(theta) * self.nonzero_sign(np.cos(theta)))
# Move each node a little further away from the circos
tx += self.nonzero_sign(x)
# Node label y-axis coordinate numerator
numerator = radius * (
theta % (self.nonzero_sign(y) * self.nonzero_sign(x) * np.pi)
)
# Node label y-axis coordinate denominator
denominator = self.nonzero_sign(x) * np.pi
# Node label y-axis coordinate
ty = 2 * (numerator / denominator)
# ----- For rotated nodes -----
# Computes the text rotation
theta_deg = to_degrees(theta)
if theta_deg >= -90 and theta_deg < 90: # right side
rot = theta_deg
else: # left side
rot = theta_deg - 180
# Store values
self.store_node_label_meta(x, y, tx, ty, rot) | python | def compute_node_label_positions(self):
self.init_node_label_meta()
for node in self.nodes:
# Define radius 'radius' and circumference 'theta'
theta = node_theta(self.nodes, node)
# multiplication factor 1.02 moved below
radius = self.plot_radius + self.nodeprops["radius"]
# Coordinates of text inside nodes
if self.node_label_layout == "numbers":
radius_adjustment = 1.0 - (1.0 / radius)
else:
radius_adjustment = 1.02
x, y = get_cartesian(r=radius * radius_adjustment, theta=theta)
# ----- For numbered nodes -----
# Node label x-axis coordinate
tx, _ = get_cartesian(r=radius, theta=theta)
# Create the quasi-circular positioning on the x axis
tx *= 1 - np.log(np.cos(theta) * self.nonzero_sign(np.cos(theta)))
# Move each node a little further away from the circos
tx += self.nonzero_sign(x)
# Node label y-axis coordinate numerator
numerator = radius * (
theta % (self.nonzero_sign(y) * self.nonzero_sign(x) * np.pi)
)
# Node label y-axis coordinate denominator
denominator = self.nonzero_sign(x) * np.pi
# Node label y-axis coordinate
ty = 2 * (numerator / denominator)
# ----- For rotated nodes -----
# Computes the text rotation
theta_deg = to_degrees(theta)
if theta_deg >= -90 and theta_deg < 90: # right side
rot = theta_deg
else: # left side
rot = theta_deg - 180
# Store values
self.store_node_label_meta(x, y, tx, ty, rot) | [
"def",
"compute_node_label_positions",
"(",
"self",
")",
":",
"self",
".",
"init_node_label_meta",
"(",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"# Define radius 'radius' and circumference 'theta'",
"theta",
"=",
"node_theta",
"(",
"self",
".",
"nodes",
... | Uses the get_cartesian function to compute the positions of each node
label in the Circos plot.
This method is always called after the compute_node_positions
method, so that the plot_radius is pre-computed.
This will also add a new attribute, `node_label_rotation` to the object
which contains the rotation angles for each of the nodes. Together with
the node coordinates this can be used to add additional annotations
with rotated text. | [
"Uses",
"the",
"get_cartesian",
"function",
"to",
"compute",
"the",
"positions",
"of",
"each",
"node",
"label",
"in",
"the",
"Circos",
"plot",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L594-L650 |
229,376 | ericmjl/nxviz | nxviz/plots.py | CircosPlot.store_node_label_meta | def store_node_label_meta(self, x, y, tx, ty, rot):
"""
This function stored coordinates-related metadate for a node
This function should not be called by the user
:param x: x location of node label or number
:type x: np.float64
:param y: y location of node label or number
:type y: np.float64
:param tx: text location x of node label (numbers)
:type tx: np.float64
:param ty: text location y of node label (numbers)
:type ty: np.float64
:param rot: rotation angle of the text (rotation)
:type rot: float
"""
# Store computed values
self.node_label_coords["x"].append(x)
self.node_label_coords["y"].append(y)
self.node_label_coords["tx"].append(tx)
self.node_label_coords["ty"].append(ty)
# Computes the text alignment for x
if x == 0:
self.node_label_aligns["has"].append("center")
elif x > 0:
self.node_label_aligns["has"].append("left")
else:
self.node_label_aligns["has"].append("right")
# Computes the text alignment for y
if self.node_label_layout == "rotate" or y == 0:
self.node_label_aligns["vas"].append("center")
elif y > 0:
self.node_label_aligns["vas"].append("bottom")
else:
self.node_label_aligns["vas"].append("top")
self.node_label_rotation.append(rot) | python | def store_node_label_meta(self, x, y, tx, ty, rot):
# Store computed values
self.node_label_coords["x"].append(x)
self.node_label_coords["y"].append(y)
self.node_label_coords["tx"].append(tx)
self.node_label_coords["ty"].append(ty)
# Computes the text alignment for x
if x == 0:
self.node_label_aligns["has"].append("center")
elif x > 0:
self.node_label_aligns["has"].append("left")
else:
self.node_label_aligns["has"].append("right")
# Computes the text alignment for y
if self.node_label_layout == "rotate" or y == 0:
self.node_label_aligns["vas"].append("center")
elif y > 0:
self.node_label_aligns["vas"].append("bottom")
else:
self.node_label_aligns["vas"].append("top")
self.node_label_rotation.append(rot) | [
"def",
"store_node_label_meta",
"(",
"self",
",",
"x",
",",
"y",
",",
"tx",
",",
"ty",
",",
"rot",
")",
":",
"# Store computed values",
"self",
".",
"node_label_coords",
"[",
"\"x\"",
"]",
".",
"append",
"(",
"x",
")",
"self",
".",
"node_label_coords",
"... | This function stored coordinates-related metadate for a node
This function should not be called by the user
:param x: x location of node label or number
:type x: np.float64
:param y: y location of node label or number
:type y: np.float64
:param tx: text location x of node label (numbers)
:type tx: np.float64
:param ty: text location y of node label (numbers)
:type ty: np.float64
:param rot: rotation angle of the text (rotation)
:type rot: float | [
"This",
"function",
"stored",
"coordinates",
"-",
"related",
"metadate",
"for",
"a",
"node",
"This",
"function",
"should",
"not",
"be",
"called",
"by",
"the",
"user"
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L671-L714 |
229,377 | ericmjl/nxviz | nxviz/plots.py | CircosPlot.draw_nodes | def draw_nodes(self):
"""
Renders nodes to the figure.
"""
node_r = self.nodeprops["radius"]
lw = self.nodeprops["linewidth"]
for i, node in enumerate(self.nodes):
x = self.node_coords["x"][i]
y = self.node_coords["y"][i]
color = self.node_colors[i]
node_patch = patches.Circle(
(x, y), node_r, lw=lw, color=color, zorder=2
)
self.ax.add_patch(node_patch)
if self.node_labels:
label_x = self.node_label_coords["x"][i]
label_y = self.node_label_coords["y"][i]
label_tx = self.node_label_coords["tx"][i]
label_ty = self.node_label_coords["ty"][i]
label_ha = self.node_label_aligns["has"][i]
label_va = self.node_label_aligns["vas"][i]
# ----- Node label rotation layout -----
if self.node_label_layout == "rotation":
rot = self.node_label_rotation[i]
self.ax.text(
s=node,
x=label_x,
y=label_y,
ha=label_ha,
va=label_va,
rotation=rot,
rotation_mode="anchor",
color=self.node_label_color[i],
fontsize=self.fontsize,
family=self.fontfamily,
)
# ----- Node label numbering layout -----
elif self.node_label_layout == "numbers":
# Draw descriptions for labels
desc = "%s - %s" % ((i, node) if (x > 0) else (node, i))
self.ax.text(
s=desc,
x=label_tx,
y=label_ty,
ha=label_ha,
va=label_va,
color=self.node_label_color[i],
fontsize=self.fontsize,
family=self.fontfamily,
)
# Add numbers to nodes
self.ax.text(
s=i, x=label_x, y=label_y, ha="center", va="center"
)
# Standard node label layout
else:
# Draw node text straight from the nodes
self.ax.text(
s=node,
x=label_x,
y=label_y,
ha=label_ha,
va=label_va,
color=self.node_label_color[i],
fontsize=self.fontsize,
family=self.fontfamily,
) | python | def draw_nodes(self):
node_r = self.nodeprops["radius"]
lw = self.nodeprops["linewidth"]
for i, node in enumerate(self.nodes):
x = self.node_coords["x"][i]
y = self.node_coords["y"][i]
color = self.node_colors[i]
node_patch = patches.Circle(
(x, y), node_r, lw=lw, color=color, zorder=2
)
self.ax.add_patch(node_patch)
if self.node_labels:
label_x = self.node_label_coords["x"][i]
label_y = self.node_label_coords["y"][i]
label_tx = self.node_label_coords["tx"][i]
label_ty = self.node_label_coords["ty"][i]
label_ha = self.node_label_aligns["has"][i]
label_va = self.node_label_aligns["vas"][i]
# ----- Node label rotation layout -----
if self.node_label_layout == "rotation":
rot = self.node_label_rotation[i]
self.ax.text(
s=node,
x=label_x,
y=label_y,
ha=label_ha,
va=label_va,
rotation=rot,
rotation_mode="anchor",
color=self.node_label_color[i],
fontsize=self.fontsize,
family=self.fontfamily,
)
# ----- Node label numbering layout -----
elif self.node_label_layout == "numbers":
# Draw descriptions for labels
desc = "%s - %s" % ((i, node) if (x > 0) else (node, i))
self.ax.text(
s=desc,
x=label_tx,
y=label_ty,
ha=label_ha,
va=label_va,
color=self.node_label_color[i],
fontsize=self.fontsize,
family=self.fontfamily,
)
# Add numbers to nodes
self.ax.text(
s=i, x=label_x, y=label_y, ha="center", va="center"
)
# Standard node label layout
else:
# Draw node text straight from the nodes
self.ax.text(
s=node,
x=label_x,
y=label_y,
ha=label_ha,
va=label_va,
color=self.node_label_color[i],
fontsize=self.fontsize,
family=self.fontfamily,
) | [
"def",
"draw_nodes",
"(",
"self",
")",
":",
"node_r",
"=",
"self",
".",
"nodeprops",
"[",
"\"radius\"",
"]",
"lw",
"=",
"self",
".",
"nodeprops",
"[",
"\"linewidth\"",
"]",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"self",
".",
"nodes",
")",
"... | Renders nodes to the figure. | [
"Renders",
"nodes",
"to",
"the",
"figure",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L716-L791 |
229,378 | ericmjl/nxviz | nxviz/plots.py | CircosPlot.draw_group_labels | def draw_group_labels(self):
"""
Renders group labels to the figure.
"""
for i, label in enumerate(self.groups):
label_x = self.group_label_coords["x"][i]
label_y = self.group_label_coords["y"][i]
label_ha = self.group_label_aligns["has"][i]
label_va = self.group_label_aligns["vas"][i]
color = self.group_label_color[i]
self.ax.text(
s=label,
x=label_x,
y=label_y,
ha=label_ha,
va=label_va,
color=color,
fontsize=self.fontsize,
family=self.fontfamily,
) | python | def draw_group_labels(self):
for i, label in enumerate(self.groups):
label_x = self.group_label_coords["x"][i]
label_y = self.group_label_coords["y"][i]
label_ha = self.group_label_aligns["has"][i]
label_va = self.group_label_aligns["vas"][i]
color = self.group_label_color[i]
self.ax.text(
s=label,
x=label_x,
y=label_y,
ha=label_ha,
va=label_va,
color=color,
fontsize=self.fontsize,
family=self.fontfamily,
) | [
"def",
"draw_group_labels",
"(",
"self",
")",
":",
"for",
"i",
",",
"label",
"in",
"enumerate",
"(",
"self",
".",
"groups",
")",
":",
"label_x",
"=",
"self",
".",
"group_label_coords",
"[",
"\"x\"",
"]",
"[",
"i",
"]",
"label_y",
"=",
"self",
".",
"g... | Renders group labels to the figure. | [
"Renders",
"group",
"labels",
"to",
"the",
"figure",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L814-L833 |
229,379 | ericmjl/nxviz | nxviz/plots.py | MatrixPlot.draw | def draw(self):
"""
Draws the plot to screen.
Note to self: Do NOT call super(MatrixPlot, self).draw(); the
underlying logic for drawing here is completely different from other
plots, and as such necessitates a different implementation.
"""
matrix = nx.to_numpy_matrix(self.graph, nodelist=self.nodes)
self.ax.matshow(matrix, cmap=self.cmap) | python | def draw(self):
matrix = nx.to_numpy_matrix(self.graph, nodelist=self.nodes)
self.ax.matshow(matrix, cmap=self.cmap) | [
"def",
"draw",
"(",
"self",
")",
":",
"matrix",
"=",
"nx",
".",
"to_numpy_matrix",
"(",
"self",
".",
"graph",
",",
"nodelist",
"=",
"self",
".",
"nodes",
")",
"self",
".",
"ax",
".",
"matshow",
"(",
"matrix",
",",
"cmap",
"=",
"self",
".",
"cmap",
... | Draws the plot to screen.
Note to self: Do NOT call super(MatrixPlot, self).draw(); the
underlying logic for drawing here is completely different from other
plots, and as such necessitates a different implementation. | [
"Draws",
"the",
"plot",
"to",
"screen",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L1018-L1027 |
229,380 | ericmjl/nxviz | nxviz/plots.py | ArcPlot.compute_node_positions | def compute_node_positions(self):
"""
Computes nodes positions.
Arranges nodes in a line starting at (x,y) = (0,0). Node radius is
assumed to be equal to 0.5 units. Nodes are placed at integer
locations.
"""
xs = [0] * len(self.nodes)
ys = [0] * len(self.nodes)
for i, _ in enumerate(self.nodes[1:], start=1):
prev_r = self.node_sizes[i - 1] / 2
curr_r = self.node_sizes[i] / 2
xs[i] = xs[i - 1] + prev_r + curr_r
self.node_coords = {"x": xs, "y": ys} | python | def compute_node_positions(self):
xs = [0] * len(self.nodes)
ys = [0] * len(self.nodes)
for i, _ in enumerate(self.nodes[1:], start=1):
prev_r = self.node_sizes[i - 1] / 2
curr_r = self.node_sizes[i] / 2
xs[i] = xs[i - 1] + prev_r + curr_r
self.node_coords = {"x": xs, "y": ys} | [
"def",
"compute_node_positions",
"(",
"self",
")",
":",
"xs",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"self",
".",
"nodes",
")",
"ys",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"self",
".",
"nodes",
")",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
... | Computes nodes positions.
Arranges nodes in a line starting at (x,y) = (0,0). Node radius is
assumed to be equal to 0.5 units. Nodes are placed at integer
locations. | [
"Computes",
"nodes",
"positions",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L1035-L1050 |
229,381 | ericmjl/nxviz | nxviz/plots.py | ArcPlot.draw_nodes | def draw_nodes(self):
"""
Draw nodes to screen.
"""
node_r = self.node_sizes
for i, node in enumerate(self.nodes):
x = self.node_coords["x"][i]
y = self.node_coords["y"][i]
color = self.node_colors[i]
node_patch = patches.Ellipse(
(x, y), node_r[i], node_r[i], lw=0, color=color, zorder=2
)
self.ax.add_patch(node_patch) | python | def draw_nodes(self):
node_r = self.node_sizes
for i, node in enumerate(self.nodes):
x = self.node_coords["x"][i]
y = self.node_coords["y"][i]
color = self.node_colors[i]
node_patch = patches.Ellipse(
(x, y), node_r[i], node_r[i], lw=0, color=color, zorder=2
)
self.ax.add_patch(node_patch) | [
"def",
"draw_nodes",
"(",
"self",
")",
":",
"node_r",
"=",
"self",
".",
"node_sizes",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"self",
".",
"nodes",
")",
":",
"x",
"=",
"self",
".",
"node_coords",
"[",
"\"x\"",
"]",
"[",
"i",
"]",
"y",
"=... | Draw nodes to screen. | [
"Draw",
"nodes",
"to",
"screen",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L1052-L1064 |
229,382 | ericmjl/nxviz | nxviz/plots.py | GeoPlot.compute_node_positions | def compute_node_positions(self):
"""
Extracts the node positions based on the specified longitude and
latitude keyword arguments.
"""
xs = []
ys = []
self.locs = dict()
for node in self.nodes:
x = self.graph.node[node][self.node_lon]
y = self.graph.node[node][self.node_lat]
xs.append(x)
ys.append(y)
self.locs[node] = (x, y)
self.node_coords = {"x": xs, "y": ys} | python | def compute_node_positions(self):
xs = []
ys = []
self.locs = dict()
for node in self.nodes:
x = self.graph.node[node][self.node_lon]
y = self.graph.node[node][self.node_lat]
xs.append(x)
ys.append(y)
self.locs[node] = (x, y)
self.node_coords = {"x": xs, "y": ys} | [
"def",
"compute_node_positions",
"(",
"self",
")",
":",
"xs",
"=",
"[",
"]",
"ys",
"=",
"[",
"]",
"self",
".",
"locs",
"=",
"dict",
"(",
")",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"x",
"=",
"self",
".",
"graph",
".",
"node",
"[",
"nod... | Extracts the node positions based on the specified longitude and
latitude keyword arguments. | [
"Extracts",
"the",
"node",
"positions",
"based",
"on",
"the",
"specified",
"longitude",
"and",
"latitude",
"keyword",
"arguments",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L1144-L1160 |
229,383 | ericmjl/nxviz | nxviz/plots.py | GeoPlot.draw_nodes | def draw_nodes(self):
"""
Draws nodes to the screen.
GeoPlot is the first plot kind to support an Altair backend in addition
to the usual matplotlib backend.
"""
if self.backend == "matplotlib":
node_r = 0.005 # temporarily hardcoded.
for i, node in enumerate(self.nodes):
x = self.node_coords["x"][i]
y = self.node_coords["y"][i]
color = self.node_colors[i]
node_patch = patches.Ellipse(
(x, y), node_r, node_r, lw=0, color=color, zorder=2
)
self.ax.add_patch(node_patch)
elif self.backend == "altair":
self.node_chart = (
alt.Chart(self.node_df)
.mark_point()
.encode(
alt.X(f"{self.node_lon}:Q", scale=alt.Scale(zero=False)),
alt.Y(f"{self.node_lat}:Q", scale=alt.Scale(zero=False)),
)
) | python | def draw_nodes(self):
if self.backend == "matplotlib":
node_r = 0.005 # temporarily hardcoded.
for i, node in enumerate(self.nodes):
x = self.node_coords["x"][i]
y = self.node_coords["y"][i]
color = self.node_colors[i]
node_patch = patches.Ellipse(
(x, y), node_r, node_r, lw=0, color=color, zorder=2
)
self.ax.add_patch(node_patch)
elif self.backend == "altair":
self.node_chart = (
alt.Chart(self.node_df)
.mark_point()
.encode(
alt.X(f"{self.node_lon}:Q", scale=alt.Scale(zero=False)),
alt.Y(f"{self.node_lat}:Q", scale=alt.Scale(zero=False)),
)
) | [
"def",
"draw_nodes",
"(",
"self",
")",
":",
"if",
"self",
".",
"backend",
"==",
"\"matplotlib\"",
":",
"node_r",
"=",
"0.005",
"# temporarily hardcoded.",
"for",
"i",
",",
"node",
"in",
"enumerate",
"(",
"self",
".",
"nodes",
")",
":",
"x",
"=",
"self",
... | Draws nodes to the screen.
GeoPlot is the first plot kind to support an Altair backend in addition
to the usual matplotlib backend. | [
"Draws",
"nodes",
"to",
"the",
"screen",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L1162-L1187 |
229,384 | ericmjl/nxviz | nxviz/plots.py | GeoPlot.draw_edges | def draw_edges(self):
"""
Draws edges to screen.
"""
if self.backend == "matplotlib":
for i, (n1, n2) in enumerate(self.edges):
x1, y1 = self.locs[n1]
x2, y2 = self.locs[n2]
color = self.edge_colors[i]
line = Line2D(
xdata=[x1, x2],
ydata=[y1, y2],
color=color,
zorder=0,
alpha=0.3,
)
self.ax.add_line(line)
elif self.backend == "altair":
marker_attrs = dict()
marker_attrs["color"] = "black" # MAGICNUMBER
marker_attrs["strokeWidth"] = 1 # MAGICNUMBER
self.edge_chart = (
alt.Chart(self.edge_df)
.mark_line(**marker_attrs)
.encode(
alt.X(f"{self.node_lon}:Q"),
alt.Y(f"{self.node_lat}:Q"),
detail="edge",
)
) | python | def draw_edges(self):
if self.backend == "matplotlib":
for i, (n1, n2) in enumerate(self.edges):
x1, y1 = self.locs[n1]
x2, y2 = self.locs[n2]
color = self.edge_colors[i]
line = Line2D(
xdata=[x1, x2],
ydata=[y1, y2],
color=color,
zorder=0,
alpha=0.3,
)
self.ax.add_line(line)
elif self.backend == "altair":
marker_attrs = dict()
marker_attrs["color"] = "black" # MAGICNUMBER
marker_attrs["strokeWidth"] = 1 # MAGICNUMBER
self.edge_chart = (
alt.Chart(self.edge_df)
.mark_line(**marker_attrs)
.encode(
alt.X(f"{self.node_lon}:Q"),
alt.Y(f"{self.node_lat}:Q"),
detail="edge",
)
) | [
"def",
"draw_edges",
"(",
"self",
")",
":",
"if",
"self",
".",
"backend",
"==",
"\"matplotlib\"",
":",
"for",
"i",
",",
"(",
"n1",
",",
"n2",
")",
"in",
"enumerate",
"(",
"self",
".",
"edges",
")",
":",
"x1",
",",
"y1",
"=",
"self",
".",
"locs",
... | Draws edges to screen. | [
"Draws",
"edges",
"to",
"screen",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/plots.py#L1189-L1218 |
229,385 | ericmjl/nxviz | travis_pypi_setup.py | update_travis_deploy_password | def update_travis_deploy_password(encrypted_password):
"""Update the deploy section of the .travis.yml file
to use the given encrypted password.
"""
config = load_yaml_config(TRAVIS_CONFIG_FILE)
config["deploy"]["password"] = dict(secure=encrypted_password)
save_yaml_config(TRAVIS_CONFIG_FILE, config)
line = (
"# This file was autogenerated and will overwrite"
" each time you run travis_pypi_setup.py\n"
)
prepend_line(TRAVIS_CONFIG_FILE, line) | python | def update_travis_deploy_password(encrypted_password):
config = load_yaml_config(TRAVIS_CONFIG_FILE)
config["deploy"]["password"] = dict(secure=encrypted_password)
save_yaml_config(TRAVIS_CONFIG_FILE, config)
line = (
"# This file was autogenerated and will overwrite"
" each time you run travis_pypi_setup.py\n"
)
prepend_line(TRAVIS_CONFIG_FILE, line) | [
"def",
"update_travis_deploy_password",
"(",
"encrypted_password",
")",
":",
"config",
"=",
"load_yaml_config",
"(",
"TRAVIS_CONFIG_FILE",
")",
"config",
"[",
"\"deploy\"",
"]",
"[",
"\"password\"",
"]",
"=",
"dict",
"(",
"secure",
"=",
"encrypted_password",
")",
... | Update the deploy section of the .travis.yml file
to use the given encrypted password. | [
"Update",
"the",
"deploy",
"section",
"of",
"the",
".",
"travis",
".",
"yml",
"file",
"to",
"use",
"the",
"given",
"encrypted",
"password",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/travis_pypi_setup.py#L93-L107 |
229,386 | ericmjl/nxviz | nxviz/io.py | graph_from_dataframe | def graph_from_dataframe(
dataframe,
threshold_by_percent_unique=0.1,
threshold_by_count_unique=None,
node_id_columns=[],
node_property_columns=[],
edge_property_columns=[],
node_type_key="type",
edge_type_key="type",
collapse_edges=True,
edge_agg_key="weight",
):
"""
Build an undirected graph from a pandas dataframe.
This function attempts to infer which cells should become nodes
based on either:
a. what percentage of the column are unique values (defaults to 10%)
b. an explicit count of unique values (i.e. any column with 7 unique
values or less)
c. an explicit list of column keys (i.e.
['employee_id', 'location_code'])
Column headers are preserved as node and edge 'types'. By default, this is
stored using the key 'type' which is used by some graph import processes
but can be reconfigured.
This function uses a MultiGraph structure during the build phase so that it
is possible to make multiple connections between nodes. By default, at the
end of the build phase, the MultiGraph is converted to a Graph and the
count of edges between each node-pair is written as a 'weight' property.
:param pandas.DataFrame dataframe: A pandas dataframe containing the data
to be converted into a graph.
:param float threshold_by_percent_unique: A percent value used to determine
whether a column should be used to generate nodes based on its
cardinality (i.e. in a dataframe with 100 rows, treat any column with
10 or less unique values as a node)
:param int threshold_by_count_unique: A numeric value used to determine
whether a column should be used to generate nodes based on its
cardinality (i.e. if 7 is supplied, treat any column with 7 or less
unique values as a node) - supplying a value will take priority over
percent_unique
:param list node_id_columns: A list of column headers to use for generating
nodes. Suppyling any value will take precedence over
threshold_by_percent_unique or threshold_by_count_unique. Note: this
can cause the size of the graph to expand significantly since every
unique value in a column will become a node.
:param list node_property_columns: A list of column headers to use for
generating properties of nodes. These can include the same column
headers used for the node id.
:param list edge_property_columns: A list of column headers to use for
generating properties of edges.
:param str node_type_key: A string that sets the key will be used to
preserve the column name as node property (this is useful for importing
networkx graphs to databases that distinguish between node 'types' or
for visually encoding those types in plots).
:param str edge_type_key: A string that sets the key will be used to keep
track of edge relationships an 'types' (this is useful for importing
networkx graphs to databases that distinguish between edge'types' or
for visually encoding those types in plots). Edge type values are
automatically set to <node_a_id>_<node_b_id>.
:param bool collapse_edges: Graphs are instantiated as a 'MultiGraph'
(allow multiple edges between nodes) and then collapsed into a 'Graph'
which only has a single edge between any two nodes. Information is
preserved by aggregating the count of those edges as a 'weight' value.
Set this value to False to return the MultiGraph. Note: this can cause
the size of the graph to expand significantly since each row can
potentially have n! edges where n is the number of columns in the
dataframe.
:param str edge_agg_key: A string that sets the key the edge count will be
assigned to when edges are aggregated.
:returns: A networkx Graph (or MultiGraph if collapse_edges is set to
False).
"""
assert isinstance(
dataframe, pd.DataFrame
), "{} is not a pandas DataFrame".format(dataframe)
M = MultiGraph()
# if explicit specification of node_id_columns is provided, use those
if len(node_id_columns) > 0:
node_columns = node_id_columns
else:
# otherwise, compute with thresholds based on the dataframe
if threshold_by_count_unique:
node_columns = sorted(
[
col
for col in dataframe.columns
if dataframe[col].nunique() <= threshold_by_count_unique
]
)
else:
node_columns = sorted(
[
col
for col in dataframe.columns
if dataframe[col].nunique() / dataframe.shape[0]
<= threshold_by_percent_unique # NOQA to preserve meaningful variable names
]
)
# use the unique values for each node column as node types
for node_type in node_columns:
M.add_nodes_from(
[
(node, {node_type_key: node_type})
for node in dataframe[node_type].unique()
]
)
# iterate over the rows and generate an edge for each pair of node columns
for i, row in dataframe.iterrows():
# assemble the edge properties as a dictionary
edge_properties = {k: row[k] for k in edge_property_columns}
# iterate over the node_ids in each node_column of the dataframe row
node_buffer = []
for node_type in node_columns:
node_id = row[node_type]
# get a reference to the node and assign any specified properties
node = M.nodes[node_id]
for k in node_property_columns:
# if values are not identical, append with a pipe delimiter
if k not in node:
node[k] = row[k]
elif isinstance(node[k], str) and str(row[k]) not in node[k]:
node[k] += "|{}".format(str(row[k]))
elif str(row[k]) not in str(node[k]):
node[k] = str(node[k]) + "|{}".format(str(row[k]))
# build edges using precomputed edge properties
for other_node_id, other_node_type in node_buffer:
# sort node_type so undirected edges all share the same type
ordered_name = "_".join(sorted([node_type, other_node_type]))
edge_properties[edge_type_key] = ordered_name
M.add_edge(node_id, other_node_id, **edge_properties)
# store the node from this column in the buffer for future edges
node_buffer.append((node_id, node_type))
if collapse_edges:
# convert the MultiGraph to a Graph
G = Graph(M)
k = edge_agg_key
# preserve the edge count as a sum of the weight values
for u, v, data in M.edges(data=True):
w = data[k] if k in data else 1.0
edge = G[u][v]
edge[k] = (w + edge[k]) if k in edge else w
return G
return M | python | def graph_from_dataframe(
dataframe,
threshold_by_percent_unique=0.1,
threshold_by_count_unique=None,
node_id_columns=[],
node_property_columns=[],
edge_property_columns=[],
node_type_key="type",
edge_type_key="type",
collapse_edges=True,
edge_agg_key="weight",
):
assert isinstance(
dataframe, pd.DataFrame
), "{} is not a pandas DataFrame".format(dataframe)
M = MultiGraph()
# if explicit specification of node_id_columns is provided, use those
if len(node_id_columns) > 0:
node_columns = node_id_columns
else:
# otherwise, compute with thresholds based on the dataframe
if threshold_by_count_unique:
node_columns = sorted(
[
col
for col in dataframe.columns
if dataframe[col].nunique() <= threshold_by_count_unique
]
)
else:
node_columns = sorted(
[
col
for col in dataframe.columns
if dataframe[col].nunique() / dataframe.shape[0]
<= threshold_by_percent_unique # NOQA to preserve meaningful variable names
]
)
# use the unique values for each node column as node types
for node_type in node_columns:
M.add_nodes_from(
[
(node, {node_type_key: node_type})
for node in dataframe[node_type].unique()
]
)
# iterate over the rows and generate an edge for each pair of node columns
for i, row in dataframe.iterrows():
# assemble the edge properties as a dictionary
edge_properties = {k: row[k] for k in edge_property_columns}
# iterate over the node_ids in each node_column of the dataframe row
node_buffer = []
for node_type in node_columns:
node_id = row[node_type]
# get a reference to the node and assign any specified properties
node = M.nodes[node_id]
for k in node_property_columns:
# if values are not identical, append with a pipe delimiter
if k not in node:
node[k] = row[k]
elif isinstance(node[k], str) and str(row[k]) not in node[k]:
node[k] += "|{}".format(str(row[k]))
elif str(row[k]) not in str(node[k]):
node[k] = str(node[k]) + "|{}".format(str(row[k]))
# build edges using precomputed edge properties
for other_node_id, other_node_type in node_buffer:
# sort node_type so undirected edges all share the same type
ordered_name = "_".join(sorted([node_type, other_node_type]))
edge_properties[edge_type_key] = ordered_name
M.add_edge(node_id, other_node_id, **edge_properties)
# store the node from this column in the buffer for future edges
node_buffer.append((node_id, node_type))
if collapse_edges:
# convert the MultiGraph to a Graph
G = Graph(M)
k = edge_agg_key
# preserve the edge count as a sum of the weight values
for u, v, data in M.edges(data=True):
w = data[k] if k in data else 1.0
edge = G[u][v]
edge[k] = (w + edge[k]) if k in edge else w
return G
return M | [
"def",
"graph_from_dataframe",
"(",
"dataframe",
",",
"threshold_by_percent_unique",
"=",
"0.1",
",",
"threshold_by_count_unique",
"=",
"None",
",",
"node_id_columns",
"=",
"[",
"]",
",",
"node_property_columns",
"=",
"[",
"]",
",",
"edge_property_columns",
"=",
"["... | Build an undirected graph from a pandas dataframe.
This function attempts to infer which cells should become nodes
based on either:
a. what percentage of the column are unique values (defaults to 10%)
b. an explicit count of unique values (i.e. any column with 7 unique
values or less)
c. an explicit list of column keys (i.e.
['employee_id', 'location_code'])
Column headers are preserved as node and edge 'types'. By default, this is
stored using the key 'type' which is used by some graph import processes
but can be reconfigured.
This function uses a MultiGraph structure during the build phase so that it
is possible to make multiple connections between nodes. By default, at the
end of the build phase, the MultiGraph is converted to a Graph and the
count of edges between each node-pair is written as a 'weight' property.
:param pandas.DataFrame dataframe: A pandas dataframe containing the data
to be converted into a graph.
:param float threshold_by_percent_unique: A percent value used to determine
whether a column should be used to generate nodes based on its
cardinality (i.e. in a dataframe with 100 rows, treat any column with
10 or less unique values as a node)
:param int threshold_by_count_unique: A numeric value used to determine
whether a column should be used to generate nodes based on its
cardinality (i.e. if 7 is supplied, treat any column with 7 or less
unique values as a node) - supplying a value will take priority over
percent_unique
:param list node_id_columns: A list of column headers to use for generating
nodes. Suppyling any value will take precedence over
threshold_by_percent_unique or threshold_by_count_unique. Note: this
can cause the size of the graph to expand significantly since every
unique value in a column will become a node.
:param list node_property_columns: A list of column headers to use for
generating properties of nodes. These can include the same column
headers used for the node id.
:param list edge_property_columns: A list of column headers to use for
generating properties of edges.
:param str node_type_key: A string that sets the key will be used to
preserve the column name as node property (this is useful for importing
networkx graphs to databases that distinguish between node 'types' or
for visually encoding those types in plots).
:param str edge_type_key: A string that sets the key will be used to keep
track of edge relationships an 'types' (this is useful for importing
networkx graphs to databases that distinguish between edge'types' or
for visually encoding those types in plots). Edge type values are
automatically set to <node_a_id>_<node_b_id>.
:param bool collapse_edges: Graphs are instantiated as a 'MultiGraph'
(allow multiple edges between nodes) and then collapsed into a 'Graph'
which only has a single edge between any two nodes. Information is
preserved by aggregating the count of those edges as a 'weight' value.
Set this value to False to return the MultiGraph. Note: this can cause
the size of the graph to expand significantly since each row can
potentially have n! edges where n is the number of columns in the
dataframe.
:param str edge_agg_key: A string that sets the key the edge count will be
assigned to when edges are aggregated.
:returns: A networkx Graph (or MultiGraph if collapse_edges is set to
False). | [
"Build",
"an",
"undirected",
"graph",
"from",
"a",
"pandas",
"dataframe",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/io.py#L5-L162 |
229,387 | ericmjl/nxviz | nxviz/utils.py | is_data_homogenous | def is_data_homogenous(data_container):
"""
Checks that all of the data in the container are of the same Python data
type. This function is called in every other function below, and as such
need not necessarily be called.
:param data_container: A generic container of data points.
:type data_container: `iterable`
"""
data_types = set([type(i) for i in data_container])
return len(data_types) == 1 | python | def is_data_homogenous(data_container):
data_types = set([type(i) for i in data_container])
return len(data_types) == 1 | [
"def",
"is_data_homogenous",
"(",
"data_container",
")",
":",
"data_types",
"=",
"set",
"(",
"[",
"type",
"(",
"i",
")",
"for",
"i",
"in",
"data_container",
"]",
")",
"return",
"len",
"(",
"data_types",
")",
"==",
"1"
] | Checks that all of the data in the container are of the same Python data
type. This function is called in every other function below, and as such
need not necessarily be called.
:param data_container: A generic container of data points.
:type data_container: `iterable` | [
"Checks",
"that",
"all",
"of",
"the",
"data",
"in",
"the",
"container",
"are",
"of",
"the",
"same",
"Python",
"data",
"type",
".",
"This",
"function",
"is",
"called",
"in",
"every",
"other",
"function",
"below",
"and",
"as",
"such",
"need",
"not",
"neces... | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/utils.py#L9-L19 |
229,388 | ericmjl/nxviz | nxviz/utils.py | infer_data_type | def infer_data_type(data_container):
"""
For a given container of data, infer the type of data as one of
continuous, categorical, or ordinal.
For now, it is a one-to-one mapping as such:
- str: categorical
- int: ordinal
- float: continuous
There may be better ways that are not currently implemented below. For
example, with a list of numbers, we can check whether the number of unique
entries is less than or equal to 12, but has over 10000+ entries. This
would be a good candidate for floats being categorical.
:param data_container: A generic container of data points.
:type data_container: `iterable`
"""
# Defensive programming checks.
# 0. Ensure that we are dealing with lists or tuples, and nothing else.
assert isinstance(data_container, list) or isinstance(
data_container, tuple
), "data_container should be a list or tuple."
# 1. Don't want to deal with only single values.
assert (
len(set(data_container)) > 1
), "There should be more than one value in the data container."
# 2. Don't want to deal with mixed data.
assert is_data_homogenous(
data_container
), "Data are not of a homogenous type!"
# Once we check that the data type of the container is homogenous, we only
# need to check the first element in the data container for its type.
datum = data_container[0]
# Return statements below
# treat binomial data as categorical
# TODO: make tests for this.
if len(set(data_container)) == 2:
return "categorical"
elif isinstance(datum, str):
return "categorical"
elif isinstance(datum, int):
return "ordinal"
elif isinstance(datum, float):
return "continuous"
else:
raise ValueError("Not possible to tell what the data type is.") | python | def infer_data_type(data_container):
# Defensive programming checks.
# 0. Ensure that we are dealing with lists or tuples, and nothing else.
assert isinstance(data_container, list) or isinstance(
data_container, tuple
), "data_container should be a list or tuple."
# 1. Don't want to deal with only single values.
assert (
len(set(data_container)) > 1
), "There should be more than one value in the data container."
# 2. Don't want to deal with mixed data.
assert is_data_homogenous(
data_container
), "Data are not of a homogenous type!"
# Once we check that the data type of the container is homogenous, we only
# need to check the first element in the data container for its type.
datum = data_container[0]
# Return statements below
# treat binomial data as categorical
# TODO: make tests for this.
if len(set(data_container)) == 2:
return "categorical"
elif isinstance(datum, str):
return "categorical"
elif isinstance(datum, int):
return "ordinal"
elif isinstance(datum, float):
return "continuous"
else:
raise ValueError("Not possible to tell what the data type is.") | [
"def",
"infer_data_type",
"(",
"data_container",
")",
":",
"# Defensive programming checks.",
"# 0. Ensure that we are dealing with lists or tuples, and nothing else.",
"assert",
"isinstance",
"(",
"data_container",
",",
"list",
")",
"or",
"isinstance",
"(",
"data_container",
"... | For a given container of data, infer the type of data as one of
continuous, categorical, or ordinal.
For now, it is a one-to-one mapping as such:
- str: categorical
- int: ordinal
- float: continuous
There may be better ways that are not currently implemented below. For
example, with a list of numbers, we can check whether the number of unique
entries is less than or equal to 12, but has over 10000+ entries. This
would be a good candidate for floats being categorical.
:param data_container: A generic container of data points.
:type data_container: `iterable` | [
"For",
"a",
"given",
"container",
"of",
"data",
"infer",
"the",
"type",
"of",
"data",
"as",
"one",
"of",
"continuous",
"categorical",
"or",
"ordinal",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/utils.py#L22-L76 |
229,389 | ericmjl/nxviz | nxviz/utils.py | is_data_diverging | def is_data_diverging(data_container):
"""
We want to use this to check whether the data are diverging or not.
This is a simple check, can be made much more sophisticated.
:param data_container: A generic container of data points.
:type data_container: `iterable`
"""
assert infer_data_type(data_container) in [
"ordinal",
"continuous",
], "Data type should be ordinal or continuous"
# Check whether the data contains negative and positive values.
has_negative = False
has_positive = False
for i in data_container:
if i < 0:
has_negative = True
elif i > 0:
has_positive = True
if has_negative and has_positive:
return True
else:
return False | python | def is_data_diverging(data_container):
assert infer_data_type(data_container) in [
"ordinal",
"continuous",
], "Data type should be ordinal or continuous"
# Check whether the data contains negative and positive values.
has_negative = False
has_positive = False
for i in data_container:
if i < 0:
has_negative = True
elif i > 0:
has_positive = True
if has_negative and has_positive:
return True
else:
return False | [
"def",
"is_data_diverging",
"(",
"data_container",
")",
":",
"assert",
"infer_data_type",
"(",
"data_container",
")",
"in",
"[",
"\"ordinal\"",
",",
"\"continuous\"",
",",
"]",
",",
"\"Data type should be ordinal or continuous\"",
"# Check whether the data contains negative a... | We want to use this to check whether the data are diverging or not.
This is a simple check, can be made much more sophisticated.
:param data_container: A generic container of data points.
:type data_container: `iterable` | [
"We",
"want",
"to",
"use",
"this",
"to",
"check",
"whether",
"the",
"data",
"are",
"diverging",
"or",
"not",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/utils.py#L79-L104 |
229,390 | ericmjl/nxviz | nxviz/utils.py | to_pandas_nodes | def to_pandas_nodes(G): # noqa: N803
"""
Convert nodes in the graph into a pandas DataFrame.
"""
data = []
for n, meta in G.nodes(data=True):
d = dict()
d["node"] = n
d.update(meta)
data.append(d)
return pd.DataFrame(data) | python | def to_pandas_nodes(G): # noqa: N803
data = []
for n, meta in G.nodes(data=True):
d = dict()
d["node"] = n
d.update(meta)
data.append(d)
return pd.DataFrame(data) | [
"def",
"to_pandas_nodes",
"(",
"G",
")",
":",
"# noqa: N803",
"data",
"=",
"[",
"]",
"for",
"n",
",",
"meta",
"in",
"G",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
"d",
"=",
"dict",
"(",
")",
"d",
"[",
"\"node\"",
"]",
"=",
"n",
"d",
"... | Convert nodes in the graph into a pandas DataFrame. | [
"Convert",
"nodes",
"in",
"the",
"graph",
"into",
"a",
"pandas",
"DataFrame",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/utils.py#L167-L177 |
229,391 | ericmjl/nxviz | nxviz/utils.py | to_pandas_edges | def to_pandas_edges(G, x_kw, y_kw, **kwargs): # noqa: N803
"""
Convert Graph edges to pandas DataFrame that's readable to Altair.
"""
# Get all attributes in nodes
attributes = ["source", "target", "x", "y", "edge", "pair"]
for e in G.edges():
attributes += list(G.edges[e].keys())
attributes = list(set(attributes))
# Build a dataframe for all edges and their attributes
df = pd.DataFrame(index=range(G.size() * 2), columns=attributes)
# Add node data to dataframe.
for i, (n1, n2, d) in enumerate(G.edges(data=True)):
idx = i * 2
x = G.node[n1][x_kw]
y = G.node[n1][y_kw]
data1 = dict(
edge=i, source=n1, target=n2, pair=(n1, n2), x=x, y=y, **d
)
data2 = dict(
edge=i, source=n1, target=n2, pair=(n1, n2), x=x, y=y, **d
)
df.loc[idx] = data1
df.loc[idx + 1] = data2
return df | python | def to_pandas_edges(G, x_kw, y_kw, **kwargs): # noqa: N803
# Get all attributes in nodes
attributes = ["source", "target", "x", "y", "edge", "pair"]
for e in G.edges():
attributes += list(G.edges[e].keys())
attributes = list(set(attributes))
# Build a dataframe for all edges and their attributes
df = pd.DataFrame(index=range(G.size() * 2), columns=attributes)
# Add node data to dataframe.
for i, (n1, n2, d) in enumerate(G.edges(data=True)):
idx = i * 2
x = G.node[n1][x_kw]
y = G.node[n1][y_kw]
data1 = dict(
edge=i, source=n1, target=n2, pair=(n1, n2), x=x, y=y, **d
)
data2 = dict(
edge=i, source=n1, target=n2, pair=(n1, n2), x=x, y=y, **d
)
df.loc[idx] = data1
df.loc[idx + 1] = data2
return df | [
"def",
"to_pandas_edges",
"(",
"G",
",",
"x_kw",
",",
"y_kw",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: N803",
"# Get all attributes in nodes",
"attributes",
"=",
"[",
"\"source\"",
",",
"\"target\"",
",",
"\"x\"",
",",
"\"y\"",
",",
"\"edge\"",
",",
"\"pa... | Convert Graph edges to pandas DataFrame that's readable to Altair. | [
"Convert",
"Graph",
"edges",
"to",
"pandas",
"DataFrame",
"that",
"s",
"readable",
"to",
"Altair",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/utils.py#L180-L209 |
229,392 | ericmjl/nxviz | nxviz/geometry.py | node_theta | def node_theta(nodelist, node):
"""
Maps node to Angle.
:param nodelist: Nodelist from the graph.
:type nodelist: list.
:param node: The node of interest. Must be in the nodelist.
:returns: theta -- the angle of the node in radians.
"""
assert len(nodelist) > 0, "nodelist must be a list of items."
assert node in nodelist, "node must be inside nodelist."
i = nodelist.index(node)
theta = -np.pi + i * 2 * np.pi / len(nodelist)
return theta | python | def node_theta(nodelist, node):
assert len(nodelist) > 0, "nodelist must be a list of items."
assert node in nodelist, "node must be inside nodelist."
i = nodelist.index(node)
theta = -np.pi + i * 2 * np.pi / len(nodelist)
return theta | [
"def",
"node_theta",
"(",
"nodelist",
",",
"node",
")",
":",
"assert",
"len",
"(",
"nodelist",
")",
">",
"0",
",",
"\"nodelist must be a list of items.\"",
"assert",
"node",
"in",
"nodelist",
",",
"\"node must be inside nodelist.\"",
"i",
"=",
"nodelist",
".",
"... | Maps node to Angle.
:param nodelist: Nodelist from the graph.
:type nodelist: list.
:param node: The node of interest. Must be in the nodelist.
:returns: theta -- the angle of the node in radians. | [
"Maps",
"node",
"to",
"Angle",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/geometry.py#L9-L24 |
229,393 | ericmjl/nxviz | nxviz/geometry.py | group_theta | def group_theta(node_length, node_idx):
"""
Returns an angle corresponding to a node of interest.
Intended to be used for placing node group labels at the correct spot.
:param float node_length: total number of nodes in the graph.
:param int node_idx: the index of the node of interest.
:returns: theta -- the angle of the node of interest in radians.
"""
theta = -np.pi + node_idx * 2 * np.pi / node_length
return theta | python | def group_theta(node_length, node_idx):
theta = -np.pi + node_idx * 2 * np.pi / node_length
return theta | [
"def",
"group_theta",
"(",
"node_length",
",",
"node_idx",
")",
":",
"theta",
"=",
"-",
"np",
".",
"pi",
"+",
"node_idx",
"*",
"2",
"*",
"np",
".",
"pi",
"/",
"node_length",
"return",
"theta"
] | Returns an angle corresponding to a node of interest.
Intended to be used for placing node group labels at the correct spot.
:param float node_length: total number of nodes in the graph.
:param int node_idx: the index of the node of interest.
:returns: theta -- the angle of the node of interest in radians. | [
"Returns",
"an",
"angle",
"corresponding",
"to",
"a",
"node",
"of",
"interest",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/geometry.py#L27-L38 |
229,394 | ericmjl/nxviz | nxviz/geometry.py | text_alignment | def text_alignment(x, y):
"""
Align text labels based on the x- and y-axis coordinate values.
This function is used for computing the appropriate alignment of the text
label.
For example, if the text is on the "right" side of the plot, we want it to
be left-aligned. If the text is on the "top" side of the plot, we want it
to be bottom-aligned.
:param x, y: (`int` or `float`) x- and y-axis coordinate respectively.
:returns: A 2-tuple of strings, the horizontal and vertical alignments
respectively.
"""
if x == 0:
ha = "center"
elif x > 0:
ha = "left"
else:
ha = "right"
if y == 0:
va = "center"
elif y > 0:
va = "bottom"
else:
va = "top"
return ha, va | python | def text_alignment(x, y):
if x == 0:
ha = "center"
elif x > 0:
ha = "left"
else:
ha = "right"
if y == 0:
va = "center"
elif y > 0:
va = "bottom"
else:
va = "top"
return ha, va | [
"def",
"text_alignment",
"(",
"x",
",",
"y",
")",
":",
"if",
"x",
"==",
"0",
":",
"ha",
"=",
"\"center\"",
"elif",
"x",
">",
"0",
":",
"ha",
"=",
"\"left\"",
"else",
":",
"ha",
"=",
"\"right\"",
"if",
"y",
"==",
"0",
":",
"va",
"=",
"\"center\"... | Align text labels based on the x- and y-axis coordinate values.
This function is used for computing the appropriate alignment of the text
label.
For example, if the text is on the "right" side of the plot, we want it to
be left-aligned. If the text is on the "top" side of the plot, we want it
to be bottom-aligned.
:param x, y: (`int` or `float`) x- and y-axis coordinate respectively.
:returns: A 2-tuple of strings, the horizontal and vertical alignments
respectively. | [
"Align",
"text",
"labels",
"based",
"on",
"the",
"x",
"-",
"and",
"y",
"-",
"axis",
"coordinate",
"values",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/geometry.py#L41-L69 |
229,395 | ericmjl/nxviz | nxviz/geometry.py | circos_radius | def circos_radius(n_nodes, node_r):
"""
Automatically computes the origin-to-node centre radius of the Circos plot
using the triangle equality sine rule.
a / sin(A) = b / sin(B) = c / sin(C)
:param n_nodes: the number of nodes in the plot.
:type n_nodes: int
:param node_r: the radius of each node.
:type node_r: float
:returns: Origin-to-node centre radius.
"""
A = 2 * np.pi / n_nodes # noqa
B = (np.pi - A) / 2 # noqa
a = 2 * node_r
return a * np.sin(B) / np.sin(A) | python | def circos_radius(n_nodes, node_r):
A = 2 * np.pi / n_nodes # noqa
B = (np.pi - A) / 2 # noqa
a = 2 * node_r
return a * np.sin(B) / np.sin(A) | [
"def",
"circos_radius",
"(",
"n_nodes",
",",
"node_r",
")",
":",
"A",
"=",
"2",
"*",
"np",
".",
"pi",
"/",
"n_nodes",
"# noqa",
"B",
"=",
"(",
"np",
".",
"pi",
"-",
"A",
")",
"/",
"2",
"# noqa",
"a",
"=",
"2",
"*",
"node_r",
"return",
"a",
"*... | Automatically computes the origin-to-node centre radius of the Circos plot
using the triangle equality sine rule.
a / sin(A) = b / sin(B) = c / sin(C)
:param n_nodes: the number of nodes in the plot.
:type n_nodes: int
:param node_r: the radius of each node.
:type node_r: float
:returns: Origin-to-node centre radius. | [
"Automatically",
"computes",
"the",
"origin",
"-",
"to",
"-",
"node",
"centre",
"radius",
"of",
"the",
"Circos",
"plot",
"using",
"the",
"triangle",
"equality",
"sine",
"rule",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/geometry.py#L101-L117 |
229,396 | ericmjl/nxviz | nxviz/polcart.py | to_polar | def to_polar(x, y, theta_units="radians"):
"""
Converts cartesian x, y to polar r, theta.
"""
assert theta_units in [
"radians",
"degrees",
], "kwarg theta_units must specified in radians or degrees"
theta = atan2(y, x)
r = sqrt(x ** 2 + y ** 2)
if theta_units == "degrees":
theta = to_degrees(theta)
return r, theta | python | def to_polar(x, y, theta_units="radians"):
assert theta_units in [
"radians",
"degrees",
], "kwarg theta_units must specified in radians or degrees"
theta = atan2(y, x)
r = sqrt(x ** 2 + y ** 2)
if theta_units == "degrees":
theta = to_degrees(theta)
return r, theta | [
"def",
"to_polar",
"(",
"x",
",",
"y",
",",
"theta_units",
"=",
"\"radians\"",
")",
":",
"assert",
"theta_units",
"in",
"[",
"\"radians\"",
",",
"\"degrees\"",
",",
"]",
",",
"\"kwarg theta_units must specified in radians or degrees\"",
"theta",
"=",
"atan2",
"(",... | Converts cartesian x, y to polar r, theta. | [
"Converts",
"cartesian",
"x",
"y",
"to",
"polar",
"r",
"theta",
"."
] | 6ea5823a8030a686f165fbe37d7a04d0f037ecc9 | https://github.com/ericmjl/nxviz/blob/6ea5823a8030a686f165fbe37d7a04d0f037ecc9/nxviz/polcart.py#L25-L40 |
229,397 | Miserlou/SoundScrape | soundscrape/soundscrape.py | download_track | def download_track(track, album_name=u'', keep_previews=False, folders=False, filenames=[], custom_path=''):
"""
Given a track, force scrape it.
"""
hard_track_url = get_hard_track_url(track['id'])
# We have no info on this track whatsoever.
if not 'title' in track:
return None
if not keep_previews:
if (track.get('duration', 0) < track.get('full_duration', 0)):
puts_safe(colored.yellow("Skipping preview track") + colored.white(": " + track['title']))
return None
# May not have a "full name"
name = track['user'].get('full_name', '')
if name == '':
name = track['user']['username']
filename = sanitize_filename(name + ' - ' + track['title'] + '.mp3')
if folders:
name_path = join(custom_path, name)
if not exists(name_path):
mkdir(name_path)
filename = join(name_path, filename)
else:
filename = join(custom_path, filename)
if exists(filename):
puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track['title']))
return None
# Skip already downloaded track.
if filename in filenames:
return None
if hard_track_url:
puts_safe(colored.green("Scraping") + colored.white(": " + track['title']))
else:
# Region coded?
puts_safe(colored.yellow("Unable to download") + colored.white(": " + track['title']))
return None
filename = download_file(hard_track_url, filename)
tagged = tag_file(filename,
artist=name,
title=track['title'],
year=track['created_at'][:4],
genre=track['genre'],
album=album_name,
artwork_url=track['artwork_url'])
if not tagged:
wav_filename = filename[:-3] + 'wav'
os.rename(filename, wav_filename)
filename = wav_filename
return filename | python | def download_track(track, album_name=u'', keep_previews=False, folders=False, filenames=[], custom_path=''):
hard_track_url = get_hard_track_url(track['id'])
# We have no info on this track whatsoever.
if not 'title' in track:
return None
if not keep_previews:
if (track.get('duration', 0) < track.get('full_duration', 0)):
puts_safe(colored.yellow("Skipping preview track") + colored.white(": " + track['title']))
return None
# May not have a "full name"
name = track['user'].get('full_name', '')
if name == '':
name = track['user']['username']
filename = sanitize_filename(name + ' - ' + track['title'] + '.mp3')
if folders:
name_path = join(custom_path, name)
if not exists(name_path):
mkdir(name_path)
filename = join(name_path, filename)
else:
filename = join(custom_path, filename)
if exists(filename):
puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track['title']))
return None
# Skip already downloaded track.
if filename in filenames:
return None
if hard_track_url:
puts_safe(colored.green("Scraping") + colored.white(": " + track['title']))
else:
# Region coded?
puts_safe(colored.yellow("Unable to download") + colored.white(": " + track['title']))
return None
filename = download_file(hard_track_url, filename)
tagged = tag_file(filename,
artist=name,
title=track['title'],
year=track['created_at'][:4],
genre=track['genre'],
album=album_name,
artwork_url=track['artwork_url'])
if not tagged:
wav_filename = filename[:-3] + 'wav'
os.rename(filename, wav_filename)
filename = wav_filename
return filename | [
"def",
"download_track",
"(",
"track",
",",
"album_name",
"=",
"u''",
",",
"keep_previews",
"=",
"False",
",",
"folders",
"=",
"False",
",",
"filenames",
"=",
"[",
"]",
",",
"custom_path",
"=",
"''",
")",
":",
"hard_track_url",
"=",
"get_hard_track_url",
"... | Given a track, force scrape it. | [
"Given",
"a",
"track",
"force",
"scrape",
"it",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L307-L366 |
229,398 | Miserlou/SoundScrape | soundscrape/soundscrape.py | get_soundcloud_data | def get_soundcloud_data(url):
"""
Scrapes a SoundCloud page for a track's important information.
Returns:
dict: of audio data
"""
data = {}
request = requests.get(url)
title_tag = request.text.split('<title>')[1].split('</title')[0]
data['title'] = title_tag.split(' by ')[0].strip()
data['artist'] = title_tag.split(' by ')[1].split('|')[0].strip()
# XXX Do more..
return data | python | def get_soundcloud_data(url):
data = {}
request = requests.get(url)
title_tag = request.text.split('<title>')[1].split('</title')[0]
data['title'] = title_tag.split(' by ')[0].strip()
data['artist'] = title_tag.split(' by ')[1].split('|')[0].strip()
# XXX Do more..
return data | [
"def",
"get_soundcloud_data",
"(",
"url",
")",
":",
"data",
"=",
"{",
"}",
"request",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"title_tag",
"=",
"request",
".",
"text",
".",
"split",
"(",
"'<title>'",
")",
"[",
"1",
"]",
".",
"split",
"(",
"'<... | Scrapes a SoundCloud page for a track's important information.
Returns:
dict: of audio data | [
"Scrapes",
"a",
"SoundCloud",
"page",
"for",
"a",
"track",
"s",
"important",
"information",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L470-L488 |
229,399 | Miserlou/SoundScrape | soundscrape/soundscrape.py | get_hard_track_url | def get_hard_track_url(item_id):
"""
Hard-scrapes a track.
"""
streams_url = "https://api.soundcloud.com/i1/tracks/%s/streams/?client_id=%s&app_version=%s" % (
item_id, AGGRESSIVE_CLIENT_ID, APP_VERSION)
response = requests.get(streams_url)
json_response = response.json()
if response.status_code == 200:
hard_track_url = json_response['http_mp3_128_url']
return hard_track_url
else:
return None | python | def get_hard_track_url(item_id):
streams_url = "https://api.soundcloud.com/i1/tracks/%s/streams/?client_id=%s&app_version=%s" % (
item_id, AGGRESSIVE_CLIENT_ID, APP_VERSION)
response = requests.get(streams_url)
json_response = response.json()
if response.status_code == 200:
hard_track_url = json_response['http_mp3_128_url']
return hard_track_url
else:
return None | [
"def",
"get_hard_track_url",
"(",
"item_id",
")",
":",
"streams_url",
"=",
"\"https://api.soundcloud.com/i1/tracks/%s/streams/?client_id=%s&app_version=%s\"",
"%",
"(",
"item_id",
",",
"AGGRESSIVE_CLIENT_ID",
",",
"APP_VERSION",
")",
"response",
"=",
"requests",
".",
"get",... | Hard-scrapes a track. | [
"Hard",
"-",
"scrapes",
"a",
"track",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L515-L529 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.