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 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
guaix-ucm/numina | numina/array/combine.py | minmax | def minmax(arrays, masks=None, dtype=None, out=None, zeros=None,
scales=None, weights=None, nmin=1, nmax=1):
"""Combine arrays using mix max rejection, with masks.
Inputs and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains the mean,
out[1] the variance and out[2] the number of points used.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:param nmin:
:param nmax:
:return: mean, variance of the mean and number of points stored
"""
return generic_combine(intl_combine.minmax_method(nmin, nmax), arrays,
masks=masks, dtype=dtype, out=out,
zeros=zeros, scales=scales, weights=weights) | python | def minmax(arrays, masks=None, dtype=None, out=None, zeros=None,
scales=None, weights=None, nmin=1, nmax=1):
"""Combine arrays using mix max rejection, with masks.
Inputs and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains the mean,
out[1] the variance and out[2] the number of points used.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:param nmin:
:param nmax:
:return: mean, variance of the mean and number of points stored
"""
return generic_combine(intl_combine.minmax_method(nmin, nmax), arrays,
masks=masks, dtype=dtype, out=out,
zeros=zeros, scales=scales, weights=weights) | [
"def",
"minmax",
"(",
"arrays",
",",
"masks",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"zeros",
"=",
"None",
",",
"scales",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"nmin",
"=",
"1",
",",
"nmax",
"=",
"1",
")",
":",
"return",
"generic_combine",
"(",
"intl_combine",
".",
"minmax_method",
"(",
"nmin",
",",
"nmax",
")",
",",
"arrays",
",",
"masks",
"=",
"masks",
",",
"dtype",
"=",
"dtype",
",",
"out",
"=",
"out",
",",
"zeros",
"=",
"zeros",
",",
"scales",
"=",
"scales",
",",
"weights",
"=",
"weights",
")"
] | Combine arrays using mix max rejection, with masks.
Inputs and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains the mean,
out[1] the variance and out[2] the number of points used.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:param nmin:
:param nmax:
:return: mean, variance of the mean and number of points stored | [
"Combine",
"arrays",
"using",
"mix",
"max",
"rejection",
"with",
"masks",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L115-L138 | train |
guaix-ucm/numina | numina/array/combine.py | flatcombine | def flatcombine(arrays, masks=None, dtype=None, scales=None,
low=3.0, high=3.0, blank=1.0):
"""Combine flat arrays.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:param blank: non-positive values are substituted by this on output
:return: mean, variance of the mean and number of points stored
"""
result = sigmaclip(arrays, masks=masks,
dtype=dtype, scales=scales,
low=low, high=high)
# Substitute values <= 0 by blank
mm = result[0] <= 0
result[0, mm] = blank
# Add values to mask
result[1:2, mm] = 0
return result | python | def flatcombine(arrays, masks=None, dtype=None, scales=None,
low=3.0, high=3.0, blank=1.0):
"""Combine flat arrays.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:param blank: non-positive values are substituted by this on output
:return: mean, variance of the mean and number of points stored
"""
result = sigmaclip(arrays, masks=masks,
dtype=dtype, scales=scales,
low=low, high=high)
# Substitute values <= 0 by blank
mm = result[0] <= 0
result[0, mm] = blank
# Add values to mask
result[1:2, mm] = 0
return result | [
"def",
"flatcombine",
"(",
"arrays",
",",
"masks",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"scales",
"=",
"None",
",",
"low",
"=",
"3.0",
",",
"high",
"=",
"3.0",
",",
"blank",
"=",
"1.0",
")",
":",
"result",
"=",
"sigmaclip",
"(",
"arrays",
",",
"masks",
"=",
"masks",
",",
"dtype",
"=",
"dtype",
",",
"scales",
"=",
"scales",
",",
"low",
"=",
"low",
",",
"high",
"=",
"high",
")",
"# Substitute values <= 0 by blank",
"mm",
"=",
"result",
"[",
"0",
"]",
"<=",
"0",
"result",
"[",
"0",
",",
"mm",
"]",
"=",
"blank",
"# Add values to mask",
"result",
"[",
"1",
":",
"2",
",",
"mm",
"]",
"=",
"0",
"return",
"result"
] | Combine flat arrays.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:param blank: non-positive values are substituted by this on output
:return: mean, variance of the mean and number of points stored | [
"Combine",
"flat",
"arrays",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L166-L188 | train |
guaix-ucm/numina | numina/array/combine.py | zerocombine | def zerocombine(arrays, masks, dtype=None, scales=None):
"""Combine zero arrays.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param scales:
:return: median, variance of the median and number of points stored
"""
result = median(arrays, masks=masks,
dtype=dtype, scales=scales)
return result | python | def zerocombine(arrays, masks, dtype=None, scales=None):
"""Combine zero arrays.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param scales:
:return: median, variance of the median and number of points stored
"""
result = median(arrays, masks=masks,
dtype=dtype, scales=scales)
return result | [
"def",
"zerocombine",
"(",
"arrays",
",",
"masks",
",",
"dtype",
"=",
"None",
",",
"scales",
"=",
"None",
")",
":",
"result",
"=",
"median",
"(",
"arrays",
",",
"masks",
"=",
"masks",
",",
"dtype",
"=",
"dtype",
",",
"scales",
"=",
"scales",
")",
"return",
"result"
] | Combine zero arrays.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param scales:
:return: median, variance of the median and number of points stored | [
"Combine",
"zero",
"arrays",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L191-L204 | train |
guaix-ucm/numina | numina/array/combine.py | sum | def sum(arrays, masks=None, dtype=None, out=None,
zeros=None, scales=None):
"""Combine arrays by addition, with masks and offsets.
Arrays and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains the sum,
out[1] the variance and out[2] the number of points used.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:return: sum, variance of the sum and number of points stored
Example:
>>> import numpy
>>> image = numpy.array([[1., 3.], [1., -1.4]])
>>> inputs = [image, image + 1]
>>> sum(inputs)
array([[[ 1.5, 3.5],
[ 1.5, -0.9]],
<BLANKLINE>
[[ 0.5, 0.5],
[ 0.5, 0.5]],
<BLANKLINE>
[[ 2. , 2. ],
[ 2. , 2. ]]])
"""
return generic_combine(intl_combine.sum_method(), arrays, masks=masks,
dtype=dtype, out=out,
zeros=zeros, scales=scales) | python | def sum(arrays, masks=None, dtype=None, out=None,
zeros=None, scales=None):
"""Combine arrays by addition, with masks and offsets.
Arrays and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains the sum,
out[1] the variance and out[2] the number of points used.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:return: sum, variance of the sum and number of points stored
Example:
>>> import numpy
>>> image = numpy.array([[1., 3.], [1., -1.4]])
>>> inputs = [image, image + 1]
>>> sum(inputs)
array([[[ 1.5, 3.5],
[ 1.5, -0.9]],
<BLANKLINE>
[[ 0.5, 0.5],
[ 0.5, 0.5]],
<BLANKLINE>
[[ 2. , 2. ],
[ 2. , 2. ]]])
"""
return generic_combine(intl_combine.sum_method(), arrays, masks=masks,
dtype=dtype, out=out,
zeros=zeros, scales=scales) | [
"def",
"sum",
"(",
"arrays",
",",
"masks",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"zeros",
"=",
"None",
",",
"scales",
"=",
"None",
")",
":",
"return",
"generic_combine",
"(",
"intl_combine",
".",
"sum_method",
"(",
")",
",",
"arrays",
",",
"masks",
"=",
"masks",
",",
"dtype",
"=",
"dtype",
",",
"out",
"=",
"out",
",",
"zeros",
"=",
"zeros",
",",
"scales",
"=",
"scales",
")"
] | Combine arrays by addition, with masks and offsets.
Arrays and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains the sum,
out[1] the variance and out[2] the number of points used.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:return: sum, variance of the sum and number of points stored
Example:
>>> import numpy
>>> image = numpy.array([[1., 3.], [1., -1.4]])
>>> inputs = [image, image + 1]
>>> sum(inputs)
array([[[ 1.5, 3.5],
[ 1.5, -0.9]],
<BLANKLINE>
[[ 0.5, 0.5],
[ 0.5, 0.5]],
<BLANKLINE>
[[ 2. , 2. ],
[ 2. , 2. ]]]) | [
"Combine",
"arrays",
"by",
"addition",
"with",
"masks",
"and",
"offsets",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L207-L242 | train |
guaix-ucm/numina | numina/array/combine.py | generic_combine | def generic_combine(method, arrays, masks=None, dtype=None,
out=None, zeros=None, scales=None, weights=None):
"""Stack arrays using different methods.
:param method: the combination method
:type method: PyCObject
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param zeros:
:param scales:
:param weights:
:return: median, variance of the median and number of points stored
"""
arrays = [numpy.asarray(arr, dtype=dtype) for arr in arrays]
if masks is not None:
masks = [numpy.asarray(msk) for msk in masks]
if out is None:
# Creating out if needed
# We need three numbers
try:
outshape = (3,) + tuple(arrays[0].shape)
out = numpy.zeros(outshape, dtype)
except AttributeError:
raise TypeError('First element in arrays does '
'not have .shape attribute')
else:
out = numpy.asanyarray(out)
intl_combine.generic_combine(
method, arrays,
out[0], out[1], out[2],
masks, zeros, scales, weights
)
return out | python | def generic_combine(method, arrays, masks=None, dtype=None,
out=None, zeros=None, scales=None, weights=None):
"""Stack arrays using different methods.
:param method: the combination method
:type method: PyCObject
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param zeros:
:param scales:
:param weights:
:return: median, variance of the median and number of points stored
"""
arrays = [numpy.asarray(arr, dtype=dtype) for arr in arrays]
if masks is not None:
masks = [numpy.asarray(msk) for msk in masks]
if out is None:
# Creating out if needed
# We need three numbers
try:
outshape = (3,) + tuple(arrays[0].shape)
out = numpy.zeros(outshape, dtype)
except AttributeError:
raise TypeError('First element in arrays does '
'not have .shape attribute')
else:
out = numpy.asanyarray(out)
intl_combine.generic_combine(
method, arrays,
out[0], out[1], out[2],
masks, zeros, scales, weights
)
return out | [
"def",
"generic_combine",
"(",
"method",
",",
"arrays",
",",
"masks",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"out",
"=",
"None",
",",
"zeros",
"=",
"None",
",",
"scales",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"arrays",
"=",
"[",
"numpy",
".",
"asarray",
"(",
"arr",
",",
"dtype",
"=",
"dtype",
")",
"for",
"arr",
"in",
"arrays",
"]",
"if",
"masks",
"is",
"not",
"None",
":",
"masks",
"=",
"[",
"numpy",
".",
"asarray",
"(",
"msk",
")",
"for",
"msk",
"in",
"masks",
"]",
"if",
"out",
"is",
"None",
":",
"# Creating out if needed",
"# We need three numbers",
"try",
":",
"outshape",
"=",
"(",
"3",
",",
")",
"+",
"tuple",
"(",
"arrays",
"[",
"0",
"]",
".",
"shape",
")",
"out",
"=",
"numpy",
".",
"zeros",
"(",
"outshape",
",",
"dtype",
")",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"'First element in arrays does '",
"'not have .shape attribute'",
")",
"else",
":",
"out",
"=",
"numpy",
".",
"asanyarray",
"(",
"out",
")",
"intl_combine",
".",
"generic_combine",
"(",
"method",
",",
"arrays",
",",
"out",
"[",
"0",
"]",
",",
"out",
"[",
"1",
"]",
",",
"out",
"[",
"2",
"]",
",",
"masks",
",",
"zeros",
",",
"scales",
",",
"weights",
")",
"return",
"out"
] | Stack arrays using different methods.
:param method: the combination method
:type method: PyCObject
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param zeros:
:param scales:
:param weights:
:return: median, variance of the median and number of points stored | [
"Stack",
"arrays",
"using",
"different",
"methods",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L245-L281 | train |
guaix-ucm/numina | numina/array/fwhm.py | compute_fwhm_1d_simple | def compute_fwhm_1d_simple(Y, xc, X=None):
"""Compute the FWHM."""
return compute_fw_at_frac_max_1d_simple(Y, xc, X=X, f=0.5) | python | def compute_fwhm_1d_simple(Y, xc, X=None):
"""Compute the FWHM."""
return compute_fw_at_frac_max_1d_simple(Y, xc, X=X, f=0.5) | [
"def",
"compute_fwhm_1d_simple",
"(",
"Y",
",",
"xc",
",",
"X",
"=",
"None",
")",
":",
"return",
"compute_fw_at_frac_max_1d_simple",
"(",
"Y",
",",
"xc",
",",
"X",
"=",
"X",
",",
"f",
"=",
"0.5",
")"
] | Compute the FWHM. | [
"Compute",
"the",
"FWHM",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/fwhm.py#L63-L65 | train |
guaix-ucm/numina | numina/array/fwhm.py | compute_fw_at_frac_max_1d_simple | def compute_fw_at_frac_max_1d_simple(Y, xc, X=None, f=0.5):
"""Compute the full width at fraction f of the maximum"""
yy = np.asarray(Y)
if yy.ndim != 1:
raise ValueError('array must be 1-d')
if yy.size == 0:
raise ValueError('array is empty')
if X is None:
xx = np.arange(yy.shape[0])
else:
xx = X
xpix = coor_to_pix_1d(xc - xx[0])
try:
peak = yy[xpix]
except IndexError:
raise ValueError('peak is out of array')
fwhm_x, _codex, _msgx = compute_fwhm_1d(xx, yy - f * peak, xc, xpix)
return peak, fwhm_x | python | def compute_fw_at_frac_max_1d_simple(Y, xc, X=None, f=0.5):
"""Compute the full width at fraction f of the maximum"""
yy = np.asarray(Y)
if yy.ndim != 1:
raise ValueError('array must be 1-d')
if yy.size == 0:
raise ValueError('array is empty')
if X is None:
xx = np.arange(yy.shape[0])
else:
xx = X
xpix = coor_to_pix_1d(xc - xx[0])
try:
peak = yy[xpix]
except IndexError:
raise ValueError('peak is out of array')
fwhm_x, _codex, _msgx = compute_fwhm_1d(xx, yy - f * peak, xc, xpix)
return peak, fwhm_x | [
"def",
"compute_fw_at_frac_max_1d_simple",
"(",
"Y",
",",
"xc",
",",
"X",
"=",
"None",
",",
"f",
"=",
"0.5",
")",
":",
"yy",
"=",
"np",
".",
"asarray",
"(",
"Y",
")",
"if",
"yy",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'array must be 1-d'",
")",
"if",
"yy",
".",
"size",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'array is empty'",
")",
"if",
"X",
"is",
"None",
":",
"xx",
"=",
"np",
".",
"arange",
"(",
"yy",
".",
"shape",
"[",
"0",
"]",
")",
"else",
":",
"xx",
"=",
"X",
"xpix",
"=",
"coor_to_pix_1d",
"(",
"xc",
"-",
"xx",
"[",
"0",
"]",
")",
"try",
":",
"peak",
"=",
"yy",
"[",
"xpix",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"'peak is out of array'",
")",
"fwhm_x",
",",
"_codex",
",",
"_msgx",
"=",
"compute_fwhm_1d",
"(",
"xx",
",",
"yy",
"-",
"f",
"*",
"peak",
",",
"xc",
",",
"xpix",
")",
"return",
"peak",
",",
"fwhm_x"
] | Compute the full width at fraction f of the maximum | [
"Compute",
"the",
"full",
"width",
"at",
"fraction",
"f",
"of",
"the",
"maximum"
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/fwhm.py#L68-L92 | train |
guaix-ucm/numina | numina/array/fwhm.py | _fwhm_side_lineal | def _fwhm_side_lineal(uu, vv):
'''Compute r12 using linear interpolation.'''
res1, = np.nonzero(vv < 0)
if len(res1) == 0:
return 0, 1 # error, no negative value
else:
# first value
i2 = res1[0]
i1 = i2 - 1
dx = uu[i2] - uu[i1]
dy = vv[i2] - vv[i1]
r12 = uu[i1] - vv[i1] * dx / dy
return r12, 0 | python | def _fwhm_side_lineal(uu, vv):
'''Compute r12 using linear interpolation.'''
res1, = np.nonzero(vv < 0)
if len(res1) == 0:
return 0, 1 # error, no negative value
else:
# first value
i2 = res1[0]
i1 = i2 - 1
dx = uu[i2] - uu[i1]
dy = vv[i2] - vv[i1]
r12 = uu[i1] - vv[i1] * dx / dy
return r12, 0 | [
"def",
"_fwhm_side_lineal",
"(",
"uu",
",",
"vv",
")",
":",
"res1",
",",
"=",
"np",
".",
"nonzero",
"(",
"vv",
"<",
"0",
")",
"if",
"len",
"(",
"res1",
")",
"==",
"0",
":",
"return",
"0",
",",
"1",
"# error, no negative value",
"else",
":",
"# first value",
"i2",
"=",
"res1",
"[",
"0",
"]",
"i1",
"=",
"i2",
"-",
"1",
"dx",
"=",
"uu",
"[",
"i2",
"]",
"-",
"uu",
"[",
"i1",
"]",
"dy",
"=",
"vv",
"[",
"i2",
"]",
"-",
"vv",
"[",
"i1",
"]",
"r12",
"=",
"uu",
"[",
"i1",
"]",
"-",
"vv",
"[",
"i1",
"]",
"*",
"dx",
"/",
"dy",
"return",
"r12",
",",
"0"
] | Compute r12 using linear interpolation. | [
"Compute",
"r12",
"using",
"linear",
"interpolation",
"."
] | 6c829495df8937f77c2de9383c1038ffb3e713e3 | https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/fwhm.py#L95-L107 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | get_ZPE | def get_ZPE(viblist):
"""Returns the zero point energy from a list of frequencies.
Parameters
----------
viblist : List of numbers or string of list of numbers.
Returns
-------
ZPE : Zero point energy in eV.
"""
if type(viblist) is str:
l = ast.literal_eval(viblist)
else:
l = viblist
l = [float(w) for w in l]
ZPE = 0.5*sum(l)*cm2ev
return(ZPE) | python | def get_ZPE(viblist):
"""Returns the zero point energy from a list of frequencies.
Parameters
----------
viblist : List of numbers or string of list of numbers.
Returns
-------
ZPE : Zero point energy in eV.
"""
if type(viblist) is str:
l = ast.literal_eval(viblist)
else:
l = viblist
l = [float(w) for w in l]
ZPE = 0.5*sum(l)*cm2ev
return(ZPE) | [
"def",
"get_ZPE",
"(",
"viblist",
")",
":",
"if",
"type",
"(",
"viblist",
")",
"is",
"str",
":",
"l",
"=",
"ast",
".",
"literal_eval",
"(",
"viblist",
")",
"else",
":",
"l",
"=",
"viblist",
"l",
"=",
"[",
"float",
"(",
"w",
")",
"for",
"w",
"in",
"l",
"]",
"ZPE",
"=",
"0.5",
"*",
"sum",
"(",
"l",
")",
"*",
"cm2ev",
"return",
"(",
"ZPE",
")"
] | Returns the zero point energy from a list of frequencies.
Parameters
----------
viblist : List of numbers or string of list of numbers.
Returns
-------
ZPE : Zero point energy in eV. | [
"Returns",
"the",
"zero",
"point",
"energy",
"from",
"a",
"list",
"of",
"frequencies",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L276-L293 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | auto_labels | def auto_labels(df):
"""Transforms atomic system information into well-formatted labels.
Parameters
----------
df : Pandas DataFrame.
Returns
-------
labels : list of system labels.
"""
systems = list(df.system)
facets = list(df.facet)
systems_labels = [w.replace('_', '\ ') for w in systems]
systems_labels = [sub(w) for w in systems_labels]
systems_labels = [w.replace('}$$_{', '') for w in systems_labels]
systems_labels = [w.replace('$', '') for w in systems_labels]
systems_labels = ['$' + w + '$' for w in systems_labels]
facets_label = [w.replace('_', '\ ') for w in facets]
facets_label = ['(' + w + ')' for w in facets_label]
labels = []
for i, sys in enumerate(systems_labels):
labels.append(sys + facets_label[i])
# labels = list(set(labels))
return(labels) | python | def auto_labels(df):
"""Transforms atomic system information into well-formatted labels.
Parameters
----------
df : Pandas DataFrame.
Returns
-------
labels : list of system labels.
"""
systems = list(df.system)
facets = list(df.facet)
systems_labels = [w.replace('_', '\ ') for w in systems]
systems_labels = [sub(w) for w in systems_labels]
systems_labels = [w.replace('}$$_{', '') for w in systems_labels]
systems_labels = [w.replace('$', '') for w in systems_labels]
systems_labels = ['$' + w + '$' for w in systems_labels]
facets_label = [w.replace('_', '\ ') for w in facets]
facets_label = ['(' + w + ')' for w in facets_label]
labels = []
for i, sys in enumerate(systems_labels):
labels.append(sys + facets_label[i])
# labels = list(set(labels))
return(labels) | [
"def",
"auto_labels",
"(",
"df",
")",
":",
"systems",
"=",
"list",
"(",
"df",
".",
"system",
")",
"facets",
"=",
"list",
"(",
"df",
".",
"facet",
")",
"systems_labels",
"=",
"[",
"w",
".",
"replace",
"(",
"'_'",
",",
"'\\ '",
")",
"for",
"w",
"in",
"systems",
"]",
"systems_labels",
"=",
"[",
"sub",
"(",
"w",
")",
"for",
"w",
"in",
"systems_labels",
"]",
"systems_labels",
"=",
"[",
"w",
".",
"replace",
"(",
"'}$$_{'",
",",
"''",
")",
"for",
"w",
"in",
"systems_labels",
"]",
"systems_labels",
"=",
"[",
"w",
".",
"replace",
"(",
"'$'",
",",
"''",
")",
"for",
"w",
"in",
"systems_labels",
"]",
"systems_labels",
"=",
"[",
"'$'",
"+",
"w",
"+",
"'$'",
"for",
"w",
"in",
"systems_labels",
"]",
"facets_label",
"=",
"[",
"w",
".",
"replace",
"(",
"'_'",
",",
"'\\ '",
")",
"for",
"w",
"in",
"facets",
"]",
"facets_label",
"=",
"[",
"'('",
"+",
"w",
"+",
"')'",
"for",
"w",
"in",
"facets_label",
"]",
"labels",
"=",
"[",
"]",
"for",
"i",
",",
"sys",
"in",
"enumerate",
"(",
"systems_labels",
")",
":",
"labels",
".",
"append",
"(",
"sys",
"+",
"facets_label",
"[",
"i",
"]",
")",
"# labels = list(set(labels))",
"return",
"(",
"labels",
")"
] | Transforms atomic system information into well-formatted labels.
Parameters
----------
df : Pandas DataFrame.
Returns
-------
labels : list of system labels. | [
"Transforms",
"atomic",
"system",
"information",
"into",
"well",
"-",
"formatted",
"labels",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L295-L321 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | proton_hydroxide_free_energy | def proton_hydroxide_free_energy(temperature, pressure, pH):
"""Returns the Gibbs free energy of proton in bulk solution.
Parameters
----------
pH : pH of bulk solution
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
Returns
-------
G_H, G_OH : Gibbs free energy of proton and hydroxide.
"""
H2 = GasMolecule('H2')
H2O = GasMolecule('H2O')
G_H2 = H2.get_free_energy(temperature = temperature, pressure = pressure)
G_H2O = H2O.get_free_energy(temperature = temperature)
G_H = (0.5*G_H2) - ((R*temperature)/(z*F))*ln10*pH
G_OH = G_H2O - G_H # Do not need Kw when water equilibrated
return(G_H, G_OH) | python | def proton_hydroxide_free_energy(temperature, pressure, pH):
"""Returns the Gibbs free energy of proton in bulk solution.
Parameters
----------
pH : pH of bulk solution
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
Returns
-------
G_H, G_OH : Gibbs free energy of proton and hydroxide.
"""
H2 = GasMolecule('H2')
H2O = GasMolecule('H2O')
G_H2 = H2.get_free_energy(temperature = temperature, pressure = pressure)
G_H2O = H2O.get_free_energy(temperature = temperature)
G_H = (0.5*G_H2) - ((R*temperature)/(z*F))*ln10*pH
G_OH = G_H2O - G_H # Do not need Kw when water equilibrated
return(G_H, G_OH) | [
"def",
"proton_hydroxide_free_energy",
"(",
"temperature",
",",
"pressure",
",",
"pH",
")",
":",
"H2",
"=",
"GasMolecule",
"(",
"'H2'",
")",
"H2O",
"=",
"GasMolecule",
"(",
"'H2O'",
")",
"G_H2",
"=",
"H2",
".",
"get_free_energy",
"(",
"temperature",
"=",
"temperature",
",",
"pressure",
"=",
"pressure",
")",
"G_H2O",
"=",
"H2O",
".",
"get_free_energy",
"(",
"temperature",
"=",
"temperature",
")",
"G_H",
"=",
"(",
"0.5",
"*",
"G_H2",
")",
"-",
"(",
"(",
"R",
"*",
"temperature",
")",
"/",
"(",
"z",
"*",
"F",
")",
")",
"*",
"ln10",
"*",
"pH",
"G_OH",
"=",
"G_H2O",
"-",
"G_H",
"# Do not need Kw when water equilibrated",
"return",
"(",
"G_H",
",",
"G_OH",
")"
] | Returns the Gibbs free energy of proton in bulk solution.
Parameters
----------
pH : pH of bulk solution
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
Returns
-------
G_H, G_OH : Gibbs free energy of proton and hydroxide. | [
"Returns",
"the",
"Gibbs",
"free",
"energy",
"of",
"proton",
"in",
"bulk",
"solution",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L323-L344 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | get_FEC | def get_FEC(molecule_list, temperature, pressure, electronic_energy='Default'):
"""Returns the Gibbs free energy corrections to be added to raw reaction energies.
Parameters
----------
molecule_list : list of strings
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
Returns
-------
G_H, G_OH : Gibbs free energy of proton and hydroxide.
"""
if not temperature or not pressure:
return(0)
else:
molecule_list = [m for m in molecule_list if m != 'star']
# print(molecule_list)
FEC_sum = []
for molecule in molecule_list:
if 'gas' in molecule:
mol = GasMolecule(molecule.replace('gas', ''))
if pressure == 'Default':
p = mol.pressure
else:
p = pressure
if electronic_energy == 'Default':
ee = mol.electronic_energy
else:
ee = electronic_energy
FEC = mol.get_free_energy(temperature=temperature, pressure=p, electronic_energy = ee)
FEC_sum.append(FEC)
if 'star' in molecule:
FEC = Adsorbate(molecule.replace('star', ''))
FEC = FEC.get_helmholtz_energy(temperature=temperature)
FEC_sum.append(FEC)
FEC_sum = sum(FEC_sum)
return (FEC_sum) | python | def get_FEC(molecule_list, temperature, pressure, electronic_energy='Default'):
"""Returns the Gibbs free energy corrections to be added to raw reaction energies.
Parameters
----------
molecule_list : list of strings
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
Returns
-------
G_H, G_OH : Gibbs free energy of proton and hydroxide.
"""
if not temperature or not pressure:
return(0)
else:
molecule_list = [m for m in molecule_list if m != 'star']
# print(molecule_list)
FEC_sum = []
for molecule in molecule_list:
if 'gas' in molecule:
mol = GasMolecule(molecule.replace('gas', ''))
if pressure == 'Default':
p = mol.pressure
else:
p = pressure
if electronic_energy == 'Default':
ee = mol.electronic_energy
else:
ee = electronic_energy
FEC = mol.get_free_energy(temperature=temperature, pressure=p, electronic_energy = ee)
FEC_sum.append(FEC)
if 'star' in molecule:
FEC = Adsorbate(molecule.replace('star', ''))
FEC = FEC.get_helmholtz_energy(temperature=temperature)
FEC_sum.append(FEC)
FEC_sum = sum(FEC_sum)
return (FEC_sum) | [
"def",
"get_FEC",
"(",
"molecule_list",
",",
"temperature",
",",
"pressure",
",",
"electronic_energy",
"=",
"'Default'",
")",
":",
"if",
"not",
"temperature",
"or",
"not",
"pressure",
":",
"return",
"(",
"0",
")",
"else",
":",
"molecule_list",
"=",
"[",
"m",
"for",
"m",
"in",
"molecule_list",
"if",
"m",
"!=",
"'star'",
"]",
"# print(molecule_list)",
"FEC_sum",
"=",
"[",
"]",
"for",
"molecule",
"in",
"molecule_list",
":",
"if",
"'gas'",
"in",
"molecule",
":",
"mol",
"=",
"GasMolecule",
"(",
"molecule",
".",
"replace",
"(",
"'gas'",
",",
"''",
")",
")",
"if",
"pressure",
"==",
"'Default'",
":",
"p",
"=",
"mol",
".",
"pressure",
"else",
":",
"p",
"=",
"pressure",
"if",
"electronic_energy",
"==",
"'Default'",
":",
"ee",
"=",
"mol",
".",
"electronic_energy",
"else",
":",
"ee",
"=",
"electronic_energy",
"FEC",
"=",
"mol",
".",
"get_free_energy",
"(",
"temperature",
"=",
"temperature",
",",
"pressure",
"=",
"p",
",",
"electronic_energy",
"=",
"ee",
")",
"FEC_sum",
".",
"append",
"(",
"FEC",
")",
"if",
"'star'",
"in",
"molecule",
":",
"FEC",
"=",
"Adsorbate",
"(",
"molecule",
".",
"replace",
"(",
"'star'",
",",
"''",
")",
")",
"FEC",
"=",
"FEC",
".",
"get_helmholtz_energy",
"(",
"temperature",
"=",
"temperature",
")",
"FEC_sum",
".",
"append",
"(",
"FEC",
")",
"FEC_sum",
"=",
"sum",
"(",
"FEC_sum",
")",
"return",
"(",
"FEC_sum",
")"
] | Returns the Gibbs free energy corrections to be added to raw reaction energies.
Parameters
----------
molecule_list : list of strings
temperature : numeric
temperature in K
pressure : numeric
pressure in mbar
Returns
-------
G_H, G_OH : Gibbs free energy of proton and hydroxide. | [
"Returns",
"the",
"Gibbs",
"free",
"energy",
"corrections",
"to",
"be",
"added",
"to",
"raw",
"reaction",
"energies",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L346-L385 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | select_data | def select_data(db_file, slab=None, facet=None):
"""Gathers relevant data from SQL database generated by CATHUB.
Parameters
----------
db_file : Path to database
slab : Which metal (slab) to select.
facet : Which facets to select.
Returns
-------
data : SQL cursor output.
"""
con = sql.connect(db_file)
cur = con.cursor()
if slab and facet:
select_command = 'select chemical_composition, facet, reactants, products, reaction_energy ' \
'from reaction where facet='+str(facet)+' and chemical_composition LIKE "%'+slab+'%";'
elif slab and not facet:
select_command = 'select chemical_composition, facet, reactants, products, reaction_energy ' \
'from reaction where chemical_composition LIKE "%'+slab+'%";'
else:
select_command = 'select chemical_composition, facet, reactants, products, reaction_energy from reaction;'
cur.execute(select_command)
data = cur.fetchall()
return(data) | python | def select_data(db_file, slab=None, facet=None):
"""Gathers relevant data from SQL database generated by CATHUB.
Parameters
----------
db_file : Path to database
slab : Which metal (slab) to select.
facet : Which facets to select.
Returns
-------
data : SQL cursor output.
"""
con = sql.connect(db_file)
cur = con.cursor()
if slab and facet:
select_command = 'select chemical_composition, facet, reactants, products, reaction_energy ' \
'from reaction where facet='+str(facet)+' and chemical_composition LIKE "%'+slab+'%";'
elif slab and not facet:
select_command = 'select chemical_composition, facet, reactants, products, reaction_energy ' \
'from reaction where chemical_composition LIKE "%'+slab+'%";'
else:
select_command = 'select chemical_composition, facet, reactants, products, reaction_energy from reaction;'
cur.execute(select_command)
data = cur.fetchall()
return(data) | [
"def",
"select_data",
"(",
"db_file",
",",
"slab",
"=",
"None",
",",
"facet",
"=",
"None",
")",
":",
"con",
"=",
"sql",
".",
"connect",
"(",
"db_file",
")",
"cur",
"=",
"con",
".",
"cursor",
"(",
")",
"if",
"slab",
"and",
"facet",
":",
"select_command",
"=",
"'select chemical_composition, facet, reactants, products, reaction_energy '",
"'from reaction where facet='",
"+",
"str",
"(",
"facet",
")",
"+",
"' and chemical_composition LIKE \"%'",
"+",
"slab",
"+",
"'%\";'",
"elif",
"slab",
"and",
"not",
"facet",
":",
"select_command",
"=",
"'select chemical_composition, facet, reactants, products, reaction_energy '",
"'from reaction where chemical_composition LIKE \"%'",
"+",
"slab",
"+",
"'%\";'",
"else",
":",
"select_command",
"=",
"'select chemical_composition, facet, reactants, products, reaction_energy from reaction;'",
"cur",
".",
"execute",
"(",
"select_command",
")",
"data",
"=",
"cur",
".",
"fetchall",
"(",
")",
"return",
"(",
"data",
")"
] | Gathers relevant data from SQL database generated by CATHUB.
Parameters
----------
db_file : Path to database
slab : Which metal (slab) to select.
facet : Which facets to select.
Returns
-------
data : SQL cursor output. | [
"Gathers",
"relevant",
"data",
"from",
"SQL",
"database",
"generated",
"by",
"CATHUB",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L476-L501 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | file_to_df | def file_to_df(file_name):
"""Read in file and return pandas data_frame.
Parameters
----------
filename : Filename including path.
Returns
-------
df : pandas data frame
"""
filename, file_extension = os.path.splitext(file_name)
if file_extension=='.csv':
df = pd.read_csv(file_name, sep=',', header=0).iloc[:,1:]
elif file_extension=='.tsv':
df = pd.read_csv(file_name, sep='\t', header=0).iloc[:,1:]
else:
print('Please provide valid csv or tsv file format with header names.')
return(df) | python | def file_to_df(file_name):
"""Read in file and return pandas data_frame.
Parameters
----------
filename : Filename including path.
Returns
-------
df : pandas data frame
"""
filename, file_extension = os.path.splitext(file_name)
if file_extension=='.csv':
df = pd.read_csv(file_name, sep=',', header=0).iloc[:,1:]
elif file_extension=='.tsv':
df = pd.read_csv(file_name, sep='\t', header=0).iloc[:,1:]
else:
print('Please provide valid csv or tsv file format with header names.')
return(df) | [
"def",
"file_to_df",
"(",
"file_name",
")",
":",
"filename",
",",
"file_extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"if",
"file_extension",
"==",
"'.csv'",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"file_name",
",",
"sep",
"=",
"','",
",",
"header",
"=",
"0",
")",
".",
"iloc",
"[",
":",
",",
"1",
":",
"]",
"elif",
"file_extension",
"==",
"'.tsv'",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"file_name",
",",
"sep",
"=",
"'\\t'",
",",
"header",
"=",
"0",
")",
".",
"iloc",
"[",
":",
",",
"1",
":",
"]",
"else",
":",
"print",
"(",
"'Please provide valid csv or tsv file format with header names.'",
")",
"return",
"(",
"df",
")"
] | Read in file and return pandas data_frame.
Parameters
----------
filename : Filename including path.
Returns
-------
df : pandas data frame | [
"Read",
"in",
"file",
"and",
"return",
"pandas",
"data_frame",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L503-L521 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | db_to_df | def db_to_df(db_file, slabs=None, facet=None):
"""Transforms database to data frame.
Parameters
----------
db_file : Path to database
slabs : Which metals (slabs) to select.
facet : Which facets to select.
Returns
-------
df : Data frame.
"""
systems = []
data = []
if slabs:
for slab in slabs:
data_tmp = select_data(db_file, slab=slab, facet=facet)
data.append(data_tmp)
subsystem = [tup[0] for i, tup in enumerate(data_tmp)]
systems.append(list(set(subsystem))[0])
else:
data_tmp = select_data(db_file)
data.append(data_tmp)
df = pd.DataFrame()
system, facet, reactants, products, reaction_energy = [], [], [], [], []
for entry in data:
for reaction in entry:
system.append(str(reaction[0]))
facet.append(str(reaction[1]))
reactants_i = [molecule for molecule in ast.literal_eval(reaction[2]).keys()]
reactants.append(reactants_i)
products_i = [molecule for molecule in ast.literal_eval(reaction[3]).keys()]
products.append(products_i)
reaction_energy.append(float(reaction[4]))
df[0] = system
df[1] = facet
df[2] = reactants
df[4] = products
df[5] = reaction_energy
df.columns = ['system', 'facet', 'reactants', 'products', 'reaction_energy']
labs = auto_labels(df)
df['labels'] = labs
df = df.sort_values(by=['facet', 'system'])
df = df.reset_index(drop=True)
return(df) | python | def db_to_df(db_file, slabs=None, facet=None):
"""Transforms database to data frame.
Parameters
----------
db_file : Path to database
slabs : Which metals (slabs) to select.
facet : Which facets to select.
Returns
-------
df : Data frame.
"""
systems = []
data = []
if slabs:
for slab in slabs:
data_tmp = select_data(db_file, slab=slab, facet=facet)
data.append(data_tmp)
subsystem = [tup[0] for i, tup in enumerate(data_tmp)]
systems.append(list(set(subsystem))[0])
else:
data_tmp = select_data(db_file)
data.append(data_tmp)
df = pd.DataFrame()
system, facet, reactants, products, reaction_energy = [], [], [], [], []
for entry in data:
for reaction in entry:
system.append(str(reaction[0]))
facet.append(str(reaction[1]))
reactants_i = [molecule for molecule in ast.literal_eval(reaction[2]).keys()]
reactants.append(reactants_i)
products_i = [molecule for molecule in ast.literal_eval(reaction[3]).keys()]
products.append(products_i)
reaction_energy.append(float(reaction[4]))
df[0] = system
df[1] = facet
df[2] = reactants
df[4] = products
df[5] = reaction_energy
df.columns = ['system', 'facet', 'reactants', 'products', 'reaction_energy']
labs = auto_labels(df)
df['labels'] = labs
df = df.sort_values(by=['facet', 'system'])
df = df.reset_index(drop=True)
return(df) | [
"def",
"db_to_df",
"(",
"db_file",
",",
"slabs",
"=",
"None",
",",
"facet",
"=",
"None",
")",
":",
"systems",
"=",
"[",
"]",
"data",
"=",
"[",
"]",
"if",
"slabs",
":",
"for",
"slab",
"in",
"slabs",
":",
"data_tmp",
"=",
"select_data",
"(",
"db_file",
",",
"slab",
"=",
"slab",
",",
"facet",
"=",
"facet",
")",
"data",
".",
"append",
"(",
"data_tmp",
")",
"subsystem",
"=",
"[",
"tup",
"[",
"0",
"]",
"for",
"i",
",",
"tup",
"in",
"enumerate",
"(",
"data_tmp",
")",
"]",
"systems",
".",
"append",
"(",
"list",
"(",
"set",
"(",
"subsystem",
")",
")",
"[",
"0",
"]",
")",
"else",
":",
"data_tmp",
"=",
"select_data",
"(",
"db_file",
")",
"data",
".",
"append",
"(",
"data_tmp",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"system",
",",
"facet",
",",
"reactants",
",",
"products",
",",
"reaction_energy",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"for",
"entry",
"in",
"data",
":",
"for",
"reaction",
"in",
"entry",
":",
"system",
".",
"append",
"(",
"str",
"(",
"reaction",
"[",
"0",
"]",
")",
")",
"facet",
".",
"append",
"(",
"str",
"(",
"reaction",
"[",
"1",
"]",
")",
")",
"reactants_i",
"=",
"[",
"molecule",
"for",
"molecule",
"in",
"ast",
".",
"literal_eval",
"(",
"reaction",
"[",
"2",
"]",
")",
".",
"keys",
"(",
")",
"]",
"reactants",
".",
"append",
"(",
"reactants_i",
")",
"products_i",
"=",
"[",
"molecule",
"for",
"molecule",
"in",
"ast",
".",
"literal_eval",
"(",
"reaction",
"[",
"3",
"]",
")",
".",
"keys",
"(",
")",
"]",
"products",
".",
"append",
"(",
"products_i",
")",
"reaction_energy",
".",
"append",
"(",
"float",
"(",
"reaction",
"[",
"4",
"]",
")",
")",
"df",
"[",
"0",
"]",
"=",
"system",
"df",
"[",
"1",
"]",
"=",
"facet",
"df",
"[",
"2",
"]",
"=",
"reactants",
"df",
"[",
"4",
"]",
"=",
"products",
"df",
"[",
"5",
"]",
"=",
"reaction_energy",
"df",
".",
"columns",
"=",
"[",
"'system'",
",",
"'facet'",
",",
"'reactants'",
",",
"'products'",
",",
"'reaction_energy'",
"]",
"labs",
"=",
"auto_labels",
"(",
"df",
")",
"df",
"[",
"'labels'",
"]",
"=",
"labs",
"df",
"=",
"df",
".",
"sort_values",
"(",
"by",
"=",
"[",
"'facet'",
",",
"'system'",
"]",
")",
"df",
"=",
"df",
".",
"reset_index",
"(",
"drop",
"=",
"True",
")",
"return",
"(",
"df",
")"
] | Transforms database to data frame.
Parameters
----------
db_file : Path to database
slabs : Which metals (slabs) to select.
facet : Which facets to select.
Returns
-------
df : Data frame. | [
"Transforms",
"database",
"to",
"data",
"frame",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L523-L571 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | unique_reactions | def unique_reactions(df):
"""Identifies unique elementary reactions in data frame.
Parameters
----------
df : Data frame.
Returns
-------
reaction_list : List of unique elementary reactions.
"""
reaction_list =[]
for idx, entry in enumerate(df['reactants']):
reaction = []
for x in entry:
reaction.append(x)
reaction.append('-->')
for y in df['products'][idx]:
reaction.append(y)
reaction_list.append(reaction)
string_list = [str(reaction) for reaction in reaction_list]
string_list = sorted(list(set(string_list)))
reaction_list = [ast.literal_eval(entry) for entry in string_list]
return(reaction_list) | python | def unique_reactions(df):
"""Identifies unique elementary reactions in data frame.
Parameters
----------
df : Data frame.
Returns
-------
reaction_list : List of unique elementary reactions.
"""
reaction_list =[]
for idx, entry in enumerate(df['reactants']):
reaction = []
for x in entry:
reaction.append(x)
reaction.append('-->')
for y in df['products'][idx]:
reaction.append(y)
reaction_list.append(reaction)
string_list = [str(reaction) for reaction in reaction_list]
string_list = sorted(list(set(string_list)))
reaction_list = [ast.literal_eval(entry) for entry in string_list]
return(reaction_list) | [
"def",
"unique_reactions",
"(",
"df",
")",
":",
"reaction_list",
"=",
"[",
"]",
"for",
"idx",
",",
"entry",
"in",
"enumerate",
"(",
"df",
"[",
"'reactants'",
"]",
")",
":",
"reaction",
"=",
"[",
"]",
"for",
"x",
"in",
"entry",
":",
"reaction",
".",
"append",
"(",
"x",
")",
"reaction",
".",
"append",
"(",
"'-->'",
")",
"for",
"y",
"in",
"df",
"[",
"'products'",
"]",
"[",
"idx",
"]",
":",
"reaction",
".",
"append",
"(",
"y",
")",
"reaction_list",
".",
"append",
"(",
"reaction",
")",
"string_list",
"=",
"[",
"str",
"(",
"reaction",
")",
"for",
"reaction",
"in",
"reaction_list",
"]",
"string_list",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"string_list",
")",
")",
")",
"reaction_list",
"=",
"[",
"ast",
".",
"literal_eval",
"(",
"entry",
")",
"for",
"entry",
"in",
"string_list",
"]",
"return",
"(",
"reaction_list",
")"
] | Identifies unique elementary reactions in data frame.
Parameters
----------
df : Data frame.
Returns
-------
reaction_list : List of unique elementary reactions. | [
"Identifies",
"unique",
"elementary",
"reactions",
"in",
"data",
"frame",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L573-L596 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | Adsorbate.get_helmholtz_energy | def get_helmholtz_energy(self, temperature, electronic_energy=0, verbose=False):
"""Returns the Helmholtz energy of an adsorbed molecule.
Parameters
----------
temperature : numeric
temperature in K
electronic_energy : numeric
energy in eV
verbose : boolean
whether to print ASE thermochemistry output
Returns
-------
helmholtz_energy : numeric
Helmholtz energy in eV
"""
thermo_object = HarmonicThermo(vib_energies=self.vib_energies,
potentialenergy=electronic_energy)
self.helmholtz_energy = thermo_object.get_helmholtz_energy(temperature=temperature, verbose=verbose)
return (self.helmholtz_energy) | python | def get_helmholtz_energy(self, temperature, electronic_energy=0, verbose=False):
"""Returns the Helmholtz energy of an adsorbed molecule.
Parameters
----------
temperature : numeric
temperature in K
electronic_energy : numeric
energy in eV
verbose : boolean
whether to print ASE thermochemistry output
Returns
-------
helmholtz_energy : numeric
Helmholtz energy in eV
"""
thermo_object = HarmonicThermo(vib_energies=self.vib_energies,
potentialenergy=electronic_energy)
self.helmholtz_energy = thermo_object.get_helmholtz_energy(temperature=temperature, verbose=verbose)
return (self.helmholtz_energy) | [
"def",
"get_helmholtz_energy",
"(",
"self",
",",
"temperature",
",",
"electronic_energy",
"=",
"0",
",",
"verbose",
"=",
"False",
")",
":",
"thermo_object",
"=",
"HarmonicThermo",
"(",
"vib_energies",
"=",
"self",
".",
"vib_energies",
",",
"potentialenergy",
"=",
"electronic_energy",
")",
"self",
".",
"helmholtz_energy",
"=",
"thermo_object",
".",
"get_helmholtz_energy",
"(",
"temperature",
"=",
"temperature",
",",
"verbose",
"=",
"verbose",
")",
"return",
"(",
"self",
".",
"helmholtz_energy",
")"
] | Returns the Helmholtz energy of an adsorbed molecule.
Parameters
----------
temperature : numeric
temperature in K
electronic_energy : numeric
energy in eV
verbose : boolean
whether to print ASE thermochemistry output
Returns
-------
helmholtz_energy : numeric
Helmholtz energy in eV | [
"Returns",
"the",
"Helmholtz",
"energy",
"of",
"an",
"adsorbed",
"molecule",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L131-L151 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | GasMolecule.get_vib_energies | def get_vib_energies(self):
"""Returns a list of vibration in energy units eV.
Returns
-------
vibs : list of vibrations in eV
"""
vibs = self.molecule_dict[self.name]['vibrations']
vibs = np.array(vibs) * cm2ev
return (vibs) | python | def get_vib_energies(self):
"""Returns a list of vibration in energy units eV.
Returns
-------
vibs : list of vibrations in eV
"""
vibs = self.molecule_dict[self.name]['vibrations']
vibs = np.array(vibs) * cm2ev
return (vibs) | [
"def",
"get_vib_energies",
"(",
"self",
")",
":",
"vibs",
"=",
"self",
".",
"molecule_dict",
"[",
"self",
".",
"name",
"]",
"[",
"'vibrations'",
"]",
"vibs",
"=",
"np",
".",
"array",
"(",
"vibs",
")",
"*",
"cm2ev",
"return",
"(",
"vibs",
")"
] | Returns a list of vibration in energy units eV.
Returns
-------
vibs : list of vibrations in eV | [
"Returns",
"a",
"list",
"of",
"vibration",
"in",
"energy",
"units",
"eV",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L265-L274 | train |
SUNCAT-Center/CatHub | cathub/reaction_networks.py | ReactionNetwork.set_intermediates | def set_intermediates(self, intermediates, betas=None, transition_states=None):
"""Sets up intermediates and specifies whether it's an electrochemical step.
Either provide individual contributions or net contributions. If both are given,
only the net contributions are used.
intermediate_list: list of basestrings
transition_states: list of True and False
electrochemical_steps: list of True and False
betas = list of charge transfer coefficients
net_corrections: A sum of all contributions per intermediate.
"""
self.intermediates = intermediates
self.betas = betas
self.transition_states = transition_states
if self.corrections is None:
self.net_corrections = [0.0 for _ in intermediates]
if not self.betas:
self.betas = [0.0 for _ in intermediates]
if not self.transition_states:
self.transition_states = [False for _ in intermediates]
# check if all lists have same length:
props = [len(self.intermediates), len(self.net_corrections), len(self.transition_states),
len(self.betas)]
if not len(set(props)) <= 1:
raise ValueError('intermediate, net_corrections, transition_states and , '
'betas all have to have the same length')
self.get_corrections()
return(True) | python | def set_intermediates(self, intermediates, betas=None, transition_states=None):
"""Sets up intermediates and specifies whether it's an electrochemical step.
Either provide individual contributions or net contributions. If both are given,
only the net contributions are used.
intermediate_list: list of basestrings
transition_states: list of True and False
electrochemical_steps: list of True and False
betas = list of charge transfer coefficients
net_corrections: A sum of all contributions per intermediate.
"""
self.intermediates = intermediates
self.betas = betas
self.transition_states = transition_states
if self.corrections is None:
self.net_corrections = [0.0 for _ in intermediates]
if not self.betas:
self.betas = [0.0 for _ in intermediates]
if not self.transition_states:
self.transition_states = [False for _ in intermediates]
# check if all lists have same length:
props = [len(self.intermediates), len(self.net_corrections), len(self.transition_states),
len(self.betas)]
if not len(set(props)) <= 1:
raise ValueError('intermediate, net_corrections, transition_states and , '
'betas all have to have the same length')
self.get_corrections()
return(True) | [
"def",
"set_intermediates",
"(",
"self",
",",
"intermediates",
",",
"betas",
"=",
"None",
",",
"transition_states",
"=",
"None",
")",
":",
"self",
".",
"intermediates",
"=",
"intermediates",
"self",
".",
"betas",
"=",
"betas",
"self",
".",
"transition_states",
"=",
"transition_states",
"if",
"self",
".",
"corrections",
"is",
"None",
":",
"self",
".",
"net_corrections",
"=",
"[",
"0.0",
"for",
"_",
"in",
"intermediates",
"]",
"if",
"not",
"self",
".",
"betas",
":",
"self",
".",
"betas",
"=",
"[",
"0.0",
"for",
"_",
"in",
"intermediates",
"]",
"if",
"not",
"self",
".",
"transition_states",
":",
"self",
".",
"transition_states",
"=",
"[",
"False",
"for",
"_",
"in",
"intermediates",
"]",
"# check if all lists have same length:",
"props",
"=",
"[",
"len",
"(",
"self",
".",
"intermediates",
")",
",",
"len",
"(",
"self",
".",
"net_corrections",
")",
",",
"len",
"(",
"self",
".",
"transition_states",
")",
",",
"len",
"(",
"self",
".",
"betas",
")",
"]",
"if",
"not",
"len",
"(",
"set",
"(",
"props",
")",
")",
"<=",
"1",
":",
"raise",
"ValueError",
"(",
"'intermediate, net_corrections, transition_states and , '",
"'betas all have to have the same length'",
")",
"self",
".",
"get_corrections",
"(",
")",
"return",
"(",
"True",
")"
] | Sets up intermediates and specifies whether it's an electrochemical step.
Either provide individual contributions or net contributions. If both are given,
only the net contributions are used.
intermediate_list: list of basestrings
transition_states: list of True and False
electrochemical_steps: list of True and False
betas = list of charge transfer coefficients
net_corrections: A sum of all contributions per intermediate. | [
"Sets",
"up",
"intermediates",
"and",
"specifies",
"whether",
"it",
"s",
"an",
"electrochemical",
"step",
".",
"Either",
"provide",
"individual",
"contributions",
"or",
"net",
"contributions",
".",
"If",
"both",
"are",
"given",
"only",
"the",
"net",
"contributions",
"are",
"used",
"."
] | 324625d1d8e740673f139658b2de4c9e1059739e | https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/reaction_networks.py#L689-L721 | train |
ryanpetrello/sdb | sdb.py | debugger | def debugger():
"""Return the current debugger instance, or create if none."""
sdb = _current[0]
if sdb is None or not sdb.active:
sdb = _current[0] = Sdb()
return sdb | python | def debugger():
"""Return the current debugger instance, or create if none."""
sdb = _current[0]
if sdb is None or not sdb.active:
sdb = _current[0] = Sdb()
return sdb | [
"def",
"debugger",
"(",
")",
":",
"sdb",
"=",
"_current",
"[",
"0",
"]",
"if",
"sdb",
"is",
"None",
"or",
"not",
"sdb",
".",
"active",
":",
"sdb",
"=",
"_current",
"[",
"0",
"]",
"=",
"Sdb",
"(",
")",
"return",
"sdb"
] | Return the current debugger instance, or create if none. | [
"Return",
"the",
"current",
"debugger",
"instance",
"or",
"create",
"if",
"none",
"."
] | 4a198757a17e753ac88081d192ecc952b4228a36 | https://github.com/ryanpetrello/sdb/blob/4a198757a17e753ac88081d192ecc952b4228a36/sdb.py#L268-L273 | train |
ryanpetrello/sdb | sdb.py | SocketCompleter.global_matches | def global_matches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace that match.
"""
matches = []
n = len(text)
for word in self.namespace:
if word[:n] == text and word != "__builtins__":
matches.append(word)
return matches | python | def global_matches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace that match.
"""
matches = []
n = len(text)
for word in self.namespace:
if word[:n] == text and word != "__builtins__":
matches.append(word)
return matches | [
"def",
"global_matches",
"(",
"self",
",",
"text",
")",
":",
"matches",
"=",
"[",
"]",
"n",
"=",
"len",
"(",
"text",
")",
"for",
"word",
"in",
"self",
".",
"namespace",
":",
"if",
"word",
"[",
":",
"n",
"]",
"==",
"text",
"and",
"word",
"!=",
"\"__builtins__\"",
":",
"matches",
".",
"append",
"(",
"word",
")",
"return",
"matches"
] | Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace that match. | [
"Compute",
"matches",
"when",
"text",
"is",
"a",
"simple",
"name",
".",
"Return",
"a",
"list",
"of",
"all",
"keywords",
"built",
"-",
"in",
"functions",
"and",
"names",
"currently",
"defined",
"in",
"self",
".",
"namespace",
"that",
"match",
"."
] | 4a198757a17e753ac88081d192ecc952b4228a36 | https://github.com/ryanpetrello/sdb/blob/4a198757a17e753ac88081d192ecc952b4228a36/sdb.py#L65-L75 | train |
restran/mountains | mountains/encoding/converter.py | dec2str | def dec2str(n):
"""
decimal number to string.
"""
s = hex(int(n))[2:].rstrip('L')
if len(s) % 2 != 0:
s = '0' + s
return hex2str(s) | python | def dec2str(n):
"""
decimal number to string.
"""
s = hex(int(n))[2:].rstrip('L')
if len(s) % 2 != 0:
s = '0' + s
return hex2str(s) | [
"def",
"dec2str",
"(",
"n",
")",
":",
"s",
"=",
"hex",
"(",
"int",
"(",
"n",
")",
")",
"[",
"2",
":",
"]",
".",
"rstrip",
"(",
"'L'",
")",
"if",
"len",
"(",
"s",
")",
"%",
"2",
"!=",
"0",
":",
"s",
"=",
"'0'",
"+",
"s",
"return",
"hex2str",
"(",
"s",
")"
] | decimal number to string. | [
"decimal",
"number",
"to",
"string",
"."
] | a97fee568b112f4e10d878f815d0db3dd0a98d74 | https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L163-L170 | train |
restran/mountains | mountains/encoding/converter.py | bin2str | def bin2str(b):
"""
Binary to string.
"""
ret = []
for pos in range(0, len(b), 8):
ret.append(chr(int(b[pos:pos + 8], 2)))
return ''.join(ret) | python | def bin2str(b):
"""
Binary to string.
"""
ret = []
for pos in range(0, len(b), 8):
ret.append(chr(int(b[pos:pos + 8], 2)))
return ''.join(ret) | [
"def",
"bin2str",
"(",
"b",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"pos",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"b",
")",
",",
"8",
")",
":",
"ret",
".",
"append",
"(",
"chr",
"(",
"int",
"(",
"b",
"[",
"pos",
":",
"pos",
"+",
"8",
"]",
",",
"2",
")",
")",
")",
"return",
"''",
".",
"join",
"(",
"ret",
")"
] | Binary to string. | [
"Binary",
"to",
"string",
"."
] | a97fee568b112f4e10d878f815d0db3dd0a98d74 | https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L183-L190 | train |
restran/mountains | mountains/encoding/converter.py | n2s | def n2s(n):
"""
Number to string.
"""
s = hex(n)[2:].rstrip("L")
if len(s) % 2 != 0:
s = "0" + s
return s.decode("hex") | python | def n2s(n):
"""
Number to string.
"""
s = hex(n)[2:].rstrip("L")
if len(s) % 2 != 0:
s = "0" + s
return s.decode("hex") | [
"def",
"n2s",
"(",
"n",
")",
":",
"s",
"=",
"hex",
"(",
"n",
")",
"[",
"2",
":",
"]",
".",
"rstrip",
"(",
"\"L\"",
")",
"if",
"len",
"(",
"s",
")",
"%",
"2",
"!=",
"0",
":",
"s",
"=",
"\"0\"",
"+",
"s",
"return",
"s",
".",
"decode",
"(",
"\"hex\"",
")"
] | Number to string. | [
"Number",
"to",
"string",
"."
] | a97fee568b112f4e10d878f815d0db3dd0a98d74 | https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L254-L261 | train |
restran/mountains | mountains/encoding/converter.py | s2b | def s2b(s):
"""
String to binary.
"""
ret = []
for c in s:
ret.append(bin(ord(c))[2:].zfill(8))
return "".join(ret) | python | def s2b(s):
"""
String to binary.
"""
ret = []
for c in s:
ret.append(bin(ord(c))[2:].zfill(8))
return "".join(ret) | [
"def",
"s2b",
"(",
"s",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"c",
"in",
"s",
":",
"ret",
".",
"append",
"(",
"bin",
"(",
"ord",
"(",
"c",
")",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"8",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"ret",
")"
] | String to binary. | [
"String",
"to",
"binary",
"."
] | a97fee568b112f4e10d878f815d0db3dd0a98d74 | https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L264-L271 | train |
restran/mountains | mountains/encoding/converter.py | long_to_bytes | def long_to_bytes(n, blocksize=0):
"""Convert an integer to a byte string.
In Python 3.2+, use the native method instead::
>>> n.to_bytes(blocksize, 'big')
For instance::
>>> n = 80
>>> n.to_bytes(2, 'big')
b'\x00P'
If the optional :data:`blocksize` is provided and greater than zero,
the byte string is padded with binary zeros (on the front) so that
the total length of the output is a multiple of blocksize.
If :data:`blocksize` is zero or not provided, the byte string will
be of minimal length.
"""
# after much testing, this algorithm was deemed to be the fastest
s = b''
n = int(n)
pack = struct.pack
while n > 0:
s = pack('>I', n & 0xffffffff) + s
n = n >> 32
# strip off leading zeros
for i in range(len(s)):
if s[i] != b'\000'[0]:
break
else:
# only happens when n == 0
s = b'\000'
i = 0
s = s[i:]
# add back some pad bytes. this could be done more efficiently w.r.t. the
# de-padding being done above, but sigh...
if blocksize > 0 and len(s) % blocksize:
s = (blocksize - len(s) % blocksize) * b'\000' + s
return s | python | def long_to_bytes(n, blocksize=0):
"""Convert an integer to a byte string.
In Python 3.2+, use the native method instead::
>>> n.to_bytes(blocksize, 'big')
For instance::
>>> n = 80
>>> n.to_bytes(2, 'big')
b'\x00P'
If the optional :data:`blocksize` is provided and greater than zero,
the byte string is padded with binary zeros (on the front) so that
the total length of the output is a multiple of blocksize.
If :data:`blocksize` is zero or not provided, the byte string will
be of minimal length.
"""
# after much testing, this algorithm was deemed to be the fastest
s = b''
n = int(n)
pack = struct.pack
while n > 0:
s = pack('>I', n & 0xffffffff) + s
n = n >> 32
# strip off leading zeros
for i in range(len(s)):
if s[i] != b'\000'[0]:
break
else:
# only happens when n == 0
s = b'\000'
i = 0
s = s[i:]
# add back some pad bytes. this could be done more efficiently w.r.t. the
# de-padding being done above, but sigh...
if blocksize > 0 and len(s) % blocksize:
s = (blocksize - len(s) % blocksize) * b'\000' + s
return s | [
"def",
"long_to_bytes",
"(",
"n",
",",
"blocksize",
"=",
"0",
")",
":",
"# after much testing, this algorithm was deemed to be the fastest",
"s",
"=",
"b''",
"n",
"=",
"int",
"(",
"n",
")",
"pack",
"=",
"struct",
".",
"pack",
"while",
"n",
">",
"0",
":",
"s",
"=",
"pack",
"(",
"'>I'",
",",
"n",
"&",
"0xffffffff",
")",
"+",
"s",
"n",
"=",
"n",
">>",
"32",
"# strip off leading zeros",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"s",
")",
")",
":",
"if",
"s",
"[",
"i",
"]",
"!=",
"b'\\000'",
"[",
"0",
"]",
":",
"break",
"else",
":",
"# only happens when n == 0",
"s",
"=",
"b'\\000'",
"i",
"=",
"0",
"s",
"=",
"s",
"[",
"i",
":",
"]",
"# add back some pad bytes. this could be done more efficiently w.r.t. the",
"# de-padding being done above, but sigh...",
"if",
"blocksize",
">",
"0",
"and",
"len",
"(",
"s",
")",
"%",
"blocksize",
":",
"s",
"=",
"(",
"blocksize",
"-",
"len",
"(",
"s",
")",
"%",
"blocksize",
")",
"*",
"b'\\000'",
"+",
"s",
"return",
"s"
] | Convert an integer to a byte string.
In Python 3.2+, use the native method instead::
>>> n.to_bytes(blocksize, 'big')
For instance::
>>> n = 80
>>> n.to_bytes(2, 'big')
b'\x00P'
If the optional :data:`blocksize` is provided and greater than zero,
the byte string is padded with binary zeros (on the front) so that
the total length of the output is a multiple of blocksize.
If :data:`blocksize` is zero or not provided, the byte string will
be of minimal length. | [
"Convert",
"an",
"integer",
"to",
"a",
"byte",
"string",
"."
] | a97fee568b112f4e10d878f815d0db3dd0a98d74 | https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/encoding/converter.py#L287-L327 | train |
kytos/kytos-utils | kytos/utils/client.py | CommonClient.make_request | def make_request(endpoint, **kwargs):
"""Send a request to server."""
data = kwargs.get('json', [])
package = kwargs.get('package', None)
method = kwargs.get('method', 'GET')
function = getattr(requests, method.lower())
try:
if package:
response = function(endpoint, data=data,
files={'file': package})
else:
response = function(endpoint, json=data)
except requests.exceptions.ConnectionError:
LOG.error("Couldn't connect to NApps server %s.", endpoint)
sys.exit(1)
return response | python | def make_request(endpoint, **kwargs):
"""Send a request to server."""
data = kwargs.get('json', [])
package = kwargs.get('package', None)
method = kwargs.get('method', 'GET')
function = getattr(requests, method.lower())
try:
if package:
response = function(endpoint, data=data,
files={'file': package})
else:
response = function(endpoint, json=data)
except requests.exceptions.ConnectionError:
LOG.error("Couldn't connect to NApps server %s.", endpoint)
sys.exit(1)
return response | [
"def",
"make_request",
"(",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
".",
"get",
"(",
"'json'",
",",
"[",
"]",
")",
"package",
"=",
"kwargs",
".",
"get",
"(",
"'package'",
",",
"None",
")",
"method",
"=",
"kwargs",
".",
"get",
"(",
"'method'",
",",
"'GET'",
")",
"function",
"=",
"getattr",
"(",
"requests",
",",
"method",
".",
"lower",
"(",
")",
")",
"try",
":",
"if",
"package",
":",
"response",
"=",
"function",
"(",
"endpoint",
",",
"data",
"=",
"data",
",",
"files",
"=",
"{",
"'file'",
":",
"package",
"}",
")",
"else",
":",
"response",
"=",
"function",
"(",
"endpoint",
",",
"json",
"=",
"data",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
":",
"LOG",
".",
"error",
"(",
"\"Couldn't connect to NApps server %s.\"",
",",
"endpoint",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"response"
] | Send a request to server. | [
"Send",
"a",
"request",
"to",
"server",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L33-L51 | train |
kytos/kytos-utils | kytos/utils/client.py | NAppsClient.get_napps | def get_napps(self):
"""Get all NApps from the server."""
endpoint = os.path.join(self._config.get('napps', 'api'), 'napps', '')
res = self.make_request(endpoint)
if res.status_code != 200:
msg = 'Error getting NApps from server (%s) - %s'
LOG.error(msg, res.status_code, res.reason)
sys.exit(1)
return json.loads(res.content.decode('utf-8'))['napps'] | python | def get_napps(self):
"""Get all NApps from the server."""
endpoint = os.path.join(self._config.get('napps', 'api'), 'napps', '')
res = self.make_request(endpoint)
if res.status_code != 200:
msg = 'Error getting NApps from server (%s) - %s'
LOG.error(msg, res.status_code, res.reason)
sys.exit(1)
return json.loads(res.content.decode('utf-8'))['napps'] | [
"def",
"get_napps",
"(",
"self",
")",
":",
"endpoint",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_config",
".",
"get",
"(",
"'napps'",
",",
"'api'",
")",
",",
"'napps'",
",",
"''",
")",
"res",
"=",
"self",
".",
"make_request",
"(",
"endpoint",
")",
"if",
"res",
".",
"status_code",
"!=",
"200",
":",
"msg",
"=",
"'Error getting NApps from server (%s) - %s'",
"LOG",
".",
"error",
"(",
"msg",
",",
"res",
".",
"status_code",
",",
"res",
".",
"reason",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"json",
".",
"loads",
"(",
"res",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"[",
"'napps'",
"]"
] | Get all NApps from the server. | [
"Get",
"all",
"NApps",
"from",
"the",
"server",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L57-L67 | train |
kytos/kytos-utils | kytos/utils/client.py | NAppsClient.get_napp | def get_napp(self, username, name):
"""Return napp metadata or None if not found."""
endpoint = os.path.join(self._config.get('napps', 'api'), 'napps',
username, name, '')
res = self.make_request(endpoint)
if res.status_code == 404: # We need to know if NApp is not found
return None
if res.status_code != 200:
msg = 'Error getting %s/%s from server: (%d) - %s'
raise KytosException(msg % (username, name, res.status_code,
res.reason))
return json.loads(res.content) | python | def get_napp(self, username, name):
"""Return napp metadata or None if not found."""
endpoint = os.path.join(self._config.get('napps', 'api'), 'napps',
username, name, '')
res = self.make_request(endpoint)
if res.status_code == 404: # We need to know if NApp is not found
return None
if res.status_code != 200:
msg = 'Error getting %s/%s from server: (%d) - %s'
raise KytosException(msg % (username, name, res.status_code,
res.reason))
return json.loads(res.content) | [
"def",
"get_napp",
"(",
"self",
",",
"username",
",",
"name",
")",
":",
"endpoint",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_config",
".",
"get",
"(",
"'napps'",
",",
"'api'",
")",
",",
"'napps'",
",",
"username",
",",
"name",
",",
"''",
")",
"res",
"=",
"self",
".",
"make_request",
"(",
"endpoint",
")",
"if",
"res",
".",
"status_code",
"==",
"404",
":",
"# We need to know if NApp is not found",
"return",
"None",
"if",
"res",
".",
"status_code",
"!=",
"200",
":",
"msg",
"=",
"'Error getting %s/%s from server: (%d) - %s'",
"raise",
"KytosException",
"(",
"msg",
"%",
"(",
"username",
",",
"name",
",",
"res",
".",
"status_code",
",",
"res",
".",
"reason",
")",
")",
"return",
"json",
".",
"loads",
"(",
"res",
".",
"content",
")"
] | Return napp metadata or None if not found. | [
"Return",
"napp",
"metadata",
"or",
"None",
"if",
"not",
"found",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L69-L80 | train |
kytos/kytos-utils | kytos/utils/client.py | NAppsClient.reload_napps | def reload_napps(self, napps=None):
"""Reload a specific NApp or all Napps.
Args:
napp (list): NApp list to be reload.
Raises:
requests.HTTPError: When there's a server error.
"""
if napps is None:
napps = []
api = self._config.get('kytos', 'api')
endpoint = os.path.join(api, 'api', 'kytos', 'core', 'reload',
'all')
response = self.make_request(endpoint)
for napp in napps:
api = self._config.get('kytos', 'api')
endpoint = os.path.join(api, 'api', 'kytos', 'core', 'reload',
napp[0], napp[1])
response = self.make_request(endpoint)
if response.status_code != 200:
raise KytosException('Error reloading the napp: Module not founded'
' or could not be imported')
return response.content | python | def reload_napps(self, napps=None):
"""Reload a specific NApp or all Napps.
Args:
napp (list): NApp list to be reload.
Raises:
requests.HTTPError: When there's a server error.
"""
if napps is None:
napps = []
api = self._config.get('kytos', 'api')
endpoint = os.path.join(api, 'api', 'kytos', 'core', 'reload',
'all')
response = self.make_request(endpoint)
for napp in napps:
api = self._config.get('kytos', 'api')
endpoint = os.path.join(api, 'api', 'kytos', 'core', 'reload',
napp[0], napp[1])
response = self.make_request(endpoint)
if response.status_code != 200:
raise KytosException('Error reloading the napp: Module not founded'
' or could not be imported')
return response.content | [
"def",
"reload_napps",
"(",
"self",
",",
"napps",
"=",
"None",
")",
":",
"if",
"napps",
"is",
"None",
":",
"napps",
"=",
"[",
"]",
"api",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'kytos'",
",",
"'api'",
")",
"endpoint",
"=",
"os",
".",
"path",
".",
"join",
"(",
"api",
",",
"'api'",
",",
"'kytos'",
",",
"'core'",
",",
"'reload'",
",",
"'all'",
")",
"response",
"=",
"self",
".",
"make_request",
"(",
"endpoint",
")",
"for",
"napp",
"in",
"napps",
":",
"api",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'kytos'",
",",
"'api'",
")",
"endpoint",
"=",
"os",
".",
"path",
".",
"join",
"(",
"api",
",",
"'api'",
",",
"'kytos'",
",",
"'core'",
",",
"'reload'",
",",
"napp",
"[",
"0",
"]",
",",
"napp",
"[",
"1",
"]",
")",
"response",
"=",
"self",
".",
"make_request",
"(",
"endpoint",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"raise",
"KytosException",
"(",
"'Error reloading the napp: Module not founded'",
"' or could not be imported'",
")",
"return",
"response",
".",
"content"
] | Reload a specific NApp or all Napps.
Args:
napp (list): NApp list to be reload.
Raises:
requests.HTTPError: When there's a server error. | [
"Reload",
"a",
"specific",
"NApp",
"or",
"all",
"Napps",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L82-L108 | train |
kytos/kytos-utils | kytos/utils/client.py | NAppsClient.upload_napp | def upload_napp(self, metadata, package):
"""Upload the napp from the current directory to the napps server."""
endpoint = os.path.join(self._config.get('napps', 'api'), 'napps', '')
metadata['token'] = self._config.get('auth', 'token')
request = self.make_request(endpoint, json=metadata, package=package,
method="POST")
if request.status_code != 201:
KytosConfig().clear_token()
LOG.error("%s: %s", request.status_code, request.reason)
sys.exit(1)
# WARNING: this will change in future versions, when 'author' will get
# removed.
username = metadata.get('username', metadata.get('author'))
name = metadata.get('name')
print("SUCCESS: NApp {}/{} uploaded.".format(username, name)) | python | def upload_napp(self, metadata, package):
"""Upload the napp from the current directory to the napps server."""
endpoint = os.path.join(self._config.get('napps', 'api'), 'napps', '')
metadata['token'] = self._config.get('auth', 'token')
request = self.make_request(endpoint, json=metadata, package=package,
method="POST")
if request.status_code != 201:
KytosConfig().clear_token()
LOG.error("%s: %s", request.status_code, request.reason)
sys.exit(1)
# WARNING: this will change in future versions, when 'author' will get
# removed.
username = metadata.get('username', metadata.get('author'))
name = metadata.get('name')
print("SUCCESS: NApp {}/{} uploaded.".format(username, name)) | [
"def",
"upload_napp",
"(",
"self",
",",
"metadata",
",",
"package",
")",
":",
"endpoint",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_config",
".",
"get",
"(",
"'napps'",
",",
"'api'",
")",
",",
"'napps'",
",",
"''",
")",
"metadata",
"[",
"'token'",
"]",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'auth'",
",",
"'token'",
")",
"request",
"=",
"self",
".",
"make_request",
"(",
"endpoint",
",",
"json",
"=",
"metadata",
",",
"package",
"=",
"package",
",",
"method",
"=",
"\"POST\"",
")",
"if",
"request",
".",
"status_code",
"!=",
"201",
":",
"KytosConfig",
"(",
")",
".",
"clear_token",
"(",
")",
"LOG",
".",
"error",
"(",
"\"%s: %s\"",
",",
"request",
".",
"status_code",
",",
"request",
".",
"reason",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# WARNING: this will change in future versions, when 'author' will get",
"# removed.",
"username",
"=",
"metadata",
".",
"get",
"(",
"'username'",
",",
"metadata",
".",
"get",
"(",
"'author'",
")",
")",
"name",
"=",
"metadata",
".",
"get",
"(",
"'name'",
")",
"print",
"(",
"\"SUCCESS: NApp {}/{} uploaded.\"",
".",
"format",
"(",
"username",
",",
"name",
")",
")"
] | Upload the napp from the current directory to the napps server. | [
"Upload",
"the",
"napp",
"from",
"the",
"current",
"directory",
"to",
"the",
"napps",
"server",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L111-L127 | train |
kytos/kytos-utils | kytos/utils/client.py | UsersClient.register | def register(self, user_dict):
"""Send an user_dict to NApps server using POST request.
Args:
user_dict(dict): Dictionary with user attributes.
Returns:
result(string): Return the response of Napps server.
"""
endpoint = os.path.join(self._config.get('napps', 'api'), 'users', '')
res = self.make_request(endpoint, method='POST', json=user_dict)
return res.content.decode('utf-8') | python | def register(self, user_dict):
"""Send an user_dict to NApps server using POST request.
Args:
user_dict(dict): Dictionary with user attributes.
Returns:
result(string): Return the response of Napps server.
"""
endpoint = os.path.join(self._config.get('napps', 'api'), 'users', '')
res = self.make_request(endpoint, method='POST', json=user_dict)
return res.content.decode('utf-8') | [
"def",
"register",
"(",
"self",
",",
"user_dict",
")",
":",
"endpoint",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_config",
".",
"get",
"(",
"'napps'",
",",
"'api'",
")",
",",
"'users'",
",",
"''",
")",
"res",
"=",
"self",
".",
"make_request",
"(",
"endpoint",
",",
"method",
"=",
"'POST'",
",",
"json",
"=",
"user_dict",
")",
"return",
"res",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
")"
] | Send an user_dict to NApps server using POST request.
Args:
user_dict(dict): Dictionary with user attributes.
Returns:
result(string): Return the response of Napps server. | [
"Send",
"an",
"user_dict",
"to",
"NApps",
"server",
"using",
"POST",
"request",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/utils/client.py#L147-L160 | train |
thomasdelaet/python-velbus | velbus/module.py | Module.on_message | def on_message(self, message):
"""
Process received message
"""
if message.address != self._address:
return
if isinstance(message, velbus.ChannelNamePart1Message) or isinstance(message, velbus.ChannelNamePart1Message2):
self._process_channel_name_message(1, message)
elif isinstance(message, velbus.ChannelNamePart2Message) or isinstance(message, velbus.ChannelNamePart2Message2):
self._process_channel_name_message(2, message)
elif isinstance(message, velbus.ChannelNamePart3Message) or isinstance(message, velbus.ChannelNamePart3Message2):
self._process_channel_name_message(3, message)
elif isinstance(message, velbus.ModuleTypeMessage):
self._process_module_type_message(message)
else:
self._on_message(message) | python | def on_message(self, message):
"""
Process received message
"""
if message.address != self._address:
return
if isinstance(message, velbus.ChannelNamePart1Message) or isinstance(message, velbus.ChannelNamePart1Message2):
self._process_channel_name_message(1, message)
elif isinstance(message, velbus.ChannelNamePart2Message) or isinstance(message, velbus.ChannelNamePart2Message2):
self._process_channel_name_message(2, message)
elif isinstance(message, velbus.ChannelNamePart3Message) or isinstance(message, velbus.ChannelNamePart3Message2):
self._process_channel_name_message(3, message)
elif isinstance(message, velbus.ModuleTypeMessage):
self._process_module_type_message(message)
else:
self._on_message(message) | [
"def",
"on_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"address",
"!=",
"self",
".",
"_address",
":",
"return",
"if",
"isinstance",
"(",
"message",
",",
"velbus",
".",
"ChannelNamePart1Message",
")",
"or",
"isinstance",
"(",
"message",
",",
"velbus",
".",
"ChannelNamePart1Message2",
")",
":",
"self",
".",
"_process_channel_name_message",
"(",
"1",
",",
"message",
")",
"elif",
"isinstance",
"(",
"message",
",",
"velbus",
".",
"ChannelNamePart2Message",
")",
"or",
"isinstance",
"(",
"message",
",",
"velbus",
".",
"ChannelNamePart2Message2",
")",
":",
"self",
".",
"_process_channel_name_message",
"(",
"2",
",",
"message",
")",
"elif",
"isinstance",
"(",
"message",
",",
"velbus",
".",
"ChannelNamePart3Message",
")",
"or",
"isinstance",
"(",
"message",
",",
"velbus",
".",
"ChannelNamePart3Message2",
")",
":",
"self",
".",
"_process_channel_name_message",
"(",
"3",
",",
"message",
")",
"elif",
"isinstance",
"(",
"message",
",",
"velbus",
".",
"ModuleTypeMessage",
")",
":",
"self",
".",
"_process_module_type_message",
"(",
"message",
")",
"else",
":",
"self",
".",
"_on_message",
"(",
"message",
")"
] | Process received message | [
"Process",
"received",
"message"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/module.py#L65-L80 | train |
thomasdelaet/python-velbus | velbus/module.py | Module.load | def load(self, callback):
"""
Retrieve names of channels
"""
if callback is None:
def callb():
"""No-op"""
pass
callback = callb
if len(self._loaded_callbacks) == 0:
self._request_module_status()
self._request_channel_name()
else:
print("++++++++++++++++++++++++++++++++++")
self._loaded_callbacks.append(callback)
self._load() | python | def load(self, callback):
"""
Retrieve names of channels
"""
if callback is None:
def callb():
"""No-op"""
pass
callback = callb
if len(self._loaded_callbacks) == 0:
self._request_module_status()
self._request_channel_name()
else:
print("++++++++++++++++++++++++++++++++++")
self._loaded_callbacks.append(callback)
self._load() | [
"def",
"load",
"(",
"self",
",",
"callback",
")",
":",
"if",
"callback",
"is",
"None",
":",
"def",
"callb",
"(",
")",
":",
"\"\"\"No-op\"\"\"",
"pass",
"callback",
"=",
"callb",
"if",
"len",
"(",
"self",
".",
"_loaded_callbacks",
")",
"==",
"0",
":",
"self",
".",
"_request_module_status",
"(",
")",
"self",
".",
"_request_channel_name",
"(",
")",
"else",
":",
"print",
"(",
"\"++++++++++++++++++++++++++++++++++\"",
")",
"self",
".",
"_loaded_callbacks",
".",
"append",
"(",
"callback",
")",
"self",
".",
"_load",
"(",
")"
] | Retrieve names of channels | [
"Retrieve",
"names",
"of",
"channels"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/module.py#L90-L105 | train |
thomasdelaet/python-velbus | velbus/module.py | Module._name_messages_complete | def _name_messages_complete(self):
"""
Check if all name messages have been received
"""
for channel in range(1, self.number_of_channels() + 1):
try:
for name_index in range(1, 4):
if not isinstance(self._name_data[channel][name_index], str):
return False
except Exception:
return False
return True | python | def _name_messages_complete(self):
"""
Check if all name messages have been received
"""
for channel in range(1, self.number_of_channels() + 1):
try:
for name_index in range(1, 4):
if not isinstance(self._name_data[channel][name_index], str):
return False
except Exception:
return False
return True | [
"def",
"_name_messages_complete",
"(",
"self",
")",
":",
"for",
"channel",
"in",
"range",
"(",
"1",
",",
"self",
".",
"number_of_channels",
"(",
")",
"+",
"1",
")",
":",
"try",
":",
"for",
"name_index",
"in",
"range",
"(",
"1",
",",
"4",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_name_data",
"[",
"channel",
"]",
"[",
"name_index",
"]",
",",
"str",
")",
":",
"return",
"False",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | Check if all name messages have been received | [
"Check",
"if",
"all",
"name",
"messages",
"have",
"been",
"received"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/module.py#L147-L158 | train |
KE-works/pykechain | pykechain/models/validators/effects.py | VisualEffect.as_json | def as_json(self):
# type: () -> dict
"""Represent effect as JSON dict."""
self._config['applyCss'] = self.applyCss
self._json['config'] = self._config
return self._json | python | def as_json(self):
# type: () -> dict
"""Represent effect as JSON dict."""
self._config['applyCss'] = self.applyCss
self._json['config'] = self._config
return self._json | [
"def",
"as_json",
"(",
"self",
")",
":",
"# type: () -> dict",
"self",
".",
"_config",
"[",
"'applyCss'",
"]",
"=",
"self",
".",
"applyCss",
"self",
".",
"_json",
"[",
"'config'",
"]",
"=",
"self",
".",
"_config",
"return",
"self",
".",
"_json"
] | Represent effect as JSON dict. | [
"Represent",
"effect",
"as",
"JSON",
"dict",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/validators/effects.py#L98-L103 | train |
samuelcolvin/grablib | grablib/download.py | Downloader._delete_stale | def _delete_stale(self):
"""
Delete files left in self._stale_files. Also delete their directories if empty.
"""
for name, hash_ in self._stale_files.items():
path = self.download_root.joinpath(name)
if not path.exists():
continue
current_hash = self._path_hash(path)
if current_hash == hash_:
progress_logger.info('deleting: %s which is stale...', name)
path.unlink()
self._stale_deleted += 1
while True:
path = path.parent
if path == self.download_root or list(path.iterdir()):
break
progress_logger.info('deleting: %s which is stale..', path.relative_to(self.download_root))
path.rmdir()
else:
progress_logger.error('Not deleting "%s" which is in the lock file but not the definition '
'file, however appears to have been modified since it was downloaded. '
'Please check and delete the file manually.', name)
raise GrablibError('stale file modified') | python | def _delete_stale(self):
"""
Delete files left in self._stale_files. Also delete their directories if empty.
"""
for name, hash_ in self._stale_files.items():
path = self.download_root.joinpath(name)
if not path.exists():
continue
current_hash = self._path_hash(path)
if current_hash == hash_:
progress_logger.info('deleting: %s which is stale...', name)
path.unlink()
self._stale_deleted += 1
while True:
path = path.parent
if path == self.download_root or list(path.iterdir()):
break
progress_logger.info('deleting: %s which is stale..', path.relative_to(self.download_root))
path.rmdir()
else:
progress_logger.error('Not deleting "%s" which is in the lock file but not the definition '
'file, however appears to have been modified since it was downloaded. '
'Please check and delete the file manually.', name)
raise GrablibError('stale file modified') | [
"def",
"_delete_stale",
"(",
"self",
")",
":",
"for",
"name",
",",
"hash_",
"in",
"self",
".",
"_stale_files",
".",
"items",
"(",
")",
":",
"path",
"=",
"self",
".",
"download_root",
".",
"joinpath",
"(",
"name",
")",
"if",
"not",
"path",
".",
"exists",
"(",
")",
":",
"continue",
"current_hash",
"=",
"self",
".",
"_path_hash",
"(",
"path",
")",
"if",
"current_hash",
"==",
"hash_",
":",
"progress_logger",
".",
"info",
"(",
"'deleting: %s which is stale...'",
",",
"name",
")",
"path",
".",
"unlink",
"(",
")",
"self",
".",
"_stale_deleted",
"+=",
"1",
"while",
"True",
":",
"path",
"=",
"path",
".",
"parent",
"if",
"path",
"==",
"self",
".",
"download_root",
"or",
"list",
"(",
"path",
".",
"iterdir",
"(",
")",
")",
":",
"break",
"progress_logger",
".",
"info",
"(",
"'deleting: %s which is stale..'",
",",
"path",
".",
"relative_to",
"(",
"self",
".",
"download_root",
")",
")",
"path",
".",
"rmdir",
"(",
")",
"else",
":",
"progress_logger",
".",
"error",
"(",
"'Not deleting \"%s\" which is in the lock file but not the definition '",
"'file, however appears to have been modified since it was downloaded. '",
"'Please check and delete the file manually.'",
",",
"name",
")",
"raise",
"GrablibError",
"(",
"'stale file modified'",
")"
] | Delete files left in self._stale_files. Also delete their directories if empty. | [
"Delete",
"files",
"left",
"in",
"self",
".",
"_stale_files",
".",
"Also",
"delete",
"their",
"directories",
"if",
"empty",
"."
] | 2fca8a3950f29fb2a97a7bd75c0839060a91cedf | https://github.com/samuelcolvin/grablib/blob/2fca8a3950f29fb2a97a7bd75c0839060a91cedf/grablib/download.py#L172-L195 | train |
samuelcolvin/grablib | grablib/download.py | Downloader._file_path | def _file_path(self, src_path, dest, regex):
"""
check src_path complies with regex and generate new filename
"""
m = re.search(regex, src_path)
if dest.endswith('/') or dest == '':
dest += '{filename}'
names = m.groupdict()
if not names and m.groups():
names = {'filename': m.groups()[-1]}
for name, value in names.items():
dest = dest.replace('{%s}' % name, value)
# remove starting slash so path can't be absolute
dest = dest.strip(' /')
if not dest:
progress_logger.error('destination path must not resolve to be null')
raise GrablibError('bad path')
new_path = self.download_root.joinpath(dest)
new_path.relative_to(self.download_root)
return new_path | python | def _file_path(self, src_path, dest, regex):
"""
check src_path complies with regex and generate new filename
"""
m = re.search(regex, src_path)
if dest.endswith('/') or dest == '':
dest += '{filename}'
names = m.groupdict()
if not names and m.groups():
names = {'filename': m.groups()[-1]}
for name, value in names.items():
dest = dest.replace('{%s}' % name, value)
# remove starting slash so path can't be absolute
dest = dest.strip(' /')
if not dest:
progress_logger.error('destination path must not resolve to be null')
raise GrablibError('bad path')
new_path = self.download_root.joinpath(dest)
new_path.relative_to(self.download_root)
return new_path | [
"def",
"_file_path",
"(",
"self",
",",
"src_path",
",",
"dest",
",",
"regex",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"regex",
",",
"src_path",
")",
"if",
"dest",
".",
"endswith",
"(",
"'/'",
")",
"or",
"dest",
"==",
"''",
":",
"dest",
"+=",
"'{filename}'",
"names",
"=",
"m",
".",
"groupdict",
"(",
")",
"if",
"not",
"names",
"and",
"m",
".",
"groups",
"(",
")",
":",
"names",
"=",
"{",
"'filename'",
":",
"m",
".",
"groups",
"(",
")",
"[",
"-",
"1",
"]",
"}",
"for",
"name",
",",
"value",
"in",
"names",
".",
"items",
"(",
")",
":",
"dest",
"=",
"dest",
".",
"replace",
"(",
"'{%s}'",
"%",
"name",
",",
"value",
")",
"# remove starting slash so path can't be absolute",
"dest",
"=",
"dest",
".",
"strip",
"(",
"' /'",
")",
"if",
"not",
"dest",
":",
"progress_logger",
".",
"error",
"(",
"'destination path must not resolve to be null'",
")",
"raise",
"GrablibError",
"(",
"'bad path'",
")",
"new_path",
"=",
"self",
".",
"download_root",
".",
"joinpath",
"(",
"dest",
")",
"new_path",
".",
"relative_to",
"(",
"self",
".",
"download_root",
")",
"return",
"new_path"
] | check src_path complies with regex and generate new filename | [
"check",
"src_path",
"complies",
"with",
"regex",
"and",
"generate",
"new",
"filename"
] | 2fca8a3950f29fb2a97a7bd75c0839060a91cedf | https://github.com/samuelcolvin/grablib/blob/2fca8a3950f29fb2a97a7bd75c0839060a91cedf/grablib/download.py#L197-L216 | train |
samuelcolvin/grablib | grablib/download.py | Downloader._lock | def _lock(self, url: str, name: str, hash_: str):
"""
Add details of the files downloaded to _new_lock so they can be saved to the lock file.
Also remove path from _stale_files, whatever remains at the end therefore is stale and can be deleted.
"""
self._new_lock.append({
'url': url,
'name': name,
'hash': hash_,
})
self._stale_files.pop(name, None) | python | def _lock(self, url: str, name: str, hash_: str):
"""
Add details of the files downloaded to _new_lock so they can be saved to the lock file.
Also remove path from _stale_files, whatever remains at the end therefore is stale and can be deleted.
"""
self._new_lock.append({
'url': url,
'name': name,
'hash': hash_,
})
self._stale_files.pop(name, None) | [
"def",
"_lock",
"(",
"self",
",",
"url",
":",
"str",
",",
"name",
":",
"str",
",",
"hash_",
":",
"str",
")",
":",
"self",
".",
"_new_lock",
".",
"append",
"(",
"{",
"'url'",
":",
"url",
",",
"'name'",
":",
"name",
",",
"'hash'",
":",
"hash_",
",",
"}",
")",
"self",
".",
"_stale_files",
".",
"pop",
"(",
"name",
",",
"None",
")"
] | Add details of the files downloaded to _new_lock so they can be saved to the lock file.
Also remove path from _stale_files, whatever remains at the end therefore is stale and can be deleted. | [
"Add",
"details",
"of",
"the",
"files",
"downloaded",
"to",
"_new_lock",
"so",
"they",
"can",
"be",
"saved",
"to",
"the",
"lock",
"file",
".",
"Also",
"remove",
"path",
"from",
"_stale_files",
"whatever",
"remains",
"at",
"the",
"end",
"therefore",
"is",
"stale",
"and",
"can",
"be",
"deleted",
"."
] | 2fca8a3950f29fb2a97a7bd75c0839060a91cedf | https://github.com/samuelcolvin/grablib/blob/2fca8a3950f29fb2a97a7bd75c0839060a91cedf/grablib/download.py#L241-L251 | train |
lobocv/crashreporter | crashreporter/crashreporter.py | CrashReporter.setup_smtp | def setup_smtp(self, host, port, user, passwd, recipients, **kwargs):
"""
Set up the crash reporter to send reports via email using SMTP
:param host: SMTP host
:param port: SMTP port
:param user: sender email address
:param passwd: sender email password
:param recipients: list or comma separated string of recipients
"""
self._smtp = kwargs
self._smtp.update({'host': host, 'port': port, 'user': user, 'passwd': passwd, 'recipients': recipients})
try:
self._smtp['timeout'] = int(kwargs.get('timeout', SMTP_DEFAULT_TIMEOUT))
except Exception as e:
logging.error(e)
self._smtp['timeout'] = None
self._smtp['from'] = kwargs.get('from', user) | python | def setup_smtp(self, host, port, user, passwd, recipients, **kwargs):
"""
Set up the crash reporter to send reports via email using SMTP
:param host: SMTP host
:param port: SMTP port
:param user: sender email address
:param passwd: sender email password
:param recipients: list or comma separated string of recipients
"""
self._smtp = kwargs
self._smtp.update({'host': host, 'port': port, 'user': user, 'passwd': passwd, 'recipients': recipients})
try:
self._smtp['timeout'] = int(kwargs.get('timeout', SMTP_DEFAULT_TIMEOUT))
except Exception as e:
logging.error(e)
self._smtp['timeout'] = None
self._smtp['from'] = kwargs.get('from', user) | [
"def",
"setup_smtp",
"(",
"self",
",",
"host",
",",
"port",
",",
"user",
",",
"passwd",
",",
"recipients",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_smtp",
"=",
"kwargs",
"self",
".",
"_smtp",
".",
"update",
"(",
"{",
"'host'",
":",
"host",
",",
"'port'",
":",
"port",
",",
"'user'",
":",
"user",
",",
"'passwd'",
":",
"passwd",
",",
"'recipients'",
":",
"recipients",
"}",
")",
"try",
":",
"self",
".",
"_smtp",
"[",
"'timeout'",
"]",
"=",
"int",
"(",
"kwargs",
".",
"get",
"(",
"'timeout'",
",",
"SMTP_DEFAULT_TIMEOUT",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"e",
")",
"self",
".",
"_smtp",
"[",
"'timeout'",
"]",
"=",
"None",
"self",
".",
"_smtp",
"[",
"'from'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'from'",
",",
"user",
")"
] | Set up the crash reporter to send reports via email using SMTP
:param host: SMTP host
:param port: SMTP port
:param user: sender email address
:param passwd: sender email password
:param recipients: list or comma separated string of recipients | [
"Set",
"up",
"the",
"crash",
"reporter",
"to",
"send",
"reports",
"via",
"email",
"using",
"SMTP"
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L95-L112 | train |
lobocv/crashreporter | crashreporter/crashreporter.py | CrashReporter.enable | def enable(self):
"""
Enable the crash reporter. CrashReporter is defaulted to be enabled on creation.
"""
if not CrashReporter.active:
CrashReporter.active = True
# Store this function so we can set it back if the CrashReporter is deactivated
self._excepthook = sys.excepthook
sys.excepthook = self.exception_handler
self.logger.info('CrashReporter: Enabled')
if self.report_dir:
if os.path.exists(self.report_dir):
if self.get_offline_reports():
# First attempt to send the reports, if that fails then start the watcher
self.submit_offline_reports()
remaining_reports = len(self.get_offline_reports())
if remaining_reports and self.watcher_enabled:
self.start_watcher()
else:
os.makedirs(self.report_dir) | python | def enable(self):
"""
Enable the crash reporter. CrashReporter is defaulted to be enabled on creation.
"""
if not CrashReporter.active:
CrashReporter.active = True
# Store this function so we can set it back if the CrashReporter is deactivated
self._excepthook = sys.excepthook
sys.excepthook = self.exception_handler
self.logger.info('CrashReporter: Enabled')
if self.report_dir:
if os.path.exists(self.report_dir):
if self.get_offline_reports():
# First attempt to send the reports, if that fails then start the watcher
self.submit_offline_reports()
remaining_reports = len(self.get_offline_reports())
if remaining_reports and self.watcher_enabled:
self.start_watcher()
else:
os.makedirs(self.report_dir) | [
"def",
"enable",
"(",
"self",
")",
":",
"if",
"not",
"CrashReporter",
".",
"active",
":",
"CrashReporter",
".",
"active",
"=",
"True",
"# Store this function so we can set it back if the CrashReporter is deactivated",
"self",
".",
"_excepthook",
"=",
"sys",
".",
"excepthook",
"sys",
".",
"excepthook",
"=",
"self",
".",
"exception_handler",
"self",
".",
"logger",
".",
"info",
"(",
"'CrashReporter: Enabled'",
")",
"if",
"self",
".",
"report_dir",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"report_dir",
")",
":",
"if",
"self",
".",
"get_offline_reports",
"(",
")",
":",
"# First attempt to send the reports, if that fails then start the watcher",
"self",
".",
"submit_offline_reports",
"(",
")",
"remaining_reports",
"=",
"len",
"(",
"self",
".",
"get_offline_reports",
"(",
")",
")",
"if",
"remaining_reports",
"and",
"self",
".",
"watcher_enabled",
":",
"self",
".",
"start_watcher",
"(",
")",
"else",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"report_dir",
")"
] | Enable the crash reporter. CrashReporter is defaulted to be enabled on creation. | [
"Enable",
"the",
"crash",
"reporter",
".",
"CrashReporter",
"is",
"defaulted",
"to",
"be",
"enabled",
"on",
"creation",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L123-L142 | train |
lobocv/crashreporter | crashreporter/crashreporter.py | CrashReporter.disable | def disable(self):
"""
Disable the crash reporter. No reports will be sent or saved.
"""
if CrashReporter.active:
CrashReporter.active = False
# Restore the original excepthook
sys.excepthook = self._excepthook
self.stop_watcher()
self.logger.info('CrashReporter: Disabled') | python | def disable(self):
"""
Disable the crash reporter. No reports will be sent or saved.
"""
if CrashReporter.active:
CrashReporter.active = False
# Restore the original excepthook
sys.excepthook = self._excepthook
self.stop_watcher()
self.logger.info('CrashReporter: Disabled') | [
"def",
"disable",
"(",
"self",
")",
":",
"if",
"CrashReporter",
".",
"active",
":",
"CrashReporter",
".",
"active",
"=",
"False",
"# Restore the original excepthook",
"sys",
".",
"excepthook",
"=",
"self",
".",
"_excepthook",
"self",
".",
"stop_watcher",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"'CrashReporter: Disabled'",
")"
] | Disable the crash reporter. No reports will be sent or saved. | [
"Disable",
"the",
"crash",
"reporter",
".",
"No",
"reports",
"will",
"be",
"sent",
"or",
"saved",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L144-L153 | train |
lobocv/crashreporter | crashreporter/crashreporter.py | CrashReporter.start_watcher | def start_watcher(self):
"""
Start the watcher that periodically checks for offline reports and attempts to upload them.
"""
if self._watcher and self._watcher.is_alive:
self._watcher_running = True
else:
self.logger.info('CrashReporter: Starting watcher.')
self._watcher = Thread(target=self._watcher_thread, name='offline_reporter')
self._watcher.setDaemon(True)
self._watcher_running = True
self._watcher.start() | python | def start_watcher(self):
"""
Start the watcher that periodically checks for offline reports and attempts to upload them.
"""
if self._watcher and self._watcher.is_alive:
self._watcher_running = True
else:
self.logger.info('CrashReporter: Starting watcher.')
self._watcher = Thread(target=self._watcher_thread, name='offline_reporter')
self._watcher.setDaemon(True)
self._watcher_running = True
self._watcher.start() | [
"def",
"start_watcher",
"(",
"self",
")",
":",
"if",
"self",
".",
"_watcher",
"and",
"self",
".",
"_watcher",
".",
"is_alive",
":",
"self",
".",
"_watcher_running",
"=",
"True",
"else",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'CrashReporter: Starting watcher.'",
")",
"self",
".",
"_watcher",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_watcher_thread",
",",
"name",
"=",
"'offline_reporter'",
")",
"self",
".",
"_watcher",
".",
"setDaemon",
"(",
"True",
")",
"self",
".",
"_watcher_running",
"=",
"True",
"self",
".",
"_watcher",
".",
"start",
"(",
")"
] | Start the watcher that periodically checks for offline reports and attempts to upload them. | [
"Start",
"the",
"watcher",
"that",
"periodically",
"checks",
"for",
"offline",
"reports",
"and",
"attempts",
"to",
"upload",
"them",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L155-L166 | train |
lobocv/crashreporter | crashreporter/crashreporter.py | CrashReporter.stop_watcher | def stop_watcher(self):
"""
Stop the watcher thread that tries to send offline reports.
"""
if self._watcher:
self._watcher_running = False
self.logger.info('CrashReporter: Stopping watcher.') | python | def stop_watcher(self):
"""
Stop the watcher thread that tries to send offline reports.
"""
if self._watcher:
self._watcher_running = False
self.logger.info('CrashReporter: Stopping watcher.') | [
"def",
"stop_watcher",
"(",
"self",
")",
":",
"if",
"self",
".",
"_watcher",
":",
"self",
".",
"_watcher_running",
"=",
"False",
"self",
".",
"logger",
".",
"info",
"(",
"'CrashReporter: Stopping watcher.'",
")"
] | Stop the watcher thread that tries to send offline reports. | [
"Stop",
"the",
"watcher",
"thread",
"that",
"tries",
"to",
"send",
"offline",
"reports",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L168-L174 | train |
lobocv/crashreporter | crashreporter/crashreporter.py | CrashReporter.subject | def subject(self):
"""
Return a string to be used as the email subject line.
"""
if self.application_name and self.application_version:
return 'Crash Report - {name} (v{version})'.format(name=self.application_name,
version=self.application_version)
else:
return 'Crash Report' | python | def subject(self):
"""
Return a string to be used as the email subject line.
"""
if self.application_name and self.application_version:
return 'Crash Report - {name} (v{version})'.format(name=self.application_name,
version=self.application_version)
else:
return 'Crash Report' | [
"def",
"subject",
"(",
"self",
")",
":",
"if",
"self",
".",
"application_name",
"and",
"self",
".",
"application_version",
":",
"return",
"'Crash Report - {name} (v{version})'",
".",
"format",
"(",
"name",
"=",
"self",
".",
"application_name",
",",
"version",
"=",
"self",
".",
"application_version",
")",
"else",
":",
"return",
"'Crash Report'"
] | Return a string to be used as the email subject line. | [
"Return",
"a",
"string",
"to",
"be",
"used",
"as",
"the",
"email",
"subject",
"line",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L301-L309 | train |
lobocv/crashreporter | crashreporter/crashreporter.py | CrashReporter.store_report | def store_report(self, payload):
"""
Save the crash report to a file. Keeping the last `offline_report_limit` files in a cyclical FIFO buffer.
The newest crash report always named is 01
"""
offline_reports = self.get_offline_reports()
if offline_reports:
# Increment the name of all existing reports 1 --> 2, 2 --> 3 etc.
for ii, report in enumerate(reversed(offline_reports)):
rpath, ext = os.path.splitext(report)
n = int(re.findall('(\d+)', rpath)[-1])
new_name = os.path.join(self.report_dir, self._report_name % (n + 1)) + ext
shutil.copy2(report, new_name)
os.remove(report)
# Delete the oldest report
if len(offline_reports) >= self.offline_report_limit:
oldest = glob.glob(os.path.join(self.report_dir, self._report_name % (self.offline_report_limit+1) + '*'))[0]
os.remove(oldest)
new_report_path = os.path.join(self.report_dir, self._report_name % 1 + '.json')
# Write a new report
with open(new_report_path, 'w') as _f:
json.dump(payload, _f)
return new_report_path | python | def store_report(self, payload):
"""
Save the crash report to a file. Keeping the last `offline_report_limit` files in a cyclical FIFO buffer.
The newest crash report always named is 01
"""
offline_reports = self.get_offline_reports()
if offline_reports:
# Increment the name of all existing reports 1 --> 2, 2 --> 3 etc.
for ii, report in enumerate(reversed(offline_reports)):
rpath, ext = os.path.splitext(report)
n = int(re.findall('(\d+)', rpath)[-1])
new_name = os.path.join(self.report_dir, self._report_name % (n + 1)) + ext
shutil.copy2(report, new_name)
os.remove(report)
# Delete the oldest report
if len(offline_reports) >= self.offline_report_limit:
oldest = glob.glob(os.path.join(self.report_dir, self._report_name % (self.offline_report_limit+1) + '*'))[0]
os.remove(oldest)
new_report_path = os.path.join(self.report_dir, self._report_name % 1 + '.json')
# Write a new report
with open(new_report_path, 'w') as _f:
json.dump(payload, _f)
return new_report_path | [
"def",
"store_report",
"(",
"self",
",",
"payload",
")",
":",
"offline_reports",
"=",
"self",
".",
"get_offline_reports",
"(",
")",
"if",
"offline_reports",
":",
"# Increment the name of all existing reports 1 --> 2, 2 --> 3 etc.",
"for",
"ii",
",",
"report",
"in",
"enumerate",
"(",
"reversed",
"(",
"offline_reports",
")",
")",
":",
"rpath",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"report",
")",
"n",
"=",
"int",
"(",
"re",
".",
"findall",
"(",
"'(\\d+)'",
",",
"rpath",
")",
"[",
"-",
"1",
"]",
")",
"new_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"report_dir",
",",
"self",
".",
"_report_name",
"%",
"(",
"n",
"+",
"1",
")",
")",
"+",
"ext",
"shutil",
".",
"copy2",
"(",
"report",
",",
"new_name",
")",
"os",
".",
"remove",
"(",
"report",
")",
"# Delete the oldest report",
"if",
"len",
"(",
"offline_reports",
")",
">=",
"self",
".",
"offline_report_limit",
":",
"oldest",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"report_dir",
",",
"self",
".",
"_report_name",
"%",
"(",
"self",
".",
"offline_report_limit",
"+",
"1",
")",
"+",
"'*'",
")",
")",
"[",
"0",
"]",
"os",
".",
"remove",
"(",
"oldest",
")",
"new_report_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"report_dir",
",",
"self",
".",
"_report_name",
"%",
"1",
"+",
"'.json'",
")",
"# Write a new report",
"with",
"open",
"(",
"new_report_path",
",",
"'w'",
")",
"as",
"_f",
":",
"json",
".",
"dump",
"(",
"payload",
",",
"_f",
")",
"return",
"new_report_path"
] | Save the crash report to a file. Keeping the last `offline_report_limit` files in a cyclical FIFO buffer.
The newest crash report always named is 01 | [
"Save",
"the",
"crash",
"report",
"to",
"a",
"file",
".",
"Keeping",
"the",
"last",
"offline_report_limit",
"files",
"in",
"a",
"cyclical",
"FIFO",
"buffer",
".",
"The",
"newest",
"crash",
"report",
"always",
"named",
"is",
"01"
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L389-L412 | train |
lobocv/crashreporter | crashreporter/crashreporter.py | CrashReporter._watcher_thread | def _watcher_thread(self):
"""
Periodically attempt to upload the crash reports. If any upload method is successful, delete the saved reports.
"""
while 1:
time.sleep(self.check_interval)
if not self._watcher_running:
break
self.logger.info('CrashReporter: Attempting to send offline reports.')
self.submit_offline_reports()
remaining_reports = len(self.get_offline_reports())
if remaining_reports == 0:
break
self._watcher = None
self.logger.info('CrashReporter: Watcher stopped.') | python | def _watcher_thread(self):
"""
Periodically attempt to upload the crash reports. If any upload method is successful, delete the saved reports.
"""
while 1:
time.sleep(self.check_interval)
if not self._watcher_running:
break
self.logger.info('CrashReporter: Attempting to send offline reports.')
self.submit_offline_reports()
remaining_reports = len(self.get_offline_reports())
if remaining_reports == 0:
break
self._watcher = None
self.logger.info('CrashReporter: Watcher stopped.') | [
"def",
"_watcher_thread",
"(",
"self",
")",
":",
"while",
"1",
":",
"time",
".",
"sleep",
"(",
"self",
".",
"check_interval",
")",
"if",
"not",
"self",
".",
"_watcher_running",
":",
"break",
"self",
".",
"logger",
".",
"info",
"(",
"'CrashReporter: Attempting to send offline reports.'",
")",
"self",
".",
"submit_offline_reports",
"(",
")",
"remaining_reports",
"=",
"len",
"(",
"self",
".",
"get_offline_reports",
"(",
")",
")",
"if",
"remaining_reports",
"==",
"0",
":",
"break",
"self",
".",
"_watcher",
"=",
"None",
"self",
".",
"logger",
".",
"info",
"(",
"'CrashReporter: Watcher stopped.'",
")"
] | Periodically attempt to upload the crash reports. If any upload method is successful, delete the saved reports. | [
"Periodically",
"attempt",
"to",
"upload",
"the",
"crash",
"reports",
".",
"If",
"any",
"upload",
"method",
"is",
"successful",
"delete",
"the",
"saved",
"reports",
"."
] | a5bbb3f37977dc64bc865dfedafc365fd5469ef8 | https://github.com/lobocv/crashreporter/blob/a5bbb3f37977dc64bc865dfedafc365fd5469ef8/crashreporter/crashreporter.py#L471-L485 | train |
uranusjr/django-gunicorn | djgunicorn/logging.py | colorize | def colorize(style, msg, resp):
"""Taken and modified from `django.utils.log.ServerFormatter.format`
to mimic runserver's styling.
"""
code = resp.status.split(maxsplit=1)[0]
if code[0] == '2':
# Put 2XX first, since it should be the common case
msg = style.HTTP_SUCCESS(msg)
elif code[0] == '1':
msg = style.HTTP_INFO(msg)
elif code == '304':
msg = style.HTTP_NOT_MODIFIED(msg)
elif code[0] == '3':
msg = style.HTTP_REDIRECT(msg)
elif code == '404':
msg = style.HTTP_NOT_FOUND(msg)
elif code[0] == '4':
msg = style.HTTP_BAD_REQUEST(msg)
else:
# Any 5XX, or any other response
msg = style.HTTP_SERVER_ERROR(msg)
return msg | python | def colorize(style, msg, resp):
"""Taken and modified from `django.utils.log.ServerFormatter.format`
to mimic runserver's styling.
"""
code = resp.status.split(maxsplit=1)[0]
if code[0] == '2':
# Put 2XX first, since it should be the common case
msg = style.HTTP_SUCCESS(msg)
elif code[0] == '1':
msg = style.HTTP_INFO(msg)
elif code == '304':
msg = style.HTTP_NOT_MODIFIED(msg)
elif code[0] == '3':
msg = style.HTTP_REDIRECT(msg)
elif code == '404':
msg = style.HTTP_NOT_FOUND(msg)
elif code[0] == '4':
msg = style.HTTP_BAD_REQUEST(msg)
else:
# Any 5XX, or any other response
msg = style.HTTP_SERVER_ERROR(msg)
return msg | [
"def",
"colorize",
"(",
"style",
",",
"msg",
",",
"resp",
")",
":",
"code",
"=",
"resp",
".",
"status",
".",
"split",
"(",
"maxsplit",
"=",
"1",
")",
"[",
"0",
"]",
"if",
"code",
"[",
"0",
"]",
"==",
"'2'",
":",
"# Put 2XX first, since it should be the common case",
"msg",
"=",
"style",
".",
"HTTP_SUCCESS",
"(",
"msg",
")",
"elif",
"code",
"[",
"0",
"]",
"==",
"'1'",
":",
"msg",
"=",
"style",
".",
"HTTP_INFO",
"(",
"msg",
")",
"elif",
"code",
"==",
"'304'",
":",
"msg",
"=",
"style",
".",
"HTTP_NOT_MODIFIED",
"(",
"msg",
")",
"elif",
"code",
"[",
"0",
"]",
"==",
"'3'",
":",
"msg",
"=",
"style",
".",
"HTTP_REDIRECT",
"(",
"msg",
")",
"elif",
"code",
"==",
"'404'",
":",
"msg",
"=",
"style",
".",
"HTTP_NOT_FOUND",
"(",
"msg",
")",
"elif",
"code",
"[",
"0",
"]",
"==",
"'4'",
":",
"msg",
"=",
"style",
".",
"HTTP_BAD_REQUEST",
"(",
"msg",
")",
"else",
":",
"# Any 5XX, or any other response",
"msg",
"=",
"style",
".",
"HTTP_SERVER_ERROR",
"(",
"msg",
")",
"return",
"msg"
] | Taken and modified from `django.utils.log.ServerFormatter.format`
to mimic runserver's styling. | [
"Taken",
"and",
"modified",
"from",
"django",
".",
"utils",
".",
"log",
".",
"ServerFormatter",
".",
"format",
"to",
"mimic",
"runserver",
"s",
"styling",
"."
] | 4fb16f48048ff5fff8f889a007f376236646497b | https://github.com/uranusjr/django-gunicorn/blob/4fb16f48048ff5fff8f889a007f376236646497b/djgunicorn/logging.py#L11-L32 | train |
uranusjr/django-gunicorn | djgunicorn/logging.py | GunicornLogger.access | def access(self, resp, req, environ, request_time):
"""Override to apply styling on access logs.
This duplicates a large portion of `gunicorn.glogging.Logger.access`,
only adding
"""
if not (self.cfg.accesslog or self.cfg.logconfig or self.cfg.syslog):
return
msg = self.make_access_message(resp, req, environ, request_time)
try:
self.access_log.info(msg)
except:
self.error(traceback.format_exc()) | python | def access(self, resp, req, environ, request_time):
"""Override to apply styling on access logs.
This duplicates a large portion of `gunicorn.glogging.Logger.access`,
only adding
"""
if not (self.cfg.accesslog or self.cfg.logconfig or self.cfg.syslog):
return
msg = self.make_access_message(resp, req, environ, request_time)
try:
self.access_log.info(msg)
except:
self.error(traceback.format_exc()) | [
"def",
"access",
"(",
"self",
",",
"resp",
",",
"req",
",",
"environ",
",",
"request_time",
")",
":",
"if",
"not",
"(",
"self",
".",
"cfg",
".",
"accesslog",
"or",
"self",
".",
"cfg",
".",
"logconfig",
"or",
"self",
".",
"cfg",
".",
"syslog",
")",
":",
"return",
"msg",
"=",
"self",
".",
"make_access_message",
"(",
"resp",
",",
"req",
",",
"environ",
",",
"request_time",
")",
"try",
":",
"self",
".",
"access_log",
".",
"info",
"(",
"msg",
")",
"except",
":",
"self",
".",
"error",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")"
] | Override to apply styling on access logs.
This duplicates a large portion of `gunicorn.glogging.Logger.access`,
only adding | [
"Override",
"to",
"apply",
"styling",
"on",
"access",
"logs",
"."
] | 4fb16f48048ff5fff8f889a007f376236646497b | https://github.com/uranusjr/django-gunicorn/blob/4fb16f48048ff5fff8f889a007f376236646497b/djgunicorn/logging.py#L60-L73 | train |
kytos/kytos-utils | kytos/cli/commands/web/api.py | WebAPI.update | def update(cls, args):
"""Call the method to update the Web UI."""
kytos_api = KytosConfig().config.get('kytos', 'api')
url = f"{kytos_api}api/kytos/core/web/update"
version = args["<version>"]
if version:
url += f"/{version}"
try:
result = requests.post(url)
except(HTTPError, URLError, requests.exceptions.ConnectionError):
LOG.error("Can't connect to server: %s", kytos_api)
return
if result.status_code != 200:
LOG.info("Error while updating web ui: %s", result.content)
else:
LOG.info("Web UI updated.") | python | def update(cls, args):
"""Call the method to update the Web UI."""
kytos_api = KytosConfig().config.get('kytos', 'api')
url = f"{kytos_api}api/kytos/core/web/update"
version = args["<version>"]
if version:
url += f"/{version}"
try:
result = requests.post(url)
except(HTTPError, URLError, requests.exceptions.ConnectionError):
LOG.error("Can't connect to server: %s", kytos_api)
return
if result.status_code != 200:
LOG.info("Error while updating web ui: %s", result.content)
else:
LOG.info("Web UI updated.") | [
"def",
"update",
"(",
"cls",
",",
"args",
")",
":",
"kytos_api",
"=",
"KytosConfig",
"(",
")",
".",
"config",
".",
"get",
"(",
"'kytos'",
",",
"'api'",
")",
"url",
"=",
"f\"{kytos_api}api/kytos/core/web/update\"",
"version",
"=",
"args",
"[",
"\"<version>\"",
"]",
"if",
"version",
":",
"url",
"+=",
"f\"/{version}\"",
"try",
":",
"result",
"=",
"requests",
".",
"post",
"(",
"url",
")",
"except",
"(",
"HTTPError",
",",
"URLError",
",",
"requests",
".",
"exceptions",
".",
"ConnectionError",
")",
":",
"LOG",
".",
"error",
"(",
"\"Can't connect to server: %s\"",
",",
"kytos_api",
")",
"return",
"if",
"result",
".",
"status_code",
"!=",
"200",
":",
"LOG",
".",
"info",
"(",
"\"Error while updating web ui: %s\"",
",",
"result",
".",
"content",
")",
"else",
":",
"LOG",
".",
"info",
"(",
"\"Web UI updated.\"",
")"
] | Call the method to update the Web UI. | [
"Call",
"the",
"method",
"to",
"update",
"the",
"Web",
"UI",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/web/api.py#L16-L33 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.disable | def disable(cls, args):
"""Disable subcommand."""
mgr = NAppsManager()
if args['all']:
napps = mgr.get_enabled()
else:
napps = args['<napp>']
for napp in napps:
mgr.set_napp(*napp)
LOG.info('NApp %s:', mgr.napp_id)
cls.disable_napp(mgr) | python | def disable(cls, args):
"""Disable subcommand."""
mgr = NAppsManager()
if args['all']:
napps = mgr.get_enabled()
else:
napps = args['<napp>']
for napp in napps:
mgr.set_napp(*napp)
LOG.info('NApp %s:', mgr.napp_id)
cls.disable_napp(mgr) | [
"def",
"disable",
"(",
"cls",
",",
"args",
")",
":",
"mgr",
"=",
"NAppsManager",
"(",
")",
"if",
"args",
"[",
"'all'",
"]",
":",
"napps",
"=",
"mgr",
".",
"get_enabled",
"(",
")",
"else",
":",
"napps",
"=",
"args",
"[",
"'<napp>'",
"]",
"for",
"napp",
"in",
"napps",
":",
"mgr",
".",
"set_napp",
"(",
"*",
"napp",
")",
"LOG",
".",
"info",
"(",
"'NApp %s:'",
",",
"mgr",
".",
"napp_id",
")",
"cls",
".",
"disable_napp",
"(",
"mgr",
")"
] | Disable subcommand. | [
"Disable",
"subcommand",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L25-L37 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.disable_napp | def disable_napp(mgr):
"""Disable a NApp."""
if mgr.is_enabled():
LOG.info(' Disabling...')
mgr.disable()
LOG.info(' Disabled.')
else:
LOG.error(" NApp isn't enabled.") | python | def disable_napp(mgr):
"""Disable a NApp."""
if mgr.is_enabled():
LOG.info(' Disabling...')
mgr.disable()
LOG.info(' Disabled.')
else:
LOG.error(" NApp isn't enabled.") | [
"def",
"disable_napp",
"(",
"mgr",
")",
":",
"if",
"mgr",
".",
"is_enabled",
"(",
")",
":",
"LOG",
".",
"info",
"(",
"' Disabling...'",
")",
"mgr",
".",
"disable",
"(",
")",
"LOG",
".",
"info",
"(",
"' Disabled.'",
")",
"else",
":",
"LOG",
".",
"error",
"(",
"\" NApp isn't enabled.\"",
")"
] | Disable a NApp. | [
"Disable",
"a",
"NApp",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L40-L47 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.enable | def enable(cls, args):
"""Enable subcommand."""
mgr = NAppsManager()
if args['all']:
napps = mgr.get_disabled()
else:
napps = args['<napp>']
cls.enable_napps(napps) | python | def enable(cls, args):
"""Enable subcommand."""
mgr = NAppsManager()
if args['all']:
napps = mgr.get_disabled()
else:
napps = args['<napp>']
cls.enable_napps(napps) | [
"def",
"enable",
"(",
"cls",
",",
"args",
")",
":",
"mgr",
"=",
"NAppsManager",
"(",
")",
"if",
"args",
"[",
"'all'",
"]",
":",
"napps",
"=",
"mgr",
".",
"get_disabled",
"(",
")",
"else",
":",
"napps",
"=",
"args",
"[",
"'<napp>'",
"]",
"cls",
".",
"enable_napps",
"(",
"napps",
")"
] | Enable subcommand. | [
"Enable",
"subcommand",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L50-L59 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.enable_napp | def enable_napp(cls, mgr):
"""Install one NApp using NAppManager object."""
try:
if not mgr.is_enabled():
LOG.info(' Enabling...')
mgr.enable()
LOG.info(' Enabled.')
except (FileNotFoundError, PermissionError) as exception:
LOG.error(' %s', exception) | python | def enable_napp(cls, mgr):
"""Install one NApp using NAppManager object."""
try:
if not mgr.is_enabled():
LOG.info(' Enabling...')
mgr.enable()
LOG.info(' Enabled.')
except (FileNotFoundError, PermissionError) as exception:
LOG.error(' %s', exception) | [
"def",
"enable_napp",
"(",
"cls",
",",
"mgr",
")",
":",
"try",
":",
"if",
"not",
"mgr",
".",
"is_enabled",
"(",
")",
":",
"LOG",
".",
"info",
"(",
"' Enabling...'",
")",
"mgr",
".",
"enable",
"(",
")",
"LOG",
".",
"info",
"(",
"' Enabled.'",
")",
"except",
"(",
"FileNotFoundError",
",",
"PermissionError",
")",
"as",
"exception",
":",
"LOG",
".",
"error",
"(",
"' %s'",
",",
"exception",
")"
] | Install one NApp using NAppManager object. | [
"Install",
"one",
"NApp",
"using",
"NAppManager",
"object",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L62-L70 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.enable_napps | def enable_napps(cls, napps):
"""Enable a list of NApps.
Args:
napps (list): List of NApps.
"""
mgr = NAppsManager()
for napp in napps:
mgr.set_napp(*napp)
LOG.info('NApp %s:', mgr.napp_id)
cls.enable_napp(mgr) | python | def enable_napps(cls, napps):
"""Enable a list of NApps.
Args:
napps (list): List of NApps.
"""
mgr = NAppsManager()
for napp in napps:
mgr.set_napp(*napp)
LOG.info('NApp %s:', mgr.napp_id)
cls.enable_napp(mgr) | [
"def",
"enable_napps",
"(",
"cls",
",",
"napps",
")",
":",
"mgr",
"=",
"NAppsManager",
"(",
")",
"for",
"napp",
"in",
"napps",
":",
"mgr",
".",
"set_napp",
"(",
"*",
"napp",
")",
"LOG",
".",
"info",
"(",
"'NApp %s:'",
",",
"mgr",
".",
"napp_id",
")",
"cls",
".",
"enable_napp",
"(",
"mgr",
")"
] | Enable a list of NApps.
Args:
napps (list): List of NApps. | [
"Enable",
"a",
"list",
"of",
"NApps",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L73-L83 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.uninstall | def uninstall(cls, args):
"""Uninstall and delete NApps.
For local installations, do not delete code outside install_path and
enabled_path.
"""
mgr = NAppsManager()
for napp in args['<napp>']:
mgr.set_napp(*napp)
LOG.info('NApp %s:', mgr.napp_id)
if mgr.is_installed():
if mgr.is_enabled():
cls.disable_napp(mgr)
LOG.info(' Uninstalling...')
mgr.uninstall()
LOG.info(' Uninstalled.')
else:
LOG.error(" NApp isn't installed.") | python | def uninstall(cls, args):
"""Uninstall and delete NApps.
For local installations, do not delete code outside install_path and
enabled_path.
"""
mgr = NAppsManager()
for napp in args['<napp>']:
mgr.set_napp(*napp)
LOG.info('NApp %s:', mgr.napp_id)
if mgr.is_installed():
if mgr.is_enabled():
cls.disable_napp(mgr)
LOG.info(' Uninstalling...')
mgr.uninstall()
LOG.info(' Uninstalled.')
else:
LOG.error(" NApp isn't installed.") | [
"def",
"uninstall",
"(",
"cls",
",",
"args",
")",
":",
"mgr",
"=",
"NAppsManager",
"(",
")",
"for",
"napp",
"in",
"args",
"[",
"'<napp>'",
"]",
":",
"mgr",
".",
"set_napp",
"(",
"*",
"napp",
")",
"LOG",
".",
"info",
"(",
"'NApp %s:'",
",",
"mgr",
".",
"napp_id",
")",
"if",
"mgr",
".",
"is_installed",
"(",
")",
":",
"if",
"mgr",
".",
"is_enabled",
"(",
")",
":",
"cls",
".",
"disable_napp",
"(",
"mgr",
")",
"LOG",
".",
"info",
"(",
"' Uninstalling...'",
")",
"mgr",
".",
"uninstall",
"(",
")",
"LOG",
".",
"info",
"(",
"' Uninstalled.'",
")",
"else",
":",
"LOG",
".",
"error",
"(",
"\" NApp isn't installed.\"",
")"
] | Uninstall and delete NApps.
For local installations, do not delete code outside install_path and
enabled_path. | [
"Uninstall",
"and",
"delete",
"NApps",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L102-L119 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.install_napps | def install_napps(cls, napps):
"""Install local or remote NApps.
This method is recursive, it will install each napps and your
dependencies.
"""
mgr = NAppsManager()
for napp in napps:
mgr.set_napp(*napp)
LOG.info(' NApp %s:', mgr.napp_id)
if not mgr.is_installed():
try:
cls.install_napp(mgr)
if not mgr.is_enabled():
cls.enable_napp(mgr)
napp_dependencies = mgr.dependencies()
if napp_dependencies:
LOG.info('Installing Dependencies:')
cls.install_napps(napp_dependencies)
else:
LOG.warning(' Napp already enabled.')
except KytosException:
continue
else:
LOG.warning(' Napp already enabled.') | python | def install_napps(cls, napps):
"""Install local or remote NApps.
This method is recursive, it will install each napps and your
dependencies.
"""
mgr = NAppsManager()
for napp in napps:
mgr.set_napp(*napp)
LOG.info(' NApp %s:', mgr.napp_id)
if not mgr.is_installed():
try:
cls.install_napp(mgr)
if not mgr.is_enabled():
cls.enable_napp(mgr)
napp_dependencies = mgr.dependencies()
if napp_dependencies:
LOG.info('Installing Dependencies:')
cls.install_napps(napp_dependencies)
else:
LOG.warning(' Napp already enabled.')
except KytosException:
continue
else:
LOG.warning(' Napp already enabled.') | [
"def",
"install_napps",
"(",
"cls",
",",
"napps",
")",
":",
"mgr",
"=",
"NAppsManager",
"(",
")",
"for",
"napp",
"in",
"napps",
":",
"mgr",
".",
"set_napp",
"(",
"*",
"napp",
")",
"LOG",
".",
"info",
"(",
"' NApp %s:'",
",",
"mgr",
".",
"napp_id",
")",
"if",
"not",
"mgr",
".",
"is_installed",
"(",
")",
":",
"try",
":",
"cls",
".",
"install_napp",
"(",
"mgr",
")",
"if",
"not",
"mgr",
".",
"is_enabled",
"(",
")",
":",
"cls",
".",
"enable_napp",
"(",
"mgr",
")",
"napp_dependencies",
"=",
"mgr",
".",
"dependencies",
"(",
")",
"if",
"napp_dependencies",
":",
"LOG",
".",
"info",
"(",
"'Installing Dependencies:'",
")",
"cls",
".",
"install_napps",
"(",
"napp_dependencies",
")",
"else",
":",
"LOG",
".",
"warning",
"(",
"' Napp already enabled.'",
")",
"except",
"KytosException",
":",
"continue",
"else",
":",
"LOG",
".",
"warning",
"(",
"' Napp already enabled.'",
")"
] | Install local or remote NApps.
This method is recursive, it will install each napps and your
dependencies. | [
"Install",
"local",
"or",
"remote",
"NApps",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L127-L152 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.install_napp | def install_napp(cls, mgr):
"""Install a NApp.
Raises:
KytosException: If a NApp hasn't been found.
"""
try:
LOG.info(' Searching local NApp...')
mgr.install_local()
LOG.info(' Found and installed.')
except FileNotFoundError:
LOG.info(' Not found. Downloading from NApps Server...')
try:
mgr.install_remote()
LOG.info(' Downloaded and installed.')
return
except HTTPError as exception:
if exception.code == 404:
LOG.error(' NApp not found.')
else:
LOG.error(' NApps Server error: %s', exception)
except URLError as exception:
LOG.error(' NApps Server error: %s', str(exception.reason))
raise KytosException("NApp not found.") | python | def install_napp(cls, mgr):
"""Install a NApp.
Raises:
KytosException: If a NApp hasn't been found.
"""
try:
LOG.info(' Searching local NApp...')
mgr.install_local()
LOG.info(' Found and installed.')
except FileNotFoundError:
LOG.info(' Not found. Downloading from NApps Server...')
try:
mgr.install_remote()
LOG.info(' Downloaded and installed.')
return
except HTTPError as exception:
if exception.code == 404:
LOG.error(' NApp not found.')
else:
LOG.error(' NApps Server error: %s', exception)
except URLError as exception:
LOG.error(' NApps Server error: %s', str(exception.reason))
raise KytosException("NApp not found.") | [
"def",
"install_napp",
"(",
"cls",
",",
"mgr",
")",
":",
"try",
":",
"LOG",
".",
"info",
"(",
"' Searching local NApp...'",
")",
"mgr",
".",
"install_local",
"(",
")",
"LOG",
".",
"info",
"(",
"' Found and installed.'",
")",
"except",
"FileNotFoundError",
":",
"LOG",
".",
"info",
"(",
"' Not found. Downloading from NApps Server...'",
")",
"try",
":",
"mgr",
".",
"install_remote",
"(",
")",
"LOG",
".",
"info",
"(",
"' Downloaded and installed.'",
")",
"return",
"except",
"HTTPError",
"as",
"exception",
":",
"if",
"exception",
".",
"code",
"==",
"404",
":",
"LOG",
".",
"error",
"(",
"' NApp not found.'",
")",
"else",
":",
"LOG",
".",
"error",
"(",
"' NApps Server error: %s'",
",",
"exception",
")",
"except",
"URLError",
"as",
"exception",
":",
"LOG",
".",
"error",
"(",
"' NApps Server error: %s'",
",",
"str",
"(",
"exception",
".",
"reason",
")",
")",
"raise",
"KytosException",
"(",
"\"NApp not found.\"",
")"
] | Install a NApp.
Raises:
KytosException: If a NApp hasn't been found. | [
"Install",
"a",
"NApp",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L155-L179 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.search | def search(cls, args):
"""Search for NApps in NApps server matching a pattern."""
safe_shell_pat = re.escape(args['<pattern>']).replace(r'\*', '.*')
pat_str = '.*{}.*'.format(safe_shell_pat)
pattern = re.compile(pat_str, re.IGNORECASE)
remote_json = NAppsManager.search(pattern)
remote = set()
for napp in remote_json:
# WARNING: This will be changed in future versions, when 'author'
# will be removed.
username = napp.get('username', napp.get('author'))
remote.add(((username, napp.get('name')), napp.get('description')))
cls._print_napps(remote) | python | def search(cls, args):
"""Search for NApps in NApps server matching a pattern."""
safe_shell_pat = re.escape(args['<pattern>']).replace(r'\*', '.*')
pat_str = '.*{}.*'.format(safe_shell_pat)
pattern = re.compile(pat_str, re.IGNORECASE)
remote_json = NAppsManager.search(pattern)
remote = set()
for napp in remote_json:
# WARNING: This will be changed in future versions, when 'author'
# will be removed.
username = napp.get('username', napp.get('author'))
remote.add(((username, napp.get('name')), napp.get('description')))
cls._print_napps(remote) | [
"def",
"search",
"(",
"cls",
",",
"args",
")",
":",
"safe_shell_pat",
"=",
"re",
".",
"escape",
"(",
"args",
"[",
"'<pattern>'",
"]",
")",
".",
"replace",
"(",
"r'\\*'",
",",
"'.*'",
")",
"pat_str",
"=",
"'.*{}.*'",
".",
"format",
"(",
"safe_shell_pat",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"pat_str",
",",
"re",
".",
"IGNORECASE",
")",
"remote_json",
"=",
"NAppsManager",
".",
"search",
"(",
"pattern",
")",
"remote",
"=",
"set",
"(",
")",
"for",
"napp",
"in",
"remote_json",
":",
"# WARNING: This will be changed in future versions, when 'author'",
"# will be removed.",
"username",
"=",
"napp",
".",
"get",
"(",
"'username'",
",",
"napp",
".",
"get",
"(",
"'author'",
")",
")",
"remote",
".",
"add",
"(",
"(",
"(",
"username",
",",
"napp",
".",
"get",
"(",
"'name'",
")",
")",
",",
"napp",
".",
"get",
"(",
"'description'",
")",
")",
")",
"cls",
".",
"_print_napps",
"(",
"remote",
")"
] | Search for NApps in NApps server matching a pattern. | [
"Search",
"for",
"NApps",
"in",
"NApps",
"server",
"matching",
"a",
"pattern",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L182-L195 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI._print_napps | def _print_napps(cls, napp_list):
"""Format the NApp list to be printed."""
mgr = NAppsManager()
enabled = mgr.get_enabled()
installed = mgr.get_installed()
napps = []
for napp, desc in sorted(napp_list):
status = 'i' if napp in installed else '-'
status += 'e' if napp in enabled else '-'
status = '[{}]'.format(status)
name = '{}/{}'.format(*napp)
napps.append((status, name, desc))
cls.print_napps(napps) | python | def _print_napps(cls, napp_list):
"""Format the NApp list to be printed."""
mgr = NAppsManager()
enabled = mgr.get_enabled()
installed = mgr.get_installed()
napps = []
for napp, desc in sorted(napp_list):
status = 'i' if napp in installed else '-'
status += 'e' if napp in enabled else '-'
status = '[{}]'.format(status)
name = '{}/{}'.format(*napp)
napps.append((status, name, desc))
cls.print_napps(napps) | [
"def",
"_print_napps",
"(",
"cls",
",",
"napp_list",
")",
":",
"mgr",
"=",
"NAppsManager",
"(",
")",
"enabled",
"=",
"mgr",
".",
"get_enabled",
"(",
")",
"installed",
"=",
"mgr",
".",
"get_installed",
"(",
")",
"napps",
"=",
"[",
"]",
"for",
"napp",
",",
"desc",
"in",
"sorted",
"(",
"napp_list",
")",
":",
"status",
"=",
"'i'",
"if",
"napp",
"in",
"installed",
"else",
"'-'",
"status",
"+=",
"'e'",
"if",
"napp",
"in",
"enabled",
"else",
"'-'",
"status",
"=",
"'[{}]'",
".",
"format",
"(",
"status",
")",
"name",
"=",
"'{}/{}'",
".",
"format",
"(",
"*",
"napp",
")",
"napps",
".",
"append",
"(",
"(",
"status",
",",
"name",
",",
"desc",
")",
")",
"cls",
".",
"print_napps",
"(",
"napps",
")"
] | Format the NApp list to be printed. | [
"Format",
"the",
"NApp",
"list",
"to",
"be",
"printed",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L198-L210 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.list | def list(cls, args): # pylint: disable=unused-argument
"""List all installed NApps and inform whether they are enabled."""
mgr = NAppsManager()
# Add status
napps = [napp + ('[ie]',) for napp in mgr.get_enabled()]
napps += [napp + ('[i-]',) for napp in mgr.get_disabled()]
# Sort, add description and reorder columns
napps.sort()
napps_ordered = []
for user, name, status in napps:
description = mgr.get_description(user, name)
version = mgr.get_version(user, name)
napp_id = f'{user}/{name}'
if version:
napp_id += f':{version}'
napps_ordered.append((status, napp_id, description))
cls.print_napps(napps_ordered) | python | def list(cls, args): # pylint: disable=unused-argument
"""List all installed NApps and inform whether they are enabled."""
mgr = NAppsManager()
# Add status
napps = [napp + ('[ie]',) for napp in mgr.get_enabled()]
napps += [napp + ('[i-]',) for napp in mgr.get_disabled()]
# Sort, add description and reorder columns
napps.sort()
napps_ordered = []
for user, name, status in napps:
description = mgr.get_description(user, name)
version = mgr.get_version(user, name)
napp_id = f'{user}/{name}'
if version:
napp_id += f':{version}'
napps_ordered.append((status, napp_id, description))
cls.print_napps(napps_ordered) | [
"def",
"list",
"(",
"cls",
",",
"args",
")",
":",
"# pylint: disable=unused-argument",
"mgr",
"=",
"NAppsManager",
"(",
")",
"# Add status",
"napps",
"=",
"[",
"napp",
"+",
"(",
"'[ie]'",
",",
")",
"for",
"napp",
"in",
"mgr",
".",
"get_enabled",
"(",
")",
"]",
"napps",
"+=",
"[",
"napp",
"+",
"(",
"'[i-]'",
",",
")",
"for",
"napp",
"in",
"mgr",
".",
"get_disabled",
"(",
")",
"]",
"# Sort, add description and reorder columns",
"napps",
".",
"sort",
"(",
")",
"napps_ordered",
"=",
"[",
"]",
"for",
"user",
",",
"name",
",",
"status",
"in",
"napps",
":",
"description",
"=",
"mgr",
".",
"get_description",
"(",
"user",
",",
"name",
")",
"version",
"=",
"mgr",
".",
"get_version",
"(",
"user",
",",
"name",
")",
"napp_id",
"=",
"f'{user}/{name}'",
"if",
"version",
":",
"napp_id",
"+=",
"f':{version}'",
"napps_ordered",
".",
"append",
"(",
"(",
"status",
",",
"napp_id",
",",
"description",
")",
")",
"cls",
".",
"print_napps",
"(",
"napps_ordered",
")"
] | List all installed NApps and inform whether they are enabled. | [
"List",
"all",
"installed",
"NApps",
"and",
"inform",
"whether",
"they",
"are",
"enabled",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L213-L233 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.print_napps | def print_napps(napps):
"""Print status, name and description."""
if not napps:
print('No NApps found.')
return
stat_w = 6 # We already know the size of Status col
name_w = max(len(n[1]) for n in napps)
desc_w = max(len(n[2]) for n in napps)
term_w = os.popen('stty size', 'r').read().split()[1]
remaining = max(0, int(term_w) - stat_w - name_w - 6)
desc_w = min(desc_w, remaining)
widths = (stat_w, name_w, desc_w)
header = '\n{:^%d} | {:^%d} | {:^%d}' % widths
row = '{:^%d} | {:<%d} | {:<%d}' % widths
print(header.format('Status', 'NApp ID', 'Description'))
print('=+='.join('=' * w for w in widths))
for user, name, desc in napps:
desc = (desc[:desc_w - 3] + '...') if len(desc) > desc_w else desc
print(row.format(user, name, desc))
print('\nStatus: (i)nstalled, (e)nabled\n') | python | def print_napps(napps):
"""Print status, name and description."""
if not napps:
print('No NApps found.')
return
stat_w = 6 # We already know the size of Status col
name_w = max(len(n[1]) for n in napps)
desc_w = max(len(n[2]) for n in napps)
term_w = os.popen('stty size', 'r').read().split()[1]
remaining = max(0, int(term_w) - stat_w - name_w - 6)
desc_w = min(desc_w, remaining)
widths = (stat_w, name_w, desc_w)
header = '\n{:^%d} | {:^%d} | {:^%d}' % widths
row = '{:^%d} | {:<%d} | {:<%d}' % widths
print(header.format('Status', 'NApp ID', 'Description'))
print('=+='.join('=' * w for w in widths))
for user, name, desc in napps:
desc = (desc[:desc_w - 3] + '...') if len(desc) > desc_w else desc
print(row.format(user, name, desc))
print('\nStatus: (i)nstalled, (e)nabled\n') | [
"def",
"print_napps",
"(",
"napps",
")",
":",
"if",
"not",
"napps",
":",
"print",
"(",
"'No NApps found.'",
")",
"return",
"stat_w",
"=",
"6",
"# We already know the size of Status col",
"name_w",
"=",
"max",
"(",
"len",
"(",
"n",
"[",
"1",
"]",
")",
"for",
"n",
"in",
"napps",
")",
"desc_w",
"=",
"max",
"(",
"len",
"(",
"n",
"[",
"2",
"]",
")",
"for",
"n",
"in",
"napps",
")",
"term_w",
"=",
"os",
".",
"popen",
"(",
"'stty size'",
",",
"'r'",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
")",
"[",
"1",
"]",
"remaining",
"=",
"max",
"(",
"0",
",",
"int",
"(",
"term_w",
")",
"-",
"stat_w",
"-",
"name_w",
"-",
"6",
")",
"desc_w",
"=",
"min",
"(",
"desc_w",
",",
"remaining",
")",
"widths",
"=",
"(",
"stat_w",
",",
"name_w",
",",
"desc_w",
")",
"header",
"=",
"'\\n{:^%d} | {:^%d} | {:^%d}'",
"%",
"widths",
"row",
"=",
"'{:^%d} | {:<%d} | {:<%d}'",
"%",
"widths",
"print",
"(",
"header",
".",
"format",
"(",
"'Status'",
",",
"'NApp ID'",
",",
"'Description'",
")",
")",
"print",
"(",
"'=+='",
".",
"join",
"(",
"'='",
"*",
"w",
"for",
"w",
"in",
"widths",
")",
")",
"for",
"user",
",",
"name",
",",
"desc",
"in",
"napps",
":",
"desc",
"=",
"(",
"desc",
"[",
":",
"desc_w",
"-",
"3",
"]",
"+",
"'...'",
")",
"if",
"len",
"(",
"desc",
")",
">",
"desc_w",
"else",
"desc",
"print",
"(",
"row",
".",
"format",
"(",
"user",
",",
"name",
",",
"desc",
")",
")",
"print",
"(",
"'\\nStatus: (i)nstalled, (e)nabled\\n'",
")"
] | Print status, name and description. | [
"Print",
"status",
"name",
"and",
"description",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L236-L258 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.delete | def delete(args):
"""Delete NApps from server."""
mgr = NAppsManager()
for napp in args['<napp>']:
mgr.set_napp(*napp)
LOG.info('Deleting NApp %s from server...', mgr.napp_id)
try:
mgr.delete()
LOG.info(' Deleted.')
except requests.HTTPError as exception:
if exception.response.status_code == 405:
LOG.error('Delete Napp is not allowed yet.')
else:
msg = json.loads(exception.response.content)
LOG.error(' Server error: %s - ', msg['error']) | python | def delete(args):
"""Delete NApps from server."""
mgr = NAppsManager()
for napp in args['<napp>']:
mgr.set_napp(*napp)
LOG.info('Deleting NApp %s from server...', mgr.napp_id)
try:
mgr.delete()
LOG.info(' Deleted.')
except requests.HTTPError as exception:
if exception.response.status_code == 405:
LOG.error('Delete Napp is not allowed yet.')
else:
msg = json.loads(exception.response.content)
LOG.error(' Server error: %s - ', msg['error']) | [
"def",
"delete",
"(",
"args",
")",
":",
"mgr",
"=",
"NAppsManager",
"(",
")",
"for",
"napp",
"in",
"args",
"[",
"'<napp>'",
"]",
":",
"mgr",
".",
"set_napp",
"(",
"*",
"napp",
")",
"LOG",
".",
"info",
"(",
"'Deleting NApp %s from server...'",
",",
"mgr",
".",
"napp_id",
")",
"try",
":",
"mgr",
".",
"delete",
"(",
")",
"LOG",
".",
"info",
"(",
"' Deleted.'",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"exception",
":",
"if",
"exception",
".",
"response",
".",
"status_code",
"==",
"405",
":",
"LOG",
".",
"error",
"(",
"'Delete Napp is not allowed yet.'",
")",
"else",
":",
"msg",
"=",
"json",
".",
"loads",
"(",
"exception",
".",
"response",
".",
"content",
")",
"LOG",
".",
"error",
"(",
"' Server error: %s - '",
",",
"msg",
"[",
"'error'",
"]",
")"
] | Delete NApps from server. | [
"Delete",
"NApps",
"from",
"server",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L261-L275 | train |
kytos/kytos-utils | kytos/cli/commands/napps/api.py | NAppsAPI.reload | def reload(cls, args):
"""Reload NApps code."""
LOG.info('Reloading NApps...')
mgr = NAppsManager()
try:
if args['all']:
mgr.reload(None)
else:
napps = args['<napp>']
mgr.reload(napps)
LOG.info('\tReloaded.')
except requests.HTTPError as exception:
if exception.response.status_code != 200:
msg = json.loads(exception.response.content)
LOG.error('\tServer error: %s - ', msg['error']) | python | def reload(cls, args):
"""Reload NApps code."""
LOG.info('Reloading NApps...')
mgr = NAppsManager()
try:
if args['all']:
mgr.reload(None)
else:
napps = args['<napp>']
mgr.reload(napps)
LOG.info('\tReloaded.')
except requests.HTTPError as exception:
if exception.response.status_code != 200:
msg = json.loads(exception.response.content)
LOG.error('\tServer error: %s - ', msg['error']) | [
"def",
"reload",
"(",
"cls",
",",
"args",
")",
":",
"LOG",
".",
"info",
"(",
"'Reloading NApps...'",
")",
"mgr",
"=",
"NAppsManager",
"(",
")",
"try",
":",
"if",
"args",
"[",
"'all'",
"]",
":",
"mgr",
".",
"reload",
"(",
"None",
")",
"else",
":",
"napps",
"=",
"args",
"[",
"'<napp>'",
"]",
"mgr",
".",
"reload",
"(",
"napps",
")",
"LOG",
".",
"info",
"(",
"'\\tReloaded.'",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"exception",
":",
"if",
"exception",
".",
"response",
".",
"status_code",
"!=",
"200",
":",
"msg",
"=",
"json",
".",
"loads",
"(",
"exception",
".",
"response",
".",
"content",
")",
"LOG",
".",
"error",
"(",
"'\\tServer error: %s - '",
",",
"msg",
"[",
"'error'",
"]",
")"
] | Reload NApps code. | [
"Reload",
"NApps",
"code",
"."
] | b4750c618d15cff75970ea6124bda4d2b9a33578 | https://github.com/kytos/kytos-utils/blob/b4750c618d15cff75970ea6124bda4d2b9a33578/kytos/cli/commands/napps/api.py#L284-L300 | train |
KE-works/pykechain | pykechain/models/property_reference.py | ReferenceProperty.choices | def choices(self):
"""Retrieve the parts that you can reference for this `ReferenceProperty`.
This method makes 2 API calls: 1) to retrieve the referenced model, and 2) to retrieve the instances of
that model.
:return: the :class:`Part`'s that can be referenced as a :class:`~pykechain.model.PartSet`.
:raises APIError: When unable to load and provide the choices
Example
-------
>>> property = project.part('Bike').property('RefTest')
>>> reference_part_choices = property.choices()
"""
# from the reference property (instance) we need to get the value of the reference property in the model
# in the reference property of the model the value is set to the ID of the model from which we can choose parts
model_parent_part = self.part.model() # makes single part call
property_model = model_parent_part.property(self.name)
referenced_model = self._client.model(pk=property_model._value['id']) # makes single part call
possible_choices = self._client.parts(model=referenced_model) # makes multiple parts call
return possible_choices | python | def choices(self):
"""Retrieve the parts that you can reference for this `ReferenceProperty`.
This method makes 2 API calls: 1) to retrieve the referenced model, and 2) to retrieve the instances of
that model.
:return: the :class:`Part`'s that can be referenced as a :class:`~pykechain.model.PartSet`.
:raises APIError: When unable to load and provide the choices
Example
-------
>>> property = project.part('Bike').property('RefTest')
>>> reference_part_choices = property.choices()
"""
# from the reference property (instance) we need to get the value of the reference property in the model
# in the reference property of the model the value is set to the ID of the model from which we can choose parts
model_parent_part = self.part.model() # makes single part call
property_model = model_parent_part.property(self.name)
referenced_model = self._client.model(pk=property_model._value['id']) # makes single part call
possible_choices = self._client.parts(model=referenced_model) # makes multiple parts call
return possible_choices | [
"def",
"choices",
"(",
"self",
")",
":",
"# from the reference property (instance) we need to get the value of the reference property in the model",
"# in the reference property of the model the value is set to the ID of the model from which we can choose parts",
"model_parent_part",
"=",
"self",
".",
"part",
".",
"model",
"(",
")",
"# makes single part call",
"property_model",
"=",
"model_parent_part",
".",
"property",
"(",
"self",
".",
"name",
")",
"referenced_model",
"=",
"self",
".",
"_client",
".",
"model",
"(",
"pk",
"=",
"property_model",
".",
"_value",
"[",
"'id'",
"]",
")",
"# makes single part call",
"possible_choices",
"=",
"self",
".",
"_client",
".",
"parts",
"(",
"model",
"=",
"referenced_model",
")",
"# makes multiple parts call",
"return",
"possible_choices"
] | Retrieve the parts that you can reference for this `ReferenceProperty`.
This method makes 2 API calls: 1) to retrieve the referenced model, and 2) to retrieve the instances of
that model.
:return: the :class:`Part`'s that can be referenced as a :class:`~pykechain.model.PartSet`.
:raises APIError: When unable to load and provide the choices
Example
-------
>>> property = project.part('Bike').property('RefTest')
>>> reference_part_choices = property.choices() | [
"Retrieve",
"the",
"parts",
"that",
"you",
"can",
"reference",
"for",
"this",
"ReferenceProperty",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/models/property_reference.py#L70-L93 | train |
biosignalsnotebooks/biosignalsnotebooks | header_footer/old/osf_notebook_class.py | opensignals_hierarchy | def opensignals_hierarchy(root=None, update=False, clone=False):
"""
Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically.
----------
Parameters
----------
root : None or str
The file path where the OpenSignalsTools Environment will be stored.
update : bool
If True the old files will be replaced by the new ones.
clone : bool
If True then all the available Notebooks will be stored in the users computer.
If False only the folder hierarchy of OpenSignalsTools will be generated, giving to the
user a blank template for creating his own Notebook Environment.
Returns
-------
out : str
The root file path of OpenSignalsTools Environment is returned.
"""
if root is None:
root = os.getcwd()
categories = list(NOTEBOOK_KEYS.keys())
# ============================ Creation of the main directory ==================================
current_dir = root + "\\opensignalstools_environment"
if not os.path.isdir(current_dir):
os.makedirs(current_dir)
# ================== Copy of 'images' 'styles' and 'signal_samples' folders ====================
for var in ["images", "styles", "signal_samples"]:
if not os.path.isdir(root + "\\opensignalstools_environment\\" + var):
src = os.getcwd() + "\\" + var
destination = current_dir + "\\" + var
shutil.copytree(src, destination)
elif update is True:
shutil.rmtree(root + "\\opensignalstools_environment\\" + var)
src = os.getcwd() + "\\" + var
destination = current_dir + "\\" + var
shutil.copytree(src, destination)
# =========================== Generation of 'Categories' folder ================================
current_dir = root + "\\opensignalstools_environment\\Categories"
if not os.path.isdir(current_dir):
os.makedirs(current_dir)
for category in categories:
if not os.path.isdir(current_dir + "\\" + category):
os.makedirs(current_dir + "\\" + category)
if clone is True:
# Fill each folder inside "Categories" directory with the respective notebooks.
# Each notebook will be created by a specific function.
dir_path = root + "\\notebook_code"
list_of_code_dirs = os.listdir(dir_path)
for folder in list_of_code_dirs:
folder_path = root + "\\notebook_code\\" + folder
if folder != "MainFiles" and folder != "__pycache__":
list_of_code_files = os.listdir(folder_path)
for file in list_of_code_files:
if file != "__pycache__":
spec = importlib.util.spec_from_file_location(file, folder_path +
"\\" + file)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.run(root + "\\opensignalstools_environment")
# Generation of opensignalstools environment main files.
main_page = notebook("Main_Files_By_Category")
main_page.write_to_file(root + "\\opensignalstools_environment", "opensignalstools",
footer=False)
by_difficulty = notebook("Main_Files_By_Difficulty", "Notebooks Grouped by Difficulty", notebook_description=DESCRIPTION_GROUP_BY)
by_difficulty.write_to_file(root + "\\opensignalstools_environment", "by_diff",
footer=False)
by_tags = notebook("Main_Files_By_Tag", "Notebooks Grouped by Tag Values",
notebook_description=DESCRIPTION_GROUP_BY)
by_tags.write_to_file(root + "\\opensignalstools_environment", "by_tag",
footer=False)
by_signal_type = notebook("Main_Files_By_Signal_Type", "Notebooks Grouped by Signal Type",
notebook_description=DESCRIPTION_GROUP_BY)
by_signal_type.write_to_file(root + "\\opensignalstools_environment",
"by_signal_type", footer=False)
signal_samples = notebook("Main_Files_Signal_Samples", "Signal Samples Library",
notebook_description=DESCRIPTION_SIGNAL_SAMPLES)
signal_samples.write_to_file(root + "\\opensignalstools_environment",
"signal_samples", footer=False)
return root + "\\opensignalstools_environment" | python | def opensignals_hierarchy(root=None, update=False, clone=False):
"""
Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically.
----------
Parameters
----------
root : None or str
The file path where the OpenSignalsTools Environment will be stored.
update : bool
If True the old files will be replaced by the new ones.
clone : bool
If True then all the available Notebooks will be stored in the users computer.
If False only the folder hierarchy of OpenSignalsTools will be generated, giving to the
user a blank template for creating his own Notebook Environment.
Returns
-------
out : str
The root file path of OpenSignalsTools Environment is returned.
"""
if root is None:
root = os.getcwd()
categories = list(NOTEBOOK_KEYS.keys())
# ============================ Creation of the main directory ==================================
current_dir = root + "\\opensignalstools_environment"
if not os.path.isdir(current_dir):
os.makedirs(current_dir)
# ================== Copy of 'images' 'styles' and 'signal_samples' folders ====================
for var in ["images", "styles", "signal_samples"]:
if not os.path.isdir(root + "\\opensignalstools_environment\\" + var):
src = os.getcwd() + "\\" + var
destination = current_dir + "\\" + var
shutil.copytree(src, destination)
elif update is True:
shutil.rmtree(root + "\\opensignalstools_environment\\" + var)
src = os.getcwd() + "\\" + var
destination = current_dir + "\\" + var
shutil.copytree(src, destination)
# =========================== Generation of 'Categories' folder ================================
current_dir = root + "\\opensignalstools_environment\\Categories"
if not os.path.isdir(current_dir):
os.makedirs(current_dir)
for category in categories:
if not os.path.isdir(current_dir + "\\" + category):
os.makedirs(current_dir + "\\" + category)
if clone is True:
# Fill each folder inside "Categories" directory with the respective notebooks.
# Each notebook will be created by a specific function.
dir_path = root + "\\notebook_code"
list_of_code_dirs = os.listdir(dir_path)
for folder in list_of_code_dirs:
folder_path = root + "\\notebook_code\\" + folder
if folder != "MainFiles" and folder != "__pycache__":
list_of_code_files = os.listdir(folder_path)
for file in list_of_code_files:
if file != "__pycache__":
spec = importlib.util.spec_from_file_location(file, folder_path +
"\\" + file)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.run(root + "\\opensignalstools_environment")
# Generation of opensignalstools environment main files.
main_page = notebook("Main_Files_By_Category")
main_page.write_to_file(root + "\\opensignalstools_environment", "opensignalstools",
footer=False)
by_difficulty = notebook("Main_Files_By_Difficulty", "Notebooks Grouped by Difficulty", notebook_description=DESCRIPTION_GROUP_BY)
by_difficulty.write_to_file(root + "\\opensignalstools_environment", "by_diff",
footer=False)
by_tags = notebook("Main_Files_By_Tag", "Notebooks Grouped by Tag Values",
notebook_description=DESCRIPTION_GROUP_BY)
by_tags.write_to_file(root + "\\opensignalstools_environment", "by_tag",
footer=False)
by_signal_type = notebook("Main_Files_By_Signal_Type", "Notebooks Grouped by Signal Type",
notebook_description=DESCRIPTION_GROUP_BY)
by_signal_type.write_to_file(root + "\\opensignalstools_environment",
"by_signal_type", footer=False)
signal_samples = notebook("Main_Files_Signal_Samples", "Signal Samples Library",
notebook_description=DESCRIPTION_SIGNAL_SAMPLES)
signal_samples.write_to_file(root + "\\opensignalstools_environment",
"signal_samples", footer=False)
return root + "\\opensignalstools_environment" | [
"def",
"opensignals_hierarchy",
"(",
"root",
"=",
"None",
",",
"update",
"=",
"False",
",",
"clone",
"=",
"False",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"os",
".",
"getcwd",
"(",
")",
"categories",
"=",
"list",
"(",
"NOTEBOOK_KEYS",
".",
"keys",
"(",
")",
")",
"# ============================ Creation of the main directory ==================================",
"current_dir",
"=",
"root",
"+",
"\"\\\\opensignalstools_environment\"",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"current_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"current_dir",
")",
"# ================== Copy of 'images' 'styles' and 'signal_samples' folders ====================",
"for",
"var",
"in",
"[",
"\"images\"",
",",
"\"styles\"",
",",
"\"signal_samples\"",
"]",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"root",
"+",
"\"\\\\opensignalstools_environment\\\\\"",
"+",
"var",
")",
":",
"src",
"=",
"os",
".",
"getcwd",
"(",
")",
"+",
"\"\\\\\"",
"+",
"var",
"destination",
"=",
"current_dir",
"+",
"\"\\\\\"",
"+",
"var",
"shutil",
".",
"copytree",
"(",
"src",
",",
"destination",
")",
"elif",
"update",
"is",
"True",
":",
"shutil",
".",
"rmtree",
"(",
"root",
"+",
"\"\\\\opensignalstools_environment\\\\\"",
"+",
"var",
")",
"src",
"=",
"os",
".",
"getcwd",
"(",
")",
"+",
"\"\\\\\"",
"+",
"var",
"destination",
"=",
"current_dir",
"+",
"\"\\\\\"",
"+",
"var",
"shutil",
".",
"copytree",
"(",
"src",
",",
"destination",
")",
"# =========================== Generation of 'Categories' folder ================================",
"current_dir",
"=",
"root",
"+",
"\"\\\\opensignalstools_environment\\\\Categories\"",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"current_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"current_dir",
")",
"for",
"category",
"in",
"categories",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"current_dir",
"+",
"\"\\\\\"",
"+",
"category",
")",
":",
"os",
".",
"makedirs",
"(",
"current_dir",
"+",
"\"\\\\\"",
"+",
"category",
")",
"if",
"clone",
"is",
"True",
":",
"# Fill each folder inside \"Categories\" directory with the respective notebooks.",
"# Each notebook will be created by a specific function.",
"dir_path",
"=",
"root",
"+",
"\"\\\\notebook_code\"",
"list_of_code_dirs",
"=",
"os",
".",
"listdir",
"(",
"dir_path",
")",
"for",
"folder",
"in",
"list_of_code_dirs",
":",
"folder_path",
"=",
"root",
"+",
"\"\\\\notebook_code\\\\\"",
"+",
"folder",
"if",
"folder",
"!=",
"\"MainFiles\"",
"and",
"folder",
"!=",
"\"__pycache__\"",
":",
"list_of_code_files",
"=",
"os",
".",
"listdir",
"(",
"folder_path",
")",
"for",
"file",
"in",
"list_of_code_files",
":",
"if",
"file",
"!=",
"\"__pycache__\"",
":",
"spec",
"=",
"importlib",
".",
"util",
".",
"spec_from_file_location",
"(",
"file",
",",
"folder_path",
"+",
"\"\\\\\"",
"+",
"file",
")",
"foo",
"=",
"importlib",
".",
"util",
".",
"module_from_spec",
"(",
"spec",
")",
"spec",
".",
"loader",
".",
"exec_module",
"(",
"foo",
")",
"foo",
".",
"run",
"(",
"root",
"+",
"\"\\\\opensignalstools_environment\"",
")",
"# Generation of opensignalstools environment main files.",
"main_page",
"=",
"notebook",
"(",
"\"Main_Files_By_Category\"",
")",
"main_page",
".",
"write_to_file",
"(",
"root",
"+",
"\"\\\\opensignalstools_environment\"",
",",
"\"opensignalstools\"",
",",
"footer",
"=",
"False",
")",
"by_difficulty",
"=",
"notebook",
"(",
"\"Main_Files_By_Difficulty\"",
",",
"\"Notebooks Grouped by Difficulty\"",
",",
"notebook_description",
"=",
"DESCRIPTION_GROUP_BY",
")",
"by_difficulty",
".",
"write_to_file",
"(",
"root",
"+",
"\"\\\\opensignalstools_environment\"",
",",
"\"by_diff\"",
",",
"footer",
"=",
"False",
")",
"by_tags",
"=",
"notebook",
"(",
"\"Main_Files_By_Tag\"",
",",
"\"Notebooks Grouped by Tag Values\"",
",",
"notebook_description",
"=",
"DESCRIPTION_GROUP_BY",
")",
"by_tags",
".",
"write_to_file",
"(",
"root",
"+",
"\"\\\\opensignalstools_environment\"",
",",
"\"by_tag\"",
",",
"footer",
"=",
"False",
")",
"by_signal_type",
"=",
"notebook",
"(",
"\"Main_Files_By_Signal_Type\"",
",",
"\"Notebooks Grouped by Signal Type\"",
",",
"notebook_description",
"=",
"DESCRIPTION_GROUP_BY",
")",
"by_signal_type",
".",
"write_to_file",
"(",
"root",
"+",
"\"\\\\opensignalstools_environment\"",
",",
"\"by_signal_type\"",
",",
"footer",
"=",
"False",
")",
"signal_samples",
"=",
"notebook",
"(",
"\"Main_Files_Signal_Samples\"",
",",
"\"Signal Samples Library\"",
",",
"notebook_description",
"=",
"DESCRIPTION_SIGNAL_SAMPLES",
")",
"signal_samples",
".",
"write_to_file",
"(",
"root",
"+",
"\"\\\\opensignalstools_environment\"",
",",
"\"signal_samples\"",
",",
"footer",
"=",
"False",
")",
"return",
"root",
"+",
"\"\\\\opensignalstools_environment\""
] | Function that generates the OpenSignalsTools Notebooks File Hierarchy programatically.
----------
Parameters
----------
root : None or str
The file path where the OpenSignalsTools Environment will be stored.
update : bool
If True the old files will be replaced by the new ones.
clone : bool
If True then all the available Notebooks will be stored in the users computer.
If False only the folder hierarchy of OpenSignalsTools will be generated, giving to the
user a blank template for creating his own Notebook Environment.
Returns
-------
out : str
The root file path of OpenSignalsTools Environment is returned. | [
"Function",
"that",
"generates",
"the",
"OpenSignalsTools",
"Notebooks",
"File",
"Hierarchy",
"programatically",
"."
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/header_footer/old/osf_notebook_class.py#L225-L321 | train |
biosignalsnotebooks/biosignalsnotebooks | header_footer/old/osf_notebook_class.py | _generate_notebook_by_tag_body | def _generate_notebook_by_tag_body(notebook_object, dict_by_tag):
"""
Internal function that is used for generation of the page where notebooks are organized by
tag values.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the body will be created.
dict_by_tag : dict
Dictionary where each key is a tag and the respective value will be a list containing the
Notebooks (title and filename) that include this tag.
"""
tag_keys = list(dict_by_tag.keys())
tag_keys.sort()
for tag in tag_keys:
if tag.lower() not in SIGNAL_TYPE_LIST:
markdown_cell = group_tag_code.TAG_TABLE_HEADER
markdown_cell = markdown_cell.replace("Tag i", tag)
for notebook_file in dict_by_tag[tag]:
split_path = notebook_file.split("\\")
notebook_type = split_path[-2]
notebook_name = split_path[-1].split("&")[0]
notebook_title = split_path[-1].split("&")[1]
markdown_cell += "\t<tr>\n\t\t<td width='20%' class='header_image_color_" + \
str(NOTEBOOK_KEYS[notebook_type]) + "'><img " \
"src='../../images/icons/" + notebook_type.title() +\
".png' width='15%'>\n\t\t</td>"
markdown_cell += "\n\t\t<td width='60%' class='center_cell open_cell_light'>" + \
notebook_title + "\n\t\t</td>"
markdown_cell += "\n\t\t<td width='20%' class='center_cell'>\n\t\t\t<a href='" \
"../" + notebook_type.title() + "/" + notebook_name + \
"'><div class='file_icon'></div></a>\n\t\t</td>\n\t</tr>"
markdown_cell += "</table>"
# ==================== Insertion of HTML table in a new Notebook cell ======================
notebook_object["cells"].append(nb.v4.new_markdown_cell(markdown_cell)) | python | def _generate_notebook_by_tag_body(notebook_object, dict_by_tag):
"""
Internal function that is used for generation of the page where notebooks are organized by
tag values.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the body will be created.
dict_by_tag : dict
Dictionary where each key is a tag and the respective value will be a list containing the
Notebooks (title and filename) that include this tag.
"""
tag_keys = list(dict_by_tag.keys())
tag_keys.sort()
for tag in tag_keys:
if tag.lower() not in SIGNAL_TYPE_LIST:
markdown_cell = group_tag_code.TAG_TABLE_HEADER
markdown_cell = markdown_cell.replace("Tag i", tag)
for notebook_file in dict_by_tag[tag]:
split_path = notebook_file.split("\\")
notebook_type = split_path[-2]
notebook_name = split_path[-1].split("&")[0]
notebook_title = split_path[-1].split("&")[1]
markdown_cell += "\t<tr>\n\t\t<td width='20%' class='header_image_color_" + \
str(NOTEBOOK_KEYS[notebook_type]) + "'><img " \
"src='../../images/icons/" + notebook_type.title() +\
".png' width='15%'>\n\t\t</td>"
markdown_cell += "\n\t\t<td width='60%' class='center_cell open_cell_light'>" + \
notebook_title + "\n\t\t</td>"
markdown_cell += "\n\t\t<td width='20%' class='center_cell'>\n\t\t\t<a href='" \
"../" + notebook_type.title() + "/" + notebook_name + \
"'><div class='file_icon'></div></a>\n\t\t</td>\n\t</tr>"
markdown_cell += "</table>"
# ==================== Insertion of HTML table in a new Notebook cell ======================
notebook_object["cells"].append(nb.v4.new_markdown_cell(markdown_cell)) | [
"def",
"_generate_notebook_by_tag_body",
"(",
"notebook_object",
",",
"dict_by_tag",
")",
":",
"tag_keys",
"=",
"list",
"(",
"dict_by_tag",
".",
"keys",
"(",
")",
")",
"tag_keys",
".",
"sort",
"(",
")",
"for",
"tag",
"in",
"tag_keys",
":",
"if",
"tag",
".",
"lower",
"(",
")",
"not",
"in",
"SIGNAL_TYPE_LIST",
":",
"markdown_cell",
"=",
"group_tag_code",
".",
"TAG_TABLE_HEADER",
"markdown_cell",
"=",
"markdown_cell",
".",
"replace",
"(",
"\"Tag i\"",
",",
"tag",
")",
"for",
"notebook_file",
"in",
"dict_by_tag",
"[",
"tag",
"]",
":",
"split_path",
"=",
"notebook_file",
".",
"split",
"(",
"\"\\\\\"",
")",
"notebook_type",
"=",
"split_path",
"[",
"-",
"2",
"]",
"notebook_name",
"=",
"split_path",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"\"&\"",
")",
"[",
"0",
"]",
"notebook_title",
"=",
"split_path",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"\"&\"",
")",
"[",
"1",
"]",
"markdown_cell",
"+=",
"\"\\t<tr>\\n\\t\\t<td width='20%' class='header_image_color_\"",
"+",
"str",
"(",
"NOTEBOOK_KEYS",
"[",
"notebook_type",
"]",
")",
"+",
"\"'><img \"",
"\"src='../../images/icons/\"",
"+",
"notebook_type",
".",
"title",
"(",
")",
"+",
"\".png' width='15%'>\\n\\t\\t</td>\"",
"markdown_cell",
"+=",
"\"\\n\\t\\t<td width='60%' class='center_cell open_cell_light'>\"",
"+",
"notebook_title",
"+",
"\"\\n\\t\\t</td>\"",
"markdown_cell",
"+=",
"\"\\n\\t\\t<td width='20%' class='center_cell'>\\n\\t\\t\\t<a href='\"",
"\"../\"",
"+",
"notebook_type",
".",
"title",
"(",
")",
"+",
"\"/\"",
"+",
"notebook_name",
"+",
"\"'><div class='file_icon'></div></a>\\n\\t\\t</td>\\n\\t</tr>\"",
"markdown_cell",
"+=",
"\"</table>\"",
"# ==================== Insertion of HTML table in a new Notebook cell ======================",
"notebook_object",
"[",
"\"cells\"",
"]",
".",
"append",
"(",
"nb",
".",
"v4",
".",
"new_markdown_cell",
"(",
"markdown_cell",
")",
")"
] | Internal function that is used for generation of the page where notebooks are organized by
tag values.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the body will be created.
dict_by_tag : dict
Dictionary where each key is a tag and the respective value will be a list containing the
Notebooks (title and filename) that include this tag. | [
"Internal",
"function",
"that",
"is",
"used",
"for",
"generation",
"of",
"the",
"page",
"where",
"notebooks",
"are",
"organized",
"by",
"tag",
"values",
"."
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/header_footer/old/osf_notebook_class.py#L640-L681 | train |
biosignalsnotebooks/biosignalsnotebooks | header_footer/old/osf_notebook_class.py | notebook.add_markdown_cell | def add_markdown_cell(self, content, tags=None):
"""
Class method responsible for adding a markdown cell with content 'content' to the
Notebook object.
----------
Parameters
----------
content : str
Text/HTML code/... to include in the markdown cell (triple quote for multiline text).
tags : list
A list of tags to include in the markdown cell metadata.
"""
self.notebook["cells"].append(nb.v4.new_markdown_cell(content, **{"metadata":
{"tags": tags}})) | python | def add_markdown_cell(self, content, tags=None):
"""
Class method responsible for adding a markdown cell with content 'content' to the
Notebook object.
----------
Parameters
----------
content : str
Text/HTML code/... to include in the markdown cell (triple quote for multiline text).
tags : list
A list of tags to include in the markdown cell metadata.
"""
self.notebook["cells"].append(nb.v4.new_markdown_cell(content, **{"metadata":
{"tags": tags}})) | [
"def",
"add_markdown_cell",
"(",
"self",
",",
"content",
",",
"tags",
"=",
"None",
")",
":",
"self",
".",
"notebook",
"[",
"\"cells\"",
"]",
".",
"append",
"(",
"nb",
".",
"v4",
".",
"new_markdown_cell",
"(",
"content",
",",
"*",
"*",
"{",
"\"metadata\"",
":",
"{",
"\"tags\"",
":",
"tags",
"}",
"}",
")",
")"
] | Class method responsible for adding a markdown cell with content 'content' to the
Notebook object.
----------
Parameters
----------
content : str
Text/HTML code/... to include in the markdown cell (triple quote for multiline text).
tags : list
A list of tags to include in the markdown cell metadata. | [
"Class",
"method",
"responsible",
"for",
"adding",
"a",
"markdown",
"cell",
"with",
"content",
"content",
"to",
"the",
"Notebook",
"object",
"."
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/header_footer/old/osf_notebook_class.py#L186-L201 | train |
biosignalsnotebooks/biosignalsnotebooks | header_footer/old/osf_notebook_class.py | notebook.add_code_cell | def add_code_cell(self, content, tags=None):
"""
Class method responsible for adding a code cell with content 'content' to the
Notebook object.
----------
Parameters
----------
content : str
Code in a string format to include in the cell (triple quote for multiline
text).
tags : list
A list of tags to include in the code cell metadata.
"""
self.notebook["cells"].append(nb.v4.new_code_cell(content, **{"metadata":
{"tags": tags}})) | python | def add_code_cell(self, content, tags=None):
"""
Class method responsible for adding a code cell with content 'content' to the
Notebook object.
----------
Parameters
----------
content : str
Code in a string format to include in the cell (triple quote for multiline
text).
tags : list
A list of tags to include in the code cell metadata.
"""
self.notebook["cells"].append(nb.v4.new_code_cell(content, **{"metadata":
{"tags": tags}})) | [
"def",
"add_code_cell",
"(",
"self",
",",
"content",
",",
"tags",
"=",
"None",
")",
":",
"self",
".",
"notebook",
"[",
"\"cells\"",
"]",
".",
"append",
"(",
"nb",
".",
"v4",
".",
"new_code_cell",
"(",
"content",
",",
"*",
"*",
"{",
"\"metadata\"",
":",
"{",
"\"tags\"",
":",
"tags",
"}",
"}",
")",
")"
] | Class method responsible for adding a code cell with content 'content' to the
Notebook object.
----------
Parameters
----------
content : str
Code in a string format to include in the cell (triple quote for multiline
text).
tags : list
A list of tags to include in the code cell metadata. | [
"Class",
"method",
"responsible",
"for",
"adding",
"a",
"code",
"cell",
"with",
"content",
"content",
"to",
"the",
"Notebook",
"object",
"."
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/header_footer/old/osf_notebook_class.py#L203-L219 | train |
mozilla/FoxPuppet | foxpuppet/windows/browser/navbar.py | NavBar.is_tracking_shield_displayed | def is_tracking_shield_displayed(self):
"""Tracking Protection shield.
Returns:
bool: True or False if the Tracking Shield is displayed.
"""
with self.selenium.context(self.selenium.CONTEXT_CHROME):
if self.window.firefox_version >= 63: # Bug 1471713, 1476218
el = self.root.find_element(*self._tracking_protection_shield_locator)
return el.get_attribute("active") is not None
el = self.root.find_element(By.ID, "tracking-protection-icon")
return bool(el.get_attribute("state")) | python | def is_tracking_shield_displayed(self):
"""Tracking Protection shield.
Returns:
bool: True or False if the Tracking Shield is displayed.
"""
with self.selenium.context(self.selenium.CONTEXT_CHROME):
if self.window.firefox_version >= 63: # Bug 1471713, 1476218
el = self.root.find_element(*self._tracking_protection_shield_locator)
return el.get_attribute("active") is not None
el = self.root.find_element(By.ID, "tracking-protection-icon")
return bool(el.get_attribute("state")) | [
"def",
"is_tracking_shield_displayed",
"(",
"self",
")",
":",
"with",
"self",
".",
"selenium",
".",
"context",
"(",
"self",
".",
"selenium",
".",
"CONTEXT_CHROME",
")",
":",
"if",
"self",
".",
"window",
".",
"firefox_version",
">=",
"63",
":",
"# Bug 1471713, 1476218",
"el",
"=",
"self",
".",
"root",
".",
"find_element",
"(",
"*",
"self",
".",
"_tracking_protection_shield_locator",
")",
"return",
"el",
".",
"get_attribute",
"(",
"\"active\"",
")",
"is",
"not",
"None",
"el",
"=",
"self",
".",
"root",
".",
"find_element",
"(",
"By",
".",
"ID",
",",
"\"tracking-protection-icon\"",
")",
"return",
"bool",
"(",
"el",
".",
"get_attribute",
"(",
"\"state\"",
")",
")"
] | Tracking Protection shield.
Returns:
bool: True or False if the Tracking Shield is displayed. | [
"Tracking",
"Protection",
"shield",
"."
] | 6575eb4c72fd024c986b254e198c8b4e6f68cddd | https://github.com/mozilla/FoxPuppet/blob/6575eb4c72fd024c986b254e198c8b4e6f68cddd/foxpuppet/windows/browser/navbar.py#L26-L38 | train |
sontek/bulby | bulby/client.py | HueBridgeClient.validate_registration | def validate_registration(self):
'''
Checks if the device + username have already been registered with the
bridge.
'''
url = '/api/%s' % self.username
response = self.make_request('GET', url)
if 'error' in response:
return False
return True | python | def validate_registration(self):
'''
Checks if the device + username have already been registered with the
bridge.
'''
url = '/api/%s' % self.username
response = self.make_request('GET', url)
if 'error' in response:
return False
return True | [
"def",
"validate_registration",
"(",
"self",
")",
":",
"url",
"=",
"'/api/%s'",
"%",
"self",
".",
"username",
"response",
"=",
"self",
".",
"make_request",
"(",
"'GET'",
",",
"url",
")",
"if",
"'error'",
"in",
"response",
":",
"return",
"False",
"return",
"True"
] | Checks if the device + username have already been registered with the
bridge. | [
"Checks",
"if",
"the",
"device",
"+",
"username",
"have",
"already",
"been",
"registered",
"with",
"the",
"bridge",
"."
] | a2e741f843ee8e361b50a6079601108bfbe52526 | https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/client.py#L64-L75 | train |
sontek/bulby | bulby/client.py | HueBridgeClient.connect | def connect(self):
'''
Registers a new device + username with the bridge
'''
# Don't try to register if we already have
if self.validate_registration():
return True
body = {
'devicetype': self.device_type,
'username': self.username,
}
response = self.make_request('POST', '/api', body)
if 'error' in response:
if response['error']['type'] == 101:
msg = 'Please press the link button and try again'
else:
msg = response['error']['description']
raise Exception(msg) | python | def connect(self):
'''
Registers a new device + username with the bridge
'''
# Don't try to register if we already have
if self.validate_registration():
return True
body = {
'devicetype': self.device_type,
'username': self.username,
}
response = self.make_request('POST', '/api', body)
if 'error' in response:
if response['error']['type'] == 101:
msg = 'Please press the link button and try again'
else:
msg = response['error']['description']
raise Exception(msg) | [
"def",
"connect",
"(",
"self",
")",
":",
"# Don't try to register if we already have",
"if",
"self",
".",
"validate_registration",
"(",
")",
":",
"return",
"True",
"body",
"=",
"{",
"'devicetype'",
":",
"self",
".",
"device_type",
",",
"'username'",
":",
"self",
".",
"username",
",",
"}",
"response",
"=",
"self",
".",
"make_request",
"(",
"'POST'",
",",
"'/api'",
",",
"body",
")",
"if",
"'error'",
"in",
"response",
":",
"if",
"response",
"[",
"'error'",
"]",
"[",
"'type'",
"]",
"==",
"101",
":",
"msg",
"=",
"'Please press the link button and try again'",
"else",
":",
"msg",
"=",
"response",
"[",
"'error'",
"]",
"[",
"'description'",
"]",
"raise",
"Exception",
"(",
"msg",
")"
] | Registers a new device + username with the bridge | [
"Registers",
"a",
"new",
"device",
"+",
"username",
"with",
"the",
"bridge"
] | a2e741f843ee8e361b50a6079601108bfbe52526 | https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/client.py#L77-L97 | train |
sontek/bulby | bulby/client.py | HueBridgeClient.get_lights | def get_lights(self):
'''
Lists all available lights on the bridge.
'''
url = '/api/%s/lights' % self.username
response = self.make_request('GET', url)
lights = []
# Did we get a success response back?
# error responses look like:
# [{'error': {'address': '/lights',
# 'description': 'unauthorized user',
# 'type': 1}}]
if 'error' in response:
raise Exception(response['error']['description'])
for id_, data in response.items():
lights.append(Light(
id_,
data['modelid'],
data['name'],
data['state'],
data['swversion'],
data['type'],
data['uniqueid']
))
lights = sorted(lights, key=lambda x: x.light_id)
self._lights = lights
return lights | python | def get_lights(self):
'''
Lists all available lights on the bridge.
'''
url = '/api/%s/lights' % self.username
response = self.make_request('GET', url)
lights = []
# Did we get a success response back?
# error responses look like:
# [{'error': {'address': '/lights',
# 'description': 'unauthorized user',
# 'type': 1}}]
if 'error' in response:
raise Exception(response['error']['description'])
for id_, data in response.items():
lights.append(Light(
id_,
data['modelid'],
data['name'],
data['state'],
data['swversion'],
data['type'],
data['uniqueid']
))
lights = sorted(lights, key=lambda x: x.light_id)
self._lights = lights
return lights | [
"def",
"get_lights",
"(",
"self",
")",
":",
"url",
"=",
"'/api/%s/lights'",
"%",
"self",
".",
"username",
"response",
"=",
"self",
".",
"make_request",
"(",
"'GET'",
",",
"url",
")",
"lights",
"=",
"[",
"]",
"# Did we get a success response back?",
"# error responses look like:",
"# [{'error': {'address': '/lights',",
"# 'description': 'unauthorized user',",
"# 'type': 1}}]",
"if",
"'error'",
"in",
"response",
":",
"raise",
"Exception",
"(",
"response",
"[",
"'error'",
"]",
"[",
"'description'",
"]",
")",
"for",
"id_",
",",
"data",
"in",
"response",
".",
"items",
"(",
")",
":",
"lights",
".",
"append",
"(",
"Light",
"(",
"id_",
",",
"data",
"[",
"'modelid'",
"]",
",",
"data",
"[",
"'name'",
"]",
",",
"data",
"[",
"'state'",
"]",
",",
"data",
"[",
"'swversion'",
"]",
",",
"data",
"[",
"'type'",
"]",
",",
"data",
"[",
"'uniqueid'",
"]",
")",
")",
"lights",
"=",
"sorted",
"(",
"lights",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"light_id",
")",
"self",
".",
"_lights",
"=",
"lights",
"return",
"lights"
] | Lists all available lights on the bridge. | [
"Lists",
"all",
"available",
"lights",
"on",
"the",
"bridge",
"."
] | a2e741f843ee8e361b50a6079601108bfbe52526 | https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/client.py#L99-L128 | train |
sontek/bulby | bulby/client.py | HueBridgeClient.set_color | def set_color(self, light_id, hex_value, brightness=None):
'''
This will set the light color based on a hex value
'''
light = self.get_light(light_id)
xy = get_xy_from_hex(hex_value)
data = {
'xy': [xy.x, xy.y],
}
if brightness is not None:
data['bri'] = brightness
return self.set_state(light.light_id, **data) | python | def set_color(self, light_id, hex_value, brightness=None):
'''
This will set the light color based on a hex value
'''
light = self.get_light(light_id)
xy = get_xy_from_hex(hex_value)
data = {
'xy': [xy.x, xy.y],
}
if brightness is not None:
data['bri'] = brightness
return self.set_state(light.light_id, **data) | [
"def",
"set_color",
"(",
"self",
",",
"light_id",
",",
"hex_value",
",",
"brightness",
"=",
"None",
")",
":",
"light",
"=",
"self",
".",
"get_light",
"(",
"light_id",
")",
"xy",
"=",
"get_xy_from_hex",
"(",
"hex_value",
")",
"data",
"=",
"{",
"'xy'",
":",
"[",
"xy",
".",
"x",
",",
"xy",
".",
"y",
"]",
",",
"}",
"if",
"brightness",
"is",
"not",
"None",
":",
"data",
"[",
"'bri'",
"]",
"=",
"brightness",
"return",
"self",
".",
"set_state",
"(",
"light",
".",
"light_id",
",",
"*",
"*",
"data",
")"
] | This will set the light color based on a hex value | [
"This",
"will",
"set",
"the",
"light",
"color",
"based",
"on",
"a",
"hex",
"value"
] | a2e741f843ee8e361b50a6079601108bfbe52526 | https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/client.py#L170-L184 | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/tools.py | plotfft | def plotfft(s, fmax, doplot=False):
""" This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: array-like
the input signal.
fmax: int
the sampling frequency.
doplot: boolean
a variable to indicate whether the plot is done or not.
Returns
-------
f: array-like
the frequency values (xx axis)
fs: array-like
the amplitude of the frequency values (yy axis)
"""
fs = abs(np.fft.fft(s))
f = linspace(0, fmax / 2, len(s) / 2)
if doplot:
#pl.plot(f[1:int(len(s) / 2)], fs[1:int(len(s) / 2)])
pass
return (f[1:int(len(s) / 2)].copy(), fs[1:int(len(s) / 2)].copy()) | python | def plotfft(s, fmax, doplot=False):
""" This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: array-like
the input signal.
fmax: int
the sampling frequency.
doplot: boolean
a variable to indicate whether the plot is done or not.
Returns
-------
f: array-like
the frequency values (xx axis)
fs: array-like
the amplitude of the frequency values (yy axis)
"""
fs = abs(np.fft.fft(s))
f = linspace(0, fmax / 2, len(s) / 2)
if doplot:
#pl.plot(f[1:int(len(s) / 2)], fs[1:int(len(s) / 2)])
pass
return (f[1:int(len(s) / 2)].copy(), fs[1:int(len(s) / 2)].copy()) | [
"def",
"plotfft",
"(",
"s",
",",
"fmax",
",",
"doplot",
"=",
"False",
")",
":",
"fs",
"=",
"abs",
"(",
"np",
".",
"fft",
".",
"fft",
"(",
"s",
")",
")",
"f",
"=",
"linspace",
"(",
"0",
",",
"fmax",
"/",
"2",
",",
"len",
"(",
"s",
")",
"/",
"2",
")",
"if",
"doplot",
":",
"#pl.plot(f[1:int(len(s) / 2)], fs[1:int(len(s) / 2)])",
"pass",
"return",
"(",
"f",
"[",
"1",
":",
"int",
"(",
"len",
"(",
"s",
")",
"/",
"2",
")",
"]",
".",
"copy",
"(",
")",
",",
"fs",
"[",
"1",
":",
"int",
"(",
"len",
"(",
"s",
")",
"/",
"2",
")",
"]",
".",
"copy",
"(",
")",
")"
] | This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: array-like
the input signal.
fmax: int
the sampling frequency.
doplot: boolean
a variable to indicate whether the plot is done or not.
Returns
-------
f: array-like
the frequency values (xx axis)
fs: array-like
the amplitude of the frequency values (yy axis) | [
"This",
"functions",
"computes",
"the",
"fft",
"of",
"a",
"signal",
"returning",
"the",
"frequency",
"and",
"their",
"magnitude",
"values",
"."
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/tools.py#L8-L34 | train |
sontek/bulby | bulby/ssdp.py | discover | def discover(service, timeout=5, retries=5):
'''
Discovers services on a network using the SSDP Protocol.
'''
group = ('239.255.255.250', 1900)
message = '\r\n'.join([
'M-SEARCH * HTTP/1.1',
'HOST: {0}:{1}',
'MAN: "ssdp:discover"',
'ST: {st}', 'MX: 3', '', ''])
socket.setdefaulttimeout(timeout)
responses = {}
for _ in range(retries):
sock = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM,
socket.IPPROTO_UDP
)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
data = message.format(*group, st=service)
sock.sendto(data.encode('utf-8'), group)
while True:
try:
response = SSDPResponse(sock.recv(1024))
responses[response.location] = response
except socket.timeout:
break
if responses:
break
return responses.values() | python | def discover(service, timeout=5, retries=5):
'''
Discovers services on a network using the SSDP Protocol.
'''
group = ('239.255.255.250', 1900)
message = '\r\n'.join([
'M-SEARCH * HTTP/1.1',
'HOST: {0}:{1}',
'MAN: "ssdp:discover"',
'ST: {st}', 'MX: 3', '', ''])
socket.setdefaulttimeout(timeout)
responses = {}
for _ in range(retries):
sock = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM,
socket.IPPROTO_UDP
)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
data = message.format(*group, st=service)
sock.sendto(data.encode('utf-8'), group)
while True:
try:
response = SSDPResponse(sock.recv(1024))
responses[response.location] = response
except socket.timeout:
break
if responses:
break
return responses.values() | [
"def",
"discover",
"(",
"service",
",",
"timeout",
"=",
"5",
",",
"retries",
"=",
"5",
")",
":",
"group",
"=",
"(",
"'239.255.255.250'",
",",
"1900",
")",
"message",
"=",
"'\\r\\n'",
".",
"join",
"(",
"[",
"'M-SEARCH * HTTP/1.1'",
",",
"'HOST: {0}:{1}'",
",",
"'MAN: \"ssdp:discover\"'",
",",
"'ST: {st}'",
",",
"'MX: 3'",
",",
"''",
",",
"''",
"]",
")",
"socket",
".",
"setdefaulttimeout",
"(",
"timeout",
")",
"responses",
"=",
"{",
"}",
"for",
"_",
"in",
"range",
"(",
"retries",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
",",
"socket",
".",
"IPPROTO_UDP",
")",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_REUSEADDR",
",",
"1",
")",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"IPPROTO_IP",
",",
"socket",
".",
"IP_MULTICAST_TTL",
",",
"2",
")",
"data",
"=",
"message",
".",
"format",
"(",
"*",
"group",
",",
"st",
"=",
"service",
")",
"sock",
".",
"sendto",
"(",
"data",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"group",
")",
"while",
"True",
":",
"try",
":",
"response",
"=",
"SSDPResponse",
"(",
"sock",
".",
"recv",
"(",
"1024",
")",
")",
"responses",
"[",
"response",
".",
"location",
"]",
"=",
"response",
"except",
"socket",
".",
"timeout",
":",
"break",
"if",
"responses",
":",
"break",
"return",
"responses",
".",
"values",
"(",
")"
] | Discovers services on a network using the SSDP Protocol. | [
"Discovers",
"services",
"on",
"a",
"network",
"using",
"the",
"SSDP",
"Protocol",
"."
] | a2e741f843ee8e361b50a6079601108bfbe52526 | https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/ssdp.py#L32-L65 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin._isinstance | def _isinstance(self, model, raise_error=True):
"""Checks if the specified model instance matches the class model.
By default this method will raise a `ValueError` if the model is not of
expected type.
Args:
model (Model) : The instance to be type checked
raise_error (bool) : Flag to specify whether to raise error on
type check failure
Raises:
ValueError: If `model` is not an instance of the respective Model
class
"""
rv = isinstance(model, self.__model__)
if not rv and raise_error:
raise ValueError('%s is not of type %s' % (model, self.__model__))
return rv | python | def _isinstance(self, model, raise_error=True):
"""Checks if the specified model instance matches the class model.
By default this method will raise a `ValueError` if the model is not of
expected type.
Args:
model (Model) : The instance to be type checked
raise_error (bool) : Flag to specify whether to raise error on
type check failure
Raises:
ValueError: If `model` is not an instance of the respective Model
class
"""
rv = isinstance(model, self.__model__)
if not rv and raise_error:
raise ValueError('%s is not of type %s' % (model, self.__model__))
return rv | [
"def",
"_isinstance",
"(",
"self",
",",
"model",
",",
"raise_error",
"=",
"True",
")",
":",
"rv",
"=",
"isinstance",
"(",
"model",
",",
"self",
".",
"__model__",
")",
"if",
"not",
"rv",
"and",
"raise_error",
":",
"raise",
"ValueError",
"(",
"'%s is not of type %s'",
"%",
"(",
"model",
",",
"self",
".",
"__model__",
")",
")",
"return",
"rv"
] | Checks if the specified model instance matches the class model.
By default this method will raise a `ValueError` if the model is not of
expected type.
Args:
model (Model) : The instance to be type checked
raise_error (bool) : Flag to specify whether to raise error on
type check failure
Raises:
ValueError: If `model` is not an instance of the respective Model
class | [
"Checks",
"if",
"the",
"specified",
"model",
"instance",
"matches",
"the",
"class",
"model",
".",
"By",
"default",
"this",
"method",
"will",
"raise",
"a",
"ValueError",
"if",
"the",
"model",
"is",
"not",
"of",
"expected",
"type",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L108-L128 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin._preprocess_params | def _preprocess_params(cls, kwargs):
"""Returns a preprocessed dictionary of parameters.
Use this to filter the kwargs passed to `new`, `create`,
`build` methods.
Args:
**kwargs: a dictionary of parameters
"""
# kwargs.pop('csrf_token', None)
for attr, val in kwargs.items():
if cls.is_the_primary_key(attr) and cls._prevent_primary_key_initialization_:
del kwargs[attr]
continue
if val == "":
# Making an assumption that there is no good usecase
# for setting an empty string. This will help prevent
# cases where empty string is sent because of client
# not clearing form fields to null
kwargs[attr] = None
continue
if attr in class_mapper(cls).relationships and attr not in cls._no_overwrite_:
rel = class_mapper(cls).relationships[attr]
if rel.uselist:
if isinstance(val, list):
if all(isinstance(v, dict) for v in val):
rel_cls = cls.mapped_rel_class(attr)
kwargs[attr] = rel_cls.update_or_new_all(
list_of_kwargs=val, keys=[rel_cls.primary_key_name()])
elif isinstance(val, dict):
rel_cls = cls.mapped_rel_class(attr)
mapping_col = rel.collection_class().keyfunc.name
list_of_kwargs = [merge(v, {mapping_col: k}) for k, v in val.items()]
kwargs[attr] = {getattr(obj, mapping_col): obj for obj in rel_cls.update_or_new_all(
list_of_kwargs=list_of_kwargs, keys=[rel_cls.primary_key_name()])}
elif isinstance(val, dict):
rel_cls = cls.mapped_rel_class(attr)
kwargs[attr] = rel_cls.update_or_new(
**merge(val, {'keys': [rel_cls.primary_key_name()]}))
return kwargs | python | def _preprocess_params(cls, kwargs):
"""Returns a preprocessed dictionary of parameters.
Use this to filter the kwargs passed to `new`, `create`,
`build` methods.
Args:
**kwargs: a dictionary of parameters
"""
# kwargs.pop('csrf_token', None)
for attr, val in kwargs.items():
if cls.is_the_primary_key(attr) and cls._prevent_primary_key_initialization_:
del kwargs[attr]
continue
if val == "":
# Making an assumption that there is no good usecase
# for setting an empty string. This will help prevent
# cases where empty string is sent because of client
# not clearing form fields to null
kwargs[attr] = None
continue
if attr in class_mapper(cls).relationships and attr not in cls._no_overwrite_:
rel = class_mapper(cls).relationships[attr]
if rel.uselist:
if isinstance(val, list):
if all(isinstance(v, dict) for v in val):
rel_cls = cls.mapped_rel_class(attr)
kwargs[attr] = rel_cls.update_or_new_all(
list_of_kwargs=val, keys=[rel_cls.primary_key_name()])
elif isinstance(val, dict):
rel_cls = cls.mapped_rel_class(attr)
mapping_col = rel.collection_class().keyfunc.name
list_of_kwargs = [merge(v, {mapping_col: k}) for k, v in val.items()]
kwargs[attr] = {getattr(obj, mapping_col): obj for obj in rel_cls.update_or_new_all(
list_of_kwargs=list_of_kwargs, keys=[rel_cls.primary_key_name()])}
elif isinstance(val, dict):
rel_cls = cls.mapped_rel_class(attr)
kwargs[attr] = rel_cls.update_or_new(
**merge(val, {'keys': [rel_cls.primary_key_name()]}))
return kwargs | [
"def",
"_preprocess_params",
"(",
"cls",
",",
"kwargs",
")",
":",
"# kwargs.pop('csrf_token', None)",
"for",
"attr",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"cls",
".",
"is_the_primary_key",
"(",
"attr",
")",
"and",
"cls",
".",
"_prevent_primary_key_initialization_",
":",
"del",
"kwargs",
"[",
"attr",
"]",
"continue",
"if",
"val",
"==",
"\"\"",
":",
"# Making an assumption that there is no good usecase",
"# for setting an empty string. This will help prevent",
"# cases where empty string is sent because of client",
"# not clearing form fields to null",
"kwargs",
"[",
"attr",
"]",
"=",
"None",
"continue",
"if",
"attr",
"in",
"class_mapper",
"(",
"cls",
")",
".",
"relationships",
"and",
"attr",
"not",
"in",
"cls",
".",
"_no_overwrite_",
":",
"rel",
"=",
"class_mapper",
"(",
"cls",
")",
".",
"relationships",
"[",
"attr",
"]",
"if",
"rel",
".",
"uselist",
":",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"if",
"all",
"(",
"isinstance",
"(",
"v",
",",
"dict",
")",
"for",
"v",
"in",
"val",
")",
":",
"rel_cls",
"=",
"cls",
".",
"mapped_rel_class",
"(",
"attr",
")",
"kwargs",
"[",
"attr",
"]",
"=",
"rel_cls",
".",
"update_or_new_all",
"(",
"list_of_kwargs",
"=",
"val",
",",
"keys",
"=",
"[",
"rel_cls",
".",
"primary_key_name",
"(",
")",
"]",
")",
"elif",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"rel_cls",
"=",
"cls",
".",
"mapped_rel_class",
"(",
"attr",
")",
"mapping_col",
"=",
"rel",
".",
"collection_class",
"(",
")",
".",
"keyfunc",
".",
"name",
"list_of_kwargs",
"=",
"[",
"merge",
"(",
"v",
",",
"{",
"mapping_col",
":",
"k",
"}",
")",
"for",
"k",
",",
"v",
"in",
"val",
".",
"items",
"(",
")",
"]",
"kwargs",
"[",
"attr",
"]",
"=",
"{",
"getattr",
"(",
"obj",
",",
"mapping_col",
")",
":",
"obj",
"for",
"obj",
"in",
"rel_cls",
".",
"update_or_new_all",
"(",
"list_of_kwargs",
"=",
"list_of_kwargs",
",",
"keys",
"=",
"[",
"rel_cls",
".",
"primary_key_name",
"(",
")",
"]",
")",
"}",
"elif",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"rel_cls",
"=",
"cls",
".",
"mapped_rel_class",
"(",
"attr",
")",
"kwargs",
"[",
"attr",
"]",
"=",
"rel_cls",
".",
"update_or_new",
"(",
"*",
"*",
"merge",
"(",
"val",
",",
"{",
"'keys'",
":",
"[",
"rel_cls",
".",
"primary_key_name",
"(",
")",
"]",
"}",
")",
")",
"return",
"kwargs"
] | Returns a preprocessed dictionary of parameters.
Use this to filter the kwargs passed to `new`, `create`,
`build` methods.
Args:
**kwargs: a dictionary of parameters | [
"Returns",
"a",
"preprocessed",
"dictionary",
"of",
"parameters",
".",
"Use",
"this",
"to",
"filter",
"the",
"kwargs",
"passed",
"to",
"new",
"create",
"build",
"methods",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L135-L174 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.update | def update(self, **kwargs):
"""Updates an instance.
Args:
**kwargs : Arbitrary keyword arguments. Column names are
keywords and their new values are the values.
Examples:
>>> customer.update(email="[email protected]", name="new")
"""
kwargs = self._preprocess_params(kwargs)
kwargs = self.preprocess_kwargs_before_update(kwargs)
for key, value in kwargs.iteritems():
cls = type(self)
if not hasattr(cls, key) or isinstance(getattr(cls, key), property):
continue
if key not in self._no_overwrite_:
setattr(self, key, value)
if isinstance(getattr(self, key), OrderingList):
getattr(self, key).reorder()
elif isinstance(getattr(cls, key), AssociationProxyInstance):
target_name = getattr(cls, key).target_collection
target_rel = getattr(self, target_name)
if isinstance(target_rel, OrderingList):
target_rel.reorder()
try:
self.session.commit()
return self
except Exception as e:
self.session.rollback()
raise e | python | def update(self, **kwargs):
"""Updates an instance.
Args:
**kwargs : Arbitrary keyword arguments. Column names are
keywords and their new values are the values.
Examples:
>>> customer.update(email="[email protected]", name="new")
"""
kwargs = self._preprocess_params(kwargs)
kwargs = self.preprocess_kwargs_before_update(kwargs)
for key, value in kwargs.iteritems():
cls = type(self)
if not hasattr(cls, key) or isinstance(getattr(cls, key), property):
continue
if key not in self._no_overwrite_:
setattr(self, key, value)
if isinstance(getattr(self, key), OrderingList):
getattr(self, key).reorder()
elif isinstance(getattr(cls, key), AssociationProxyInstance):
target_name = getattr(cls, key).target_collection
target_rel = getattr(self, target_name)
if isinstance(target_rel, OrderingList):
target_rel.reorder()
try:
self.session.commit()
return self
except Exception as e:
self.session.rollback()
raise e | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_preprocess_params",
"(",
"kwargs",
")",
"kwargs",
"=",
"self",
".",
"preprocess_kwargs_before_update",
"(",
"kwargs",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"cls",
"=",
"type",
"(",
"self",
")",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"key",
")",
"or",
"isinstance",
"(",
"getattr",
"(",
"cls",
",",
"key",
")",
",",
"property",
")",
":",
"continue",
"if",
"key",
"not",
"in",
"self",
".",
"_no_overwrite_",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"value",
")",
"if",
"isinstance",
"(",
"getattr",
"(",
"self",
",",
"key",
")",
",",
"OrderingList",
")",
":",
"getattr",
"(",
"self",
",",
"key",
")",
".",
"reorder",
"(",
")",
"elif",
"isinstance",
"(",
"getattr",
"(",
"cls",
",",
"key",
")",
",",
"AssociationProxyInstance",
")",
":",
"target_name",
"=",
"getattr",
"(",
"cls",
",",
"key",
")",
".",
"target_collection",
"target_rel",
"=",
"getattr",
"(",
"self",
",",
"target_name",
")",
"if",
"isinstance",
"(",
"target_rel",
",",
"OrderingList",
")",
":",
"target_rel",
".",
"reorder",
"(",
")",
"try",
":",
"self",
".",
"session",
".",
"commit",
"(",
")",
"return",
"self",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"e"
] | Updates an instance.
Args:
**kwargs : Arbitrary keyword arguments. Column names are
keywords and their new values are the values.
Examples:
>>> customer.update(email="[email protected]", name="new") | [
"Updates",
"an",
"instance",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L203-L235 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.filter_by | def filter_by(cls, **kwargs):
"""Same as SQLAlchemy's filter_by. Additionally this accepts
two special keyword arguments `limit` and `reverse` for limiting
the results and reversing the order respectively.
Args:
**kwargs: filter parameters
Examples:
>>> user = User.filter_by(email="[email protected]")
>>> shipments = Shipment.filter_by(country="India", limit=3, reverse=True)
"""
limit = kwargs.pop('limit', None)
reverse = kwargs.pop('reverse', False)
q = cls.query.filter_by(**kwargs)
if reverse:
q = q.order_by(cls.id.desc())
if limit:
q = q.limit(limit)
return q | python | def filter_by(cls, **kwargs):
"""Same as SQLAlchemy's filter_by. Additionally this accepts
two special keyword arguments `limit` and `reverse` for limiting
the results and reversing the order respectively.
Args:
**kwargs: filter parameters
Examples:
>>> user = User.filter_by(email="[email protected]")
>>> shipments = Shipment.filter_by(country="India", limit=3, reverse=True)
"""
limit = kwargs.pop('limit', None)
reverse = kwargs.pop('reverse', False)
q = cls.query.filter_by(**kwargs)
if reverse:
q = q.order_by(cls.id.desc())
if limit:
q = q.limit(limit)
return q | [
"def",
"filter_by",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"limit",
"=",
"kwargs",
".",
"pop",
"(",
"'limit'",
",",
"None",
")",
"reverse",
"=",
"kwargs",
".",
"pop",
"(",
"'reverse'",
",",
"False",
")",
"q",
"=",
"cls",
".",
"query",
".",
"filter_by",
"(",
"*",
"*",
"kwargs",
")",
"if",
"reverse",
":",
"q",
"=",
"q",
".",
"order_by",
"(",
"cls",
".",
"id",
".",
"desc",
"(",
")",
")",
"if",
"limit",
":",
"q",
"=",
"q",
".",
"limit",
"(",
"limit",
")",
"return",
"q"
] | Same as SQLAlchemy's filter_by. Additionally this accepts
two special keyword arguments `limit` and `reverse` for limiting
the results and reversing the order respectively.
Args:
**kwargs: filter parameters
Examples:
>>> user = User.filter_by(email="[email protected]")
>>> shipments = Shipment.filter_by(country="India", limit=3, reverse=True) | [
"Same",
"as",
"SQLAlchemy",
"s",
"filter_by",
".",
"Additionally",
"this",
"accepts",
"two",
"special",
"keyword",
"arguments",
"limit",
"and",
"reverse",
"for",
"limiting",
"the",
"results",
"and",
"reversing",
"the",
"order",
"respectively",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L238-L261 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.count | def count(cls, *criterion, **kwargs):
"""Returns a count of the instances meeting the specified
filter criterion and kwargs.
Examples:
>>> User.count()
500
>>> User.count(country="India")
300
>>> User.count(User.age > 50, country="India")
39
"""
if criterion or kwargs:
return cls.filter(
*criterion,
**kwargs).count()
else:
return cls.query.count() | python | def count(cls, *criterion, **kwargs):
"""Returns a count of the instances meeting the specified
filter criterion and kwargs.
Examples:
>>> User.count()
500
>>> User.count(country="India")
300
>>> User.count(User.age > 50, country="India")
39
"""
if criterion or kwargs:
return cls.filter(
*criterion,
**kwargs).count()
else:
return cls.query.count() | [
"def",
"count",
"(",
"cls",
",",
"*",
"criterion",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"criterion",
"or",
"kwargs",
":",
"return",
"cls",
".",
"filter",
"(",
"*",
"criterion",
",",
"*",
"*",
"kwargs",
")",
".",
"count",
"(",
")",
"else",
":",
"return",
"cls",
".",
"query",
".",
"count",
"(",
")"
] | Returns a count of the instances meeting the specified
filter criterion and kwargs.
Examples:
>>> User.count()
500
>>> User.count(country="India")
300
>>> User.count(User.age > 50, country="India")
39 | [
"Returns",
"a",
"count",
"of",
"the",
"instances",
"meeting",
"the",
"specified",
"filter",
"criterion",
"and",
"kwargs",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L290-L311 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.new | def new(cls, **kwargs):
"""Returns a new, unsaved instance of the model class.
"""
kwargs = cls.preprocess_kwargs_before_new(kwargs)
if cls.__mapper__.polymorphic_on is not None:
discriminator_key = cls.__mapper__.polymorphic_on.name
discriminator_val = kwargs.get(discriminator_key)
if discriminator_val is not None and discriminator_val in cls.__mapper__.polymorphic_map:
actual_cls = cls.__mapper__.polymorphic_map[discriminator_val].class_
return actual_cls(
**subdict(
actual_cls._preprocess_params(kwargs),
actual_cls.all_settable_keys())
)
return cls(**subdict(cls._preprocess_params(kwargs), cls.all_settable_keys())) | python | def new(cls, **kwargs):
"""Returns a new, unsaved instance of the model class.
"""
kwargs = cls.preprocess_kwargs_before_new(kwargs)
if cls.__mapper__.polymorphic_on is not None:
discriminator_key = cls.__mapper__.polymorphic_on.name
discriminator_val = kwargs.get(discriminator_key)
if discriminator_val is not None and discriminator_val in cls.__mapper__.polymorphic_map:
actual_cls = cls.__mapper__.polymorphic_map[discriminator_val].class_
return actual_cls(
**subdict(
actual_cls._preprocess_params(kwargs),
actual_cls.all_settable_keys())
)
return cls(**subdict(cls._preprocess_params(kwargs), cls.all_settable_keys())) | [
"def",
"new",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"cls",
".",
"preprocess_kwargs_before_new",
"(",
"kwargs",
")",
"if",
"cls",
".",
"__mapper__",
".",
"polymorphic_on",
"is",
"not",
"None",
":",
"discriminator_key",
"=",
"cls",
".",
"__mapper__",
".",
"polymorphic_on",
".",
"name",
"discriminator_val",
"=",
"kwargs",
".",
"get",
"(",
"discriminator_key",
")",
"if",
"discriminator_val",
"is",
"not",
"None",
"and",
"discriminator_val",
"in",
"cls",
".",
"__mapper__",
".",
"polymorphic_map",
":",
"actual_cls",
"=",
"cls",
".",
"__mapper__",
".",
"polymorphic_map",
"[",
"discriminator_val",
"]",
".",
"class_",
"return",
"actual_cls",
"(",
"*",
"*",
"subdict",
"(",
"actual_cls",
".",
"_preprocess_params",
"(",
"kwargs",
")",
",",
"actual_cls",
".",
"all_settable_keys",
"(",
")",
")",
")",
"return",
"cls",
"(",
"*",
"*",
"subdict",
"(",
"cls",
".",
"_preprocess_params",
"(",
"kwargs",
")",
",",
"cls",
".",
"all_settable_keys",
"(",
")",
")",
")"
] | Returns a new, unsaved instance of the model class. | [
"Returns",
"a",
"new",
"unsaved",
"instance",
"of",
"the",
"model",
"class",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L371-L386 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.add | def add(cls, model, commit=True):
"""Adds a model instance to session and commits the
transaction.
Args:
model: The instance to add.
Examples:
>>> customer = Customer.new(name="hari", email="[email protected]")
>>> Customer.add(customer)
[email protected]
"""
if not isinstance(model, cls):
raise ValueError('%s is not of type %s' % (model, cls))
cls.session.add(model)
try:
if commit:
cls.session.commit()
return model
except:
cls.session.rollback()
raise | python | def add(cls, model, commit=True):
"""Adds a model instance to session and commits the
transaction.
Args:
model: The instance to add.
Examples:
>>> customer = Customer.new(name="hari", email="[email protected]")
>>> Customer.add(customer)
[email protected]
"""
if not isinstance(model, cls):
raise ValueError('%s is not of type %s' % (model, cls))
cls.session.add(model)
try:
if commit:
cls.session.commit()
return model
except:
cls.session.rollback()
raise | [
"def",
"add",
"(",
"cls",
",",
"model",
",",
"commit",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"cls",
")",
":",
"raise",
"ValueError",
"(",
"'%s is not of type %s'",
"%",
"(",
"model",
",",
"cls",
")",
")",
"cls",
".",
"session",
".",
"add",
"(",
"model",
")",
"try",
":",
"if",
"commit",
":",
"cls",
".",
"session",
".",
"commit",
"(",
")",
"return",
"model",
"except",
":",
"cls",
".",
"session",
".",
"rollback",
"(",
")",
"raise"
] | Adds a model instance to session and commits the
transaction.
Args:
model: The instance to add.
Examples:
>>> customer = Customer.new(name="hari", email="[email protected]")
>>> Customer.add(customer)
[email protected] | [
"Adds",
"a",
"model",
"instance",
"to",
"session",
"and",
"commits",
"the",
"transaction",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L389-L413 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.add_all | def add_all(cls, models, commit=True, check_type=False):
"""Batch method for adding a list of model instances
to the db in one get_or_404.
Args:
models (list): A list of the instances to add.
commit (bool, optional): Defaults to True. If False, the
transaction won't get committed.
check_type (bool, optional) : If True, each instance
is type checked and exception is thrown if it is
not an instance of the model. By default, False.
Returns:
list: A list of `Model` instances
"""
if check_type:
for model in models:
if not isinstance(model, cls):
raise ValueError('%s is not of type %s' (model, cls))
if None in models:
cls.session.add_all([m for m in models if m is not None])
else:
cls.session.add_all(models)
try:
if commit:
cls.session.commit()
return models
except:
cls.session.rollback()
raise | python | def add_all(cls, models, commit=True, check_type=False):
"""Batch method for adding a list of model instances
to the db in one get_or_404.
Args:
models (list): A list of the instances to add.
commit (bool, optional): Defaults to True. If False, the
transaction won't get committed.
check_type (bool, optional) : If True, each instance
is type checked and exception is thrown if it is
not an instance of the model. By default, False.
Returns:
list: A list of `Model` instances
"""
if check_type:
for model in models:
if not isinstance(model, cls):
raise ValueError('%s is not of type %s' (model, cls))
if None in models:
cls.session.add_all([m for m in models if m is not None])
else:
cls.session.add_all(models)
try:
if commit:
cls.session.commit()
return models
except:
cls.session.rollback()
raise | [
"def",
"add_all",
"(",
"cls",
",",
"models",
",",
"commit",
"=",
"True",
",",
"check_type",
"=",
"False",
")",
":",
"if",
"check_type",
":",
"for",
"model",
"in",
"models",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"cls",
")",
":",
"raise",
"ValueError",
"(",
"'%s is not of type %s'",
"(",
"model",
",",
"cls",
")",
")",
"if",
"None",
"in",
"models",
":",
"cls",
".",
"session",
".",
"add_all",
"(",
"[",
"m",
"for",
"m",
"in",
"models",
"if",
"m",
"is",
"not",
"None",
"]",
")",
"else",
":",
"cls",
".",
"session",
".",
"add_all",
"(",
"models",
")",
"try",
":",
"if",
"commit",
":",
"cls",
".",
"session",
".",
"commit",
"(",
")",
"return",
"models",
"except",
":",
"cls",
".",
"session",
".",
"rollback",
"(",
")",
"raise"
] | Batch method for adding a list of model instances
to the db in one get_or_404.
Args:
models (list): A list of the instances to add.
commit (bool, optional): Defaults to True. If False, the
transaction won't get committed.
check_type (bool, optional) : If True, each instance
is type checked and exception is thrown if it is
not an instance of the model. By default, False.
Returns:
list: A list of `Model` instances | [
"Batch",
"method",
"for",
"adding",
"a",
"list",
"of",
"model",
"instances",
"to",
"the",
"db",
"in",
"one",
"get_or_404",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L416-L447 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.get | def get(cls, keyval, key='id', user_id=None):
"""Fetches a single instance which has value `keyval`
for the attribute `key`.
Args:
keyval: The value of the attribute.
key (str, optional): The attribute to search by. By default,
it is 'id'.
Returns:
A model instance if found. Else None.
Examples:
>>> User.get(35)
[email protected]
>>> User.get('[email protected]', key='email')
[email protected]
"""
if keyval is None:
return None
if (key in cls.__table__.columns
and cls.__table__.columns[key].primary_key):
# if user_id and hasattr(cls, 'user_id'):
# return cls.query.filter_by(id=keyval, user_id=user_id).first()
return cls.query.get(keyval)
else:
result = cls.query.filter(
getattr(cls, key) == keyval)
# if user_id and hasattr(cls, 'user_id'):
# result = result.filter(cls.user_id == user_id)
return result.first() | python | def get(cls, keyval, key='id', user_id=None):
"""Fetches a single instance which has value `keyval`
for the attribute `key`.
Args:
keyval: The value of the attribute.
key (str, optional): The attribute to search by. By default,
it is 'id'.
Returns:
A model instance if found. Else None.
Examples:
>>> User.get(35)
[email protected]
>>> User.get('[email protected]', key='email')
[email protected]
"""
if keyval is None:
return None
if (key in cls.__table__.columns
and cls.__table__.columns[key].primary_key):
# if user_id and hasattr(cls, 'user_id'):
# return cls.query.filter_by(id=keyval, user_id=user_id).first()
return cls.query.get(keyval)
else:
result = cls.query.filter(
getattr(cls, key) == keyval)
# if user_id and hasattr(cls, 'user_id'):
# result = result.filter(cls.user_id == user_id)
return result.first() | [
"def",
"get",
"(",
"cls",
",",
"keyval",
",",
"key",
"=",
"'id'",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"keyval",
"is",
"None",
":",
"return",
"None",
"if",
"(",
"key",
"in",
"cls",
".",
"__table__",
".",
"columns",
"and",
"cls",
".",
"__table__",
".",
"columns",
"[",
"key",
"]",
".",
"primary_key",
")",
":",
"# if user_id and hasattr(cls, 'user_id'):",
"# return cls.query.filter_by(id=keyval, user_id=user_id).first()",
"return",
"cls",
".",
"query",
".",
"get",
"(",
"keyval",
")",
"else",
":",
"result",
"=",
"cls",
".",
"query",
".",
"filter",
"(",
"getattr",
"(",
"cls",
",",
"key",
")",
"==",
"keyval",
")",
"# if user_id and hasattr(cls, 'user_id'):",
"# result = result.filter(cls.user_id == user_id)",
"return",
"result",
".",
"first",
"(",
")"
] | Fetches a single instance which has value `keyval`
for the attribute `key`.
Args:
keyval: The value of the attribute.
key (str, optional): The attribute to search by. By default,
it is 'id'.
Returns:
A model instance if found. Else None.
Examples:
>>> User.get(35)
[email protected]
>>> User.get('[email protected]', key='email')
[email protected] | [
"Fetches",
"a",
"single",
"instance",
"which",
"has",
"value",
"keyval",
"for",
"the",
"attribute",
"key",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L458-L494 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.get_all | def get_all(cls, keyvals, key='id', user_id=None):
"""Works like a map function from keyvals to instances.
Args:
keyvals(list): The list of values of the attribute.
key (str, optional): The attribute to search by. By default, it is
'id'.
Returns:
list: A list of model instances, in the same order as the list of
keyvals.
Examples:
>>> User.get_all([2,5,7, 8000, 11])
[email protected], [email protected], [email protected], None, [email protected]
>>> User.get_all(['[email protected]', '[email protected]'], key='email')
[email protected], [email protected]
"""
if len(keyvals) == 0:
return []
original_keyvals = keyvals
keyvals_set = list(set(keyvals))
resultset = cls.query.filter(getattr(cls, key).in_(keyvals_set))
# This is ridiculous. user_id check cannot be here. A hangover
# from the time this lib was inside our app codebase
# if user_id and hasattr(cls, 'user_id'):
# resultset = resultset.filter(cls.user_id == user_id)
# We need the results in the same order as the input keyvals
# So order by field in SQL
key_result_mapping = {getattr(result, key): result for result in resultset.all()}
return [key_result_mapping.get(kv) for kv in original_keyvals] | python | def get_all(cls, keyvals, key='id', user_id=None):
"""Works like a map function from keyvals to instances.
Args:
keyvals(list): The list of values of the attribute.
key (str, optional): The attribute to search by. By default, it is
'id'.
Returns:
list: A list of model instances, in the same order as the list of
keyvals.
Examples:
>>> User.get_all([2,5,7, 8000, 11])
[email protected], [email protected], [email protected], None, [email protected]
>>> User.get_all(['[email protected]', '[email protected]'], key='email')
[email protected], [email protected]
"""
if len(keyvals) == 0:
return []
original_keyvals = keyvals
keyvals_set = list(set(keyvals))
resultset = cls.query.filter(getattr(cls, key).in_(keyvals_set))
# This is ridiculous. user_id check cannot be here. A hangover
# from the time this lib was inside our app codebase
# if user_id and hasattr(cls, 'user_id'):
# resultset = resultset.filter(cls.user_id == user_id)
# We need the results in the same order as the input keyvals
# So order by field in SQL
key_result_mapping = {getattr(result, key): result for result in resultset.all()}
return [key_result_mapping.get(kv) for kv in original_keyvals] | [
"def",
"get_all",
"(",
"cls",
",",
"keyvals",
",",
"key",
"=",
"'id'",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"len",
"(",
"keyvals",
")",
"==",
"0",
":",
"return",
"[",
"]",
"original_keyvals",
"=",
"keyvals",
"keyvals_set",
"=",
"list",
"(",
"set",
"(",
"keyvals",
")",
")",
"resultset",
"=",
"cls",
".",
"query",
".",
"filter",
"(",
"getattr",
"(",
"cls",
",",
"key",
")",
".",
"in_",
"(",
"keyvals_set",
")",
")",
"# This is ridiculous. user_id check cannot be here. A hangover",
"# from the time this lib was inside our app codebase",
"# if user_id and hasattr(cls, 'user_id'):",
"# resultset = resultset.filter(cls.user_id == user_id)",
"# We need the results in the same order as the input keyvals",
"# So order by field in SQL",
"key_result_mapping",
"=",
"{",
"getattr",
"(",
"result",
",",
"key",
")",
":",
"result",
"for",
"result",
"in",
"resultset",
".",
"all",
"(",
")",
"}",
"return",
"[",
"key_result_mapping",
".",
"get",
"(",
"kv",
")",
"for",
"kv",
"in",
"original_keyvals",
"]"
] | Works like a map function from keyvals to instances.
Args:
keyvals(list): The list of values of the attribute.
key (str, optional): The attribute to search by. By default, it is
'id'.
Returns:
list: A list of model instances, in the same order as the list of
keyvals.
Examples:
>>> User.get_all([2,5,7, 8000, 11])
[email protected], [email protected], [email protected], None, [email protected]
>>> User.get_all(['[email protected]', '[email protected]'], key='email')
[email protected], [email protected] | [
"Works",
"like",
"a",
"map",
"function",
"from",
"keyvals",
"to",
"instances",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L497-L537 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.create | def create(cls, **kwargs):
"""Initializes a new instance, adds it to the db and commits
the transaction.
Args:
**kwargs: The keyword arguments for the init constructor.
Examples:
>>> user = User.create(name="Vicky", email="[email protected]")
>>> user.id
35
"""
try:
return cls.add(cls.new(**kwargs))
except:
cls.session.rollback()
raise | python | def create(cls, **kwargs):
"""Initializes a new instance, adds it to the db and commits
the transaction.
Args:
**kwargs: The keyword arguments for the init constructor.
Examples:
>>> user = User.create(name="Vicky", email="[email protected]")
>>> user.id
35
"""
try:
return cls.add(cls.new(**kwargs))
except:
cls.session.rollback()
raise | [
"def",
"create",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"cls",
".",
"add",
"(",
"cls",
".",
"new",
"(",
"*",
"*",
"kwargs",
")",
")",
"except",
":",
"cls",
".",
"session",
".",
"rollback",
"(",
")",
"raise"
] | Initializes a new instance, adds it to the db and commits
the transaction.
Args:
**kwargs: The keyword arguments for the init constructor.
Examples:
>>> user = User.create(name="Vicky", email="[email protected]")
>>> user.id
35 | [
"Initializes",
"a",
"new",
"instance",
"adds",
"it",
"to",
"the",
"db",
"and",
"commits",
"the",
"transaction",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L559-L577 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.find_or_create | def find_or_create(cls, **kwargs):
"""Checks if an instance already exists by filtering with the
kwargs. If yes, returns that instance. If not, creates a new
instance with kwargs and returns it
Args:
**kwargs: The keyword arguments which are used for filtering
and initialization.
keys(list, optional): A special keyword argument.
If passed, only the set of keys mentioned here will be used
for filtering. Useful when we want to 'find' based on a subset
of the keys and create with all the keys
Examples:
>>> customer = Customer.find_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer.id
45
>>> customer1 = Customer.find_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer1==customer
True
>>> customer2 = Customer.find_or_create(
... name="vicky", email="[email protected]", country="Russia")
>>> customer2==customer
False
>>> customer3 = Customer.find_or_create(
... name="vicky", email="[email protected]", country="Russia",
... keys=['name', 'email'])
>>> customer3==customer
True
"""
keys = kwargs.pop('keys') if 'keys' in kwargs else []
return cls.first(**subdict(kwargs, keys)) or cls.create(**kwargs) | python | def find_or_create(cls, **kwargs):
"""Checks if an instance already exists by filtering with the
kwargs. If yes, returns that instance. If not, creates a new
instance with kwargs and returns it
Args:
**kwargs: The keyword arguments which are used for filtering
and initialization.
keys(list, optional): A special keyword argument.
If passed, only the set of keys mentioned here will be used
for filtering. Useful when we want to 'find' based on a subset
of the keys and create with all the keys
Examples:
>>> customer = Customer.find_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer.id
45
>>> customer1 = Customer.find_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer1==customer
True
>>> customer2 = Customer.find_or_create(
... name="vicky", email="[email protected]", country="Russia")
>>> customer2==customer
False
>>> customer3 = Customer.find_or_create(
... name="vicky", email="[email protected]", country="Russia",
... keys=['name', 'email'])
>>> customer3==customer
True
"""
keys = kwargs.pop('keys') if 'keys' in kwargs else []
return cls.first(**subdict(kwargs, keys)) or cls.create(**kwargs) | [
"def",
"find_or_create",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"keys",
"=",
"kwargs",
".",
"pop",
"(",
"'keys'",
")",
"if",
"'keys'",
"in",
"kwargs",
"else",
"[",
"]",
"return",
"cls",
".",
"first",
"(",
"*",
"*",
"subdict",
"(",
"kwargs",
",",
"keys",
")",
")",
"or",
"cls",
".",
"create",
"(",
"*",
"*",
"kwargs",
")"
] | Checks if an instance already exists by filtering with the
kwargs. If yes, returns that instance. If not, creates a new
instance with kwargs and returns it
Args:
**kwargs: The keyword arguments which are used for filtering
and initialization.
keys(list, optional): A special keyword argument.
If passed, only the set of keys mentioned here will be used
for filtering. Useful when we want to 'find' based on a subset
of the keys and create with all the keys
Examples:
>>> customer = Customer.find_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer.id
45
>>> customer1 = Customer.find_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer1==customer
True
>>> customer2 = Customer.find_or_create(
... name="vicky", email="[email protected]", country="Russia")
>>> customer2==customer
False
>>> customer3 = Customer.find_or_create(
... name="vicky", email="[email protected]", country="Russia",
... keys=['name', 'email'])
>>> customer3==customer
True | [
"Checks",
"if",
"an",
"instance",
"already",
"exists",
"by",
"filtering",
"with",
"the",
"kwargs",
".",
"If",
"yes",
"returns",
"that",
"instance",
".",
"If",
"not",
"creates",
"a",
"new",
"instance",
"with",
"kwargs",
"and",
"returns",
"it"
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L580-L615 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.update_or_create | def update_or_create(cls, **kwargs):
"""Checks if an instance already exists by filtering with the
kwargs. If yes, updates the instance with new kwargs and
returns that instance. If not, creates a new
instance with kwargs and returns it.
Args:
**kwargs: The keyword arguments which are used for filtering
and initialization.
keys (list, optional): A special keyword argument. If passed,
only the set of keys mentioned here will be used for filtering.
Useful when we want to 'filter' based on a subset of the keys
and create with all the keys.
Examples:
>>> customer = Customer.update_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer.id
45
>>> customer1 = Customer.update_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer1==customer
True
>>> customer2 = Customer.update_or_create(
... name="vicky", email="[email protected]", country="Russia")
>>> customer2==customer
False
>>> customer3 = Customer.update_or_create(
... name="vicky", email="[email protected]", country="Russia",
... keys=['name', 'email'])
>>> customer3==customer
True
"""
keys = kwargs.pop('keys') if 'keys' in kwargs else []
filter_kwargs = subdict(kwargs, keys)
if filter_kwargs == {}:
obj = None
else:
obj = cls.first(**filter_kwargs)
if obj is not None:
for key, value in kwargs.iteritems():
if (key not in keys and
key not in cls._no_overwrite_):
setattr(obj, key, value)
try:
cls.session.commit()
except:
cls.session.rollback()
raise
else:
obj = cls.create(**kwargs)
return obj | python | def update_or_create(cls, **kwargs):
"""Checks if an instance already exists by filtering with the
kwargs. If yes, updates the instance with new kwargs and
returns that instance. If not, creates a new
instance with kwargs and returns it.
Args:
**kwargs: The keyword arguments which are used for filtering
and initialization.
keys (list, optional): A special keyword argument. If passed,
only the set of keys mentioned here will be used for filtering.
Useful when we want to 'filter' based on a subset of the keys
and create with all the keys.
Examples:
>>> customer = Customer.update_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer.id
45
>>> customer1 = Customer.update_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer1==customer
True
>>> customer2 = Customer.update_or_create(
... name="vicky", email="[email protected]", country="Russia")
>>> customer2==customer
False
>>> customer3 = Customer.update_or_create(
... name="vicky", email="[email protected]", country="Russia",
... keys=['name', 'email'])
>>> customer3==customer
True
"""
keys = kwargs.pop('keys') if 'keys' in kwargs else []
filter_kwargs = subdict(kwargs, keys)
if filter_kwargs == {}:
obj = None
else:
obj = cls.first(**filter_kwargs)
if obj is not None:
for key, value in kwargs.iteritems():
if (key not in keys and
key not in cls._no_overwrite_):
setattr(obj, key, value)
try:
cls.session.commit()
except:
cls.session.rollback()
raise
else:
obj = cls.create(**kwargs)
return obj | [
"def",
"update_or_create",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"keys",
"=",
"kwargs",
".",
"pop",
"(",
"'keys'",
")",
"if",
"'keys'",
"in",
"kwargs",
"else",
"[",
"]",
"filter_kwargs",
"=",
"subdict",
"(",
"kwargs",
",",
"keys",
")",
"if",
"filter_kwargs",
"==",
"{",
"}",
":",
"obj",
"=",
"None",
"else",
":",
"obj",
"=",
"cls",
".",
"first",
"(",
"*",
"*",
"filter_kwargs",
")",
"if",
"obj",
"is",
"not",
"None",
":",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"(",
"key",
"not",
"in",
"keys",
"and",
"key",
"not",
"in",
"cls",
".",
"_no_overwrite_",
")",
":",
"setattr",
"(",
"obj",
",",
"key",
",",
"value",
")",
"try",
":",
"cls",
".",
"session",
".",
"commit",
"(",
")",
"except",
":",
"cls",
".",
"session",
".",
"rollback",
"(",
")",
"raise",
"else",
":",
"obj",
"=",
"cls",
".",
"create",
"(",
"*",
"*",
"kwargs",
")",
"return",
"obj"
] | Checks if an instance already exists by filtering with the
kwargs. If yes, updates the instance with new kwargs and
returns that instance. If not, creates a new
instance with kwargs and returns it.
Args:
**kwargs: The keyword arguments which are used for filtering
and initialization.
keys (list, optional): A special keyword argument. If passed,
only the set of keys mentioned here will be used for filtering.
Useful when we want to 'filter' based on a subset of the keys
and create with all the keys.
Examples:
>>> customer = Customer.update_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer.id
45
>>> customer1 = Customer.update_or_create(
... name="vicky", email="[email protected]", country="India")
>>> customer1==customer
True
>>> customer2 = Customer.update_or_create(
... name="vicky", email="[email protected]", country="Russia")
>>> customer2==customer
False
>>> customer3 = Customer.update_or_create(
... name="vicky", email="[email protected]", country="Russia",
... keys=['name', 'email'])
>>> customer3==customer
True | [
"Checks",
"if",
"an",
"instance",
"already",
"exists",
"by",
"filtering",
"with",
"the",
"kwargs",
".",
"If",
"yes",
"updates",
"the",
"instance",
"with",
"new",
"kwargs",
"and",
"returns",
"that",
"instance",
".",
"If",
"not",
"creates",
"a",
"new",
"instance",
"with",
"kwargs",
"and",
"returns",
"it",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L671-L725 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.create_all | def create_all(cls, list_of_kwargs):
"""Batch method for creating a list of instances
Args:
list_of_kwargs(list of dicts): hereA list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
Examples:
>>> Customer.create_all([
... {'name': 'Vicky', 'age': 34, 'user_id': 1},
... {'name': 'Ron', 'age': 40, 'user_id': 1, 'gender': 'Male'}])
"""
try:
return cls.add_all([
cls.new(**kwargs) if kwargs is not None else None for kwargs in list_of_kwargs])
except:
cls.session.rollback()
raise | python | def create_all(cls, list_of_kwargs):
"""Batch method for creating a list of instances
Args:
list_of_kwargs(list of dicts): hereA list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
Examples:
>>> Customer.create_all([
... {'name': 'Vicky', 'age': 34, 'user_id': 1},
... {'name': 'Ron', 'age': 40, 'user_id': 1, 'gender': 'Male'}])
"""
try:
return cls.add_all([
cls.new(**kwargs) if kwargs is not None else None for kwargs in list_of_kwargs])
except:
cls.session.rollback()
raise | [
"def",
"create_all",
"(",
"cls",
",",
"list_of_kwargs",
")",
":",
"try",
":",
"return",
"cls",
".",
"add_all",
"(",
"[",
"cls",
".",
"new",
"(",
"*",
"*",
"kwargs",
")",
"if",
"kwargs",
"is",
"not",
"None",
"else",
"None",
"for",
"kwargs",
"in",
"list_of_kwargs",
"]",
")",
"except",
":",
"cls",
".",
"session",
".",
"rollback",
"(",
")",
"raise"
] | Batch method for creating a list of instances
Args:
list_of_kwargs(list of dicts): hereA list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
Examples:
>>> Customer.create_all([
... {'name': 'Vicky', 'age': 34, 'user_id': 1},
... {'name': 'Ron', 'age': 40, 'user_id': 1, 'gender': 'Male'}]) | [
"Batch",
"method",
"for",
"creating",
"a",
"list",
"of",
"instances"
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L728-L747 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.find_or_create_all | def find_or_create_all(cls, list_of_kwargs, keys=[]):
"""Batch method for querying for a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
keys (list, optional): A list of keys to use for the
initial finding step. Matching is done only on these
attributes.
Examples:
>>> Customer.find_or_create_all([
... {'name': 'Vicky', 'email': '[email protected]', 'age': 34},
... {'name': 'Ron', 'age': 40, 'email': '[email protected]',
... 'gender': 'Male'}], keys=['name', 'email'])
"""
list_of_kwargs_wo_dupes, markers = remove_and_mark_duplicate_dicts(
list_of_kwargs, keys)
added_objs = cls.add_all([
cls.first(**subdict(kwargs, keys)) or cls.new(**kwargs)
for kwargs in list_of_kwargs_wo_dupes])
result_objs = []
iterator_of_added_objs = iter(added_objs)
for idx in range(len(list_of_kwargs)):
if idx in markers:
result_objs.append(added_objs[markers[idx]])
else:
result_objs.append(next(
iterator_of_added_objs))
return result_objs | python | def find_or_create_all(cls, list_of_kwargs, keys=[]):
"""Batch method for querying for a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
keys (list, optional): A list of keys to use for the
initial finding step. Matching is done only on these
attributes.
Examples:
>>> Customer.find_or_create_all([
... {'name': 'Vicky', 'email': '[email protected]', 'age': 34},
... {'name': 'Ron', 'age': 40, 'email': '[email protected]',
... 'gender': 'Male'}], keys=['name', 'email'])
"""
list_of_kwargs_wo_dupes, markers = remove_and_mark_duplicate_dicts(
list_of_kwargs, keys)
added_objs = cls.add_all([
cls.first(**subdict(kwargs, keys)) or cls.new(**kwargs)
for kwargs in list_of_kwargs_wo_dupes])
result_objs = []
iterator_of_added_objs = iter(added_objs)
for idx in range(len(list_of_kwargs)):
if idx in markers:
result_objs.append(added_objs[markers[idx]])
else:
result_objs.append(next(
iterator_of_added_objs))
return result_objs | [
"def",
"find_or_create_all",
"(",
"cls",
",",
"list_of_kwargs",
",",
"keys",
"=",
"[",
"]",
")",
":",
"list_of_kwargs_wo_dupes",
",",
"markers",
"=",
"remove_and_mark_duplicate_dicts",
"(",
"list_of_kwargs",
",",
"keys",
")",
"added_objs",
"=",
"cls",
".",
"add_all",
"(",
"[",
"cls",
".",
"first",
"(",
"*",
"*",
"subdict",
"(",
"kwargs",
",",
"keys",
")",
")",
"or",
"cls",
".",
"new",
"(",
"*",
"*",
"kwargs",
")",
"for",
"kwargs",
"in",
"list_of_kwargs_wo_dupes",
"]",
")",
"result_objs",
"=",
"[",
"]",
"iterator_of_added_objs",
"=",
"iter",
"(",
"added_objs",
")",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"list_of_kwargs",
")",
")",
":",
"if",
"idx",
"in",
"markers",
":",
"result_objs",
".",
"append",
"(",
"added_objs",
"[",
"markers",
"[",
"idx",
"]",
"]",
")",
"else",
":",
"result_objs",
".",
"append",
"(",
"next",
"(",
"iterator_of_added_objs",
")",
")",
"return",
"result_objs"
] | Batch method for querying for a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
keys (list, optional): A list of keys to use for the
initial finding step. Matching is done only on these
attributes.
Examples:
>>> Customer.find_or_create_all([
... {'name': 'Vicky', 'email': '[email protected]', 'age': 34},
... {'name': 'Ron', 'age': 40, 'email': '[email protected]',
... 'gender': 'Male'}], keys=['name', 'email']) | [
"Batch",
"method",
"for",
"querying",
"for",
"a",
"list",
"of",
"instances",
"and",
"creating",
"them",
"if",
"required"
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L750-L783 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.update_or_create_all | def update_or_create_all(cls, list_of_kwargs, keys=[]):
"""Batch method for updating a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
keys (list, optional): A list of keys to use for the
initial finding step. Matching is done only on these
attributes.
Examples:
>>> Customer.update_or_create_all([
... {'name': 'Vicky', 'email': '[email protected]', 'age': 34},
... {'name': 'Ron', 'age': 40, 'email': '[email protected]',
... 'gender': 'Male'}], keys=['name', 'email'])
"""
objs = []
for kwargs in list_of_kwargs:
filter_kwargs = subdict(kwargs, keys)
if filter_kwargs == {}:
obj = None
else:
obj = cls.first(**filter_kwargs)
if obj is not None:
for key, value in kwargs.iteritems():
if (key not in keys and
key not in cls._no_overwrite_):
setattr(obj, key, value)
else:
obj = cls.new(**kwargs)
objs.append(obj)
try:
return cls.add_all(objs)
except:
cls.session.rollback()
raise | python | def update_or_create_all(cls, list_of_kwargs, keys=[]):
"""Batch method for updating a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
keys (list, optional): A list of keys to use for the
initial finding step. Matching is done only on these
attributes.
Examples:
>>> Customer.update_or_create_all([
... {'name': 'Vicky', 'email': '[email protected]', 'age': 34},
... {'name': 'Ron', 'age': 40, 'email': '[email protected]',
... 'gender': 'Male'}], keys=['name', 'email'])
"""
objs = []
for kwargs in list_of_kwargs:
filter_kwargs = subdict(kwargs, keys)
if filter_kwargs == {}:
obj = None
else:
obj = cls.first(**filter_kwargs)
if obj is not None:
for key, value in kwargs.iteritems():
if (key not in keys and
key not in cls._no_overwrite_):
setattr(obj, key, value)
else:
obj = cls.new(**kwargs)
objs.append(obj)
try:
return cls.add_all(objs)
except:
cls.session.rollback()
raise | [
"def",
"update_or_create_all",
"(",
"cls",
",",
"list_of_kwargs",
",",
"keys",
"=",
"[",
"]",
")",
":",
"objs",
"=",
"[",
"]",
"for",
"kwargs",
"in",
"list_of_kwargs",
":",
"filter_kwargs",
"=",
"subdict",
"(",
"kwargs",
",",
"keys",
")",
"if",
"filter_kwargs",
"==",
"{",
"}",
":",
"obj",
"=",
"None",
"else",
":",
"obj",
"=",
"cls",
".",
"first",
"(",
"*",
"*",
"filter_kwargs",
")",
"if",
"obj",
"is",
"not",
"None",
":",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"if",
"(",
"key",
"not",
"in",
"keys",
"and",
"key",
"not",
"in",
"cls",
".",
"_no_overwrite_",
")",
":",
"setattr",
"(",
"obj",
",",
"key",
",",
"value",
")",
"else",
":",
"obj",
"=",
"cls",
".",
"new",
"(",
"*",
"*",
"kwargs",
")",
"objs",
".",
"append",
"(",
"obj",
")",
"try",
":",
"return",
"cls",
".",
"add_all",
"(",
"objs",
")",
"except",
":",
"cls",
".",
"session",
".",
"rollback",
"(",
")",
"raise"
] | Batch method for updating a list of instances and
creating them if required
Args:
list_of_kwargs(list of dicts): A list of dicts where
each dict denotes the keyword args that you would pass
to the create method separately
keys (list, optional): A list of keys to use for the
initial finding step. Matching is done only on these
attributes.
Examples:
>>> Customer.update_or_create_all([
... {'name': 'Vicky', 'email': '[email protected]', 'age': 34},
... {'name': 'Ron', 'age': 40, 'email': '[email protected]',
... 'gender': 'Male'}], keys=['name', 'email']) | [
"Batch",
"method",
"for",
"updating",
"a",
"list",
"of",
"instances",
"and",
"creating",
"them",
"if",
"required"
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L786-L825 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.build | def build(cls, **kwargs):
"""Similar to create. But the transaction is not committed
Args:
**kwargs : The keyword arguments for the constructor
Returns:
A model instance which has been added to db session. But session
transaction has not been committed yet.
"""
return cls.add(cls.new(**kwargs), commit=False) | python | def build(cls, **kwargs):
"""Similar to create. But the transaction is not committed
Args:
**kwargs : The keyword arguments for the constructor
Returns:
A model instance which has been added to db session. But session
transaction has not been committed yet.
"""
return cls.add(cls.new(**kwargs), commit=False) | [
"def",
"build",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
".",
"add",
"(",
"cls",
".",
"new",
"(",
"*",
"*",
"kwargs",
")",
",",
"commit",
"=",
"False",
")"
] | Similar to create. But the transaction is not committed
Args:
**kwargs : The keyword arguments for the constructor
Returns:
A model instance which has been added to db session. But session
transaction has not been committed yet. | [
"Similar",
"to",
"create",
".",
"But",
"the",
"transaction",
"is",
"not",
"committed"
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L870-L882 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.find_or_build | def find_or_build(cls, **kwargs):
"""Checks if an instance already exists in db with these kwargs else
returns a new, saved instance of the service's model class.
Args:
**kwargs: instance parameters
"""
keys = kwargs.pop('keys') if 'keys' in kwargs else []
return cls.first(**subdict(kwargs, keys)) or cls.build(**kwargs) | python | def find_or_build(cls, **kwargs):
"""Checks if an instance already exists in db with these kwargs else
returns a new, saved instance of the service's model class.
Args:
**kwargs: instance parameters
"""
keys = kwargs.pop('keys') if 'keys' in kwargs else []
return cls.first(**subdict(kwargs, keys)) or cls.build(**kwargs) | [
"def",
"find_or_build",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"keys",
"=",
"kwargs",
".",
"pop",
"(",
"'keys'",
")",
"if",
"'keys'",
"in",
"kwargs",
"else",
"[",
"]",
"return",
"cls",
".",
"first",
"(",
"*",
"*",
"subdict",
"(",
"kwargs",
",",
"keys",
")",
")",
"or",
"cls",
".",
"build",
"(",
"*",
"*",
"kwargs",
")"
] | Checks if an instance already exists in db with these kwargs else
returns a new, saved instance of the service's model class.
Args:
**kwargs: instance parameters | [
"Checks",
"if",
"an",
"instance",
"already",
"exists",
"in",
"db",
"with",
"these",
"kwargs",
"else",
"returns",
"a",
"new",
"saved",
"instance",
"of",
"the",
"service",
"s",
"model",
"class",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L885-L893 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.build_all | def build_all(cls, list_of_kwargs):
"""Similar to `create_all`. But transaction is not committed.
"""
return cls.add_all([
cls.new(**kwargs) for kwargs in list_of_kwargs], commit=False) | python | def build_all(cls, list_of_kwargs):
"""Similar to `create_all`. But transaction is not committed.
"""
return cls.add_all([
cls.new(**kwargs) for kwargs in list_of_kwargs], commit=False) | [
"def",
"build_all",
"(",
"cls",
",",
"list_of_kwargs",
")",
":",
"return",
"cls",
".",
"add_all",
"(",
"[",
"cls",
".",
"new",
"(",
"*",
"*",
"kwargs",
")",
"for",
"kwargs",
"in",
"list_of_kwargs",
"]",
",",
"commit",
"=",
"False",
")"
] | Similar to `create_all`. But transaction is not committed. | [
"Similar",
"to",
"create_all",
".",
"But",
"transaction",
"is",
"not",
"committed",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L909-L913 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.find_or_build_all | def find_or_build_all(cls, list_of_kwargs):
"""Similar to `find_or_create_all`. But transaction is not committed.
"""
return cls.add_all([cls.first(**kwargs) or cls.new(**kwargs)
for kwargs in list_of_kwargs], commit=False) | python | def find_or_build_all(cls, list_of_kwargs):
"""Similar to `find_or_create_all`. But transaction is not committed.
"""
return cls.add_all([cls.first(**kwargs) or cls.new(**kwargs)
for kwargs in list_of_kwargs], commit=False) | [
"def",
"find_or_build_all",
"(",
"cls",
",",
"list_of_kwargs",
")",
":",
"return",
"cls",
".",
"add_all",
"(",
"[",
"cls",
".",
"first",
"(",
"*",
"*",
"kwargs",
")",
"or",
"cls",
".",
"new",
"(",
"*",
"*",
"kwargs",
")",
"for",
"kwargs",
"in",
"list_of_kwargs",
"]",
",",
"commit",
"=",
"False",
")"
] | Similar to `find_or_create_all`. But transaction is not committed. | [
"Similar",
"to",
"find_or_create_all",
".",
"But",
"transaction",
"is",
"not",
"committed",
"."
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L916-L920 | train |
SuryaSankar/flask-sqlalchemy-booster | flask_sqlalchemy_booster/model_booster/queryable_mixin.py | QueryableMixin.update_all | def update_all(cls, *criterion, **kwargs):
"""Batch method for updating all instances obeying the criterion
Args:
*criterion: SQLAlchemy query criterion for filtering what
instances to update
**kwargs: The parameters to be updated
Examples:
>>> User.update_all(active=True)
>>> Customer.update_all(Customer.country=='India', active=True)
The second example sets active=True for all customers with
country India.
"""
try:
r = cls.query.filter(*criterion).update(kwargs, 'fetch')
cls.session.commit()
return r
except:
cls.session.rollback()
raise | python | def update_all(cls, *criterion, **kwargs):
"""Batch method for updating all instances obeying the criterion
Args:
*criterion: SQLAlchemy query criterion for filtering what
instances to update
**kwargs: The parameters to be updated
Examples:
>>> User.update_all(active=True)
>>> Customer.update_all(Customer.country=='India', active=True)
The second example sets active=True for all customers with
country India.
"""
try:
r = cls.query.filter(*criterion).update(kwargs, 'fetch')
cls.session.commit()
return r
except:
cls.session.rollback()
raise | [
"def",
"update_all",
"(",
"cls",
",",
"*",
"criterion",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"r",
"=",
"cls",
".",
"query",
".",
"filter",
"(",
"*",
"criterion",
")",
".",
"update",
"(",
"kwargs",
",",
"'fetch'",
")",
"cls",
".",
"session",
".",
"commit",
"(",
")",
"return",
"r",
"except",
":",
"cls",
".",
"session",
".",
"rollback",
"(",
")",
"raise"
] | Batch method for updating all instances obeying the criterion
Args:
*criterion: SQLAlchemy query criterion for filtering what
instances to update
**kwargs: The parameters to be updated
Examples:
>>> User.update_all(active=True)
>>> Customer.update_all(Customer.country=='India', active=True)
The second example sets active=True for all customers with
country India. | [
"Batch",
"method",
"for",
"updating",
"all",
"instances",
"obeying",
"the",
"criterion"
] | 444048d167ab7718f758e943665ef32d101423a5 | https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/queryable_mixin.py#L923-L946 | train |
biosignalsnotebooks/biosignalsnotebooks | biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/peakdelta.py | peakdelta | def peakdelta(v, delta, x=None):
"""
Returns two arrays
function [maxtab, mintab]=peakdelta(v, delta, x)
%PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = peakdelta(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consists of two columns. Column 1
% contains indices in V, and column 2 the found values.
%
% With [MAXTAB, MINTAB] = peakdelta(V, DELTA, X) the indices
% in MAXTAB and MINTAB are replaced with the corresponding
% X-values.
%
% A point is considered a maximum peak if it has the maximal
% value, and was preceded (to the left) by a value lower by
% DELTA.
% Eli Billauer, 3.4.05 (Explicitly not copyrighted).
% This function is released to the public domain; Any use is allowed.
"""
maxtab = []
mintab = []
if x is None:
x = arange(len(v))
v = asarray(v)
if len(v) != len(x):
sys.exit('Input vectors v and x must have same length')
if not isscalar(delta):
sys.exit('Input argument delta must be a scalar')
if delta <= 0:
sys.exit('Input argument delta must be positive')
mn, mx = Inf, -Inf
mnpos, mxpos = NaN, NaN
lookformax = True
for i in arange(len(v)):
this = v[i]
if this > mx:
mx = this
mxpos = x[i]
if this < mn:
mn = this
mnpos = x[i]
if lookformax:
if this < mx - delta:
maxtab.append((mxpos, mx))
mn = this
mnpos = x[i]
lookformax = False
else:
if this > mn + delta:
mintab.append((mnpos, mn))
mx = this
mxpos = x[i]
lookformax = True
return array(maxtab), array(mintab) | python | def peakdelta(v, delta, x=None):
"""
Returns two arrays
function [maxtab, mintab]=peakdelta(v, delta, x)
%PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = peakdelta(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consists of two columns. Column 1
% contains indices in V, and column 2 the found values.
%
% With [MAXTAB, MINTAB] = peakdelta(V, DELTA, X) the indices
% in MAXTAB and MINTAB are replaced with the corresponding
% X-values.
%
% A point is considered a maximum peak if it has the maximal
% value, and was preceded (to the left) by a value lower by
% DELTA.
% Eli Billauer, 3.4.05 (Explicitly not copyrighted).
% This function is released to the public domain; Any use is allowed.
"""
maxtab = []
mintab = []
if x is None:
x = arange(len(v))
v = asarray(v)
if len(v) != len(x):
sys.exit('Input vectors v and x must have same length')
if not isscalar(delta):
sys.exit('Input argument delta must be a scalar')
if delta <= 0:
sys.exit('Input argument delta must be positive')
mn, mx = Inf, -Inf
mnpos, mxpos = NaN, NaN
lookformax = True
for i in arange(len(v)):
this = v[i]
if this > mx:
mx = this
mxpos = x[i]
if this < mn:
mn = this
mnpos = x[i]
if lookformax:
if this < mx - delta:
maxtab.append((mxpos, mx))
mn = this
mnpos = x[i]
lookformax = False
else:
if this > mn + delta:
mintab.append((mnpos, mn))
mx = this
mxpos = x[i]
lookformax = True
return array(maxtab), array(mintab) | [
"def",
"peakdelta",
"(",
"v",
",",
"delta",
",",
"x",
"=",
"None",
")",
":",
"maxtab",
"=",
"[",
"]",
"mintab",
"=",
"[",
"]",
"if",
"x",
"is",
"None",
":",
"x",
"=",
"arange",
"(",
"len",
"(",
"v",
")",
")",
"v",
"=",
"asarray",
"(",
"v",
")",
"if",
"len",
"(",
"v",
")",
"!=",
"len",
"(",
"x",
")",
":",
"sys",
".",
"exit",
"(",
"'Input vectors v and x must have same length'",
")",
"if",
"not",
"isscalar",
"(",
"delta",
")",
":",
"sys",
".",
"exit",
"(",
"'Input argument delta must be a scalar'",
")",
"if",
"delta",
"<=",
"0",
":",
"sys",
".",
"exit",
"(",
"'Input argument delta must be positive'",
")",
"mn",
",",
"mx",
"=",
"Inf",
",",
"-",
"Inf",
"mnpos",
",",
"mxpos",
"=",
"NaN",
",",
"NaN",
"lookformax",
"=",
"True",
"for",
"i",
"in",
"arange",
"(",
"len",
"(",
"v",
")",
")",
":",
"this",
"=",
"v",
"[",
"i",
"]",
"if",
"this",
">",
"mx",
":",
"mx",
"=",
"this",
"mxpos",
"=",
"x",
"[",
"i",
"]",
"if",
"this",
"<",
"mn",
":",
"mn",
"=",
"this",
"mnpos",
"=",
"x",
"[",
"i",
"]",
"if",
"lookformax",
":",
"if",
"this",
"<",
"mx",
"-",
"delta",
":",
"maxtab",
".",
"append",
"(",
"(",
"mxpos",
",",
"mx",
")",
")",
"mn",
"=",
"this",
"mnpos",
"=",
"x",
"[",
"i",
"]",
"lookformax",
"=",
"False",
"else",
":",
"if",
"this",
">",
"mn",
"+",
"delta",
":",
"mintab",
".",
"append",
"(",
"(",
"mnpos",
",",
"mn",
")",
")",
"mx",
"=",
"this",
"mxpos",
"=",
"x",
"[",
"i",
"]",
"lookformax",
"=",
"True",
"return",
"array",
"(",
"maxtab",
")",
",",
"array",
"(",
"mintab",
")"
] | Returns two arrays
function [maxtab, mintab]=peakdelta(v, delta, x)
%PEAKDET Detect peaks in a vector
% [MAXTAB, MINTAB] = peakdelta(V, DELTA) finds the local
% maxima and minima ("peaks") in the vector V.
% MAXTAB and MINTAB consists of two columns. Column 1
% contains indices in V, and column 2 the found values.
%
% With [MAXTAB, MINTAB] = peakdelta(V, DELTA, X) the indices
% in MAXTAB and MINTAB are replaced with the corresponding
% X-values.
%
% A point is considered a maximum peak if it has the maximal
% value, and was preceded (to the left) by a value lower by
% DELTA.
% Eli Billauer, 3.4.05 (Explicitly not copyrighted).
% This function is released to the public domain; Any use is allowed. | [
"Returns",
"two",
"arrays"
] | aaa01d4125180b3a34f1e26e0d3ff08c23f666d3 | https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/peakdelta.py#L15-L81 | train |
thomasdelaet/python-velbus | velbus/modules/vmbpbn.py | VMB2PBNModule.on_status_update | def on_status_update(self, channel, callback):
"""
Callback to execute on status of update of channel
"""
if channel not in self._callbacks:
self._callbacks[channel] = []
self._callbacks[channel].append(callback) | python | def on_status_update(self, channel, callback):
"""
Callback to execute on status of update of channel
"""
if channel not in self._callbacks:
self._callbacks[channel] = []
self._callbacks[channel].append(callback) | [
"def",
"on_status_update",
"(",
"self",
",",
"channel",
",",
"callback",
")",
":",
"if",
"channel",
"not",
"in",
"self",
".",
"_callbacks",
":",
"self",
".",
"_callbacks",
"[",
"channel",
"]",
"=",
"[",
"]",
"self",
".",
"_callbacks",
"[",
"channel",
"]",
".",
"append",
"(",
"callback",
")"
] | Callback to execute on status of update of channel | [
"Callback",
"to",
"execute",
"on",
"status",
"of",
"update",
"of",
"channel"
] | af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/modules/vmbpbn.py#L46-L52 | train |
KE-works/pykechain | pykechain/utils.py | temp_chdir | def temp_chdir(cwd=None):
"""
Create and return a temporary directory which you can use as a context manager.
When you are out of the context the temprorary disk gets erased.
.. versionadded:: 2.3
:param cwd: path to change working directory back to path when out of context
:type cwd: basestring or None
:return: in context a temporary directory
Example
-------
>>> with temp_chdir() as temp_dir:
>>> # do things here
>>> print(temp_dir) # etc etc
...
>>> # when moving out of the context the temp_dir is destroyed
>>> pass
"""
if six.PY3:
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tempwd:
origin = cwd or os.getcwd()
os.chdir(tempwd)
try:
yield tempwd if os.path.exists(tempwd) else ''
finally:
os.chdir(origin)
else:
from tempfile import mkdtemp
tempwd = mkdtemp()
origin = cwd or os.getcwd()
os.chdir(tempwd)
try:
yield tempwd if os.path.exists(tempwd) else ''
finally:
os.chdir(origin) | python | def temp_chdir(cwd=None):
"""
Create and return a temporary directory which you can use as a context manager.
When you are out of the context the temprorary disk gets erased.
.. versionadded:: 2.3
:param cwd: path to change working directory back to path when out of context
:type cwd: basestring or None
:return: in context a temporary directory
Example
-------
>>> with temp_chdir() as temp_dir:
>>> # do things here
>>> print(temp_dir) # etc etc
...
>>> # when moving out of the context the temp_dir is destroyed
>>> pass
"""
if six.PY3:
from tempfile import TemporaryDirectory
with TemporaryDirectory() as tempwd:
origin = cwd or os.getcwd()
os.chdir(tempwd)
try:
yield tempwd if os.path.exists(tempwd) else ''
finally:
os.chdir(origin)
else:
from tempfile import mkdtemp
tempwd = mkdtemp()
origin = cwd or os.getcwd()
os.chdir(tempwd)
try:
yield tempwd if os.path.exists(tempwd) else ''
finally:
os.chdir(origin) | [
"def",
"temp_chdir",
"(",
"cwd",
"=",
"None",
")",
":",
"if",
"six",
".",
"PY3",
":",
"from",
"tempfile",
"import",
"TemporaryDirectory",
"with",
"TemporaryDirectory",
"(",
")",
"as",
"tempwd",
":",
"origin",
"=",
"cwd",
"or",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"tempwd",
")",
"try",
":",
"yield",
"tempwd",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"tempwd",
")",
"else",
"''",
"finally",
":",
"os",
".",
"chdir",
"(",
"origin",
")",
"else",
":",
"from",
"tempfile",
"import",
"mkdtemp",
"tempwd",
"=",
"mkdtemp",
"(",
")",
"origin",
"=",
"cwd",
"or",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"tempwd",
")",
"try",
":",
"yield",
"tempwd",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"tempwd",
")",
"else",
"''",
"finally",
":",
"os",
".",
"chdir",
"(",
"origin",
")"
] | Create and return a temporary directory which you can use as a context manager.
When you are out of the context the temprorary disk gets erased.
.. versionadded:: 2.3
:param cwd: path to change working directory back to path when out of context
:type cwd: basestring or None
:return: in context a temporary directory
Example
-------
>>> with temp_chdir() as temp_dir:
>>> # do things here
>>> print(temp_dir) # etc etc
...
>>> # when moving out of the context the temp_dir is destroyed
>>> pass | [
"Create",
"and",
"return",
"a",
"temporary",
"directory",
"which",
"you",
"can",
"use",
"as",
"a",
"context",
"manager",
"."
] | b0296cf34328fd41660bf6f0b9114fd0167c40c4 | https://github.com/KE-works/pykechain/blob/b0296cf34328fd41660bf6f0b9114fd0167c40c4/pykechain/utils.py#L42-L83 | train |
Subsets and Splits