repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
sequencelengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
sequencelengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
---|---|---|---|---|---|---|---|---|---|---|
MSchnei/pyprf_feature | pyprf_feature/analysis/old/pRF_mdlCrt.py | crtPrfNrlTc | def crtPrfNrlTc(aryBoxCar, varNumMtDrctn, varNumVol, tplPngSize, varNumX,
varExtXmin, varExtXmax, varNumY, varExtYmin, varExtYmax,
varNumPrfSizes, varPrfStdMin, varPrfStdMax, varPar):
"""Create neural model time courses from pixel-wise boxcar functions.
Parameters
----------
aryBoxCar : 4d numpy array, shape [n_x_pix, n_y_pix, n_mtn_dir, n_vol]
Description of input 1.
varNumMtDrctn : float, positive
Description of input 2.
varNumVol : float, positive
Description of input 2.
tplPngSize : tuple
Description of input 2.
varNumX : float, positive
Description of input 2.
varExtXmin : float, positive
Description of input 2.
varExtXmax : float, positive
Description of input 2.
varNumY : float, positive
Description of input 2.
varExtYmin : float, positive
Description of input 2.
varExtYmax : float, positive
Description of input 2.
varNumPrfSizes : float, positive
Description of input 2.
varPrfStdMin : float, positive
Description of input 2.
varPrfStdMax : float, positive
Description of input 2.
varPar : float, positive
Description of input 2.
Returns
-------
aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol]
Closed data.
Reference
---------
[1]
"""
print('------Create neural time course models')
# Vector with the x-indicies of the positions in the super-sampled visual
# space at which to create pRF models.
vecX = np.linspace(0, (tplPngSize[0] - 1), varNumX, endpoint=True)
# Vector with the y-indicies of the positions in the super-sampled visual
# space at which to create pRF models.
vecY = np.linspace(0, (tplPngSize[1] - 1), varNumY, endpoint=True)
# We calculate the scaling factor from degrees of visual angle to pixels
# separately for the x- and the y-directions (the two should be the same).
varDgr2PixX = tplPngSize[0] / (varExtXmax - varExtXmin)
varDgr2PixY = tplPngSize[1] / (varExtYmax - varExtYmin)
# Check whether varDgr2PixX and varDgr2PixY are similar:
strErrMsg = 'ERROR. The ratio of X and Y dimensions in stimulus ' + \
'space (in degrees of visual angle) and the ratio of X and Y ' + \
'dimensions in the upsampled visual space do not agree'
assert 0.5 > np.absolute((varDgr2PixX - varDgr2PixY)), strErrMsg
# Vector with pRF sizes to be modelled (still in degree of visual angle):
vecPrfSd = np.linspace(varPrfStdMin, varPrfStdMax, varNumPrfSizes,
endpoint=True)
# We multiply the vector containing pRF sizes with the scaling factors.
# Now the vector with the pRF sizes can be used directly for creation of
# Gaussian pRF models in visual space.
vecPrfSd = np.multiply(vecPrfSd, varDgr2PixX)
# Number of pRF models to be created (i.e. number of possible combinations
# of x-position, y-position, and standard deviation):
varNumMdls = varNumX * varNumY * varNumPrfSizes
# Array for the x-position, y-position, and standard deviations for which
# pRF model time courses are going to be created, where the columns
# correspond to: (0) an index starting from zero, (1) the x-position, (2)
# the y-position, and (3) the standard deviation. The parameters are in
# units of the upsampled visual space.
aryMdlParams = np.zeros((varNumMdls, 4))
# Counter for parameter array:
varCntMdlPrms = 0
# Put all combinations of x-position, y-position, and standard deviations
# into the array:
# Loop through x-positions:
for idxX in range(0, varNumX):
# Loop through y-positions:
for idxY in range(0, varNumY):
# Loop through standard deviations (of Gaussian pRF models):
for idxSd in range(0, varNumPrfSizes):
# Place index and parameters in array:
aryMdlParams[varCntMdlPrms, 0] = varCntMdlPrms
aryMdlParams[varCntMdlPrms, 1] = vecX[idxX]
aryMdlParams[varCntMdlPrms, 2] = vecY[idxY]
aryMdlParams[varCntMdlPrms, 3] = vecPrfSd[idxSd]
# Increment parameter index:
varCntMdlPrms = varCntMdlPrms + 1
# The long array with all the combinations of model parameters is put into
# separate chunks for parallelisation, using a list of arrays.
lstMdlParams = np.array_split(aryMdlParams, varPar)
# Create a queue to put the results in:
queOut = mp.Queue()
# Empty list for results from parallel processes (for pRF model time course
# results):
lstPrfTc = [None] * varPar
# Empty list for processes:
lstPrcs = [None] * varPar
print('---------Creating parallel processes')
# Create processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvlGauss2D,
args=(idxPrc, aryBoxCar,
lstMdlParams[idxPrc], tplPngSize,
varNumVol, queOut)
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
# Start processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].start()
# Collect results from queue:
for idxPrc in range(0, varPar):
lstPrfTc[idxPrc] = queOut.get(True)
# Join processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].join()
print('---------Collecting results from parallel processes')
# Put output arrays from parallel process into one big array
lstPrfTc = sorted(lstPrfTc)
aryPrfTc = np.empty((0, varNumMtDrctn, varNumVol))
for idx in range(0, varPar):
aryPrfTc = np.concatenate((aryPrfTc, lstPrfTc[idx][1]), axis=0)
# check that all the models were collected correctly
assert aryPrfTc.shape[0] == varNumMdls
# Clean up:
del(aryMdlParams)
del(lstMdlParams)
del(lstPrfTc)
# Array representing the low-resolution visual space, of the form
# aryPrfTc[x-position, y-position, pRF-size, varNum Vol], which will hold
# the pRF model time courses.
aryNrlTc = np.zeros([varNumX, varNumY, varNumPrfSizes, varNumMtDrctn,
varNumVol])
# We use the same loop structure for organising the pRF model time courses
# that we used for creating the parameter array. Counter:
varCntMdlPrms = 0
# Put all combinations of x-position, y-position, and standard deviations
# into the array:
# Loop through x-positions:
for idxX in range(0, varNumX):
# Loop through y-positions:
for idxY in range(0, varNumY):
# Loop through standard deviations (of Gaussian pRF models):
for idxSd in range(0, varNumPrfSizes):
# Put the pRF model time course into its correct position in
# the 4D array, leaving out the first column (which contains
# the index):
aryNrlTc[idxX, idxY, idxSd, :, :] = aryPrfTc[
varCntMdlPrms, :, :]
# Increment parameter index:
varCntMdlPrms = varCntMdlPrms + 1
return aryNrlTc | python | def crtPrfNrlTc(aryBoxCar, varNumMtDrctn, varNumVol, tplPngSize, varNumX,
varExtXmin, varExtXmax, varNumY, varExtYmin, varExtYmax,
varNumPrfSizes, varPrfStdMin, varPrfStdMax, varPar):
"""Create neural model time courses from pixel-wise boxcar functions.
Parameters
----------
aryBoxCar : 4d numpy array, shape [n_x_pix, n_y_pix, n_mtn_dir, n_vol]
Description of input 1.
varNumMtDrctn : float, positive
Description of input 2.
varNumVol : float, positive
Description of input 2.
tplPngSize : tuple
Description of input 2.
varNumX : float, positive
Description of input 2.
varExtXmin : float, positive
Description of input 2.
varExtXmax : float, positive
Description of input 2.
varNumY : float, positive
Description of input 2.
varExtYmin : float, positive
Description of input 2.
varExtYmax : float, positive
Description of input 2.
varNumPrfSizes : float, positive
Description of input 2.
varPrfStdMin : float, positive
Description of input 2.
varPrfStdMax : float, positive
Description of input 2.
varPar : float, positive
Description of input 2.
Returns
-------
aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol]
Closed data.
Reference
---------
[1]
"""
print('------Create neural time course models')
# Vector with the x-indicies of the positions in the super-sampled visual
# space at which to create pRF models.
vecX = np.linspace(0, (tplPngSize[0] - 1), varNumX, endpoint=True)
# Vector with the y-indicies of the positions in the super-sampled visual
# space at which to create pRF models.
vecY = np.linspace(0, (tplPngSize[1] - 1), varNumY, endpoint=True)
# We calculate the scaling factor from degrees of visual angle to pixels
# separately for the x- and the y-directions (the two should be the same).
varDgr2PixX = tplPngSize[0] / (varExtXmax - varExtXmin)
varDgr2PixY = tplPngSize[1] / (varExtYmax - varExtYmin)
# Check whether varDgr2PixX and varDgr2PixY are similar:
strErrMsg = 'ERROR. The ratio of X and Y dimensions in stimulus ' + \
'space (in degrees of visual angle) and the ratio of X and Y ' + \
'dimensions in the upsampled visual space do not agree'
assert 0.5 > np.absolute((varDgr2PixX - varDgr2PixY)), strErrMsg
# Vector with pRF sizes to be modelled (still in degree of visual angle):
vecPrfSd = np.linspace(varPrfStdMin, varPrfStdMax, varNumPrfSizes,
endpoint=True)
# We multiply the vector containing pRF sizes with the scaling factors.
# Now the vector with the pRF sizes can be used directly for creation of
# Gaussian pRF models in visual space.
vecPrfSd = np.multiply(vecPrfSd, varDgr2PixX)
# Number of pRF models to be created (i.e. number of possible combinations
# of x-position, y-position, and standard deviation):
varNumMdls = varNumX * varNumY * varNumPrfSizes
# Array for the x-position, y-position, and standard deviations for which
# pRF model time courses are going to be created, where the columns
# correspond to: (0) an index starting from zero, (1) the x-position, (2)
# the y-position, and (3) the standard deviation. The parameters are in
# units of the upsampled visual space.
aryMdlParams = np.zeros((varNumMdls, 4))
# Counter for parameter array:
varCntMdlPrms = 0
# Put all combinations of x-position, y-position, and standard deviations
# into the array:
# Loop through x-positions:
for idxX in range(0, varNumX):
# Loop through y-positions:
for idxY in range(0, varNumY):
# Loop through standard deviations (of Gaussian pRF models):
for idxSd in range(0, varNumPrfSizes):
# Place index and parameters in array:
aryMdlParams[varCntMdlPrms, 0] = varCntMdlPrms
aryMdlParams[varCntMdlPrms, 1] = vecX[idxX]
aryMdlParams[varCntMdlPrms, 2] = vecY[idxY]
aryMdlParams[varCntMdlPrms, 3] = vecPrfSd[idxSd]
# Increment parameter index:
varCntMdlPrms = varCntMdlPrms + 1
# The long array with all the combinations of model parameters is put into
# separate chunks for parallelisation, using a list of arrays.
lstMdlParams = np.array_split(aryMdlParams, varPar)
# Create a queue to put the results in:
queOut = mp.Queue()
# Empty list for results from parallel processes (for pRF model time course
# results):
lstPrfTc = [None] * varPar
# Empty list for processes:
lstPrcs = [None] * varPar
print('---------Creating parallel processes')
# Create processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvlGauss2D,
args=(idxPrc, aryBoxCar,
lstMdlParams[idxPrc], tplPngSize,
varNumVol, queOut)
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
# Start processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].start()
# Collect results from queue:
for idxPrc in range(0, varPar):
lstPrfTc[idxPrc] = queOut.get(True)
# Join processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].join()
print('---------Collecting results from parallel processes')
# Put output arrays from parallel process into one big array
lstPrfTc = sorted(lstPrfTc)
aryPrfTc = np.empty((0, varNumMtDrctn, varNumVol))
for idx in range(0, varPar):
aryPrfTc = np.concatenate((aryPrfTc, lstPrfTc[idx][1]), axis=0)
# check that all the models were collected correctly
assert aryPrfTc.shape[0] == varNumMdls
# Clean up:
del(aryMdlParams)
del(lstMdlParams)
del(lstPrfTc)
# Array representing the low-resolution visual space, of the form
# aryPrfTc[x-position, y-position, pRF-size, varNum Vol], which will hold
# the pRF model time courses.
aryNrlTc = np.zeros([varNumX, varNumY, varNumPrfSizes, varNumMtDrctn,
varNumVol])
# We use the same loop structure for organising the pRF model time courses
# that we used for creating the parameter array. Counter:
varCntMdlPrms = 0
# Put all combinations of x-position, y-position, and standard deviations
# into the array:
# Loop through x-positions:
for idxX in range(0, varNumX):
# Loop through y-positions:
for idxY in range(0, varNumY):
# Loop through standard deviations (of Gaussian pRF models):
for idxSd in range(0, varNumPrfSizes):
# Put the pRF model time course into its correct position in
# the 4D array, leaving out the first column (which contains
# the index):
aryNrlTc[idxX, idxY, idxSd, :, :] = aryPrfTc[
varCntMdlPrms, :, :]
# Increment parameter index:
varCntMdlPrms = varCntMdlPrms + 1
return aryNrlTc | [
"def",
"crtPrfNrlTc",
"(",
"aryBoxCar",
",",
"varNumMtDrctn",
",",
"varNumVol",
",",
"tplPngSize",
",",
"varNumX",
",",
"varExtXmin",
",",
"varExtXmax",
",",
"varNumY",
",",
"varExtYmin",
",",
"varExtYmax",
",",
"varNumPrfSizes",
",",
"varPrfStdMin",
",",
"varPrfStdMax",
",",
"varPar",
")",
":",
"print",
"(",
"'------Create neural time course models'",
")",
"# Vector with the x-indicies of the positions in the super-sampled visual",
"# space at which to create pRF models.",
"vecX",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"(",
"tplPngSize",
"[",
"0",
"]",
"-",
"1",
")",
",",
"varNumX",
",",
"endpoint",
"=",
"True",
")",
"# Vector with the y-indicies of the positions in the super-sampled visual",
"# space at which to create pRF models.",
"vecY",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"(",
"tplPngSize",
"[",
"1",
"]",
"-",
"1",
")",
",",
"varNumY",
",",
"endpoint",
"=",
"True",
")",
"# We calculate the scaling factor from degrees of visual angle to pixels",
"# separately for the x- and the y-directions (the two should be the same).",
"varDgr2PixX",
"=",
"tplPngSize",
"[",
"0",
"]",
"/",
"(",
"varExtXmax",
"-",
"varExtXmin",
")",
"varDgr2PixY",
"=",
"tplPngSize",
"[",
"1",
"]",
"/",
"(",
"varExtYmax",
"-",
"varExtYmin",
")",
"# Check whether varDgr2PixX and varDgr2PixY are similar:",
"strErrMsg",
"=",
"'ERROR. The ratio of X and Y dimensions in stimulus '",
"+",
"'space (in degrees of visual angle) and the ratio of X and Y '",
"+",
"'dimensions in the upsampled visual space do not agree'",
"assert",
"0.5",
">",
"np",
".",
"absolute",
"(",
"(",
"varDgr2PixX",
"-",
"varDgr2PixY",
")",
")",
",",
"strErrMsg",
"# Vector with pRF sizes to be modelled (still in degree of visual angle):",
"vecPrfSd",
"=",
"np",
".",
"linspace",
"(",
"varPrfStdMin",
",",
"varPrfStdMax",
",",
"varNumPrfSizes",
",",
"endpoint",
"=",
"True",
")",
"# We multiply the vector containing pRF sizes with the scaling factors.",
"# Now the vector with the pRF sizes can be used directly for creation of",
"# Gaussian pRF models in visual space.",
"vecPrfSd",
"=",
"np",
".",
"multiply",
"(",
"vecPrfSd",
",",
"varDgr2PixX",
")",
"# Number of pRF models to be created (i.e. number of possible combinations",
"# of x-position, y-position, and standard deviation):",
"varNumMdls",
"=",
"varNumX",
"*",
"varNumY",
"*",
"varNumPrfSizes",
"# Array for the x-position, y-position, and standard deviations for which",
"# pRF model time courses are going to be created, where the columns",
"# correspond to: (0) an index starting from zero, (1) the x-position, (2)",
"# the y-position, and (3) the standard deviation. The parameters are in",
"# units of the upsampled visual space.",
"aryMdlParams",
"=",
"np",
".",
"zeros",
"(",
"(",
"varNumMdls",
",",
"4",
")",
")",
"# Counter for parameter array:",
"varCntMdlPrms",
"=",
"0",
"# Put all combinations of x-position, y-position, and standard deviations",
"# into the array:",
"# Loop through x-positions:",
"for",
"idxX",
"in",
"range",
"(",
"0",
",",
"varNumX",
")",
":",
"# Loop through y-positions:",
"for",
"idxY",
"in",
"range",
"(",
"0",
",",
"varNumY",
")",
":",
"# Loop through standard deviations (of Gaussian pRF models):",
"for",
"idxSd",
"in",
"range",
"(",
"0",
",",
"varNumPrfSizes",
")",
":",
"# Place index and parameters in array:",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"0",
"]",
"=",
"varCntMdlPrms",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"1",
"]",
"=",
"vecX",
"[",
"idxX",
"]",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"2",
"]",
"=",
"vecY",
"[",
"idxY",
"]",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"3",
"]",
"=",
"vecPrfSd",
"[",
"idxSd",
"]",
"# Increment parameter index:",
"varCntMdlPrms",
"=",
"varCntMdlPrms",
"+",
"1",
"# The long array with all the combinations of model parameters is put into",
"# separate chunks for parallelisation, using a list of arrays.",
"lstMdlParams",
"=",
"np",
".",
"array_split",
"(",
"aryMdlParams",
",",
"varPar",
")",
"# Create a queue to put the results in:",
"queOut",
"=",
"mp",
".",
"Queue",
"(",
")",
"# Empty list for results from parallel processes (for pRF model time course",
"# results):",
"lstPrfTc",
"=",
"[",
"None",
"]",
"*",
"varPar",
"# Empty list for processes:",
"lstPrcs",
"=",
"[",
"None",
"]",
"*",
"varPar",
"print",
"(",
"'---------Creating parallel processes'",
")",
"# Create processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
"=",
"mp",
".",
"Process",
"(",
"target",
"=",
"cnvlGauss2D",
",",
"args",
"=",
"(",
"idxPrc",
",",
"aryBoxCar",
",",
"lstMdlParams",
"[",
"idxPrc",
"]",
",",
"tplPngSize",
",",
"varNumVol",
",",
"queOut",
")",
")",
"# Daemon (kills processes when exiting):",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"Daemon",
"=",
"True",
"# Start processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"start",
"(",
")",
"# Collect results from queue:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrfTc",
"[",
"idxPrc",
"]",
"=",
"queOut",
".",
"get",
"(",
"True",
")",
"# Join processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"join",
"(",
")",
"print",
"(",
"'---------Collecting results from parallel processes'",
")",
"# Put output arrays from parallel process into one big array",
"lstPrfTc",
"=",
"sorted",
"(",
"lstPrfTc",
")",
"aryPrfTc",
"=",
"np",
".",
"empty",
"(",
"(",
"0",
",",
"varNumMtDrctn",
",",
"varNumVol",
")",
")",
"for",
"idx",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"aryPrfTc",
"=",
"np",
".",
"concatenate",
"(",
"(",
"aryPrfTc",
",",
"lstPrfTc",
"[",
"idx",
"]",
"[",
"1",
"]",
")",
",",
"axis",
"=",
"0",
")",
"# check that all the models were collected correctly",
"assert",
"aryPrfTc",
".",
"shape",
"[",
"0",
"]",
"==",
"varNumMdls",
"# Clean up:",
"del",
"(",
"aryMdlParams",
")",
"del",
"(",
"lstMdlParams",
")",
"del",
"(",
"lstPrfTc",
")",
"# Array representing the low-resolution visual space, of the form",
"# aryPrfTc[x-position, y-position, pRF-size, varNum Vol], which will hold",
"# the pRF model time courses.",
"aryNrlTc",
"=",
"np",
".",
"zeros",
"(",
"[",
"varNumX",
",",
"varNumY",
",",
"varNumPrfSizes",
",",
"varNumMtDrctn",
",",
"varNumVol",
"]",
")",
"# We use the same loop structure for organising the pRF model time courses",
"# that we used for creating the parameter array. Counter:",
"varCntMdlPrms",
"=",
"0",
"# Put all combinations of x-position, y-position, and standard deviations",
"# into the array:",
"# Loop through x-positions:",
"for",
"idxX",
"in",
"range",
"(",
"0",
",",
"varNumX",
")",
":",
"# Loop through y-positions:",
"for",
"idxY",
"in",
"range",
"(",
"0",
",",
"varNumY",
")",
":",
"# Loop through standard deviations (of Gaussian pRF models):",
"for",
"idxSd",
"in",
"range",
"(",
"0",
",",
"varNumPrfSizes",
")",
":",
"# Put the pRF model time course into its correct position in",
"# the 4D array, leaving out the first column (which contains",
"# the index):",
"aryNrlTc",
"[",
"idxX",
",",
"idxY",
",",
"idxSd",
",",
":",
",",
":",
"]",
"=",
"aryPrfTc",
"[",
"varCntMdlPrms",
",",
":",
",",
":",
"]",
"# Increment parameter index:",
"varCntMdlPrms",
"=",
"varCntMdlPrms",
"+",
"1",
"return",
"aryNrlTc"
] | Create neural model time courses from pixel-wise boxcar functions.
Parameters
----------
aryBoxCar : 4d numpy array, shape [n_x_pix, n_y_pix, n_mtn_dir, n_vol]
Description of input 1.
varNumMtDrctn : float, positive
Description of input 2.
varNumVol : float, positive
Description of input 2.
tplPngSize : tuple
Description of input 2.
varNumX : float, positive
Description of input 2.
varExtXmin : float, positive
Description of input 2.
varExtXmax : float, positive
Description of input 2.
varNumY : float, positive
Description of input 2.
varExtYmin : float, positive
Description of input 2.
varExtYmax : float, positive
Description of input 2.
varNumPrfSizes : float, positive
Description of input 2.
varPrfStdMin : float, positive
Description of input 2.
varPrfStdMax : float, positive
Description of input 2.
varPar : float, positive
Description of input 2.
Returns
-------
aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol]
Closed data.
Reference
---------
[1] | [
"Create",
"neural",
"model",
"time",
"courses",
"from",
"pixel",
"-",
"wise",
"boxcar",
"functions",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/old/pRF_mdlCrt.py#L253-L445 |
MSchnei/pyprf_feature | pyprf_feature/analysis/old/pRF_mdlCrt.py | cnvlPwBoxCarFn | def cnvlPwBoxCarFn(aryNrlTc, varNumVol, varTr, tplPngSize, varNumMtDrctn,
switchHrfSet, lgcOldSchoolHrf, varPar,):
"""Create 2D Gaussian kernel.
Parameters
----------
aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol]
Description of input 1.
varNumVol : float, positive
Description of input 2.
varTr : float, positive
Description of input 1.
tplPngSize : tuple
Description of input 1.
varNumMtDrctn : int, positive
Description of input 1.
switchHrfSet :
Description of input 1.
lgcOldSchoolHrf : int, positive
Description of input 1.
varPar : int, positive
Description of input 1.
Returns
-------
data : 2d numpy array, shape [n_samples, n_measurements]
Closed data.
Reference
---------
[1]
"""
print('------Convolve every pixel box car function with hrf function(s)')
# Create hrf time course function:
if switchHrfSet == 3:
lstHrf = [spmt, dspmt, ddspmt]
elif switchHrfSet == 2:
lstHrf = [spmt, dspmt]
elif switchHrfSet == 1:
lstHrf = [spmt]
# adjust the input, if necessary, such that input is 2D, with last dim time
tplInpShp = aryNrlTc.shape
aryNrlTc = np.reshape(aryNrlTc, (-1, aryNrlTc.shape[-1]))
# Put input data into chunks:
lstNrlTc = np.array_split(aryNrlTc, varPar)
# Create a queue to put the results in:
queOut = mp.Queue()
# Empty list for processes:
lstPrcs = [None] * varPar
# Empty list for results of parallel processes:
lstConv = [None] * varPar
print('---------Creating parallel processes')
if lgcOldSchoolHrf:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvlTcOld,
args=(idxPrc,
lstNrlTc[idxPrc],
varTr,
varNumVol,
queOut)
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
else:
# Create processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvlTc,
args=(idxPrc,
lstNrlTc[idxPrc],
lstHrf,
varTr,
varNumVol,
queOut)
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
# Start processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].start()
# Collect results from queue:
for idxPrc in range(0, varPar):
lstConv[idxPrc] = queOut.get(True)
# Join processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].join()
print('---------Collecting results from parallel processes')
# Put output into correct order:
lstConv = sorted(lstConv)
# Concatenate convolved pixel time courses (into the same order
aryNrlTcConv = np.zeros((0, switchHrfSet, varNumVol))
for idxRes in range(0, varPar):
aryNrlTcConv = np.concatenate((aryNrlTcConv, lstConv[idxRes][1]),
axis=0)
# clean up
del(aryNrlTc)
del(lstConv)
# Reshape results:
tplOutShp = tplInpShp[:-2] + (varNumMtDrctn * len(lstHrf), ) + \
(tplInpShp[-1], )
# Return:
return np.reshape(aryNrlTcConv, tplOutShp) | python | def cnvlPwBoxCarFn(aryNrlTc, varNumVol, varTr, tplPngSize, varNumMtDrctn,
switchHrfSet, lgcOldSchoolHrf, varPar,):
"""Create 2D Gaussian kernel.
Parameters
----------
aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol]
Description of input 1.
varNumVol : float, positive
Description of input 2.
varTr : float, positive
Description of input 1.
tplPngSize : tuple
Description of input 1.
varNumMtDrctn : int, positive
Description of input 1.
switchHrfSet :
Description of input 1.
lgcOldSchoolHrf : int, positive
Description of input 1.
varPar : int, positive
Description of input 1.
Returns
-------
data : 2d numpy array, shape [n_samples, n_measurements]
Closed data.
Reference
---------
[1]
"""
print('------Convolve every pixel box car function with hrf function(s)')
# Create hrf time course function:
if switchHrfSet == 3:
lstHrf = [spmt, dspmt, ddspmt]
elif switchHrfSet == 2:
lstHrf = [spmt, dspmt]
elif switchHrfSet == 1:
lstHrf = [spmt]
# adjust the input, if necessary, such that input is 2D, with last dim time
tplInpShp = aryNrlTc.shape
aryNrlTc = np.reshape(aryNrlTc, (-1, aryNrlTc.shape[-1]))
# Put input data into chunks:
lstNrlTc = np.array_split(aryNrlTc, varPar)
# Create a queue to put the results in:
queOut = mp.Queue()
# Empty list for processes:
lstPrcs = [None] * varPar
# Empty list for results of parallel processes:
lstConv = [None] * varPar
print('---------Creating parallel processes')
if lgcOldSchoolHrf:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvlTcOld,
args=(idxPrc,
lstNrlTc[idxPrc],
varTr,
varNumVol,
queOut)
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
else:
# Create processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvlTc,
args=(idxPrc,
lstNrlTc[idxPrc],
lstHrf,
varTr,
varNumVol,
queOut)
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
# Start processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].start()
# Collect results from queue:
for idxPrc in range(0, varPar):
lstConv[idxPrc] = queOut.get(True)
# Join processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].join()
print('---------Collecting results from parallel processes')
# Put output into correct order:
lstConv = sorted(lstConv)
# Concatenate convolved pixel time courses (into the same order
aryNrlTcConv = np.zeros((0, switchHrfSet, varNumVol))
for idxRes in range(0, varPar):
aryNrlTcConv = np.concatenate((aryNrlTcConv, lstConv[idxRes][1]),
axis=0)
# clean up
del(aryNrlTc)
del(lstConv)
# Reshape results:
tplOutShp = tplInpShp[:-2] + (varNumMtDrctn * len(lstHrf), ) + \
(tplInpShp[-1], )
# Return:
return np.reshape(aryNrlTcConv, tplOutShp) | [
"def",
"cnvlPwBoxCarFn",
"(",
"aryNrlTc",
",",
"varNumVol",
",",
"varTr",
",",
"tplPngSize",
",",
"varNumMtDrctn",
",",
"switchHrfSet",
",",
"lgcOldSchoolHrf",
",",
"varPar",
",",
")",
":",
"print",
"(",
"'------Convolve every pixel box car function with hrf function(s)'",
")",
"# Create hrf time course function:",
"if",
"switchHrfSet",
"==",
"3",
":",
"lstHrf",
"=",
"[",
"spmt",
",",
"dspmt",
",",
"ddspmt",
"]",
"elif",
"switchHrfSet",
"==",
"2",
":",
"lstHrf",
"=",
"[",
"spmt",
",",
"dspmt",
"]",
"elif",
"switchHrfSet",
"==",
"1",
":",
"lstHrf",
"=",
"[",
"spmt",
"]",
"# adjust the input, if necessary, such that input is 2D, with last dim time",
"tplInpShp",
"=",
"aryNrlTc",
".",
"shape",
"aryNrlTc",
"=",
"np",
".",
"reshape",
"(",
"aryNrlTc",
",",
"(",
"-",
"1",
",",
"aryNrlTc",
".",
"shape",
"[",
"-",
"1",
"]",
")",
")",
"# Put input data into chunks:",
"lstNrlTc",
"=",
"np",
".",
"array_split",
"(",
"aryNrlTc",
",",
"varPar",
")",
"# Create a queue to put the results in:",
"queOut",
"=",
"mp",
".",
"Queue",
"(",
")",
"# Empty list for processes:",
"lstPrcs",
"=",
"[",
"None",
"]",
"*",
"varPar",
"# Empty list for results of parallel processes:",
"lstConv",
"=",
"[",
"None",
"]",
"*",
"varPar",
"print",
"(",
"'---------Creating parallel processes'",
")",
"if",
"lgcOldSchoolHrf",
":",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
"=",
"mp",
".",
"Process",
"(",
"target",
"=",
"cnvlTcOld",
",",
"args",
"=",
"(",
"idxPrc",
",",
"lstNrlTc",
"[",
"idxPrc",
"]",
",",
"varTr",
",",
"varNumVol",
",",
"queOut",
")",
")",
"# Daemon (kills processes when exiting):",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"Daemon",
"=",
"True",
"else",
":",
"# Create processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
"=",
"mp",
".",
"Process",
"(",
"target",
"=",
"cnvlTc",
",",
"args",
"=",
"(",
"idxPrc",
",",
"lstNrlTc",
"[",
"idxPrc",
"]",
",",
"lstHrf",
",",
"varTr",
",",
"varNumVol",
",",
"queOut",
")",
")",
"# Daemon (kills processes when exiting):",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"Daemon",
"=",
"True",
"# Start processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"start",
"(",
")",
"# Collect results from queue:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstConv",
"[",
"idxPrc",
"]",
"=",
"queOut",
".",
"get",
"(",
"True",
")",
"# Join processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"join",
"(",
")",
"print",
"(",
"'---------Collecting results from parallel processes'",
")",
"# Put output into correct order:",
"lstConv",
"=",
"sorted",
"(",
"lstConv",
")",
"# Concatenate convolved pixel time courses (into the same order",
"aryNrlTcConv",
"=",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"switchHrfSet",
",",
"varNumVol",
")",
")",
"for",
"idxRes",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"aryNrlTcConv",
"=",
"np",
".",
"concatenate",
"(",
"(",
"aryNrlTcConv",
",",
"lstConv",
"[",
"idxRes",
"]",
"[",
"1",
"]",
")",
",",
"axis",
"=",
"0",
")",
"# clean up",
"del",
"(",
"aryNrlTc",
")",
"del",
"(",
"lstConv",
")",
"# Reshape results:",
"tplOutShp",
"=",
"tplInpShp",
"[",
":",
"-",
"2",
"]",
"+",
"(",
"varNumMtDrctn",
"*",
"len",
"(",
"lstHrf",
")",
",",
")",
"+",
"(",
"tplInpShp",
"[",
"-",
"1",
"]",
",",
")",
"# Return:",
"return",
"np",
".",
"reshape",
"(",
"aryNrlTcConv",
",",
"tplOutShp",
")"
] | Create 2D Gaussian kernel.
Parameters
----------
aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol]
Description of input 1.
varNumVol : float, positive
Description of input 2.
varTr : float, positive
Description of input 1.
tplPngSize : tuple
Description of input 1.
varNumMtDrctn : int, positive
Description of input 1.
switchHrfSet :
Description of input 1.
lgcOldSchoolHrf : int, positive
Description of input 1.
varPar : int, positive
Description of input 1.
Returns
-------
data : 2d numpy array, shape [n_samples, n_measurements]
Closed data.
Reference
---------
[1] | [
"Create",
"2D",
"Gaussian",
"kernel",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/old/pRF_mdlCrt.py#L448-L562 |
MSchnei/pyprf_feature | pyprf_feature/analysis/old/pRF_mdlCrt.py | rsmplInHighRes | def rsmplInHighRes(aryBoxCarConv,
tplPngSize,
tplVslSpcHighSze,
varNumMtDrctn,
varNumVol):
"""Resample pixel-time courses in high-res visual space.
Parameters
----------
input1 : 2d numpy array, shape [n_samples, n_measurements]
Description of input 1.
input2 : float, positive
Description of input 2.
Returns
-------
data : 2d numpy array, shape [n_samples, n_measurements]
Closed data.
Reference
---------
[1]
"""
# Array for super-sampled pixel-time courses:
aryBoxCarConvHigh = np.zeros((tplVslSpcHighSze[0],
tplVslSpcHighSze[1],
varNumMtDrctn,
varNumVol))
# Loop through volumes:
for idxMtn in range(0, varNumMtDrctn):
for idxVol in range(0, varNumVol):
# Range for the coordinates:
vecRange = np.arange(0, tplPngSize[0])
# The following array describes the coordinates of the pixels in
# the flattened array (i.e. "vecOrigPixVal"). In other words, these
# are the row and column coordinates of the original pizel values.
crd2, crd1 = np.meshgrid(vecRange, vecRange)
aryOrixPixCoo = np.column_stack((crd1.flatten(), crd2.flatten()))
# The following vector will contain the actual original pixel
# values:
vecOrigPixVal = aryBoxCarConv[:, :, idxMtn, idxVol]
vecOrigPixVal = vecOrigPixVal.flatten()
# The sampling interval for the creation of the super-sampled pixel
# data (complex numbers are used as a convention for inclusive
# intervals in "np.mgrid()").:
varStpSzeX = np.complex(tplVslSpcHighSze[0])
varStpSzeY = np.complex(tplVslSpcHighSze[1])
# The following grid has the coordinates of the points at which we
# would like to re-sample the pixel data:
aryPixGridX, aryPixGridY = np.mgrid[0:tplPngSize[0]:varStpSzeX,
0:tplPngSize[1]:varStpSzeY]
# The actual resampling:
aryResampled = griddata(aryOrixPixCoo,
vecOrigPixVal,
(aryPixGridX, aryPixGridY),
method='nearest')
# Put super-sampled pixel time courses into array:
aryBoxCarConvHigh[:, :, idxMtn, idxVol] = aryResampled
return aryBoxCarConvHigh | python | def rsmplInHighRes(aryBoxCarConv,
tplPngSize,
tplVslSpcHighSze,
varNumMtDrctn,
varNumVol):
"""Resample pixel-time courses in high-res visual space.
Parameters
----------
input1 : 2d numpy array, shape [n_samples, n_measurements]
Description of input 1.
input2 : float, positive
Description of input 2.
Returns
-------
data : 2d numpy array, shape [n_samples, n_measurements]
Closed data.
Reference
---------
[1]
"""
# Array for super-sampled pixel-time courses:
aryBoxCarConvHigh = np.zeros((tplVslSpcHighSze[0],
tplVslSpcHighSze[1],
varNumMtDrctn,
varNumVol))
# Loop through volumes:
for idxMtn in range(0, varNumMtDrctn):
for idxVol in range(0, varNumVol):
# Range for the coordinates:
vecRange = np.arange(0, tplPngSize[0])
# The following array describes the coordinates of the pixels in
# the flattened array (i.e. "vecOrigPixVal"). In other words, these
# are the row and column coordinates of the original pizel values.
crd2, crd1 = np.meshgrid(vecRange, vecRange)
aryOrixPixCoo = np.column_stack((crd1.flatten(), crd2.flatten()))
# The following vector will contain the actual original pixel
# values:
vecOrigPixVal = aryBoxCarConv[:, :, idxMtn, idxVol]
vecOrigPixVal = vecOrigPixVal.flatten()
# The sampling interval for the creation of the super-sampled pixel
# data (complex numbers are used as a convention for inclusive
# intervals in "np.mgrid()").:
varStpSzeX = np.complex(tplVslSpcHighSze[0])
varStpSzeY = np.complex(tplVslSpcHighSze[1])
# The following grid has the coordinates of the points at which we
# would like to re-sample the pixel data:
aryPixGridX, aryPixGridY = np.mgrid[0:tplPngSize[0]:varStpSzeX,
0:tplPngSize[1]:varStpSzeY]
# The actual resampling:
aryResampled = griddata(aryOrixPixCoo,
vecOrigPixVal,
(aryPixGridX, aryPixGridY),
method='nearest')
# Put super-sampled pixel time courses into array:
aryBoxCarConvHigh[:, :, idxMtn, idxVol] = aryResampled
return aryBoxCarConvHigh | [
"def",
"rsmplInHighRes",
"(",
"aryBoxCarConv",
",",
"tplPngSize",
",",
"tplVslSpcHighSze",
",",
"varNumMtDrctn",
",",
"varNumVol",
")",
":",
"# Array for super-sampled pixel-time courses:",
"aryBoxCarConvHigh",
"=",
"np",
".",
"zeros",
"(",
"(",
"tplVslSpcHighSze",
"[",
"0",
"]",
",",
"tplVslSpcHighSze",
"[",
"1",
"]",
",",
"varNumMtDrctn",
",",
"varNumVol",
")",
")",
"# Loop through volumes:",
"for",
"idxMtn",
"in",
"range",
"(",
"0",
",",
"varNumMtDrctn",
")",
":",
"for",
"idxVol",
"in",
"range",
"(",
"0",
",",
"varNumVol",
")",
":",
"# Range for the coordinates:",
"vecRange",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"tplPngSize",
"[",
"0",
"]",
")",
"# The following array describes the coordinates of the pixels in",
"# the flattened array (i.e. \"vecOrigPixVal\"). In other words, these",
"# are the row and column coordinates of the original pizel values.",
"crd2",
",",
"crd1",
"=",
"np",
".",
"meshgrid",
"(",
"vecRange",
",",
"vecRange",
")",
"aryOrixPixCoo",
"=",
"np",
".",
"column_stack",
"(",
"(",
"crd1",
".",
"flatten",
"(",
")",
",",
"crd2",
".",
"flatten",
"(",
")",
")",
")",
"# The following vector will contain the actual original pixel",
"# values:",
"vecOrigPixVal",
"=",
"aryBoxCarConv",
"[",
":",
",",
":",
",",
"idxMtn",
",",
"idxVol",
"]",
"vecOrigPixVal",
"=",
"vecOrigPixVal",
".",
"flatten",
"(",
")",
"# The sampling interval for the creation of the super-sampled pixel",
"# data (complex numbers are used as a convention for inclusive",
"# intervals in \"np.mgrid()\").:",
"varStpSzeX",
"=",
"np",
".",
"complex",
"(",
"tplVslSpcHighSze",
"[",
"0",
"]",
")",
"varStpSzeY",
"=",
"np",
".",
"complex",
"(",
"tplVslSpcHighSze",
"[",
"1",
"]",
")",
"# The following grid has the coordinates of the points at which we",
"# would like to re-sample the pixel data:",
"aryPixGridX",
",",
"aryPixGridY",
"=",
"np",
".",
"mgrid",
"[",
"0",
":",
"tplPngSize",
"[",
"0",
"]",
":",
"varStpSzeX",
",",
"0",
":",
"tplPngSize",
"[",
"1",
"]",
":",
"varStpSzeY",
"]",
"# The actual resampling:",
"aryResampled",
"=",
"griddata",
"(",
"aryOrixPixCoo",
",",
"vecOrigPixVal",
",",
"(",
"aryPixGridX",
",",
"aryPixGridY",
")",
",",
"method",
"=",
"'nearest'",
")",
"# Put super-sampled pixel time courses into array:",
"aryBoxCarConvHigh",
"[",
":",
",",
":",
",",
"idxMtn",
",",
"idxVol",
"]",
"=",
"aryResampled",
"return",
"aryBoxCarConvHigh"
] | Resample pixel-time courses in high-res visual space.
Parameters
----------
input1 : 2d numpy array, shape [n_samples, n_measurements]
Description of input 1.
input2 : float, positive
Description of input 2.
Returns
-------
data : 2d numpy array, shape [n_samples, n_measurements]
Closed data.
Reference
---------
[1] | [
"Resample",
"pixel",
"-",
"time",
"courses",
"in",
"high",
"-",
"res",
"visual",
"space",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/old/pRF_mdlCrt.py#L565-L633 |
MSchnei/pyprf_feature | pyprf_feature/analysis/pyprf_sim_ep.py | get_arg_parse | def get_arg_parse():
"""Parses the Command Line Arguments using argparse."""
# Create parser object:
objParser = argparse.ArgumentParser()
# Add argument to namespace -strCsvPrf results file path:
objParser.add_argument('-strCsvPrf', required=True,
metavar='/path/to/my_prior_res',
help='Absolute file path of prior pRF results. \
Ignored if in testing mode.'
)
# Add argument to namespace -strStmApr results file path:
objParser.add_argument('-strStmApr', required=True,
metavar='/path/to/my_prior_res',
help='Absolute file path to npy file with \
stimulus apertures. Ignored if in testing \
mode.'
)
# Add argument to namespace -lgcNoise flag:
objParser.add_argument('-lgcNoise', dest='lgcNoise',
action='store_true', default=False,
help='Should noise be added to the simulated pRF\
time course?')
# Add argument to namespace -lgcRtnNrl flag:
objParser.add_argument('-lgcRtnNrl', dest='lgcRtnNrl',
action='store_true', default=False,
help='Should neural time course, unconvolved with \
hrf, be returned as well?')
objParser.add_argument('-supsur', nargs='+',
help='List of floats that represent the ratio of \
size neg surround to size pos center.',
type=float, default=None)
# Namespace object containign arguments and values:
objNspc = objParser.parse_args()
return objNspc | python | def get_arg_parse():
"""Parses the Command Line Arguments using argparse."""
# Create parser object:
objParser = argparse.ArgumentParser()
# Add argument to namespace -strCsvPrf results file path:
objParser.add_argument('-strCsvPrf', required=True,
metavar='/path/to/my_prior_res',
help='Absolute file path of prior pRF results. \
Ignored if in testing mode.'
)
# Add argument to namespace -strStmApr results file path:
objParser.add_argument('-strStmApr', required=True,
metavar='/path/to/my_prior_res',
help='Absolute file path to npy file with \
stimulus apertures. Ignored if in testing \
mode.'
)
# Add argument to namespace -lgcNoise flag:
objParser.add_argument('-lgcNoise', dest='lgcNoise',
action='store_true', default=False,
help='Should noise be added to the simulated pRF\
time course?')
# Add argument to namespace -lgcRtnNrl flag:
objParser.add_argument('-lgcRtnNrl', dest='lgcRtnNrl',
action='store_true', default=False,
help='Should neural time course, unconvolved with \
hrf, be returned as well?')
objParser.add_argument('-supsur', nargs='+',
help='List of floats that represent the ratio of \
size neg surround to size pos center.',
type=float, default=None)
# Namespace object containign arguments and values:
objNspc = objParser.parse_args()
return objNspc | [
"def",
"get_arg_parse",
"(",
")",
":",
"# Create parser object:",
"objParser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"# Add argument to namespace -strCsvPrf results file path:",
"objParser",
".",
"add_argument",
"(",
"'-strCsvPrf'",
",",
"required",
"=",
"True",
",",
"metavar",
"=",
"'/path/to/my_prior_res'",
",",
"help",
"=",
"'Absolute file path of prior pRF results. \\\n Ignored if in testing mode.'",
")",
"# Add argument to namespace -strStmApr results file path:",
"objParser",
".",
"add_argument",
"(",
"'-strStmApr'",
",",
"required",
"=",
"True",
",",
"metavar",
"=",
"'/path/to/my_prior_res'",
",",
"help",
"=",
"'Absolute file path to npy file with \\\n stimulus apertures. Ignored if in testing \\\n mode.'",
")",
"# Add argument to namespace -lgcNoise flag:",
"objParser",
".",
"add_argument",
"(",
"'-lgcNoise'",
",",
"dest",
"=",
"'lgcNoise'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Should noise be added to the simulated pRF\\\n time course?'",
")",
"# Add argument to namespace -lgcRtnNrl flag:",
"objParser",
".",
"add_argument",
"(",
"'-lgcRtnNrl'",
",",
"dest",
"=",
"'lgcRtnNrl'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Should neural time course, unconvolved with \\\n hrf, be returned as well?'",
")",
"objParser",
".",
"add_argument",
"(",
"'-supsur'",
",",
"nargs",
"=",
"'+'",
",",
"help",
"=",
"'List of floats that represent the ratio of \\\n size neg surround to size pos center.'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"None",
")",
"# Namespace object containign arguments and values:",
"objNspc",
"=",
"objParser",
".",
"parse_args",
"(",
")",
"return",
"objNspc"
] | Parses the Command Line Arguments using argparse. | [
"Parses",
"the",
"Command",
"Line",
"Arguments",
"using",
"argparse",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/pyprf_sim_ep.py#L14-L54 |
MSchnei/pyprf_feature | pyprf_feature/analysis/pyprf_sim_ep.py | main | def main():
"""pyprf_sim entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
# input arguments, but since we use 'argparse' it is redundant.
# lstArgs = sys.argv[1:]
strWelcome = 'pyprf_sim ' + __version__
strDec = '=' * len(strWelcome)
print(strDec + '\n' + strWelcome + '\n' + strDec)
objNspc = get_arg_parse()
# Print info if no config argument is provided.
if any(item is None for item in [objNspc.strCsvPrf, objNspc.strStmApr]):
print('Please provide necessary file paths, e.g.:')
print(' pyprf_sim -strCsvPrf /path/to/my_config_file.csv')
print(' -strStmApr /path/to/my_stim_apertures.npy')
else:
# Signal non-test mode to lower functions (needed for pytest):
lgcTest = False
# Call to main function, to invoke pRF analysis:
pyprf_sim(objNspc.strCsvPrf, objNspc.strStmApr, lgcTest=lgcTest,
lgcNoise=objNspc.lgcNoise, lgcRtnNrl=objNspc.lgcRtnNrl,
lstRat=objNspc.supsur) | python | def main():
"""pyprf_sim entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
# input arguments, but since we use 'argparse' it is redundant.
# lstArgs = sys.argv[1:]
strWelcome = 'pyprf_sim ' + __version__
strDec = '=' * len(strWelcome)
print(strDec + '\n' + strWelcome + '\n' + strDec)
objNspc = get_arg_parse()
# Print info if no config argument is provided.
if any(item is None for item in [objNspc.strCsvPrf, objNspc.strStmApr]):
print('Please provide necessary file paths, e.g.:')
print(' pyprf_sim -strCsvPrf /path/to/my_config_file.csv')
print(' -strStmApr /path/to/my_stim_apertures.npy')
else:
# Signal non-test mode to lower functions (needed for pytest):
lgcTest = False
# Call to main function, to invoke pRF analysis:
pyprf_sim(objNspc.strCsvPrf, objNspc.strStmApr, lgcTest=lgcTest,
lgcNoise=objNspc.lgcNoise, lgcRtnNrl=objNspc.lgcRtnNrl,
lstRat=objNspc.supsur) | [
"def",
"main",
"(",
")",
":",
"# Get list of input arguments (without first one, which is the path to the",
"# function that is called): --NOTE: This is another way of accessing",
"# input arguments, but since we use 'argparse' it is redundant.",
"# lstArgs = sys.argv[1:]",
"strWelcome",
"=",
"'pyprf_sim '",
"+",
"__version__",
"strDec",
"=",
"'='",
"*",
"len",
"(",
"strWelcome",
")",
"print",
"(",
"strDec",
"+",
"'\\n'",
"+",
"strWelcome",
"+",
"'\\n'",
"+",
"strDec",
")",
"objNspc",
"=",
"get_arg_parse",
"(",
")",
"# Print info if no config argument is provided.",
"if",
"any",
"(",
"item",
"is",
"None",
"for",
"item",
"in",
"[",
"objNspc",
".",
"strCsvPrf",
",",
"objNspc",
".",
"strStmApr",
"]",
")",
":",
"print",
"(",
"'Please provide necessary file paths, e.g.:'",
")",
"print",
"(",
"' pyprf_sim -strCsvPrf /path/to/my_config_file.csv'",
")",
"print",
"(",
"' -strStmApr /path/to/my_stim_apertures.npy'",
")",
"else",
":",
"# Signal non-test mode to lower functions (needed for pytest):",
"lgcTest",
"=",
"False",
"# Call to main function, to invoke pRF analysis:",
"pyprf_sim",
"(",
"objNspc",
".",
"strCsvPrf",
",",
"objNspc",
".",
"strStmApr",
",",
"lgcTest",
"=",
"lgcTest",
",",
"lgcNoise",
"=",
"objNspc",
".",
"lgcNoise",
",",
"lgcRtnNrl",
"=",
"objNspc",
".",
"lgcRtnNrl",
",",
"lstRat",
"=",
"objNspc",
".",
"supsur",
")"
] | pyprf_sim entry point. | [
"pyprf_sim",
"entry",
"point",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/pyprf_sim_ep.py#L57-L83 |
lvieirajr/mongorest | mongorest/decorators.py | login_required | def login_required(wrapped):
"""
Requires that the user is logged in and authorized to execute requests
Except if the method is in authorized_methods of the auth_collection
Then he can execute the requests even not being authorized
"""
@wraps(wrapped)
def wrapper(*args, **kwargs):
request = args[1]
auth_collection = settings.AUTH_COLLECTION[
settings.AUTH_COLLECTION.rfind('.') + 1:
].lower()
auth_document = request.environ.get(auth_collection)
if auth_document and auth_document.is_authorized(request):
setattr(request, auth_collection, auth_document)
return wrapped(*args, **kwargs)
return Response(response=serialize(UnauthorizedError()), status=401)
if hasattr(wrapped, 'decorators'):
wrapper.decorators = wrapped.decorators
wrapper.decorators.append('login_required')
else:
wrapper.decorators = ['login_required']
return wrapper | python | def login_required(wrapped):
"""
Requires that the user is logged in and authorized to execute requests
Except if the method is in authorized_methods of the auth_collection
Then he can execute the requests even not being authorized
"""
@wraps(wrapped)
def wrapper(*args, **kwargs):
request = args[1]
auth_collection = settings.AUTH_COLLECTION[
settings.AUTH_COLLECTION.rfind('.') + 1:
].lower()
auth_document = request.environ.get(auth_collection)
if auth_document and auth_document.is_authorized(request):
setattr(request, auth_collection, auth_document)
return wrapped(*args, **kwargs)
return Response(response=serialize(UnauthorizedError()), status=401)
if hasattr(wrapped, 'decorators'):
wrapper.decorators = wrapped.decorators
wrapper.decorators.append('login_required')
else:
wrapper.decorators = ['login_required']
return wrapper | [
"def",
"login_required",
"(",
"wrapped",
")",
":",
"@",
"wraps",
"(",
"wrapped",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"args",
"[",
"1",
"]",
"auth_collection",
"=",
"settings",
".",
"AUTH_COLLECTION",
"[",
"settings",
".",
"AUTH_COLLECTION",
".",
"rfind",
"(",
"'.'",
")",
"+",
"1",
":",
"]",
".",
"lower",
"(",
")",
"auth_document",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"auth_collection",
")",
"if",
"auth_document",
"and",
"auth_document",
".",
"is_authorized",
"(",
"request",
")",
":",
"setattr",
"(",
"request",
",",
"auth_collection",
",",
"auth_document",
")",
"return",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"Response",
"(",
"response",
"=",
"serialize",
"(",
"UnauthorizedError",
"(",
")",
")",
",",
"status",
"=",
"401",
")",
"if",
"hasattr",
"(",
"wrapped",
",",
"'decorators'",
")",
":",
"wrapper",
".",
"decorators",
"=",
"wrapped",
".",
"decorators",
"wrapper",
".",
"decorators",
".",
"append",
"(",
"'login_required'",
")",
"else",
":",
"wrapper",
".",
"decorators",
"=",
"[",
"'login_required'",
"]",
"return",
"wrapper"
] | Requires that the user is logged in and authorized to execute requests
Except if the method is in authorized_methods of the auth_collection
Then he can execute the requests even not being authorized | [
"Requires",
"that",
"the",
"user",
"is",
"logged",
"in",
"and",
"authorized",
"to",
"execute",
"requests",
"Except",
"if",
"the",
"method",
"is",
"in",
"authorized_methods",
"of",
"the",
"auth_collection",
"Then",
"he",
"can",
"execute",
"the",
"requests",
"even",
"not",
"being",
"authorized"
] | train | https://github.com/lvieirajr/mongorest/blob/00f4487ded33254434bc51ff09d48c7a936bd465/mongorest/decorators.py#L17-L44 |
lvieirajr/mongorest | mongorest/decorators.py | serializable | def serializable(wrapped):
"""
If a keyword argument 'serialize' with a True value is passed to the
Wrapped function, the return of the wrapped function will be serialized.
Nothing happens if the argument is not passed or the value is not True
"""
@wraps(wrapped)
def wrapper(*args, **kwargs):
should_serialize = kwargs.pop('serialize', False)
result = wrapped(*args, **kwargs)
return serialize(result) if should_serialize else result
if hasattr(wrapped, 'decorators'):
wrapper.decorators = wrapped.decorators
wrapper.decorators.append('serializable')
else:
wrapper.decorators = ['serializable']
return wrapper | python | def serializable(wrapped):
"""
If a keyword argument 'serialize' with a True value is passed to the
Wrapped function, the return of the wrapped function will be serialized.
Nothing happens if the argument is not passed or the value is not True
"""
@wraps(wrapped)
def wrapper(*args, **kwargs):
should_serialize = kwargs.pop('serialize', False)
result = wrapped(*args, **kwargs)
return serialize(result) if should_serialize else result
if hasattr(wrapped, 'decorators'):
wrapper.decorators = wrapped.decorators
wrapper.decorators.append('serializable')
else:
wrapper.decorators = ['serializable']
return wrapper | [
"def",
"serializable",
"(",
"wrapped",
")",
":",
"@",
"wraps",
"(",
"wrapped",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"should_serialize",
"=",
"kwargs",
".",
"pop",
"(",
"'serialize'",
",",
"False",
")",
"result",
"=",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"serialize",
"(",
"result",
")",
"if",
"should_serialize",
"else",
"result",
"if",
"hasattr",
"(",
"wrapped",
",",
"'decorators'",
")",
":",
"wrapper",
".",
"decorators",
"=",
"wrapped",
".",
"decorators",
"wrapper",
".",
"decorators",
".",
"append",
"(",
"'serializable'",
")",
"else",
":",
"wrapper",
".",
"decorators",
"=",
"[",
"'serializable'",
"]",
"return",
"wrapper"
] | If a keyword argument 'serialize' with a True value is passed to the
Wrapped function, the return of the wrapped function will be serialized.
Nothing happens if the argument is not passed or the value is not True | [
"If",
"a",
"keyword",
"argument",
"serialize",
"with",
"a",
"True",
"value",
"is",
"passed",
"to",
"the",
"Wrapped",
"function",
"the",
"return",
"of",
"the",
"wrapped",
"function",
"will",
"be",
"serialized",
".",
"Nothing",
"happens",
"if",
"the",
"argument",
"is",
"not",
"passed",
"or",
"the",
"value",
"is",
"not",
"True"
] | train | https://github.com/lvieirajr/mongorest/blob/00f4487ded33254434bc51ff09d48c7a936bd465/mongorest/decorators.py#L47-L67 |
lvieirajr/mongorest | mongorest/utils.py | deserialize | def deserialize(to_deserialize, *args, **kwargs):
"""
Deserializes a string into a PyMongo BSON
"""
if isinstance(to_deserialize, string_types):
if re.match('^[0-9a-f]{24}$', to_deserialize):
return ObjectId(to_deserialize)
try:
return bson_loads(to_deserialize, *args, **kwargs)
except:
return bson_loads(bson_dumps(to_deserialize), *args, **kwargs)
else:
return bson_loads(bson_dumps(to_deserialize), *args, **kwargs) | python | def deserialize(to_deserialize, *args, **kwargs):
"""
Deserializes a string into a PyMongo BSON
"""
if isinstance(to_deserialize, string_types):
if re.match('^[0-9a-f]{24}$', to_deserialize):
return ObjectId(to_deserialize)
try:
return bson_loads(to_deserialize, *args, **kwargs)
except:
return bson_loads(bson_dumps(to_deserialize), *args, **kwargs)
else:
return bson_loads(bson_dumps(to_deserialize), *args, **kwargs) | [
"def",
"deserialize",
"(",
"to_deserialize",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"to_deserialize",
",",
"string_types",
")",
":",
"if",
"re",
".",
"match",
"(",
"'^[0-9a-f]{24}$'",
",",
"to_deserialize",
")",
":",
"return",
"ObjectId",
"(",
"to_deserialize",
")",
"try",
":",
"return",
"bson_loads",
"(",
"to_deserialize",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
":",
"return",
"bson_loads",
"(",
"bson_dumps",
"(",
"to_deserialize",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"bson_loads",
"(",
"bson_dumps",
"(",
"to_deserialize",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Deserializes a string into a PyMongo BSON | [
"Deserializes",
"a",
"string",
"into",
"a",
"PyMongo",
"BSON"
] | train | https://github.com/lvieirajr/mongorest/blob/00f4487ded33254434bc51ff09d48c7a936bd465/mongorest/utils.py#L16-L28 |
musically-ut/seqfile | seqfile/seqfile.py | _doAtomicFileCreation | def _doAtomicFileCreation(filePath):
"""Tries to atomically create the requested file."""
try:
_os.close(_os.open(filePath, _os.O_CREAT | _os.O_EXCL))
return True
except OSError as e:
if e.errno == _errno.EEXIST:
return False
else:
raise e | python | def _doAtomicFileCreation(filePath):
"""Tries to atomically create the requested file."""
try:
_os.close(_os.open(filePath, _os.O_CREAT | _os.O_EXCL))
return True
except OSError as e:
if e.errno == _errno.EEXIST:
return False
else:
raise e | [
"def",
"_doAtomicFileCreation",
"(",
"filePath",
")",
":",
"try",
":",
"_os",
".",
"close",
"(",
"_os",
".",
"open",
"(",
"filePath",
",",
"_os",
".",
"O_CREAT",
"|",
"_os",
".",
"O_EXCL",
")",
")",
"return",
"True",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"_errno",
".",
"EEXIST",
":",
"return",
"False",
"else",
":",
"raise",
"e"
] | Tries to atomically create the requested file. | [
"Tries",
"to",
"atomically",
"create",
"the",
"requested",
"file",
"."
] | train | https://github.com/musically-ut/seqfile/blob/796e366fe8871b6dc72cb6bbc570e4a61a8f947c/seqfile/seqfile.py#L11-L20 |
musically-ut/seqfile | seqfile/seqfile.py | findNextFile | def findNextFile(folder='.',
prefix=None,
suffix=None,
fnameGen=None,
base=0,
maxattempts=10):
"""Finds the next available file-name in a sequence.
This function will create a file of zero size and will return the path to
it to the caller. No files which exist will be altered in this operation
and concurrent executions of this function will return separate files. In
case of conflict, the function will attempt to generate a new file name up
to maxattempts number of times before failing.
The sequence will start from the base argument (default: 0).
If used with the prefix/suffix, it will look for the next file in the
sequence ignoring any gaps. Hence, if the files "a.0.txt" and "a.3.txt"
exist, then the next file returned will be "a.4.txt" when called with
prefix="a." and suffix=".txt".
In case fnameGen is provided, the first generated filename which does not
exist will be created and its path will be returned. Hence, if the files
"a.0.txt" and "a.3.txt" exist, then the next file returned will be
"a.1.txt" when called with fnameGen = lambda x : "a." + str(x) + ".txt"
Args:
folder - string which has path to the folder where the file should
be created (default: '.')
prefix - prefix of the file to be generated (default: '')
suffix - suffix of the file to be generated (default: '')
fnameGen - function which generates the filenames given a number as
input (default: None)
base - the first index to count (default: 0)
maxattempts - number of attempts to create the file before failing with
OSError (default: 10)
Returns:
Path of the file which follows the provided pattern and can be opened
for writing.
Raises:
RuntimeError - If an incorrect combination of arguments is provided.
OSError - If is unable to create a file (wrong path, drive full,
illegal character in filename, etc.).
"""
expFolder = _os.path.expanduser(_os.path.expandvars(folder))
return _findNextFile(expFolder, prefix, suffix, fnameGen,
base, maxattempts, 0) | python | def findNextFile(folder='.',
prefix=None,
suffix=None,
fnameGen=None,
base=0,
maxattempts=10):
"""Finds the next available file-name in a sequence.
This function will create a file of zero size and will return the path to
it to the caller. No files which exist will be altered in this operation
and concurrent executions of this function will return separate files. In
case of conflict, the function will attempt to generate a new file name up
to maxattempts number of times before failing.
The sequence will start from the base argument (default: 0).
If used with the prefix/suffix, it will look for the next file in the
sequence ignoring any gaps. Hence, if the files "a.0.txt" and "a.3.txt"
exist, then the next file returned will be "a.4.txt" when called with
prefix="a." and suffix=".txt".
In case fnameGen is provided, the first generated filename which does not
exist will be created and its path will be returned. Hence, if the files
"a.0.txt" and "a.3.txt" exist, then the next file returned will be
"a.1.txt" when called with fnameGen = lambda x : "a." + str(x) + ".txt"
Args:
folder - string which has path to the folder where the file should
be created (default: '.')
prefix - prefix of the file to be generated (default: '')
suffix - suffix of the file to be generated (default: '')
fnameGen - function which generates the filenames given a number as
input (default: None)
base - the first index to count (default: 0)
maxattempts - number of attempts to create the file before failing with
OSError (default: 10)
Returns:
Path of the file which follows the provided pattern and can be opened
for writing.
Raises:
RuntimeError - If an incorrect combination of arguments is provided.
OSError - If is unable to create a file (wrong path, drive full,
illegal character in filename, etc.).
"""
expFolder = _os.path.expanduser(_os.path.expandvars(folder))
return _findNextFile(expFolder, prefix, suffix, fnameGen,
base, maxattempts, 0) | [
"def",
"findNextFile",
"(",
"folder",
"=",
"'.'",
",",
"prefix",
"=",
"None",
",",
"suffix",
"=",
"None",
",",
"fnameGen",
"=",
"None",
",",
"base",
"=",
"0",
",",
"maxattempts",
"=",
"10",
")",
":",
"expFolder",
"=",
"_os",
".",
"path",
".",
"expanduser",
"(",
"_os",
".",
"path",
".",
"expandvars",
"(",
"folder",
")",
")",
"return",
"_findNextFile",
"(",
"expFolder",
",",
"prefix",
",",
"suffix",
",",
"fnameGen",
",",
"base",
",",
"maxattempts",
",",
"0",
")"
] | Finds the next available file-name in a sequence.
This function will create a file of zero size and will return the path to
it to the caller. No files which exist will be altered in this operation
and concurrent executions of this function will return separate files. In
case of conflict, the function will attempt to generate a new file name up
to maxattempts number of times before failing.
The sequence will start from the base argument (default: 0).
If used with the prefix/suffix, it will look for the next file in the
sequence ignoring any gaps. Hence, if the files "a.0.txt" and "a.3.txt"
exist, then the next file returned will be "a.4.txt" when called with
prefix="a." and suffix=".txt".
In case fnameGen is provided, the first generated filename which does not
exist will be created and its path will be returned. Hence, if the files
"a.0.txt" and "a.3.txt" exist, then the next file returned will be
"a.1.txt" when called with fnameGen = lambda x : "a." + str(x) + ".txt"
Args:
folder - string which has path to the folder where the file should
be created (default: '.')
prefix - prefix of the file to be generated (default: '')
suffix - suffix of the file to be generated (default: '')
fnameGen - function which generates the filenames given a number as
input (default: None)
base - the first index to count (default: 0)
maxattempts - number of attempts to create the file before failing with
OSError (default: 10)
Returns:
Path of the file which follows the provided pattern and can be opened
for writing.
Raises:
RuntimeError - If an incorrect combination of arguments is provided.
OSError - If is unable to create a file (wrong path, drive full,
illegal character in filename, etc.). | [
"Finds",
"the",
"next",
"available",
"file",
"-",
"name",
"in",
"a",
"sequence",
"."
] | train | https://github.com/musically-ut/seqfile/blob/796e366fe8871b6dc72cb6bbc570e4a61a8f947c/seqfile/seqfile.py#L97-L145 |
musically-ut/seqfile | seqfile/seqfile.py | _run | def _run(passedArgs=None, stderr=None, stdout=None, exitFn=None):
"""Executes the script, gets prefix/suffix from the command prompt and
produces output on STDOUT. For help with command line options, invoke
script with '--help'.
"""
description = """Finds the next available file-name in a sequence.
This program will create a file of zero size and will output the path to it
on STDOUT. No files which exist will be altered in this operation and
concurrent invocations of this program will return separate files. In case
of conflict, this program will attempt to generate a new file name up to
'maxattempts' number of times before failing. (See --max-attempts)
The sequence will start from the base argument (See --base, default: 0).
This program will look for the next file in the sequence ignoring any gaps.
Hence, if the files "a.0.txt" and "a.3.txt" exist, then the next file
returned will be "a.4.txt" when called with prefix="a." and suffix=".txt".
Returns:
Path of the file which follows the provided pattern and can be opened
for writing.
Otherwise, it prints an error (wrong path, drive full, illegal
character in filename, etc.) to stderr and exits with a non-zero error
code.
"""
argParser = _argparse.ArgumentParser(
description=description,
formatter_class=_argparse.RawTextHelpFormatter)
argParser.add_argument('prefix',
help='Prefix for the sequence of files.')
argParser.add_argument('suffix',
help='Suffix for the sequence of files.',
nargs='?',
default='')
argParser.add_argument('folder',
help='The folder where the file will be created.',
nargs='?',
default=_os.getcwd())
argParser.add_argument('-m', '--max-attempts',
help='Number of attempts to make before giving up.',
default=10)
argParser.add_argument('-b', '--base',
help='From where to start counting (default: 0).',
default=0)
passedArgs = passedArgs if passedArgs is not None else _sys.argv[1:]
args = argParser.parse_args(passedArgs)
stdout = _sys.stdout if stdout is None else stdout
stderr = _sys.stderr if stderr is None else stderr
try:
nextFile = findNextFile(args.folder, prefix=args.prefix,
suffix=args.suffix,
maxattempts=args.max_attempts,
base=args.base)
# The newline will be converted to the correct platform specific line
# ending as `sys.stdout` is opened in non-binary mode.
# Hence, we do not need to explicitly print out `\r\n` for Windows.
stdout.write(nextFile + u'\n')
except OSError as e:
stderr.write(_os.strerror(e.errno) + u'\n')
_sys.exit(e.errno) | python | def _run(passedArgs=None, stderr=None, stdout=None, exitFn=None):
"""Executes the script, gets prefix/suffix from the command prompt and
produces output on STDOUT. For help with command line options, invoke
script with '--help'.
"""
description = """Finds the next available file-name in a sequence.
This program will create a file of zero size and will output the path to it
on STDOUT. No files which exist will be altered in this operation and
concurrent invocations of this program will return separate files. In case
of conflict, this program will attempt to generate a new file name up to
'maxattempts' number of times before failing. (See --max-attempts)
The sequence will start from the base argument (See --base, default: 0).
This program will look for the next file in the sequence ignoring any gaps.
Hence, if the files "a.0.txt" and "a.3.txt" exist, then the next file
returned will be "a.4.txt" when called with prefix="a." and suffix=".txt".
Returns:
Path of the file which follows the provided pattern and can be opened
for writing.
Otherwise, it prints an error (wrong path, drive full, illegal
character in filename, etc.) to stderr and exits with a non-zero error
code.
"""
argParser = _argparse.ArgumentParser(
description=description,
formatter_class=_argparse.RawTextHelpFormatter)
argParser.add_argument('prefix',
help='Prefix for the sequence of files.')
argParser.add_argument('suffix',
help='Suffix for the sequence of files.',
nargs='?',
default='')
argParser.add_argument('folder',
help='The folder where the file will be created.',
nargs='?',
default=_os.getcwd())
argParser.add_argument('-m', '--max-attempts',
help='Number of attempts to make before giving up.',
default=10)
argParser.add_argument('-b', '--base',
help='From where to start counting (default: 0).',
default=0)
passedArgs = passedArgs if passedArgs is not None else _sys.argv[1:]
args = argParser.parse_args(passedArgs)
stdout = _sys.stdout if stdout is None else stdout
stderr = _sys.stderr if stderr is None else stderr
try:
nextFile = findNextFile(args.folder, prefix=args.prefix,
suffix=args.suffix,
maxattempts=args.max_attempts,
base=args.base)
# The newline will be converted to the correct platform specific line
# ending as `sys.stdout` is opened in non-binary mode.
# Hence, we do not need to explicitly print out `\r\n` for Windows.
stdout.write(nextFile + u'\n')
except OSError as e:
stderr.write(_os.strerror(e.errno) + u'\n')
_sys.exit(e.errno) | [
"def",
"_run",
"(",
"passedArgs",
"=",
"None",
",",
"stderr",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"exitFn",
"=",
"None",
")",
":",
"description",
"=",
"\"\"\"Finds the next available file-name in a sequence.\n\n This program will create a file of zero size and will output the path to it\n on STDOUT. No files which exist will be altered in this operation and\n concurrent invocations of this program will return separate files. In case\n of conflict, this program will attempt to generate a new file name up to\n 'maxattempts' number of times before failing. (See --max-attempts)\n\n The sequence will start from the base argument (See --base, default: 0).\n\n This program will look for the next file in the sequence ignoring any gaps.\n Hence, if the files \"a.0.txt\" and \"a.3.txt\" exist, then the next file\n returned will be \"a.4.txt\" when called with prefix=\"a.\" and suffix=\".txt\".\n\n Returns:\n Path of the file which follows the provided pattern and can be opened\n for writing.\n\n Otherwise, it prints an error (wrong path, drive full, illegal\n character in filename, etc.) to stderr and exits with a non-zero error\n code.\n \"\"\"",
"argParser",
"=",
"_argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
",",
"formatter_class",
"=",
"_argparse",
".",
"RawTextHelpFormatter",
")",
"argParser",
".",
"add_argument",
"(",
"'prefix'",
",",
"help",
"=",
"'Prefix for the sequence of files.'",
")",
"argParser",
".",
"add_argument",
"(",
"'suffix'",
",",
"help",
"=",
"'Suffix for the sequence of files.'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"''",
")",
"argParser",
".",
"add_argument",
"(",
"'folder'",
",",
"help",
"=",
"'The folder where the file will be created.'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"_os",
".",
"getcwd",
"(",
")",
")",
"argParser",
".",
"add_argument",
"(",
"'-m'",
",",
"'--max-attempts'",
",",
"help",
"=",
"'Number of attempts to make before giving up.'",
",",
"default",
"=",
"10",
")",
"argParser",
".",
"add_argument",
"(",
"'-b'",
",",
"'--base'",
",",
"help",
"=",
"'From where to start counting (default: 0).'",
",",
"default",
"=",
"0",
")",
"passedArgs",
"=",
"passedArgs",
"if",
"passedArgs",
"is",
"not",
"None",
"else",
"_sys",
".",
"argv",
"[",
"1",
":",
"]",
"args",
"=",
"argParser",
".",
"parse_args",
"(",
"passedArgs",
")",
"stdout",
"=",
"_sys",
".",
"stdout",
"if",
"stdout",
"is",
"None",
"else",
"stdout",
"stderr",
"=",
"_sys",
".",
"stderr",
"if",
"stderr",
"is",
"None",
"else",
"stderr",
"try",
":",
"nextFile",
"=",
"findNextFile",
"(",
"args",
".",
"folder",
",",
"prefix",
"=",
"args",
".",
"prefix",
",",
"suffix",
"=",
"args",
".",
"suffix",
",",
"maxattempts",
"=",
"args",
".",
"max_attempts",
",",
"base",
"=",
"args",
".",
"base",
")",
"# The newline will be converted to the correct platform specific line",
"# ending as `sys.stdout` is opened in non-binary mode.",
"# Hence, we do not need to explicitly print out `\\r\\n` for Windows.",
"stdout",
".",
"write",
"(",
"nextFile",
"+",
"u'\\n'",
")",
"except",
"OSError",
"as",
"e",
":",
"stderr",
".",
"write",
"(",
"_os",
".",
"strerror",
"(",
"e",
".",
"errno",
")",
"+",
"u'\\n'",
")",
"_sys",
".",
"exit",
"(",
"e",
".",
"errno",
")"
] | Executes the script, gets prefix/suffix from the command prompt and
produces output on STDOUT. For help with command line options, invoke
script with '--help'. | [
"Executes",
"the",
"script",
"gets",
"prefix",
"/",
"suffix",
"from",
"the",
"command",
"prompt",
"and",
"produces",
"output",
"on",
"STDOUT",
".",
"For",
"help",
"with",
"command",
"line",
"options",
"invoke",
"script",
"with",
"--",
"help",
"."
] | train | https://github.com/musically-ut/seqfile/blob/796e366fe8871b6dc72cb6bbc570e4a61a8f947c/seqfile/seqfile.py#L148-L215 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | _errstr | def _errstr(value):
"""Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If
it's truncated, the returned value will have '...' on the end.
"""
value = str(value) # We won't make the caller convert value to a string each time.
if len(value) > MAX_ERROR_STR_LEN:
return value[:MAX_ERROR_STR_LEN] + '...'
else:
return value | python | def _errstr(value):
"""Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If
it's truncated, the returned value will have '...' on the end.
"""
value = str(value) # We won't make the caller convert value to a string each time.
if len(value) > MAX_ERROR_STR_LEN:
return value[:MAX_ERROR_STR_LEN] + '...'
else:
return value | [
"def",
"_errstr",
"(",
"value",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"# We won't make the caller convert value to a string each time.",
"if",
"len",
"(",
"value",
")",
">",
"MAX_ERROR_STR_LEN",
":",
"return",
"value",
"[",
":",
"MAX_ERROR_STR_LEN",
"]",
"+",
"'...'",
"else",
":",
"return",
"value"
] | Returns the value str, truncated to MAX_ERROR_STR_LEN characters. If
it's truncated, the returned value will have '...' on the end. | [
"Returns",
"the",
"value",
"str",
"truncated",
"to",
"MAX_ERROR_STR_LEN",
"characters",
".",
"If",
"it",
"s",
"truncated",
"the",
"returned",
"value",
"will",
"have",
"...",
"on",
"the",
"end",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L75-L84 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | _getStrippedValue | def _getStrippedValue(value, strip):
"""Like the strip() string method, except the strip argument describes
different behavior:
If strip is None, whitespace is stripped.
If strip is a string, the characters in the string are stripped.
If strip is False, nothing is stripped."""
if strip is None:
value = value.strip() # Call strip() with no arguments to strip whitespace.
elif isinstance(strip, str):
value = value.strip(strip) # Call strip(), passing the strip argument.
elif strip is False:
pass # Don't strip anything.
return value | python | def _getStrippedValue(value, strip):
"""Like the strip() string method, except the strip argument describes
different behavior:
If strip is None, whitespace is stripped.
If strip is a string, the characters in the string are stripped.
If strip is False, nothing is stripped."""
if strip is None:
value = value.strip() # Call strip() with no arguments to strip whitespace.
elif isinstance(strip, str):
value = value.strip(strip) # Call strip(), passing the strip argument.
elif strip is False:
pass # Don't strip anything.
return value | [
"def",
"_getStrippedValue",
"(",
"value",
",",
"strip",
")",
":",
"if",
"strip",
"is",
"None",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"# Call strip() with no arguments to strip whitespace.",
"elif",
"isinstance",
"(",
"strip",
",",
"str",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
"strip",
")",
"# Call strip(), passing the strip argument.",
"elif",
"strip",
"is",
"False",
":",
"pass",
"# Don't strip anything.",
"return",
"value"
] | Like the strip() string method, except the strip argument describes
different behavior:
If strip is None, whitespace is stripped.
If strip is a string, the characters in the string are stripped.
If strip is False, nothing is stripped. | [
"Like",
"the",
"strip",
"()",
"string",
"method",
"except",
"the",
"strip",
"argument",
"describes",
"different",
"behavior",
":"
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L87-L102 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | _raiseValidationException | def _raiseValidationException(standardExcMsg, customExcMsg=None):
"""Raise ValidationException with standardExcMsg, unless customExcMsg is specified."""
if customExcMsg is None:
raise ValidationException(str(standardExcMsg))
else:
raise ValidationException(str(customExcMsg)) | python | def _raiseValidationException(standardExcMsg, customExcMsg=None):
"""Raise ValidationException with standardExcMsg, unless customExcMsg is specified."""
if customExcMsg is None:
raise ValidationException(str(standardExcMsg))
else:
raise ValidationException(str(customExcMsg)) | [
"def",
"_raiseValidationException",
"(",
"standardExcMsg",
",",
"customExcMsg",
"=",
"None",
")",
":",
"if",
"customExcMsg",
"is",
"None",
":",
"raise",
"ValidationException",
"(",
"str",
"(",
"standardExcMsg",
")",
")",
"else",
":",
"raise",
"ValidationException",
"(",
"str",
"(",
"customExcMsg",
")",
")"
] | Raise ValidationException with standardExcMsg, unless customExcMsg is specified. | [
"Raise",
"ValidationException",
"with",
"standardExcMsg",
"unless",
"customExcMsg",
"is",
"specified",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L105-L110 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | _prevalidationCheck | def _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg=None):
"""Returns a tuple of two values: the first is a bool that tells the caller
if they should immediately return True, the second is a new, possibly stripped
value to replace the value passed for value parameter.
We'd want the caller immediately return value in some cases where further
validation isn't needed, such as if value is blank and blanks are
allowed, or if value matches an allowlist or blocklist regex.
This function is called by the validate*() functions to perform some common
housekeeping."""
# TODO - add a allowlistFirst and blocklistFirst to determine which is checked first. (Right now it's allowlist)
value = str(value)
# Optionally strip whitespace or other characters from value.
value = _getStrippedValue(value, strip)
# Validate for blank values.
if not blank and value == '':
# value is blank but blanks aren't allowed.
_raiseValidationException(_('Blank values are not allowed.'), excMsg)
elif blank and value == '':
return True, value # The value is blank and blanks are allowed, so return True to indicate that the caller should return value immediately.
# NOTE: We check if something matches the allow-list first, then we check the block-list second.
# Check the allowlistRegexes.
if allowlistRegexes is not None:
for regex in allowlistRegexes:
if isinstance(regex, re.Pattern):
if regex.search(value, re.IGNORECASE) is not None:
return True, value # The value is in the allowlist, so return True to indicate that the caller should return value immediately.
else:
if re.search(regex, value, re.IGNORECASE) is not None:
return True, value # The value is in the allowlist, so return True to indicate that the caller should return value immediately.
# Check the blocklistRegexes.
if blocklistRegexes is not None:
for blocklistRegexItem in blocklistRegexes:
if isinstance(blocklistRegexItem, str):
regex, response = blocklistRegexItem, DEFAULT_BLOCKLIST_RESPONSE
else:
regex, response = blocklistRegexItem
if isinstance(regex, re.Pattern) and regex.search(value, re.IGNORECASE) is not None:
_raiseValidationException(response, excMsg) # value is on a blocklist
elif re.search(regex, value, re.IGNORECASE) is not None:
_raiseValidationException(response, excMsg) # value is on a blocklist
return False, value | python | def _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg=None):
"""Returns a tuple of two values: the first is a bool that tells the caller
if they should immediately return True, the second is a new, possibly stripped
value to replace the value passed for value parameter.
We'd want the caller immediately return value in some cases where further
validation isn't needed, such as if value is blank and blanks are
allowed, or if value matches an allowlist or blocklist regex.
This function is called by the validate*() functions to perform some common
housekeeping."""
# TODO - add a allowlistFirst and blocklistFirst to determine which is checked first. (Right now it's allowlist)
value = str(value)
# Optionally strip whitespace or other characters from value.
value = _getStrippedValue(value, strip)
# Validate for blank values.
if not blank and value == '':
# value is blank but blanks aren't allowed.
_raiseValidationException(_('Blank values are not allowed.'), excMsg)
elif blank and value == '':
return True, value # The value is blank and blanks are allowed, so return True to indicate that the caller should return value immediately.
# NOTE: We check if something matches the allow-list first, then we check the block-list second.
# Check the allowlistRegexes.
if allowlistRegexes is not None:
for regex in allowlistRegexes:
if isinstance(regex, re.Pattern):
if regex.search(value, re.IGNORECASE) is not None:
return True, value # The value is in the allowlist, so return True to indicate that the caller should return value immediately.
else:
if re.search(regex, value, re.IGNORECASE) is not None:
return True, value # The value is in the allowlist, so return True to indicate that the caller should return value immediately.
# Check the blocklistRegexes.
if blocklistRegexes is not None:
for blocklistRegexItem in blocklistRegexes:
if isinstance(blocklistRegexItem, str):
regex, response = blocklistRegexItem, DEFAULT_BLOCKLIST_RESPONSE
else:
regex, response = blocklistRegexItem
if isinstance(regex, re.Pattern) and regex.search(value, re.IGNORECASE) is not None:
_raiseValidationException(response, excMsg) # value is on a blocklist
elif re.search(regex, value, re.IGNORECASE) is not None:
_raiseValidationException(response, excMsg) # value is on a blocklist
return False, value | [
"def",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
"=",
"None",
")",
":",
"# TODO - add a allowlistFirst and blocklistFirst to determine which is checked first. (Right now it's allowlist)",
"value",
"=",
"str",
"(",
"value",
")",
"# Optionally strip whitespace or other characters from value.",
"value",
"=",
"_getStrippedValue",
"(",
"value",
",",
"strip",
")",
"# Validate for blank values.",
"if",
"not",
"blank",
"and",
"value",
"==",
"''",
":",
"# value is blank but blanks aren't allowed.",
"_raiseValidationException",
"(",
"_",
"(",
"'Blank values are not allowed.'",
")",
",",
"excMsg",
")",
"elif",
"blank",
"and",
"value",
"==",
"''",
":",
"return",
"True",
",",
"value",
"# The value is blank and blanks are allowed, so return True to indicate that the caller should return value immediately.",
"# NOTE: We check if something matches the allow-list first, then we check the block-list second.",
"# Check the allowlistRegexes.",
"if",
"allowlistRegexes",
"is",
"not",
"None",
":",
"for",
"regex",
"in",
"allowlistRegexes",
":",
"if",
"isinstance",
"(",
"regex",
",",
"re",
".",
"Pattern",
")",
":",
"if",
"regex",
".",
"search",
"(",
"value",
",",
"re",
".",
"IGNORECASE",
")",
"is",
"not",
"None",
":",
"return",
"True",
",",
"value",
"# The value is in the allowlist, so return True to indicate that the caller should return value immediately.",
"else",
":",
"if",
"re",
".",
"search",
"(",
"regex",
",",
"value",
",",
"re",
".",
"IGNORECASE",
")",
"is",
"not",
"None",
":",
"return",
"True",
",",
"value",
"# The value is in the allowlist, so return True to indicate that the caller should return value immediately.",
"# Check the blocklistRegexes.",
"if",
"blocklistRegexes",
"is",
"not",
"None",
":",
"for",
"blocklistRegexItem",
"in",
"blocklistRegexes",
":",
"if",
"isinstance",
"(",
"blocklistRegexItem",
",",
"str",
")",
":",
"regex",
",",
"response",
"=",
"blocklistRegexItem",
",",
"DEFAULT_BLOCKLIST_RESPONSE",
"else",
":",
"regex",
",",
"response",
"=",
"blocklistRegexItem",
"if",
"isinstance",
"(",
"regex",
",",
"re",
".",
"Pattern",
")",
"and",
"regex",
".",
"search",
"(",
"value",
",",
"re",
".",
"IGNORECASE",
")",
"is",
"not",
"None",
":",
"_raiseValidationException",
"(",
"response",
",",
"excMsg",
")",
"# value is on a blocklist",
"elif",
"re",
".",
"search",
"(",
"regex",
",",
"value",
",",
"re",
".",
"IGNORECASE",
")",
"is",
"not",
"None",
":",
"_raiseValidationException",
"(",
"response",
",",
"excMsg",
")",
"# value is on a blocklist",
"return",
"False",
",",
"value"
] | Returns a tuple of two values: the first is a bool that tells the caller
if they should immediately return True, the second is a new, possibly stripped
value to replace the value passed for value parameter.
We'd want the caller immediately return value in some cases where further
validation isn't needed, such as if value is blank and blanks are
allowed, or if value matches an allowlist or blocklist regex.
This function is called by the validate*() functions to perform some common
housekeeping. | [
"Returns",
"a",
"tuple",
"of",
"two",
"values",
":",
"the",
"first",
"is",
"a",
"bool",
"that",
"tells",
"the",
"caller",
"if",
"they",
"should",
"immediately",
"return",
"True",
"the",
"second",
"is",
"a",
"new",
"possibly",
"stripped",
"value",
"to",
"replace",
"the",
"value",
"passed",
"for",
"value",
"parameter",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L113-L164 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | _validateGenericParameters | def _validateGenericParameters(blank, strip, allowlistRegexes, blocklistRegexes):
"""Returns None if the blank, strip, and blocklistRegexes parameters are valid
of PySimpleValidate's validation functions have. Raises a PySimpleValidateException
if any of the arguments are invalid."""
# Check blank parameter.
if not isinstance(blank, bool):
raise PySimpleValidateException('blank argument must be a bool')
# Check strip parameter.
if not isinstance(strip, (bool, str, type(None))):
raise PySimpleValidateException('strip argument must be a bool, None, or str')
# Check allowlistRegexes parameter (including each regex in it).
if allowlistRegexes is None:
allowlistRegexes = [] # allowlistRegexes defaults to a blank list.
try:
len(allowlistRegexes) # Make sure allowlistRegexes is a sequence.
except:
raise PySimpleValidateException('allowlistRegexes must be a sequence of regex_strs')
for response in allowlistRegexes:
if not isinstance(response[0], str):
raise PySimpleValidateException('allowlistRegexes must be a sequence of regex_strs')
# Check allowlistRegexes parameter (including each regex in it).
# NOTE: blocklistRegexes is NOT the same format as allowlistRegex, it can
# include an "invalid input reason" string to display if the input matches
# the blocklist regex.
if blocklistRegexes is None:
blocklistRegexes = [] # blocklistRegexes defaults to a blank list.
try:
len(blocklistRegexes) # Make sure blocklistRegexes is a sequence of (regex_str, str) or strs.
except:
raise PySimpleValidateException('blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs')
for response in blocklistRegexes:
if isinstance(response, str):
continue
if len(response) != 2:
raise PySimpleValidateException('blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs')
if not isinstance(response[0], str) or not isinstance(response[1], str):
raise PySimpleValidateException('blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs') | python | def _validateGenericParameters(blank, strip, allowlistRegexes, blocklistRegexes):
"""Returns None if the blank, strip, and blocklistRegexes parameters are valid
of PySimpleValidate's validation functions have. Raises a PySimpleValidateException
if any of the arguments are invalid."""
# Check blank parameter.
if not isinstance(blank, bool):
raise PySimpleValidateException('blank argument must be a bool')
# Check strip parameter.
if not isinstance(strip, (bool, str, type(None))):
raise PySimpleValidateException('strip argument must be a bool, None, or str')
# Check allowlistRegexes parameter (including each regex in it).
if allowlistRegexes is None:
allowlistRegexes = [] # allowlistRegexes defaults to a blank list.
try:
len(allowlistRegexes) # Make sure allowlistRegexes is a sequence.
except:
raise PySimpleValidateException('allowlistRegexes must be a sequence of regex_strs')
for response in allowlistRegexes:
if not isinstance(response[0], str):
raise PySimpleValidateException('allowlistRegexes must be a sequence of regex_strs')
# Check allowlistRegexes parameter (including each regex in it).
# NOTE: blocklistRegexes is NOT the same format as allowlistRegex, it can
# include an "invalid input reason" string to display if the input matches
# the blocklist regex.
if blocklistRegexes is None:
blocklistRegexes = [] # blocklistRegexes defaults to a blank list.
try:
len(blocklistRegexes) # Make sure blocklistRegexes is a sequence of (regex_str, str) or strs.
except:
raise PySimpleValidateException('blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs')
for response in blocklistRegexes:
if isinstance(response, str):
continue
if len(response) != 2:
raise PySimpleValidateException('blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs')
if not isinstance(response[0], str) or not isinstance(response[1], str):
raise PySimpleValidateException('blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs') | [
"def",
"_validateGenericParameters",
"(",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
")",
":",
"# Check blank parameter.",
"if",
"not",
"isinstance",
"(",
"blank",
",",
"bool",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'blank argument must be a bool'",
")",
"# Check strip parameter.",
"if",
"not",
"isinstance",
"(",
"strip",
",",
"(",
"bool",
",",
"str",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'strip argument must be a bool, None, or str'",
")",
"# Check allowlistRegexes parameter (including each regex in it).",
"if",
"allowlistRegexes",
"is",
"None",
":",
"allowlistRegexes",
"=",
"[",
"]",
"# allowlistRegexes defaults to a blank list.",
"try",
":",
"len",
"(",
"allowlistRegexes",
")",
"# Make sure allowlistRegexes is a sequence.",
"except",
":",
"raise",
"PySimpleValidateException",
"(",
"'allowlistRegexes must be a sequence of regex_strs'",
")",
"for",
"response",
"in",
"allowlistRegexes",
":",
"if",
"not",
"isinstance",
"(",
"response",
"[",
"0",
"]",
",",
"str",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'allowlistRegexes must be a sequence of regex_strs'",
")",
"# Check allowlistRegexes parameter (including each regex in it).",
"# NOTE: blocklistRegexes is NOT the same format as allowlistRegex, it can",
"# include an \"invalid input reason\" string to display if the input matches",
"# the blocklist regex.",
"if",
"blocklistRegexes",
"is",
"None",
":",
"blocklistRegexes",
"=",
"[",
"]",
"# blocklistRegexes defaults to a blank list.",
"try",
":",
"len",
"(",
"blocklistRegexes",
")",
"# Make sure blocklistRegexes is a sequence of (regex_str, str) or strs.",
"except",
":",
"raise",
"PySimpleValidateException",
"(",
"'blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs'",
")",
"for",
"response",
"in",
"blocklistRegexes",
":",
"if",
"isinstance",
"(",
"response",
",",
"str",
")",
":",
"continue",
"if",
"len",
"(",
"response",
")",
"!=",
"2",
":",
"raise",
"PySimpleValidateException",
"(",
"'blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs'",
")",
"if",
"not",
"isinstance",
"(",
"response",
"[",
"0",
"]",
",",
"str",
")",
"or",
"not",
"isinstance",
"(",
"response",
"[",
"1",
"]",
",",
"str",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'blocklistRegexes must be a sequence of (regex_str, str) tuples or regex_strs'",
")"
] | Returns None if the blank, strip, and blocklistRegexes parameters are valid
of PySimpleValidate's validation functions have. Raises a PySimpleValidateException
if any of the arguments are invalid. | [
"Returns",
"None",
"if",
"the",
"blank",
"strip",
"and",
"blocklistRegexes",
"parameters",
"are",
"valid",
"of",
"PySimpleValidate",
"s",
"validation",
"functions",
"have",
".",
"Raises",
"a",
"PySimpleValidateException",
"if",
"any",
"of",
"the",
"arguments",
"are",
"invalid",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L167-L209 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | _validateParamsFor_validateNum | def _validateParamsFor_validateNum(min=None, max=None, lessThan=None, greaterThan=None):
"""Raises an exception if the arguments are invalid. This is called by
the validateNum(), validateInt(), and validateFloat() functions to
check its arguments. This code was refactored out to a separate function
so that the PyInputPlus module (or other modules) could check their
parameters' arguments for inputNum() etc.
"""
if (min is not None) and (greaterThan is not None):
raise PySimpleValidateException('only one argument for min or greaterThan can be passed, not both')
if (max is not None) and (lessThan is not None):
raise PySimpleValidateException('only one argument for max or lessThan can be passed, not both')
if (min is not None) and (max is not None) and (min > max):
raise PySimpleValidateException('the min argument must be less than or equal to the max argument')
if (min is not None) and (lessThan is not None) and (min >= lessThan):
raise PySimpleValidateException('the min argument must be less than the lessThan argument')
if (max is not None) and (greaterThan is not None) and (max <= greaterThan):
raise PySimpleValidateException('the max argument must be greater than the greaterThan argument')
for name, val in (('min', min), ('max', max),
('lessThan', lessThan), ('greaterThan', greaterThan)):
if not isinstance(val, (int, float, type(None))):
raise PySimpleValidateException(name + ' argument must be int, float, or NoneType') | python | def _validateParamsFor_validateNum(min=None, max=None, lessThan=None, greaterThan=None):
"""Raises an exception if the arguments are invalid. This is called by
the validateNum(), validateInt(), and validateFloat() functions to
check its arguments. This code was refactored out to a separate function
so that the PyInputPlus module (or other modules) could check their
parameters' arguments for inputNum() etc.
"""
if (min is not None) and (greaterThan is not None):
raise PySimpleValidateException('only one argument for min or greaterThan can be passed, not both')
if (max is not None) and (lessThan is not None):
raise PySimpleValidateException('only one argument for max or lessThan can be passed, not both')
if (min is not None) and (max is not None) and (min > max):
raise PySimpleValidateException('the min argument must be less than or equal to the max argument')
if (min is not None) and (lessThan is not None) and (min >= lessThan):
raise PySimpleValidateException('the min argument must be less than the lessThan argument')
if (max is not None) and (greaterThan is not None) and (max <= greaterThan):
raise PySimpleValidateException('the max argument must be greater than the greaterThan argument')
for name, val in (('min', min), ('max', max),
('lessThan', lessThan), ('greaterThan', greaterThan)):
if not isinstance(val, (int, float, type(None))):
raise PySimpleValidateException(name + ' argument must be int, float, or NoneType') | [
"def",
"_validateParamsFor_validateNum",
"(",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"lessThan",
"=",
"None",
",",
"greaterThan",
"=",
"None",
")",
":",
"if",
"(",
"min",
"is",
"not",
"None",
")",
"and",
"(",
"greaterThan",
"is",
"not",
"None",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'only one argument for min or greaterThan can be passed, not both'",
")",
"if",
"(",
"max",
"is",
"not",
"None",
")",
"and",
"(",
"lessThan",
"is",
"not",
"None",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'only one argument for max or lessThan can be passed, not both'",
")",
"if",
"(",
"min",
"is",
"not",
"None",
")",
"and",
"(",
"max",
"is",
"not",
"None",
")",
"and",
"(",
"min",
">",
"max",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'the min argument must be less than or equal to the max argument'",
")",
"if",
"(",
"min",
"is",
"not",
"None",
")",
"and",
"(",
"lessThan",
"is",
"not",
"None",
")",
"and",
"(",
"min",
">=",
"lessThan",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'the min argument must be less than the lessThan argument'",
")",
"if",
"(",
"max",
"is",
"not",
"None",
")",
"and",
"(",
"greaterThan",
"is",
"not",
"None",
")",
"and",
"(",
"max",
"<=",
"greaterThan",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'the max argument must be greater than the greaterThan argument'",
")",
"for",
"name",
",",
"val",
"in",
"(",
"(",
"'min'",
",",
"min",
")",
",",
"(",
"'max'",
",",
"max",
")",
",",
"(",
"'lessThan'",
",",
"lessThan",
")",
",",
"(",
"'greaterThan'",
",",
"greaterThan",
")",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"(",
"int",
",",
"float",
",",
"type",
"(",
"None",
")",
")",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"name",
"+",
"' argument must be int, float, or NoneType'",
")"
] | Raises an exception if the arguments are invalid. This is called by
the validateNum(), validateInt(), and validateFloat() functions to
check its arguments. This code was refactored out to a separate function
so that the PyInputPlus module (or other modules) could check their
parameters' arguments for inputNum() etc. | [
"Raises",
"an",
"exception",
"if",
"the",
"arguments",
"are",
"invalid",
".",
"This",
"is",
"called",
"by",
"the",
"validateNum",
"()",
"validateInt",
"()",
"and",
"validateFloat",
"()",
"functions",
"to",
"check",
"its",
"arguments",
".",
"This",
"code",
"was",
"refactored",
"out",
"to",
"a",
"separate",
"function",
"so",
"that",
"the",
"PyInputPlus",
"module",
"(",
"or",
"other",
"modules",
")",
"could",
"check",
"their",
"parameters",
"arguments",
"for",
"inputNum",
"()",
"etc",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L212-L235 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateStr | def validateStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a string. This function
is identical to the built-in input() function, but also offers the
PySimpleValidate features of not allowing blank values by default,
automatically stripping whitespace, and having allowlist/blocklist
regular expressions.
Returns value, so it can be used inline in an expression:
print('Hello, ' + validateStr(your_name))
* value (str): The value being validated as a string.
* blank (bool): If True, a blank string will be accepted. Defaults to False. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateStr('hello')
'hello'
>>> pysv.validateStr('')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: Blank values are not allowed.
>>> pysv.validateStr('', blank=True)
''
>>> pysv.validateStr(' hello ')
'hello'
>>> pysv.validateStr('hello', blocklistRegexes=['hello'])
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: This response is invalid.
>>> pysv.validateStr('hello', blocklistRegexes=[('hello', 'Hello is not allowed')])
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: Hello is not allowed
>>> pysv.validateStr('hello', allowlistRegexes=['hello'], blocklistRegexes=['llo'])
'hello'
"""
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
return value | python | def validateStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a string. This function
is identical to the built-in input() function, but also offers the
PySimpleValidate features of not allowing blank values by default,
automatically stripping whitespace, and having allowlist/blocklist
regular expressions.
Returns value, so it can be used inline in an expression:
print('Hello, ' + validateStr(your_name))
* value (str): The value being validated as a string.
* blank (bool): If True, a blank string will be accepted. Defaults to False. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateStr('hello')
'hello'
>>> pysv.validateStr('')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: Blank values are not allowed.
>>> pysv.validateStr('', blank=True)
''
>>> pysv.validateStr(' hello ')
'hello'
>>> pysv.validateStr('hello', blocklistRegexes=['hello'])
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: This response is invalid.
>>> pysv.validateStr('hello', blocklistRegexes=[('hello', 'Hello is not allowed')])
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: Hello is not allowed
>>> pysv.validateStr('hello', allowlistRegexes=['hello'], blocklistRegexes=['llo'])
'hello'
"""
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
return value | [
"def",
"validateStr",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"# Validate parameters.",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"return",
"value"
] | Raises ValidationException if value is not a string. This function
is identical to the built-in input() function, but also offers the
PySimpleValidate features of not allowing blank values by default,
automatically stripping whitespace, and having allowlist/blocklist
regular expressions.
Returns value, so it can be used inline in an expression:
print('Hello, ' + validateStr(your_name))
* value (str): The value being validated as a string.
* blank (bool): If True, a blank string will be accepted. Defaults to False. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateStr('hello')
'hello'
>>> pysv.validateStr('')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: Blank values are not allowed.
>>> pysv.validateStr('', blank=True)
''
>>> pysv.validateStr(' hello ')
'hello'
>>> pysv.validateStr('hello', blocklistRegexes=['hello'])
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: This response is invalid.
>>> pysv.validateStr('hello', blocklistRegexes=[('hello', 'Hello is not allowed')])
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: Hello is not allowed
>>> pysv.validateStr('hello', allowlistRegexes=['hello'], blocklistRegexes=['llo'])
'hello' | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"string",
".",
"This",
"function",
"is",
"identical",
"to",
"the",
"built",
"-",
"in",
"input",
"()",
"function",
"but",
"also",
"offers",
"the",
"PySimpleValidate",
"features",
"of",
"not",
"allowing",
"blank",
"values",
"by",
"default",
"automatically",
"stripping",
"whitespace",
"and",
"having",
"allowlist",
"/",
"blocklist",
"regular",
"expressions",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L238-L283 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateNum | def validateNum(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, _numType='num',
min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
"""Raises ValidationException if value is not a float or int.
Returns value, so it can be used inline in an expression:
print(2 + validateNum(your_number))
Note that since int() and float() ignore leading or trailing whitespace
when converting a string to a number, so does this validateNum().
* value (str): The value being validated as an int or float.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* _numType (str): One of 'num', 'int', or 'float' for the kind of number to validate against, where 'num' means int or float.
* min (int, float): The (inclusive) minimum value for the value to pass validation.
* max (int, float): The (inclusive) maximum value for the value to pass validation.
* lessThan (int, float): The (exclusive) minimum value for the value to pass validation.
* greaterThan (int, float): The (exclusive) maximum value for the value to pass validation.
* excMsg (str): A custom message to use in the raised ValidationException.
If you specify min or max, you cannot also respectively specify lessThan
or greaterThan. Doing so will raise PySimpleValidateException.
>>> import pysimplevalidate as pysv
>>> pysv.validateNum('3')
3
>>> pysv.validateNum('3.0')
3.0
>>> pysv.validateNum(' 3.0 ')
3.0
>>> pysv.validateNum('549873259847598437598435798435793.589985743957435794357')
5.498732598475984e+32
>>> pysv.validateNum('4', lessThan=4)
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: Number must be less than 4.
>>> pysv.validateNum('4', max=4)
4
>>> pysv.validateNum('4', min=2, max=5)
4
"""
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)
_validateParamsFor_validateNum(min=min, max=max, lessThan=lessThan, greaterThan=greaterThan)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
# If we can convert value to an int/float, then do so. For example,
# if an allowlist regex allows '42', then we should return 42/42.0.
if (_numType == 'num' and '.' in value) or (_numType == 'float'):
try:
return float(value)
except ValueError:
return value # Return the value as is.
if (_numType == 'num' and '.' not in value) or (_numType == 'int'):
try:
return int(value)
except ValueError:
return value # Return the value as is.
# Validate the value's type (and convert value back to a number type).
if (_numType == 'num' and '.' in value):
# We are expecting a "num" (float or int) type and the user entered a float.
try:
value = float(value)
except:
_raiseValidationException(_('%r is not a number.') % (_errstr(value)), excMsg)
elif (_numType == 'num' and '.' not in value):
# We are expecting a "num" (float or int) type and the user entered an int.
try:
value = int(value)
except:
_raiseValidationException(_('%r is not a number.') % (_errstr(value)), excMsg)
elif _numType == 'float':
try:
value = float(value)
except:
_raiseValidationException(_('%r is not a float.') % (_errstr(value)), excMsg)
elif _numType == 'int':
try:
if float(value) % 1 != 0:
# The number is a float that doesn't end with ".0"
_raiseValidationException(_('%r is not an integer.') % (_errstr(value)), excMsg)
value = int(float(value))
except:
_raiseValidationException(_('%r is not an integer.') % (_errstr(value)), excMsg)
# Validate against min argument.
if min is not None and value < min:
_raiseValidationException(_('Number must be at minimum %s.') % (min), excMsg)
# Validate against max argument.
if max is not None and value > max:
_raiseValidationException(_('Number must be at maximum %s.') % (max), excMsg)
# Validate against max argument.
if lessThan is not None and value >= lessThan:
_raiseValidationException(_('Number must be less than %s.') % (lessThan), excMsg)
# Validate against max argument.
if greaterThan is not None and value <= greaterThan:
_raiseValidationException(_('Number must be greater than %s.') % (greaterThan), excMsg)
return value | python | def validateNum(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, _numType='num',
min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
"""Raises ValidationException if value is not a float or int.
Returns value, so it can be used inline in an expression:
print(2 + validateNum(your_number))
Note that since int() and float() ignore leading or trailing whitespace
when converting a string to a number, so does this validateNum().
* value (str): The value being validated as an int or float.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* _numType (str): One of 'num', 'int', or 'float' for the kind of number to validate against, where 'num' means int or float.
* min (int, float): The (inclusive) minimum value for the value to pass validation.
* max (int, float): The (inclusive) maximum value for the value to pass validation.
* lessThan (int, float): The (exclusive) minimum value for the value to pass validation.
* greaterThan (int, float): The (exclusive) maximum value for the value to pass validation.
* excMsg (str): A custom message to use in the raised ValidationException.
If you specify min or max, you cannot also respectively specify lessThan
or greaterThan. Doing so will raise PySimpleValidateException.
>>> import pysimplevalidate as pysv
>>> pysv.validateNum('3')
3
>>> pysv.validateNum('3.0')
3.0
>>> pysv.validateNum(' 3.0 ')
3.0
>>> pysv.validateNum('549873259847598437598435798435793.589985743957435794357')
5.498732598475984e+32
>>> pysv.validateNum('4', lessThan=4)
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: Number must be less than 4.
>>> pysv.validateNum('4', max=4)
4
>>> pysv.validateNum('4', min=2, max=5)
4
"""
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)
_validateParamsFor_validateNum(min=min, max=max, lessThan=lessThan, greaterThan=greaterThan)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
# If we can convert value to an int/float, then do so. For example,
# if an allowlist regex allows '42', then we should return 42/42.0.
if (_numType == 'num' and '.' in value) or (_numType == 'float'):
try:
return float(value)
except ValueError:
return value # Return the value as is.
if (_numType == 'num' and '.' not in value) or (_numType == 'int'):
try:
return int(value)
except ValueError:
return value # Return the value as is.
# Validate the value's type (and convert value back to a number type).
if (_numType == 'num' and '.' in value):
# We are expecting a "num" (float or int) type and the user entered a float.
try:
value = float(value)
except:
_raiseValidationException(_('%r is not a number.') % (_errstr(value)), excMsg)
elif (_numType == 'num' and '.' not in value):
# We are expecting a "num" (float or int) type and the user entered an int.
try:
value = int(value)
except:
_raiseValidationException(_('%r is not a number.') % (_errstr(value)), excMsg)
elif _numType == 'float':
try:
value = float(value)
except:
_raiseValidationException(_('%r is not a float.') % (_errstr(value)), excMsg)
elif _numType == 'int':
try:
if float(value) % 1 != 0:
# The number is a float that doesn't end with ".0"
_raiseValidationException(_('%r is not an integer.') % (_errstr(value)), excMsg)
value = int(float(value))
except:
_raiseValidationException(_('%r is not an integer.') % (_errstr(value)), excMsg)
# Validate against min argument.
if min is not None and value < min:
_raiseValidationException(_('Number must be at minimum %s.') % (min), excMsg)
# Validate against max argument.
if max is not None and value > max:
_raiseValidationException(_('Number must be at maximum %s.') % (max), excMsg)
# Validate against max argument.
if lessThan is not None and value >= lessThan:
_raiseValidationException(_('Number must be less than %s.') % (lessThan), excMsg)
# Validate against max argument.
if greaterThan is not None and value <= greaterThan:
_raiseValidationException(_('Number must be greater than %s.') % (greaterThan), excMsg)
return value | [
"def",
"validateNum",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"_numType",
"=",
"'num'",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"lessThan",
"=",
"None",
",",
"greaterThan",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"# Validate parameters.",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"_validateParamsFor_validateNum",
"(",
"min",
"=",
"min",
",",
"max",
"=",
"max",
",",
"lessThan",
"=",
"lessThan",
",",
"greaterThan",
"=",
"greaterThan",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"# If we can convert value to an int/float, then do so. For example,",
"# if an allowlist regex allows '42', then we should return 42/42.0.",
"if",
"(",
"_numType",
"==",
"'num'",
"and",
"'.'",
"in",
"value",
")",
"or",
"(",
"_numType",
"==",
"'float'",
")",
":",
"try",
":",
"return",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"return",
"value",
"# Return the value as is.",
"if",
"(",
"_numType",
"==",
"'num'",
"and",
"'.'",
"not",
"in",
"value",
")",
"or",
"(",
"_numType",
"==",
"'int'",
")",
":",
"try",
":",
"return",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"return",
"value",
"# Return the value as is.",
"# Validate the value's type (and convert value back to a number type).",
"if",
"(",
"_numType",
"==",
"'num'",
"and",
"'.'",
"in",
"value",
")",
":",
"# We are expecting a \"num\" (float or int) type and the user entered a float.",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a number.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")",
"elif",
"(",
"_numType",
"==",
"'num'",
"and",
"'.'",
"not",
"in",
"value",
")",
":",
"# We are expecting a \"num\" (float or int) type and the user entered an int.",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a number.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")",
"elif",
"_numType",
"==",
"'float'",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a float.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")",
"elif",
"_numType",
"==",
"'int'",
":",
"try",
":",
"if",
"float",
"(",
"value",
")",
"%",
"1",
"!=",
"0",
":",
"# The number is a float that doesn't end with \".0\"",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not an integer.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")",
"value",
"=",
"int",
"(",
"float",
"(",
"value",
")",
")",
"except",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not an integer.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")",
"# Validate against min argument.",
"if",
"min",
"is",
"not",
"None",
"and",
"value",
"<",
"min",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'Number must be at minimum %s.'",
")",
"%",
"(",
"min",
")",
",",
"excMsg",
")",
"# Validate against max argument.",
"if",
"max",
"is",
"not",
"None",
"and",
"value",
">",
"max",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'Number must be at maximum %s.'",
")",
"%",
"(",
"max",
")",
",",
"excMsg",
")",
"# Validate against max argument.",
"if",
"lessThan",
"is",
"not",
"None",
"and",
"value",
">=",
"lessThan",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'Number must be less than %s.'",
")",
"%",
"(",
"lessThan",
")",
",",
"excMsg",
")",
"# Validate against max argument.",
"if",
"greaterThan",
"is",
"not",
"None",
"and",
"value",
"<=",
"greaterThan",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'Number must be greater than %s.'",
")",
"%",
"(",
"greaterThan",
")",
",",
"excMsg",
")",
"return",
"value"
] | Raises ValidationException if value is not a float or int.
Returns value, so it can be used inline in an expression:
print(2 + validateNum(your_number))
Note that since int() and float() ignore leading or trailing whitespace
when converting a string to a number, so does this validateNum().
* value (str): The value being validated as an int or float.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* _numType (str): One of 'num', 'int', or 'float' for the kind of number to validate against, where 'num' means int or float.
* min (int, float): The (inclusive) minimum value for the value to pass validation.
* max (int, float): The (inclusive) maximum value for the value to pass validation.
* lessThan (int, float): The (exclusive) minimum value for the value to pass validation.
* greaterThan (int, float): The (exclusive) maximum value for the value to pass validation.
* excMsg (str): A custom message to use in the raised ValidationException.
If you specify min or max, you cannot also respectively specify lessThan
or greaterThan. Doing so will raise PySimpleValidateException.
>>> import pysimplevalidate as pysv
>>> pysv.validateNum('3')
3
>>> pysv.validateNum('3.0')
3.0
>>> pysv.validateNum(' 3.0 ')
3.0
>>> pysv.validateNum('549873259847598437598435798435793.589985743957435794357')
5.498732598475984e+32
>>> pysv.validateNum('4', lessThan=4)
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: Number must be less than 4.
>>> pysv.validateNum('4', max=4)
4
>>> pysv.validateNum('4', min=2, max=5)
4 | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"float",
"or",
"int",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L286-L393 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateInt | def validateInt(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
"""Raises ValidationException if value is not a int.
Returns value, so it can be used inline in an expression:
print(2 + validateInt(your_number))
Note that since int() and ignore leading or trailing whitespace
when converting a string to a number, so does this validateNum().
* value (str): The value being validated as an int or float.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* _numType (str): One of 'num', 'int', or 'float' for the kind of number to validate against, where 'num' means int or float.
* min (int, float): The (inclusive) minimum value for the value to pass validation.
* max (int, float): The (inclusive) maximum value for the value to pass validation.
* lessThan (int, float): The (exclusive) minimum value for the value to pass validation.
* greaterThan (int, float): The (exclusive) maximum value for the value to pass validation.
* excMsg (str): A custom message to use in the raised ValidationException.
If you specify min or max, you cannot also respectively specify lessThan
or greaterThan. Doing so will raise PySimpleValidateException.
>>> import pysimplevalidate as pysv
>>> pysv.validateInt('42')
42
>>> pysv.validateInt('forty two')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'forty two' is not an integer.
"""
return validateNum(value=value, blank=blank, strip=strip, allowlistRegexes=None,
blocklistRegexes=blocklistRegexes, _numType='int', min=min, max=max,
lessThan=lessThan, greaterThan=greaterThan) | python | def validateInt(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
min=None, max=None, lessThan=None, greaterThan=None, excMsg=None):
"""Raises ValidationException if value is not a int.
Returns value, so it can be used inline in an expression:
print(2 + validateInt(your_number))
Note that since int() and ignore leading or trailing whitespace
when converting a string to a number, so does this validateNum().
* value (str): The value being validated as an int or float.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* _numType (str): One of 'num', 'int', or 'float' for the kind of number to validate against, where 'num' means int or float.
* min (int, float): The (inclusive) minimum value for the value to pass validation.
* max (int, float): The (inclusive) maximum value for the value to pass validation.
* lessThan (int, float): The (exclusive) minimum value for the value to pass validation.
* greaterThan (int, float): The (exclusive) maximum value for the value to pass validation.
* excMsg (str): A custom message to use in the raised ValidationException.
If you specify min or max, you cannot also respectively specify lessThan
or greaterThan. Doing so will raise PySimpleValidateException.
>>> import pysimplevalidate as pysv
>>> pysv.validateInt('42')
42
>>> pysv.validateInt('forty two')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'forty two' is not an integer.
"""
return validateNum(value=value, blank=blank, strip=strip, allowlistRegexes=None,
blocklistRegexes=blocklistRegexes, _numType='int', min=min, max=max,
lessThan=lessThan, greaterThan=greaterThan) | [
"def",
"validateInt",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"lessThan",
"=",
"None",
",",
"greaterThan",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"return",
"validateNum",
"(",
"value",
"=",
"value",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
",",
"_numType",
"=",
"'int'",
",",
"min",
"=",
"min",
",",
"max",
"=",
"max",
",",
"lessThan",
"=",
"lessThan",
",",
"greaterThan",
"=",
"greaterThan",
")"
] | Raises ValidationException if value is not a int.
Returns value, so it can be used inline in an expression:
print(2 + validateInt(your_number))
Note that since int() and ignore leading or trailing whitespace
when converting a string to a number, so does this validateNum().
* value (str): The value being validated as an int or float.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* _numType (str): One of 'num', 'int', or 'float' for the kind of number to validate against, where 'num' means int or float.
* min (int, float): The (inclusive) minimum value for the value to pass validation.
* max (int, float): The (inclusive) maximum value for the value to pass validation.
* lessThan (int, float): The (exclusive) minimum value for the value to pass validation.
* greaterThan (int, float): The (exclusive) maximum value for the value to pass validation.
* excMsg (str): A custom message to use in the raised ValidationException.
If you specify min or max, you cannot also respectively specify lessThan
or greaterThan. Doing so will raise PySimpleValidateException.
>>> import pysimplevalidate as pysv
>>> pysv.validateInt('42')
42
>>> pysv.validateInt('forty two')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'forty two' is not an integer. | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"int",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L396-L432 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | _validateParamsFor_validateChoice | def _validateParamsFor_validateChoice(choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
numbered=False, lettered=False, caseSensitive=False, excMsg=None):
"""Raises PySimpleValidateException if the arguments are invalid. This is called by
the validateChoice() function to check its arguments. This code was
refactored out to a separate function so that the PyInputPlus module (or
other modules) could check their parameters' arguments for inputChoice().
"""
if not isinstance(caseSensitive, bool):
raise PySimpleValidateException('caseSensitive argument must be a bool')
try:
len(choices)
except:
raise PySimpleValidateException('choices arg must be a sequence')
if blank == False and len(choices) < 2:
raise PySimpleValidateException('choices must have at least two items if blank is False')
elif blank == True and len(choices) < 1:
raise PySimpleValidateException('choices must have at least one item')
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)
for choice in choices:
if not isinstance(choice, str):
raise PySimpleValidateException('choice %r must be a string' % (_errstr(choice)))
if lettered and len(choices) > 26:
raise PySimpleValidateException('lettered argument cannot be True if there are more than 26 choices')
if numbered and lettered:
raise PySimpleValidateException('numbered and lettered arguments cannot both be True')
if len(choices) != len(set(choices)):
raise PySimpleValidateException('duplicate entries in choices argument')
if not caseSensitive and len(choices) != len(set([choice.upper() for choice in choices])):
raise PySimpleValidateException('duplicate case-insensitive entries in choices argument') | python | def _validateParamsFor_validateChoice(choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
numbered=False, lettered=False, caseSensitive=False, excMsg=None):
"""Raises PySimpleValidateException if the arguments are invalid. This is called by
the validateChoice() function to check its arguments. This code was
refactored out to a separate function so that the PyInputPlus module (or
other modules) could check their parameters' arguments for inputChoice().
"""
if not isinstance(caseSensitive, bool):
raise PySimpleValidateException('caseSensitive argument must be a bool')
try:
len(choices)
except:
raise PySimpleValidateException('choices arg must be a sequence')
if blank == False and len(choices) < 2:
raise PySimpleValidateException('choices must have at least two items if blank is False')
elif blank == True and len(choices) < 1:
raise PySimpleValidateException('choices must have at least one item')
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=None, blocklistRegexes=blocklistRegexes)
for choice in choices:
if not isinstance(choice, str):
raise PySimpleValidateException('choice %r must be a string' % (_errstr(choice)))
if lettered and len(choices) > 26:
raise PySimpleValidateException('lettered argument cannot be True if there are more than 26 choices')
if numbered and lettered:
raise PySimpleValidateException('numbered and lettered arguments cannot both be True')
if len(choices) != len(set(choices)):
raise PySimpleValidateException('duplicate entries in choices argument')
if not caseSensitive and len(choices) != len(set([choice.upper() for choice in choices])):
raise PySimpleValidateException('duplicate case-insensitive entries in choices argument') | [
"def",
"_validateParamsFor_validateChoice",
"(",
"choices",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"numbered",
"=",
"False",
",",
"lettered",
"=",
"False",
",",
"caseSensitive",
"=",
"False",
",",
"excMsg",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"caseSensitive",
",",
"bool",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'caseSensitive argument must be a bool'",
")",
"try",
":",
"len",
"(",
"choices",
")",
"except",
":",
"raise",
"PySimpleValidateException",
"(",
"'choices arg must be a sequence'",
")",
"if",
"blank",
"==",
"False",
"and",
"len",
"(",
"choices",
")",
"<",
"2",
":",
"raise",
"PySimpleValidateException",
"(",
"'choices must have at least two items if blank is False'",
")",
"elif",
"blank",
"==",
"True",
"and",
"len",
"(",
"choices",
")",
"<",
"1",
":",
"raise",
"PySimpleValidateException",
"(",
"'choices must have at least one item'",
")",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"for",
"choice",
"in",
"choices",
":",
"if",
"not",
"isinstance",
"(",
"choice",
",",
"str",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'choice %r must be a string'",
"%",
"(",
"_errstr",
"(",
"choice",
")",
")",
")",
"if",
"lettered",
"and",
"len",
"(",
"choices",
")",
">",
"26",
":",
"raise",
"PySimpleValidateException",
"(",
"'lettered argument cannot be True if there are more than 26 choices'",
")",
"if",
"numbered",
"and",
"lettered",
":",
"raise",
"PySimpleValidateException",
"(",
"'numbered and lettered arguments cannot both be True'",
")",
"if",
"len",
"(",
"choices",
")",
"!=",
"len",
"(",
"set",
"(",
"choices",
")",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'duplicate entries in choices argument'",
")",
"if",
"not",
"caseSensitive",
"and",
"len",
"(",
"choices",
")",
"!=",
"len",
"(",
"set",
"(",
"[",
"choice",
".",
"upper",
"(",
")",
"for",
"choice",
"in",
"choices",
"]",
")",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'duplicate case-insensitive entries in choices argument'",
")"
] | Raises PySimpleValidateException if the arguments are invalid. This is called by
the validateChoice() function to check its arguments. This code was
refactored out to a separate function so that the PyInputPlus module (or
other modules) could check their parameters' arguments for inputChoice(). | [
"Raises",
"PySimpleValidateException",
"if",
"the",
"arguments",
"are",
"invalid",
".",
"This",
"is",
"called",
"by",
"the",
"validateChoice",
"()",
"function",
"to",
"check",
"its",
"arguments",
".",
"This",
"code",
"was",
"refactored",
"out",
"to",
"a",
"separate",
"function",
"so",
"that",
"the",
"PyInputPlus",
"module",
"(",
"or",
"other",
"modules",
")",
"could",
"check",
"their",
"parameters",
"arguments",
"for",
"inputChoice",
"()",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L488-L523 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateChoice | def validateChoice(value, choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
numbered=False, lettered=False, caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not one of the values in
choices. Returns the selected choice.
Returns the value in choices that was selected, so it can be used inline
in an expression:
print('You chose ' + validateChoice(your_choice, ['cat', 'dog']))
Note that value itself is not returned: validateChoice('CAT', ['cat', 'dog'])
will return 'cat', not 'CAT'.
If lettered is True, lower or uppercase letters will be accepted regardless
of what caseSensitive is set to. The caseSensitive argument only matters
for matching with the text of the strings in choices.
* value (str): The value being validated.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* numbered (bool): If True, this function will also accept a string of the choice's number, i.e. '1' or '2'.
* lettered (bool): If True, this function will also accept a string of the choice's letter, i.e. 'A' or 'B' or 'a' or 'b'.
* caseSensitive (bool): If True, then the exact case of the option must be entered.
* excMsg (str): A custom message to use in the raised ValidationException.
Returns the choice selected as it appeared in choices. That is, if 'cat'
was a choice and the user entered 'CAT' while caseSensitive is False,
this function will return 'cat'.
>>> import pysimplevalidate as pysv
>>> pysv.validateChoice('dog', ['dog', 'cat', 'moose'])
'dog'
>>> pysv.validateChoice('DOG', ['dog', 'cat', 'moose'])
'dog'
>>> pysv.validateChoice('2', ['dog', 'cat', 'moose'], numbered=True)
'cat'
>>> pysv.validateChoice('a', ['dog', 'cat', 'moose'], lettered=True)
'dog'
>>> pysv.validateChoice('C', ['dog', 'cat', 'moose'], lettered=True)
'moose'
>>> pysv.validateChoice('dog', ['dog', 'cat', 'moose'], lettered=True)
'dog'
>>> pysv.validateChoice('spider', ['dog', 'cat', 'moose'])
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'spider' is not a valid choice.
"""
# Validate parameters.
_validateParamsFor_validateChoice(choices=choices, blank=blank, strip=strip, allowlistRegexes=None,
blocklistRegexes=blocklistRegexes, numbered=numbered, lettered=lettered, caseSensitive=caseSensitive)
if '' in choices:
# blank needs to be set to True here, otherwise '' won't be accepted as a choice.
blank = True
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
# Validate against choices.
if value in choices:
return value
if numbered and value.isdigit() and 0 < int(value) <= len(choices): # value must be 1 to len(choices)
# Numbered options begins at 1, not 0.
return choices[int(value) - 1] # -1 because the numbers are 1 to len(choices) but the index are 0 to len(choices) - 1
if lettered and len(value) == 1 and value.isalpha() and 0 < ord(value.upper()) - 64 <= len(choices):
# Lettered options are always case-insensitive.
return choices[ord(value.upper()) - 65]
if not caseSensitive and value.upper() in [choice.upper() for choice in choices]:
# Return the original item in choices that value has a case-insensitive match with.
return choices[[choice.upper() for choice in choices].index(value.upper())]
_raiseValidationException(_('%r is not a valid choice.') % (_errstr(value)), excMsg) | python | def validateChoice(value, choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
numbered=False, lettered=False, caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not one of the values in
choices. Returns the selected choice.
Returns the value in choices that was selected, so it can be used inline
in an expression:
print('You chose ' + validateChoice(your_choice, ['cat', 'dog']))
Note that value itself is not returned: validateChoice('CAT', ['cat', 'dog'])
will return 'cat', not 'CAT'.
If lettered is True, lower or uppercase letters will be accepted regardless
of what caseSensitive is set to. The caseSensitive argument only matters
for matching with the text of the strings in choices.
* value (str): The value being validated.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* numbered (bool): If True, this function will also accept a string of the choice's number, i.e. '1' or '2'.
* lettered (bool): If True, this function will also accept a string of the choice's letter, i.e. 'A' or 'B' or 'a' or 'b'.
* caseSensitive (bool): If True, then the exact case of the option must be entered.
* excMsg (str): A custom message to use in the raised ValidationException.
Returns the choice selected as it appeared in choices. That is, if 'cat'
was a choice and the user entered 'CAT' while caseSensitive is False,
this function will return 'cat'.
>>> import pysimplevalidate as pysv
>>> pysv.validateChoice('dog', ['dog', 'cat', 'moose'])
'dog'
>>> pysv.validateChoice('DOG', ['dog', 'cat', 'moose'])
'dog'
>>> pysv.validateChoice('2', ['dog', 'cat', 'moose'], numbered=True)
'cat'
>>> pysv.validateChoice('a', ['dog', 'cat', 'moose'], lettered=True)
'dog'
>>> pysv.validateChoice('C', ['dog', 'cat', 'moose'], lettered=True)
'moose'
>>> pysv.validateChoice('dog', ['dog', 'cat', 'moose'], lettered=True)
'dog'
>>> pysv.validateChoice('spider', ['dog', 'cat', 'moose'])
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'spider' is not a valid choice.
"""
# Validate parameters.
_validateParamsFor_validateChoice(choices=choices, blank=blank, strip=strip, allowlistRegexes=None,
blocklistRegexes=blocklistRegexes, numbered=numbered, lettered=lettered, caseSensitive=caseSensitive)
if '' in choices:
# blank needs to be set to True here, otherwise '' won't be accepted as a choice.
blank = True
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
# Validate against choices.
if value in choices:
return value
if numbered and value.isdigit() and 0 < int(value) <= len(choices): # value must be 1 to len(choices)
# Numbered options begins at 1, not 0.
return choices[int(value) - 1] # -1 because the numbers are 1 to len(choices) but the index are 0 to len(choices) - 1
if lettered and len(value) == 1 and value.isalpha() and 0 < ord(value.upper()) - 64 <= len(choices):
# Lettered options are always case-insensitive.
return choices[ord(value.upper()) - 65]
if not caseSensitive and value.upper() in [choice.upper() for choice in choices]:
# Return the original item in choices that value has a case-insensitive match with.
return choices[[choice.upper() for choice in choices].index(value.upper())]
_raiseValidationException(_('%r is not a valid choice.') % (_errstr(value)), excMsg) | [
"def",
"validateChoice",
"(",
"value",
",",
"choices",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"numbered",
"=",
"False",
",",
"lettered",
"=",
"False",
",",
"caseSensitive",
"=",
"False",
",",
"excMsg",
"=",
"None",
")",
":",
"# Validate parameters.",
"_validateParamsFor_validateChoice",
"(",
"choices",
"=",
"choices",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
",",
"numbered",
"=",
"numbered",
",",
"lettered",
"=",
"lettered",
",",
"caseSensitive",
"=",
"caseSensitive",
")",
"if",
"''",
"in",
"choices",
":",
"# blank needs to be set to True here, otherwise '' won't be accepted as a choice.",
"blank",
"=",
"True",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"# Validate against choices.",
"if",
"value",
"in",
"choices",
":",
"return",
"value",
"if",
"numbered",
"and",
"value",
".",
"isdigit",
"(",
")",
"and",
"0",
"<",
"int",
"(",
"value",
")",
"<=",
"len",
"(",
"choices",
")",
":",
"# value must be 1 to len(choices)",
"# Numbered options begins at 1, not 0.",
"return",
"choices",
"[",
"int",
"(",
"value",
")",
"-",
"1",
"]",
"# -1 because the numbers are 1 to len(choices) but the index are 0 to len(choices) - 1",
"if",
"lettered",
"and",
"len",
"(",
"value",
")",
"==",
"1",
"and",
"value",
".",
"isalpha",
"(",
")",
"and",
"0",
"<",
"ord",
"(",
"value",
".",
"upper",
"(",
")",
")",
"-",
"64",
"<=",
"len",
"(",
"choices",
")",
":",
"# Lettered options are always case-insensitive.",
"return",
"choices",
"[",
"ord",
"(",
"value",
".",
"upper",
"(",
")",
")",
"-",
"65",
"]",
"if",
"not",
"caseSensitive",
"and",
"value",
".",
"upper",
"(",
")",
"in",
"[",
"choice",
".",
"upper",
"(",
")",
"for",
"choice",
"in",
"choices",
"]",
":",
"# Return the original item in choices that value has a case-insensitive match with.",
"return",
"choices",
"[",
"[",
"choice",
".",
"upper",
"(",
")",
"for",
"choice",
"in",
"choices",
"]",
".",
"index",
"(",
"value",
".",
"upper",
"(",
")",
")",
"]",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid choice.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not one of the values in
choices. Returns the selected choice.
Returns the value in choices that was selected, so it can be used inline
in an expression:
print('You chose ' + validateChoice(your_choice, ['cat', 'dog']))
Note that value itself is not returned: validateChoice('CAT', ['cat', 'dog'])
will return 'cat', not 'CAT'.
If lettered is True, lower or uppercase letters will be accepted regardless
of what caseSensitive is set to. The caseSensitive argument only matters
for matching with the text of the strings in choices.
* value (str): The value being validated.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* numbered (bool): If True, this function will also accept a string of the choice's number, i.e. '1' or '2'.
* lettered (bool): If True, this function will also accept a string of the choice's letter, i.e. 'A' or 'B' or 'a' or 'b'.
* caseSensitive (bool): If True, then the exact case of the option must be entered.
* excMsg (str): A custom message to use in the raised ValidationException.
Returns the choice selected as it appeared in choices. That is, if 'cat'
was a choice and the user entered 'CAT' while caseSensitive is False,
this function will return 'cat'.
>>> import pysimplevalidate as pysv
>>> pysv.validateChoice('dog', ['dog', 'cat', 'moose'])
'dog'
>>> pysv.validateChoice('DOG', ['dog', 'cat', 'moose'])
'dog'
>>> pysv.validateChoice('2', ['dog', 'cat', 'moose'], numbered=True)
'cat'
>>> pysv.validateChoice('a', ['dog', 'cat', 'moose'], lettered=True)
'dog'
>>> pysv.validateChoice('C', ['dog', 'cat', 'moose'], lettered=True)
'moose'
>>> pysv.validateChoice('dog', ['dog', 'cat', 'moose'], lettered=True)
'dog'
>>> pysv.validateChoice('spider', ['dog', 'cat', 'moose'])
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'spider' is not a valid choice. | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"one",
"of",
"the",
"values",
"in",
"choices",
".",
"Returns",
"the",
"selected",
"choice",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L526-L608 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | _validateParamsFor__validateToDateTimeFormat | def _validateParamsFor__validateToDateTimeFormat(formats, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises PySimpleValidateException if the arguments are invalid. This is called by
the validateTime() function to check its arguments. This code was
refactored out to a separate function so that the PyInputPlus module (or
other modules) could check their parameters' arguments for inputTime().
"""
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
if formats is None:
raise PySimpleValidateException('formats parameter must be specified')
if isinstance(formats, str):
raise PySimpleValidateException('formats argument must be a non-str sequence of strftime format strings')
try:
len(formats)
except:
raise PySimpleValidateException('formats argument must be a non-str sequence of strftime format strings')
for format in formats:
try:
time.strftime(format) # This will raise an exception if the format is invalid.
except:
raise PySimpleValidateException('formats argument contains invalid strftime format strings') | python | def _validateParamsFor__validateToDateTimeFormat(formats, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises PySimpleValidateException if the arguments are invalid. This is called by
the validateTime() function to check its arguments. This code was
refactored out to a separate function so that the PyInputPlus module (or
other modules) could check their parameters' arguments for inputTime().
"""
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
if formats is None:
raise PySimpleValidateException('formats parameter must be specified')
if isinstance(formats, str):
raise PySimpleValidateException('formats argument must be a non-str sequence of strftime format strings')
try:
len(formats)
except:
raise PySimpleValidateException('formats argument must be a non-str sequence of strftime format strings')
for format in formats:
try:
time.strftime(format) # This will raise an exception if the format is invalid.
except:
raise PySimpleValidateException('formats argument contains invalid strftime format strings') | [
"def",
"_validateParamsFor__validateToDateTimeFormat",
"(",
"formats",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"if",
"formats",
"is",
"None",
":",
"raise",
"PySimpleValidateException",
"(",
"'formats parameter must be specified'",
")",
"if",
"isinstance",
"(",
"formats",
",",
"str",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'formats argument must be a non-str sequence of strftime format strings'",
")",
"try",
":",
"len",
"(",
"formats",
")",
"except",
":",
"raise",
"PySimpleValidateException",
"(",
"'formats argument must be a non-str sequence of strftime format strings'",
")",
"for",
"format",
"in",
"formats",
":",
"try",
":",
"time",
".",
"strftime",
"(",
"format",
")",
"# This will raise an exception if the format is invalid.",
"except",
":",
"raise",
"PySimpleValidateException",
"(",
"'formats argument contains invalid strftime format strings'",
")"
] | Raises PySimpleValidateException if the arguments are invalid. This is called by
the validateTime() function to check its arguments. This code was
refactored out to a separate function so that the PyInputPlus module (or
other modules) could check their parameters' arguments for inputTime(). | [
"Raises",
"PySimpleValidateException",
"if",
"the",
"arguments",
"are",
"invalid",
".",
"This",
"is",
"called",
"by",
"the",
"validateTime",
"()",
"function",
"to",
"check",
"its",
"arguments",
".",
"This",
"code",
"was",
"refactored",
"out",
"to",
"a",
"separate",
"function",
"so",
"that",
"the",
"PyInputPlus",
"module",
"(",
"or",
"other",
"modules",
")",
"could",
"check",
"their",
"parameters",
"arguments",
"for",
"inputTime",
"()",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L611-L633 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateTime | def validateTime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%H:%M:%S', '%H:%M', '%X'), excMsg=None):
"""Raises ValidationException if value is not a time formatted in one
of the formats formats. Returns a datetime.time object of value.
* value (str): The value being validated as a time.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid time.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateTime('12:00:01')
datetime.time(12, 0, 1)
>>> pysv.validateTime('13:00:01')
datetime.time(13, 0, 1)
>>> pysv.validateTime('25:00:01')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '25:00:01' is not a valid time.
>>> pysv.validateTime('hour 12 minute 01', formats=['hour %H minute %M'])
datetime.time(12, 1)
"""
# TODO - handle this
# Reuse the logic in _validateToDateTimeFormat() for this function.
try:
dt = _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
return datetime.time(dt.hour, dt.minute, dt.second, dt.microsecond)
except ValidationException:
_raiseValidationException(_('%r is not a valid time.') % (_errstr(value)), excMsg) | python | def validateTime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%H:%M:%S', '%H:%M', '%X'), excMsg=None):
"""Raises ValidationException if value is not a time formatted in one
of the formats formats. Returns a datetime.time object of value.
* value (str): The value being validated as a time.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid time.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateTime('12:00:01')
datetime.time(12, 0, 1)
>>> pysv.validateTime('13:00:01')
datetime.time(13, 0, 1)
>>> pysv.validateTime('25:00:01')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '25:00:01' is not a valid time.
>>> pysv.validateTime('hour 12 minute 01', formats=['hour %H minute %M'])
datetime.time(12, 1)
"""
# TODO - handle this
# Reuse the logic in _validateToDateTimeFormat() for this function.
try:
dt = _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
return datetime.time(dt.hour, dt.minute, dt.second, dt.microsecond)
except ValidationException:
_raiseValidationException(_('%r is not a valid time.') % (_errstr(value)), excMsg) | [
"def",
"validateTime",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"formats",
"=",
"(",
"'%H:%M:%S'",
",",
"'%H:%M'",
",",
"'%X'",
")",
",",
"excMsg",
"=",
"None",
")",
":",
"# TODO - handle this",
"# Reuse the logic in _validateToDateTimeFormat() for this function.",
"try",
":",
"dt",
"=",
"_validateToDateTimeFormat",
"(",
"value",
",",
"formats",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"return",
"datetime",
".",
"time",
"(",
"dt",
".",
"hour",
",",
"dt",
".",
"minute",
",",
"dt",
".",
"second",
",",
"dt",
".",
"microsecond",
")",
"except",
"ValidationException",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid time.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not a time formatted in one
of the formats formats. Returns a datetime.time object of value.
* value (str): The value being validated as a time.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid time.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateTime('12:00:01')
datetime.time(12, 0, 1)
>>> pysv.validateTime('13:00:01')
datetime.time(13, 0, 1)
>>> pysv.validateTime('25:00:01')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '25:00:01' is not a valid time.
>>> pysv.validateTime('hour 12 minute 01', formats=['hour %H minute %M'])
datetime.time(12, 1) | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"time",
"formatted",
"in",
"one",
"of",
"the",
"formats",
"formats",
".",
"Returns",
"a",
"datetime",
".",
"time",
"object",
"of",
"value",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L658-L691 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateDate | def validateDate(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%Y/%m/%d', '%y/%m/%d', '%m/%d/%Y', '%m/%d/%y', '%x'), excMsg=None):
"""Raises ValidationException if value is not a time formatted in one
of the formats formats. Returns a datetime.date object of value.
* value (str): The value being validated as a time.
* blank (bool): If True, a blank string for value will be accepted.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid date.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDate('2/29/2004')
datetime.date(2004, 2, 29)
>>> pysv.validateDate('2/29/2005')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '2/29/2005' is not a valid date.
>>> pysv.validateDate('September 2019', formats=['%B %Y'])
datetime.date(2019, 9, 1)
"""
# Reuse the logic in _validateToDateTimeFormat() for this function.
try:
dt = _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
return datetime.date(dt.year, dt.month, dt.day)
except ValidationException:
_raiseValidationException(_('%r is not a valid date.') % (_errstr(value)), excMsg) | python | def validateDate(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%Y/%m/%d', '%y/%m/%d', '%m/%d/%Y', '%m/%d/%y', '%x'), excMsg=None):
"""Raises ValidationException if value is not a time formatted in one
of the formats formats. Returns a datetime.date object of value.
* value (str): The value being validated as a time.
* blank (bool): If True, a blank string for value will be accepted.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid date.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDate('2/29/2004')
datetime.date(2004, 2, 29)
>>> pysv.validateDate('2/29/2005')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '2/29/2005' is not a valid date.
>>> pysv.validateDate('September 2019', formats=['%B %Y'])
datetime.date(2019, 9, 1)
"""
# Reuse the logic in _validateToDateTimeFormat() for this function.
try:
dt = _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
return datetime.date(dt.year, dt.month, dt.day)
except ValidationException:
_raiseValidationException(_('%r is not a valid date.') % (_errstr(value)), excMsg) | [
"def",
"validateDate",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"formats",
"=",
"(",
"'%Y/%m/%d'",
",",
"'%y/%m/%d'",
",",
"'%m/%d/%Y'",
",",
"'%m/%d/%y'",
",",
"'%x'",
")",
",",
"excMsg",
"=",
"None",
")",
":",
"# Reuse the logic in _validateToDateTimeFormat() for this function.",
"try",
":",
"dt",
"=",
"_validateToDateTimeFormat",
"(",
"value",
",",
"formats",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"return",
"datetime",
".",
"date",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
")",
"except",
"ValidationException",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid date.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not a time formatted in one
of the formats formats. Returns a datetime.date object of value.
* value (str): The value being validated as a time.
* blank (bool): If True, a blank string for value will be accepted.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid date.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDate('2/29/2004')
datetime.date(2004, 2, 29)
>>> pysv.validateDate('2/29/2005')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '2/29/2005' is not a valid date.
>>> pysv.validateDate('September 2019', formats=['%B %Y'])
datetime.date(2019, 9, 1) | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"time",
"formatted",
"in",
"one",
"of",
"the",
"formats",
"formats",
".",
"Returns",
"a",
"datetime",
".",
"date",
"object",
"of",
"value",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L694-L722 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateDatetime | def validateDatetime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S',
'%Y/%m/%d %H:%M', '%y/%m/%d %H:%M', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M', '%x %H:%M',
'%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S'), excMsg=None):
"""Raises ValidationException if value is not a datetime formatted in one
of the formats formats. Returns a datetime.datetime object of value.
* value (str): The value being validated as a datetime.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid datetime.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDatetime('2018/10/31 12:00:01')
datetime.datetime(2018, 10, 31, 12, 0, 1)
>>> pysv.validateDatetime('10/31/2018 12:00:01')
datetime.datetime(2018, 10, 31, 12, 0, 1)
>>> pysv.validateDatetime('10/31/2018')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '10/31/2018' is not a valid date and time.
"""
# Reuse the logic in _validateToDateTimeFormat() for this function.
try:
return _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
except ValidationException:
_raiseValidationException(_('%r is not a valid date and time.') % (_errstr(value)), excMsg) | python | def validateDatetime(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
formats=('%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S',
'%Y/%m/%d %H:%M', '%y/%m/%d %H:%M', '%m/%d/%Y %H:%M', '%m/%d/%y %H:%M', '%x %H:%M',
'%Y/%m/%d %H:%M:%S', '%y/%m/%d %H:%M:%S', '%m/%d/%Y %H:%M:%S', '%m/%d/%y %H:%M:%S', '%x %H:%M:%S'), excMsg=None):
"""Raises ValidationException if value is not a datetime formatted in one
of the formats formats. Returns a datetime.datetime object of value.
* value (str): The value being validated as a datetime.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid datetime.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDatetime('2018/10/31 12:00:01')
datetime.datetime(2018, 10, 31, 12, 0, 1)
>>> pysv.validateDatetime('10/31/2018 12:00:01')
datetime.datetime(2018, 10, 31, 12, 0, 1)
>>> pysv.validateDatetime('10/31/2018')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '10/31/2018' is not a valid date and time.
"""
# Reuse the logic in _validateToDateTimeFormat() for this function.
try:
return _validateToDateTimeFormat(value, formats, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
except ValidationException:
_raiseValidationException(_('%r is not a valid date and time.') % (_errstr(value)), excMsg) | [
"def",
"validateDatetime",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"formats",
"=",
"(",
"'%Y/%m/%d %H:%M:%S'",
",",
"'%y/%m/%d %H:%M:%S'",
",",
"'%m/%d/%Y %H:%M:%S'",
",",
"'%m/%d/%y %H:%M:%S'",
",",
"'%x %H:%M:%S'",
",",
"'%Y/%m/%d %H:%M'",
",",
"'%y/%m/%d %H:%M'",
",",
"'%m/%d/%Y %H:%M'",
",",
"'%m/%d/%y %H:%M'",
",",
"'%x %H:%M'",
",",
"'%Y/%m/%d %H:%M:%S'",
",",
"'%y/%m/%d %H:%M:%S'",
",",
"'%m/%d/%Y %H:%M:%S'",
",",
"'%m/%d/%y %H:%M:%S'",
",",
"'%x %H:%M:%S'",
")",
",",
"excMsg",
"=",
"None",
")",
":",
"# Reuse the logic in _validateToDateTimeFormat() for this function.",
"try",
":",
"return",
"_validateToDateTimeFormat",
"(",
"value",
",",
"formats",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"except",
"ValidationException",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid date and time.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not a datetime formatted in one
of the formats formats. Returns a datetime.datetime object of value.
* value (str): The value being validated as a datetime.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* formats: A tuple of strings that can be passed to time.strftime, dictating the possible formats for a valid datetime.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDatetime('2018/10/31 12:00:01')
datetime.datetime(2018, 10, 31, 12, 0, 1)
>>> pysv.validateDatetime('10/31/2018 12:00:01')
datetime.datetime(2018, 10, 31, 12, 0, 1)
>>> pysv.validateDatetime('10/31/2018')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '10/31/2018' is not a valid date and time. | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"datetime",
"formatted",
"in",
"one",
"of",
"the",
"formats",
"formats",
".",
"Returns",
"a",
"datetime",
".",
"datetime",
"object",
"of",
"value",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L725-L755 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateFilename | def validateFilename(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a valid filename.
Filenames can't contain \\ / : * ? " < > | or end with a space.
Returns the value argument.
Note that this validates filenames, not filepaths. The / and \\ characters
are invalid for filenames.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateFilename('foobar.txt')
'foobar.txt'
>>> pysv.validateFilename('???.exe')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '???.exe' is not a valid filename.
>>> pysv.validateFilename('/full/path/to/foo.txt')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '/full/path/to/foo.txt' is not a valid filename.
"""
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
if (value != value.strip()) or (any(c in value for c in '\\/:*?"<>|')):
_raiseValidationException(_('%r is not a valid filename.') % (_errstr(value)), excMsg)
return value | python | def validateFilename(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a valid filename.
Filenames can't contain \\ / : * ? " < > | or end with a space.
Returns the value argument.
Note that this validates filenames, not filepaths. The / and \\ characters
are invalid for filenames.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateFilename('foobar.txt')
'foobar.txt'
>>> pysv.validateFilename('???.exe')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '???.exe' is not a valid filename.
>>> pysv.validateFilename('/full/path/to/foo.txt')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '/full/path/to/foo.txt' is not a valid filename.
"""
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
if (value != value.strip()) or (any(c in value for c in '\\/:*?"<>|')):
_raiseValidationException(_('%r is not a valid filename.') % (_errstr(value)), excMsg)
return value | [
"def",
"validateFilename",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"if",
"(",
"value",
"!=",
"value",
".",
"strip",
"(",
")",
")",
"or",
"(",
"any",
"(",
"c",
"in",
"value",
"for",
"c",
"in",
"'\\\\/:*?\"<>|'",
")",
")",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid filename.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")",
"return",
"value"
] | Raises ValidationException if value is not a valid filename.
Filenames can't contain \\ / : * ? " < > | or end with a space.
Returns the value argument.
Note that this validates filenames, not filepaths. The / and \\ characters
are invalid for filenames.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateFilename('foobar.txt')
'foobar.txt'
>>> pysv.validateFilename('???.exe')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '???.exe' is not a valid filename.
>>> pysv.validateFilename('/full/path/to/foo.txt')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '/full/path/to/foo.txt' is not a valid filename. | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"valid",
"filename",
".",
"Filenames",
"can",
"t",
"contain",
"\\\\",
"/",
":",
"*",
"?",
"<",
">",
"|",
"or",
"end",
"with",
"a",
"space",
".",
"Returns",
"the",
"value",
"argument",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L758-L792 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateFilepath | def validateFilepath(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, mustExist=False):
r"""Raises ValidationException if value is not a valid filename.
Filenames can't contain \\ / : * ? " < > |
Returns the value argument.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateFilepath('foo.txt')
'foo.txt'
>>> pysv.validateFilepath('/spam/foo.txt')
'/spam/foo.txt'
>>> pysv.validateFilepath(r'c:\spam\foo.txt')
'c:\\spam\\foo.txt'
>>> pysv.validateFilepath(r'c:\spam\???.txt')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'c:\\spam\\???.txt' is not a valid file path.
"""
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
if (value != value.strip()) or (any(c in value for c in '*?"<>|')): # Same as validateFilename, except we allow \ and / and :
if ':' in value:
if value.find(':', 2) != -1 or not value[0].isalpha():
# For Windows: Colon can only be found at the beginning, e.g. 'C:\', or the first letter is not a letter drive.
_raiseValidationException(_('%r is not a valid file path.') % (_errstr(value)), excMsg)
_raiseValidationException(_('%r is not a valid file path.') % (_errstr(value)), excMsg)
return value
raise NotImplementedError() | python | def validateFilepath(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, mustExist=False):
r"""Raises ValidationException if value is not a valid filename.
Filenames can't contain \\ / : * ? " < > |
Returns the value argument.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateFilepath('foo.txt')
'foo.txt'
>>> pysv.validateFilepath('/spam/foo.txt')
'/spam/foo.txt'
>>> pysv.validateFilepath(r'c:\spam\foo.txt')
'c:\\spam\\foo.txt'
>>> pysv.validateFilepath(r'c:\spam\???.txt')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'c:\\spam\\???.txt' is not a valid file path.
"""
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
if (value != value.strip()) or (any(c in value for c in '*?"<>|')): # Same as validateFilename, except we allow \ and / and :
if ':' in value:
if value.find(':', 2) != -1 or not value[0].isalpha():
# For Windows: Colon can only be found at the beginning, e.g. 'C:\', or the first letter is not a letter drive.
_raiseValidationException(_('%r is not a valid file path.') % (_errstr(value)), excMsg)
_raiseValidationException(_('%r is not a valid file path.') % (_errstr(value)), excMsg)
return value
raise NotImplementedError() | [
"def",
"validateFilepath",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
",",
"mustExist",
"=",
"False",
")",
":",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"if",
"(",
"value",
"!=",
"value",
".",
"strip",
"(",
")",
")",
"or",
"(",
"any",
"(",
"c",
"in",
"value",
"for",
"c",
"in",
"'*?\"<>|'",
")",
")",
":",
"# Same as validateFilename, except we allow \\ and / and :",
"if",
"':'",
"in",
"value",
":",
"if",
"value",
".",
"find",
"(",
"':'",
",",
"2",
")",
"!=",
"-",
"1",
"or",
"not",
"value",
"[",
"0",
"]",
".",
"isalpha",
"(",
")",
":",
"# For Windows: Colon can only be found at the beginning, e.g. 'C:\\', or the first letter is not a letter drive.",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid file path.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid file path.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")",
"return",
"value",
"raise",
"NotImplementedError",
"(",
")"
] | r"""Raises ValidationException if value is not a valid filename.
Filenames can't contain \\ / : * ? " < > |
Returns the value argument.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateFilepath('foo.txt')
'foo.txt'
>>> pysv.validateFilepath('/spam/foo.txt')
'/spam/foo.txt'
>>> pysv.validateFilepath(r'c:\spam\foo.txt')
'c:\\spam\\foo.txt'
>>> pysv.validateFilepath(r'c:\spam\???.txt')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'c:\\spam\\???.txt' is not a valid file path. | [
"r",
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"valid",
"filename",
".",
"Filenames",
"can",
"t",
"contain",
"\\\\",
"/",
":",
"*",
"?",
"<",
">",
"|",
"Returns",
"the",
"value",
"argument",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L795-L830 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateIP | def validateIP(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not an IPv4 or IPv6 address.
Returns the value argument.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateIP('127.0.0.1')
'127.0.0.1'
>>> pysv.validateIP('255.255.255.255')
'255.255.255.255'
>>> pysv.validateIP('256.256.256.256')
Traceback (most recent call last):
pysimplevalidate.ValidationException: '256.256.256.256' is not a valid IP address.
>>> pysv.validateIP('1:2:3:4:5:6:7:8')
'1:2:3:4:5:6:7:8'
>>> pysv.validateIP('1::8')
'1::8'
>>> pysv.validateIP('fe80::7:8%eth0')
'fe80::7:8%eth0'
>>> pysv.validateIP('::255.255.255.255')
'::255.255.255.255'
"""
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
# Reuse the logic in validateRegex()
try:
try:
# Check if value is an IPv4 address.
if validateRegex(value=value, regex=IPV4_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes):
return value
except:
pass # Go on to check if it's an IPv6 address.
# Check if value is an IPv6 address.
if validateRegex(value=value, regex=IPV6_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes):
return value
except ValidationException:
_raiseValidationException(_('%r is not a valid IP address.') % (_errstr(value)), excMsg) | python | def validateIP(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not an IPv4 or IPv6 address.
Returns the value argument.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateIP('127.0.0.1')
'127.0.0.1'
>>> pysv.validateIP('255.255.255.255')
'255.255.255.255'
>>> pysv.validateIP('256.256.256.256')
Traceback (most recent call last):
pysimplevalidate.ValidationException: '256.256.256.256' is not a valid IP address.
>>> pysv.validateIP('1:2:3:4:5:6:7:8')
'1:2:3:4:5:6:7:8'
>>> pysv.validateIP('1::8')
'1::8'
>>> pysv.validateIP('fe80::7:8%eth0')
'fe80::7:8%eth0'
>>> pysv.validateIP('::255.255.255.255')
'::255.255.255.255'
"""
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
# Reuse the logic in validateRegex()
try:
try:
# Check if value is an IPv4 address.
if validateRegex(value=value, regex=IPV4_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes):
return value
except:
pass # Go on to check if it's an IPv6 address.
# Check if value is an IPv6 address.
if validateRegex(value=value, regex=IPV6_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes):
return value
except ValidationException:
_raiseValidationException(_('%r is not a valid IP address.') % (_errstr(value)), excMsg) | [
"def",
"validateIP",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"# Validate parameters.",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"# Reuse the logic in validateRegex()",
"try",
":",
"try",
":",
"# Check if value is an IPv4 address.",
"if",
"validateRegex",
"(",
"value",
"=",
"value",
",",
"regex",
"=",
"IPV4_REGEX",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
":",
"return",
"value",
"except",
":",
"pass",
"# Go on to check if it's an IPv6 address.",
"# Check if value is an IPv6 address.",
"if",
"validateRegex",
"(",
"value",
"=",
"value",
",",
"regex",
"=",
"IPV6_REGEX",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
":",
"return",
"value",
"except",
"ValidationException",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid IP address.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not an IPv4 or IPv6 address.
Returns the value argument.
* value (str): The value being validated as an IP address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateIP('127.0.0.1')
'127.0.0.1'
>>> pysv.validateIP('255.255.255.255')
'255.255.255.255'
>>> pysv.validateIP('256.256.256.256')
Traceback (most recent call last):
pysimplevalidate.ValidationException: '256.256.256.256' is not a valid IP address.
>>> pysv.validateIP('1:2:3:4:5:6:7:8')
'1:2:3:4:5:6:7:8'
>>> pysv.validateIP('1::8')
'1::8'
>>> pysv.validateIP('fe80::7:8%eth0')
'fe80::7:8%eth0'
>>> pysv.validateIP('::255.255.255.255')
'::255.255.255.255' | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"an",
"IPv4",
"or",
"IPv6",
"address",
".",
"Returns",
"the",
"value",
"argument",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L833-L881 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateRegex | def validateRegex(value, regex, flags=0, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value does not match the regular expression in regex.
Returns the value argument.
This is similar to calling inputStr() and using the allowlistRegexes
keyword argument, however, validateRegex() allows you to pass regex
flags such as re.IGNORECASE or re.VERBOSE. You can also pass a regex
object directly.
If you want to check if a string is a regular expression string, call
validateRegexStr().
* value (str): The value being validated as a regular expression string.
* regex (str, regex): The regular expression to match the value against.
* flags (int): Identical to the flags argument in re.compile(). Pass re.VERBOSE et al here.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> pysv.validateRegex('cat bat rat', r'(cat)|(dog)|(moose)', re.IGNORECASE)
'cat'
>>> pysv.validateRegex('He said "Hello".', r'"(.*?)"', re.IGNORECASE)
'"Hello"'
"""
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
# Search value with regex, whether regex is a str or regex object.
if isinstance(regex, str):
# TODO - check flags to see they're valid regex flags.
mo = re.compile(regex, flags).search(value)
elif isinstance(regex, REGEX_TYPE):
mo = regex.search(value)
else:
raise PySimpleValidateException('regex must be a str or regex object')
if mo is not None:
return mo.group()
else:
_raiseValidationException(_('%r does not match the specified pattern.') % (_errstr(value)), excMsg) | python | def validateRegex(value, regex, flags=0, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value does not match the regular expression in regex.
Returns the value argument.
This is similar to calling inputStr() and using the allowlistRegexes
keyword argument, however, validateRegex() allows you to pass regex
flags such as re.IGNORECASE or re.VERBOSE. You can also pass a regex
object directly.
If you want to check if a string is a regular expression string, call
validateRegexStr().
* value (str): The value being validated as a regular expression string.
* regex (str, regex): The regular expression to match the value against.
* flags (int): Identical to the flags argument in re.compile(). Pass re.VERBOSE et al here.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> pysv.validateRegex('cat bat rat', r'(cat)|(dog)|(moose)', re.IGNORECASE)
'cat'
>>> pysv.validateRegex('He said "Hello".', r'"(.*?)"', re.IGNORECASE)
'"Hello"'
"""
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
# Search value with regex, whether regex is a str or regex object.
if isinstance(regex, str):
# TODO - check flags to see they're valid regex flags.
mo = re.compile(regex, flags).search(value)
elif isinstance(regex, REGEX_TYPE):
mo = regex.search(value)
else:
raise PySimpleValidateException('regex must be a str or regex object')
if mo is not None:
return mo.group()
else:
_raiseValidationException(_('%r does not match the specified pattern.') % (_errstr(value)), excMsg) | [
"def",
"validateRegex",
"(",
"value",
",",
"regex",
",",
"flags",
"=",
"0",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"# Validate parameters.",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"# Search value with regex, whether regex is a str or regex object.",
"if",
"isinstance",
"(",
"regex",
",",
"str",
")",
":",
"# TODO - check flags to see they're valid regex flags.",
"mo",
"=",
"re",
".",
"compile",
"(",
"regex",
",",
"flags",
")",
".",
"search",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"regex",
",",
"REGEX_TYPE",
")",
":",
"mo",
"=",
"regex",
".",
"search",
"(",
"value",
")",
"else",
":",
"raise",
"PySimpleValidateException",
"(",
"'regex must be a str or regex object'",
")",
"if",
"mo",
"is",
"not",
"None",
":",
"return",
"mo",
".",
"group",
"(",
")",
"else",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r does not match the specified pattern.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value does not match the regular expression in regex.
Returns the value argument.
This is similar to calling inputStr() and using the allowlistRegexes
keyword argument, however, validateRegex() allows you to pass regex
flags such as re.IGNORECASE or re.VERBOSE. You can also pass a regex
object directly.
If you want to check if a string is a regular expression string, call
validateRegexStr().
* value (str): The value being validated as a regular expression string.
* regex (str, regex): The regular expression to match the value against.
* flags (int): Identical to the flags argument in re.compile(). Pass re.VERBOSE et al here.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> pysv.validateRegex('cat bat rat', r'(cat)|(dog)|(moose)', re.IGNORECASE)
'cat'
>>> pysv.validateRegex('He said "Hello".', r'"(.*?)"', re.IGNORECASE)
'"Hello"' | [
"Raises",
"ValidationException",
"if",
"value",
"does",
"not",
"match",
"the",
"regular",
"expression",
"in",
"regex",
".",
"Returns",
"the",
"value",
"argument",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L959-L1005 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateRegexStr | def validateRegexStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value can't be used as a regular expression string.
Returns the value argument as a regex object.
If you want to check if a string matches a regular expression, call
validateRegex().
* value (str): The value being validated as a regular expression string.
* regex (str, regex): The regular expression to match the value against.
* flags (int): Identical to the flags argument in re.compile(). Pass re.VERBOSE et al here.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateRegexStr('(cat)|(dog)')
re.compile('(cat)|(dog)')
>>> pysv.validateRegexStr('"(.*?)"')
re.compile('"(.*?)"')
>>> pysv.validateRegexStr('"(.*?"')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '"(.*?"' is not a valid regular expression: missing ), unterminated subpattern at position 1
"""
# TODO - I'd be nice to check regexes in other languages, i.e. JS and Perl.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
try:
return re.compile(value)
except Exception as ex:
_raiseValidationException(_('%r is not a valid regular expression: %s') % (_errstr(value), ex), excMsg) | python | def validateRegexStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value can't be used as a regular expression string.
Returns the value argument as a regex object.
If you want to check if a string matches a regular expression, call
validateRegex().
* value (str): The value being validated as a regular expression string.
* regex (str, regex): The regular expression to match the value against.
* flags (int): Identical to the flags argument in re.compile(). Pass re.VERBOSE et al here.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateRegexStr('(cat)|(dog)')
re.compile('(cat)|(dog)')
>>> pysv.validateRegexStr('"(.*?)"')
re.compile('"(.*?)"')
>>> pysv.validateRegexStr('"(.*?"')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '"(.*?"' is not a valid regular expression: missing ), unterminated subpattern at position 1
"""
# TODO - I'd be nice to check regexes in other languages, i.e. JS and Perl.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
try:
return re.compile(value)
except Exception as ex:
_raiseValidationException(_('%r is not a valid regular expression: %s') % (_errstr(value), ex), excMsg) | [
"def",
"validateRegexStr",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"# TODO - I'd be nice to check regexes in other languages, i.e. JS and Perl.",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"try",
":",
"return",
"re",
".",
"compile",
"(",
"value",
")",
"except",
"Exception",
"as",
"ex",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid regular expression: %s'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
",",
"ex",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value can't be used as a regular expression string.
Returns the value argument as a regex object.
If you want to check if a string matches a regular expression, call
validateRegex().
* value (str): The value being validated as a regular expression string.
* regex (str, regex): The regular expression to match the value against.
* flags (int): Identical to the flags argument in re.compile(). Pass re.VERBOSE et al here.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateRegexStr('(cat)|(dog)')
re.compile('(cat)|(dog)')
>>> pysv.validateRegexStr('"(.*?)"')
re.compile('"(.*?)"')
>>> pysv.validateRegexStr('"(.*?"')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '"(.*?"' is not a valid regular expression: missing ), unterminated subpattern at position 1 | [
"Raises",
"ValidationException",
"if",
"value",
"can",
"t",
"be",
"used",
"as",
"a",
"regular",
"expression",
"string",
".",
"Returns",
"the",
"value",
"argument",
"as",
"a",
"regex",
"object",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1008-L1045 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateURL | def validateURL(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a URL.
Returns the value argument.
The "http" or "https" protocol part of the URL is optional.
* value (str): The value being validated as a URL.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateURL('https://inventwithpython.com')
'https://inventwithpython.com'
>>> pysv.validateURL('inventwithpython.com')
'inventwithpython.com'
>>> pysv.validateURL('localhost')
'localhost'
>>> pysv.validateURL('mailto:[email protected]')
'mailto:[email protected]'
>>> pysv.validateURL('ftp://example.com')
'example.com'
>>> pysv.validateURL('https://inventwithpython.com/blog/2018/02/02/how-to-ask-for-programming-help/')
'https://inventwithpython.com/blog/2018/02/02/how-to-ask-for-programming-help/'
>>> pysv.validateURL('blah blah blah')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'blah blah blah' is not a valid URL.
"""
# Reuse the logic in validateRegex()
try:
result = validateRegex(value=value, regex=URL_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
if result is not None:
return result
except ValidationException:
# 'localhost' is also an acceptable URL:
if value == 'localhost':
return value
_raiseValidationException(_('%r is not a valid URL.') % (value), excMsg) | python | def validateURL(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a URL.
Returns the value argument.
The "http" or "https" protocol part of the URL is optional.
* value (str): The value being validated as a URL.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateURL('https://inventwithpython.com')
'https://inventwithpython.com'
>>> pysv.validateURL('inventwithpython.com')
'inventwithpython.com'
>>> pysv.validateURL('localhost')
'localhost'
>>> pysv.validateURL('mailto:[email protected]')
'mailto:[email protected]'
>>> pysv.validateURL('ftp://example.com')
'example.com'
>>> pysv.validateURL('https://inventwithpython.com/blog/2018/02/02/how-to-ask-for-programming-help/')
'https://inventwithpython.com/blog/2018/02/02/how-to-ask-for-programming-help/'
>>> pysv.validateURL('blah blah blah')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'blah blah blah' is not a valid URL.
"""
# Reuse the logic in validateRegex()
try:
result = validateRegex(value=value, regex=URL_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
if result is not None:
return result
except ValidationException:
# 'localhost' is also an acceptable URL:
if value == 'localhost':
return value
_raiseValidationException(_('%r is not a valid URL.') % (value), excMsg) | [
"def",
"validateURL",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"# Reuse the logic in validateRegex()",
"try",
":",
"result",
"=",
"validateRegex",
"(",
"value",
"=",
"value",
",",
"regex",
"=",
"URL_REGEX",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"except",
"ValidationException",
":",
"# 'localhost' is also an acceptable URL:",
"if",
"value",
"==",
"'localhost'",
":",
"return",
"value",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid URL.'",
")",
"%",
"(",
"value",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not a URL.
Returns the value argument.
The "http" or "https" protocol part of the URL is optional.
* value (str): The value being validated as a URL.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateURL('https://inventwithpython.com')
'https://inventwithpython.com'
>>> pysv.validateURL('inventwithpython.com')
'inventwithpython.com'
>>> pysv.validateURL('localhost')
'localhost'
>>> pysv.validateURL('mailto:[email protected]')
'mailto:[email protected]'
>>> pysv.validateURL('ftp://example.com')
'example.com'
>>> pysv.validateURL('https://inventwithpython.com/blog/2018/02/02/how-to-ask-for-programming-help/')
'https://inventwithpython.com/blog/2018/02/02/how-to-ask-for-programming-help/'
>>> pysv.validateURL('blah blah blah')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'blah blah blah' is not a valid URL. | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"URL",
".",
"Returns",
"the",
"value",
"argument",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1048-L1090 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateEmail | def validateEmail(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not an email address.
Returns the value argument.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateEmail('[email protected]')
'[email protected]'
>>> pysv.validateEmail('alinventwithpython.com')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'alinventwithpython.com' is not a valid email address.
"""
# Reuse the logic in validateRegex()
try:
result = validateRegex(value=value, regex=EMAIL_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
if result is not None:
return result
except ValidationException:
_raiseValidationException(_('%r is not a valid email address.') % (value), excMsg) | python | def validateEmail(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not an email address.
Returns the value argument.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateEmail('[email protected]')
'[email protected]'
>>> pysv.validateEmail('alinventwithpython.com')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'alinventwithpython.com' is not a valid email address.
"""
# Reuse the logic in validateRegex()
try:
result = validateRegex(value=value, regex=EMAIL_REGEX, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
if result is not None:
return result
except ValidationException:
_raiseValidationException(_('%r is not a valid email address.') % (value), excMsg) | [
"def",
"validateEmail",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"# Reuse the logic in validateRegex()",
"try",
":",
"result",
"=",
"validateRegex",
"(",
"value",
"=",
"value",
",",
"regex",
"=",
"EMAIL_REGEX",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result",
"except",
"ValidationException",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid email address.'",
")",
"%",
"(",
"value",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not an email address.
Returns the value argument.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateEmail('[email protected]')
'[email protected]'
>>> pysv.validateEmail('alinventwithpython.com')
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: 'alinventwithpython.com' is not a valid email address. | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"an",
"email",
"address",
".",
"Returns",
"the",
"value",
"argument",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1093-L1119 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateYesNo | def validateYesNo(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, yesVal='yes', noVal='no', caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not a yes or no response.
Returns the yesVal or noVal argument, not value.
Note that value can be any case (by default) and can also just match the
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* caseSensitive (bool): Determines if value must match the case of yesVal and noVal. Defaults to False.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateYesNo('y')
'yes'
>>> pysv.validateYesNo('YES')
'yes'
>>> pysv.validateYesNo('No')
'no'
>>> pysv.validateYesNo('OUI', yesVal='oui', noVal='no')
'oui'
"""
# Validate parameters. TODO - can probably improve this to remove the duplication.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
yesVal = str(yesVal)
noVal = str(noVal)
if len(yesVal) == 0:
raise PySimpleValidateException('yesVal argument must be a non-empty string.')
if len(noVal) == 0:
raise PySimpleValidateException('noVal argument must be a non-empty string.')
if (yesVal == noVal) or (not caseSensitive and yesVal.upper() == noVal.upper()):
raise PySimpleValidateException('yesVal and noVal arguments must be different.')
if (yesVal[0] == noVal[0]) or (not caseSensitive and yesVal[0].upper() == noVal[0].upper()):
raise PySimpleValidateException('first character of yesVal and noVal arguments must be different')
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
if caseSensitive:
if value in (yesVal, yesVal[0]):
return yesVal
elif value in (noVal, noVal[0]):
return noVal
else:
if value.upper() in (yesVal.upper(), yesVal[0].upper()):
return yesVal
elif value.upper() in (noVal.upper(), noVal[0].upper()):
return noVal
_raiseValidationException(_('%r is not a valid %s/%s response.') % (_errstr(value), yesVal, noVal), excMsg) | python | def validateYesNo(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, yesVal='yes', noVal='no', caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not a yes or no response.
Returns the yesVal or noVal argument, not value.
Note that value can be any case (by default) and can also just match the
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* caseSensitive (bool): Determines if value must match the case of yesVal and noVal. Defaults to False.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateYesNo('y')
'yes'
>>> pysv.validateYesNo('YES')
'yes'
>>> pysv.validateYesNo('No')
'no'
>>> pysv.validateYesNo('OUI', yesVal='oui', noVal='no')
'oui'
"""
# Validate parameters. TODO - can probably improve this to remove the duplication.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
yesVal = str(yesVal)
noVal = str(noVal)
if len(yesVal) == 0:
raise PySimpleValidateException('yesVal argument must be a non-empty string.')
if len(noVal) == 0:
raise PySimpleValidateException('noVal argument must be a non-empty string.')
if (yesVal == noVal) or (not caseSensitive and yesVal.upper() == noVal.upper()):
raise PySimpleValidateException('yesVal and noVal arguments must be different.')
if (yesVal[0] == noVal[0]) or (not caseSensitive and yesVal[0].upper() == noVal[0].upper()):
raise PySimpleValidateException('first character of yesVal and noVal arguments must be different')
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
if caseSensitive:
if value in (yesVal, yesVal[0]):
return yesVal
elif value in (noVal, noVal[0]):
return noVal
else:
if value.upper() in (yesVal.upper(), yesVal[0].upper()):
return yesVal
elif value.upper() in (noVal.upper(), noVal[0].upper()):
return noVal
_raiseValidationException(_('%r is not a valid %s/%s response.') % (_errstr(value), yesVal, noVal), excMsg) | [
"def",
"validateYesNo",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"yesVal",
"=",
"'yes'",
",",
"noVal",
"=",
"'no'",
",",
"caseSensitive",
"=",
"False",
",",
"excMsg",
"=",
"None",
")",
":",
"# Validate parameters. TODO - can probably improve this to remove the duplication.",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"yesVal",
"=",
"str",
"(",
"yesVal",
")",
"noVal",
"=",
"str",
"(",
"noVal",
")",
"if",
"len",
"(",
"yesVal",
")",
"==",
"0",
":",
"raise",
"PySimpleValidateException",
"(",
"'yesVal argument must be a non-empty string.'",
")",
"if",
"len",
"(",
"noVal",
")",
"==",
"0",
":",
"raise",
"PySimpleValidateException",
"(",
"'noVal argument must be a non-empty string.'",
")",
"if",
"(",
"yesVal",
"==",
"noVal",
")",
"or",
"(",
"not",
"caseSensitive",
"and",
"yesVal",
".",
"upper",
"(",
")",
"==",
"noVal",
".",
"upper",
"(",
")",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'yesVal and noVal arguments must be different.'",
")",
"if",
"(",
"yesVal",
"[",
"0",
"]",
"==",
"noVal",
"[",
"0",
"]",
")",
"or",
"(",
"not",
"caseSensitive",
"and",
"yesVal",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"==",
"noVal",
"[",
"0",
"]",
".",
"upper",
"(",
")",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'first character of yesVal and noVal arguments must be different'",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"if",
"caseSensitive",
":",
"if",
"value",
"in",
"(",
"yesVal",
",",
"yesVal",
"[",
"0",
"]",
")",
":",
"return",
"yesVal",
"elif",
"value",
"in",
"(",
"noVal",
",",
"noVal",
"[",
"0",
"]",
")",
":",
"return",
"noVal",
"else",
":",
"if",
"value",
".",
"upper",
"(",
")",
"in",
"(",
"yesVal",
".",
"upper",
"(",
")",
",",
"yesVal",
"[",
"0",
"]",
".",
"upper",
"(",
")",
")",
":",
"return",
"yesVal",
"elif",
"value",
".",
"upper",
"(",
")",
"in",
"(",
"noVal",
".",
"upper",
"(",
")",
",",
"noVal",
"[",
"0",
"]",
".",
"upper",
"(",
")",
")",
":",
"return",
"noVal",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a valid %s/%s response.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
",",
"yesVal",
",",
"noVal",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not a yes or no response.
Returns the yesVal or noVal argument, not value.
Note that value can be any case (by default) and can also just match the
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* caseSensitive (bool): Determines if value must match the case of yesVal and noVal. Defaults to False.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateYesNo('y')
'yes'
>>> pysv.validateYesNo('YES')
'yes'
>>> pysv.validateYesNo('No')
'no'
>>> pysv.validateYesNo('OUI', yesVal='oui', noVal='no')
'oui' | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"yes",
"or",
"no",
"response",
".",
"Returns",
"the",
"yesVal",
"or",
"noVal",
"argument",
"not",
"value",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1122-L1180 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateBool | def validateBool(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, trueVal='True', falseVal='False', caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not an email address.
Returns the yesVal or noVal argument, not value.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateYesNo('y')
'yes'
>>> pysv.validateYesNo('YES')
'yes'
>>> pysv.validateYesNo('No')
'no'
>>> pysv.validateYesNo('OUI', yesVal='oui', noVal='no')
'oui'
"""
# Validate parameters. TODO - can probably improve this to remove the duplication.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
# Replace the exception messages used in validateYesNo():
trueVal = str(trueVal)
falseVal = str(falseVal)
if len(trueVal) == 0:
raise PySimpleValidateException('trueVal argument must be a non-empty string.')
if len(falseVal) == 0:
raise PySimpleValidateException('falseVal argument must be a non-empty string.')
if (trueVal == falseVal) or (not caseSensitive and trueVal.upper() == falseVal.upper()):
raise PySimpleValidateException('trueVal and noVal arguments must be different.')
if (trueVal[0] == falseVal[0]) or (not caseSensitive and trueVal[0].upper() == falseVal[0].upper()):
raise PySimpleValidateException('first character of trueVal and noVal arguments must be different')
result = validateYesNo(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, yesVal=trueVal, noVal=falseVal, caseSensitive=caseSensitive, excMsg=None)
# Return a bool value instead of a string.
if result == trueVal:
return True
elif result == falseVal:
return False
else:
assert False, 'inner validateYesNo() call returned something that was not yesVal or noVal. This should never happen.' | python | def validateBool(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, trueVal='True', falseVal='False', caseSensitive=False, excMsg=None):
"""Raises ValidationException if value is not an email address.
Returns the yesVal or noVal argument, not value.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateYesNo('y')
'yes'
>>> pysv.validateYesNo('YES')
'yes'
>>> pysv.validateYesNo('No')
'no'
>>> pysv.validateYesNo('OUI', yesVal='oui', noVal='no')
'oui'
"""
# Validate parameters. TODO - can probably improve this to remove the duplication.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
# Replace the exception messages used in validateYesNo():
trueVal = str(trueVal)
falseVal = str(falseVal)
if len(trueVal) == 0:
raise PySimpleValidateException('trueVal argument must be a non-empty string.')
if len(falseVal) == 0:
raise PySimpleValidateException('falseVal argument must be a non-empty string.')
if (trueVal == falseVal) or (not caseSensitive and trueVal.upper() == falseVal.upper()):
raise PySimpleValidateException('trueVal and noVal arguments must be different.')
if (trueVal[0] == falseVal[0]) or (not caseSensitive and trueVal[0].upper() == falseVal[0].upper()):
raise PySimpleValidateException('first character of trueVal and noVal arguments must be different')
result = validateYesNo(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, yesVal=trueVal, noVal=falseVal, caseSensitive=caseSensitive, excMsg=None)
# Return a bool value instead of a string.
if result == trueVal:
return True
elif result == falseVal:
return False
else:
assert False, 'inner validateYesNo() call returned something that was not yesVal or noVal. This should never happen.' | [
"def",
"validateBool",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"trueVal",
"=",
"'True'",
",",
"falseVal",
"=",
"'False'",
",",
"caseSensitive",
"=",
"False",
",",
"excMsg",
"=",
"None",
")",
":",
"# Validate parameters. TODO - can probably improve this to remove the duplication.",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"# Replace the exception messages used in validateYesNo():",
"trueVal",
"=",
"str",
"(",
"trueVal",
")",
"falseVal",
"=",
"str",
"(",
"falseVal",
")",
"if",
"len",
"(",
"trueVal",
")",
"==",
"0",
":",
"raise",
"PySimpleValidateException",
"(",
"'trueVal argument must be a non-empty string.'",
")",
"if",
"len",
"(",
"falseVal",
")",
"==",
"0",
":",
"raise",
"PySimpleValidateException",
"(",
"'falseVal argument must be a non-empty string.'",
")",
"if",
"(",
"trueVal",
"==",
"falseVal",
")",
"or",
"(",
"not",
"caseSensitive",
"and",
"trueVal",
".",
"upper",
"(",
")",
"==",
"falseVal",
".",
"upper",
"(",
")",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'trueVal and noVal arguments must be different.'",
")",
"if",
"(",
"trueVal",
"[",
"0",
"]",
"==",
"falseVal",
"[",
"0",
"]",
")",
"or",
"(",
"not",
"caseSensitive",
"and",
"trueVal",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"==",
"falseVal",
"[",
"0",
"]",
".",
"upper",
"(",
")",
")",
":",
"raise",
"PySimpleValidateException",
"(",
"'first character of trueVal and noVal arguments must be different'",
")",
"result",
"=",
"validateYesNo",
"(",
"value",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
",",
"yesVal",
"=",
"trueVal",
",",
"noVal",
"=",
"falseVal",
",",
"caseSensitive",
"=",
"caseSensitive",
",",
"excMsg",
"=",
"None",
")",
"# Return a bool value instead of a string.",
"if",
"result",
"==",
"trueVal",
":",
"return",
"True",
"elif",
"result",
"==",
"falseVal",
":",
"return",
"False",
"else",
":",
"assert",
"False",
",",
"'inner validateYesNo() call returned something that was not yesVal or noVal. This should never happen.'"
] | Raises ValidationException if value is not an email address.
Returns the yesVal or noVal argument, not value.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateYesNo('y')
'yes'
>>> pysv.validateYesNo('YES')
'yes'
>>> pysv.validateYesNo('No')
'no'
>>> pysv.validateYesNo('OUI', yesVal='oui', noVal='no')
'oui' | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"an",
"email",
"address",
".",
"Returns",
"the",
"yesVal",
"or",
"noVal",
"argument",
"not",
"value",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1183-L1232 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateState | def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False):
"""Raises ValidationException if value is not a USA state.
Returns the capitalized state abbreviation, unless returnStateName is True
in which case it returns the titlecased state name.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
* returnStateName (bool): If True, the full state name is returned, i.e. 'California'. Otherwise, the abbreviation, i.e. 'CA'. Defaults to False.
>>> import pysimplevalidate as pysv
>>> pysv.validateState('tx')
'TX'
>>> pysv.validateState('california')
'CA'
>>> pysv.validateState('WASHINGTON')
'WA'
>>> pysv.validateState('WASHINGTON', returnStateName=True)
'Washington'
"""
# TODO - note that this is USA-centric. I should work on trying to make this more international.
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
if value.upper() in USA_STATES_UPPER.keys(): # check if value is a state abbreviation
if returnStateName:
return USA_STATES[value.upper()] # Return full state name.
else:
return value.upper() # Return abbreviation.
elif value.title() in USA_STATES.values(): # check if value is a state name
if returnStateName:
return value.title() # Return full state name.
else:
return USA_STATES_REVERSED[value.title()] # Return abbreviation.
_raiseValidationException(_('%r is not a state.') % (_errstr(value)), excMsg) | python | def validateState(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None, returnStateName=False):
"""Raises ValidationException if value is not a USA state.
Returns the capitalized state abbreviation, unless returnStateName is True
in which case it returns the titlecased state name.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
* returnStateName (bool): If True, the full state name is returned, i.e. 'California'. Otherwise, the abbreviation, i.e. 'CA'. Defaults to False.
>>> import pysimplevalidate as pysv
>>> pysv.validateState('tx')
'TX'
>>> pysv.validateState('california')
'CA'
>>> pysv.validateState('WASHINGTON')
'WA'
>>> pysv.validateState('WASHINGTON', returnStateName=True)
'Washington'
"""
# TODO - note that this is USA-centric. I should work on trying to make this more international.
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
if value.upper() in USA_STATES_UPPER.keys(): # check if value is a state abbreviation
if returnStateName:
return USA_STATES[value.upper()] # Return full state name.
else:
return value.upper() # Return abbreviation.
elif value.title() in USA_STATES.values(): # check if value is a state name
if returnStateName:
return value.title() # Return full state name.
else:
return USA_STATES_REVERSED[value.title()] # Return abbreviation.
_raiseValidationException(_('%r is not a state.') % (_errstr(value)), excMsg) | [
"def",
"validateState",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
",",
"returnStateName",
"=",
"False",
")",
":",
"# TODO - note that this is USA-centric. I should work on trying to make this more international.",
"# Validate parameters.",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"if",
"value",
".",
"upper",
"(",
")",
"in",
"USA_STATES_UPPER",
".",
"keys",
"(",
")",
":",
"# check if value is a state abbreviation",
"if",
"returnStateName",
":",
"return",
"USA_STATES",
"[",
"value",
".",
"upper",
"(",
")",
"]",
"# Return full state name.",
"else",
":",
"return",
"value",
".",
"upper",
"(",
")",
"# Return abbreviation.",
"elif",
"value",
".",
"title",
"(",
")",
"in",
"USA_STATES",
".",
"values",
"(",
")",
":",
"# check if value is a state name",
"if",
"returnStateName",
":",
"return",
"value",
".",
"title",
"(",
")",
"# Return full state name.",
"else",
":",
"return",
"USA_STATES_REVERSED",
"[",
"value",
".",
"title",
"(",
")",
"]",
"# Return abbreviation.",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a state.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not a USA state.
Returns the capitalized state abbreviation, unless returnStateName is True
in which case it returns the titlecased state name.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
* returnStateName (bool): If True, the full state name is returned, i.e. 'California'. Otherwise, the abbreviation, i.e. 'CA'. Defaults to False.
>>> import pysimplevalidate as pysv
>>> pysv.validateState('tx')
'TX'
>>> pysv.validateState('california')
'CA'
>>> pysv.validateState('WASHINGTON')
'WA'
>>> pysv.validateState('WASHINGTON', returnStateName=True)
'Washington' | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"USA",
"state",
".",
"Returns",
"the",
"capitalized",
"state",
"abbreviation",
"unless",
"returnStateName",
"is",
"True",
"in",
"which",
"case",
"it",
"returns",
"the",
"titlecased",
"state",
"name",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1235-L1279 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateMonth | def validateMonth(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, monthNames=ENGLISH_MONTHS, excMsg=None):
"""Raises ValidationException if value is not a month, like 'Jan' or 'March'.
Returns the titlecased month.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* monthNames (Mapping): A mapping of uppercase month abbreviations to month names, i.e. {'JAN': 'January', ... }. The default provides English month names.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateMonth('Jan')
'January'
>>> pysv.validateMonth('MARCH')
'March'
"""
# returns full month name, e.g. 'January'
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
try:
if (monthNames == ENGLISH_MONTHS) and (1 <= int(value) <= 12): # This check here only applies to months, not when validateDayOfWeek() calls this function.
return ENGLISH_MONTH_NAMES[int(value) - 1]
except:
pass # continue if the user didn't enter a number 1 to 12.
# Both month names and month abbreviations will be at least 3 characters.
if len(value) < 3:
_raiseValidationException(_('%r is not a month.') % (_errstr(value)), excMsg)
if value[:3].upper() in monthNames.keys(): # check if value is a month abbreviation
return monthNames[value[:3].upper()] # It turns out that titlecase is good for all the month.
elif value.upper() in monthNames.values(): # check if value is a month name
return value.title()
_raiseValidationException(_('%r is not a month.') % (_errstr(value)), excMsg) | python | def validateMonth(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, monthNames=ENGLISH_MONTHS, excMsg=None):
"""Raises ValidationException if value is not a month, like 'Jan' or 'March'.
Returns the titlecased month.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* monthNames (Mapping): A mapping of uppercase month abbreviations to month names, i.e. {'JAN': 'January', ... }. The default provides English month names.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateMonth('Jan')
'January'
>>> pysv.validateMonth('MARCH')
'March'
"""
# returns full month name, e.g. 'January'
# Validate parameters.
_validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes)
returnNow, value = _prevalidationCheck(value, blank, strip, allowlistRegexes, blocklistRegexes, excMsg)
if returnNow:
return value
try:
if (monthNames == ENGLISH_MONTHS) and (1 <= int(value) <= 12): # This check here only applies to months, not when validateDayOfWeek() calls this function.
return ENGLISH_MONTH_NAMES[int(value) - 1]
except:
pass # continue if the user didn't enter a number 1 to 12.
# Both month names and month abbreviations will be at least 3 characters.
if len(value) < 3:
_raiseValidationException(_('%r is not a month.') % (_errstr(value)), excMsg)
if value[:3].upper() in monthNames.keys(): # check if value is a month abbreviation
return monthNames[value[:3].upper()] # It turns out that titlecase is good for all the month.
elif value.upper() in monthNames.values(): # check if value is a month name
return value.title()
_raiseValidationException(_('%r is not a month.') % (_errstr(value)), excMsg) | [
"def",
"validateMonth",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"monthNames",
"=",
"ENGLISH_MONTHS",
",",
"excMsg",
"=",
"None",
")",
":",
"# returns full month name, e.g. 'January'",
"# Validate parameters.",
"_validateGenericParameters",
"(",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
")",
"returnNow",
",",
"value",
"=",
"_prevalidationCheck",
"(",
"value",
",",
"blank",
",",
"strip",
",",
"allowlistRegexes",
",",
"blocklistRegexes",
",",
"excMsg",
")",
"if",
"returnNow",
":",
"return",
"value",
"try",
":",
"if",
"(",
"monthNames",
"==",
"ENGLISH_MONTHS",
")",
"and",
"(",
"1",
"<=",
"int",
"(",
"value",
")",
"<=",
"12",
")",
":",
"# This check here only applies to months, not when validateDayOfWeek() calls this function.",
"return",
"ENGLISH_MONTH_NAMES",
"[",
"int",
"(",
"value",
")",
"-",
"1",
"]",
"except",
":",
"pass",
"# continue if the user didn't enter a number 1 to 12.",
"# Both month names and month abbreviations will be at least 3 characters.",
"if",
"len",
"(",
"value",
")",
"<",
"3",
":",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a month.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")",
"if",
"value",
"[",
":",
"3",
"]",
".",
"upper",
"(",
")",
"in",
"monthNames",
".",
"keys",
"(",
")",
":",
"# check if value is a month abbreviation",
"return",
"monthNames",
"[",
"value",
"[",
":",
"3",
"]",
".",
"upper",
"(",
")",
"]",
"# It turns out that titlecase is good for all the month.",
"elif",
"value",
".",
"upper",
"(",
")",
"in",
"monthNames",
".",
"values",
"(",
")",
":",
"# check if value is a month name",
"return",
"value",
".",
"title",
"(",
")",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a month.'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not a month, like 'Jan' or 'March'.
Returns the titlecased month.
* value (str): The value being validated as an email address.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* monthNames (Mapping): A mapping of uppercase month abbreviations to month names, i.e. {'JAN': 'January', ... }. The default provides English month names.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateMonth('Jan')
'January'
>>> pysv.validateMonth('MARCH')
'March' | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"month",
"like",
"Jan",
"or",
"March",
".",
"Returns",
"the",
"titlecased",
"month",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1294-L1338 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateDayOfWeek | def validateDayOfWeek(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, dayNames=ENGLISH_DAYS_OF_WEEK, excMsg=None):
"""Raises ValidationException if value is not a day of the week, such as 'Mon' or 'Friday'.
Returns the titlecased day of the week.
* value (str): The value being validated as a day of the week.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* dayNames (Mapping): A mapping of uppercase day abbreviations to day names, i.e. {'SUN': 'Sunday', ...} The default provides English day names.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDayOfWeek('mon')
'Monday'
>>> pysv.validateDayOfWeek('THURSday')
'Thursday'
"""
# TODO - reuse validateChoice for this function
# returns full day of the week str, e.g. 'Sunday'
# Reuses validateMonth.
try:
return validateMonth(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, monthNames=ENGLISH_DAYS_OF_WEEK)
except:
# Replace the exception message.
_raiseValidationException(_('%r is not a day of the week') % (_errstr(value)), excMsg) | python | def validateDayOfWeek(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, dayNames=ENGLISH_DAYS_OF_WEEK, excMsg=None):
"""Raises ValidationException if value is not a day of the week, such as 'Mon' or 'Friday'.
Returns the titlecased day of the week.
* value (str): The value being validated as a day of the week.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* dayNames (Mapping): A mapping of uppercase day abbreviations to day names, i.e. {'SUN': 'Sunday', ...} The default provides English day names.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDayOfWeek('mon')
'Monday'
>>> pysv.validateDayOfWeek('THURSday')
'Thursday'
"""
# TODO - reuse validateChoice for this function
# returns full day of the week str, e.g. 'Sunday'
# Reuses validateMonth.
try:
return validateMonth(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, monthNames=ENGLISH_DAYS_OF_WEEK)
except:
# Replace the exception message.
_raiseValidationException(_('%r is not a day of the week') % (_errstr(value)), excMsg) | [
"def",
"validateDayOfWeek",
"(",
"value",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"dayNames",
"=",
"ENGLISH_DAYS_OF_WEEK",
",",
"excMsg",
"=",
"None",
")",
":",
"# TODO - reuse validateChoice for this function",
"# returns full day of the week str, e.g. 'Sunday'",
"# Reuses validateMonth.",
"try",
":",
"return",
"validateMonth",
"(",
"value",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
",",
"monthNames",
"=",
"ENGLISH_DAYS_OF_WEEK",
")",
"except",
":",
"# Replace the exception message.",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a day of the week'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not a day of the week, such as 'Mon' or 'Friday'.
Returns the titlecased day of the week.
* value (str): The value being validated as a day of the week.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* dayNames (Mapping): A mapping of uppercase day abbreviations to day names, i.e. {'SUN': 'Sunday', ...} The default provides English day names.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDayOfWeek('mon')
'Monday'
>>> pysv.validateDayOfWeek('THURSday')
'Thursday' | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"day",
"of",
"the",
"week",
"such",
"as",
"Mon",
"or",
"Friday",
".",
"Returns",
"the",
"titlecased",
"day",
"of",
"the",
"week",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1341-L1369 |
asweigart/pysimplevalidate | src/pysimplevalidate/__init__.py | validateDayOfMonth | def validateDayOfMonth(value, year, month, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a day of the month, from
1 to 28, 29, 30, or 31 depending on the month and year.
Returns value.
* value (str): The value being validated as existing as a numbered day in the given year and month.
* year (int): The given year.
* month (int): The given month. 1 is January, 2 is February, and so on.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDayOfMonth('31', 2019, 10)
31
>>> pysv.validateDayOfMonth('32', 2019, 10)
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '32' is not a day in the month of October 2019
>>> pysv.validateDayOfMonth('29', 2004, 2)
29
>>> pysv.validateDayOfMonth('29', 2005, 2)
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '29' is not a day in the month of February 2005
"""
try:
daysInMonth = calendar.monthrange(year, month)[1]
except:
raise PySimpleValidateException('invalid arguments for year and/or month')
try:
return validateInt(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, min=1, max=daysInMonth)
except:
# Replace the exception message.
_raiseValidationException(_('%r is not a day in the month of %s %s') % (_errstr(value), ENGLISH_MONTH_NAMES[month - 1], year), excMsg) | python | def validateDayOfMonth(value, year, month, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None):
"""Raises ValidationException if value is not a day of the month, from
1 to 28, 29, 30, or 31 depending on the month and year.
Returns value.
* value (str): The value being validated as existing as a numbered day in the given year and month.
* year (int): The given year.
* month (int): The given month. 1 is January, 2 is February, and so on.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDayOfMonth('31', 2019, 10)
31
>>> pysv.validateDayOfMonth('32', 2019, 10)
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '32' is not a day in the month of October 2019
>>> pysv.validateDayOfMonth('29', 2004, 2)
29
>>> pysv.validateDayOfMonth('29', 2005, 2)
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '29' is not a day in the month of February 2005
"""
try:
daysInMonth = calendar.monthrange(year, month)[1]
except:
raise PySimpleValidateException('invalid arguments for year and/or month')
try:
return validateInt(value, blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes, min=1, max=daysInMonth)
except:
# Replace the exception message.
_raiseValidationException(_('%r is not a day in the month of %s %s') % (_errstr(value), ENGLISH_MONTH_NAMES[month - 1], year), excMsg) | [
"def",
"validateDayOfMonth",
"(",
"value",
",",
"year",
",",
"month",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"excMsg",
"=",
"None",
")",
":",
"try",
":",
"daysInMonth",
"=",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"month",
")",
"[",
"1",
"]",
"except",
":",
"raise",
"PySimpleValidateException",
"(",
"'invalid arguments for year and/or month'",
")",
"try",
":",
"return",
"validateInt",
"(",
"value",
",",
"blank",
"=",
"blank",
",",
"strip",
"=",
"strip",
",",
"allowlistRegexes",
"=",
"allowlistRegexes",
",",
"blocklistRegexes",
"=",
"blocklistRegexes",
",",
"min",
"=",
"1",
",",
"max",
"=",
"daysInMonth",
")",
"except",
":",
"# Replace the exception message.",
"_raiseValidationException",
"(",
"_",
"(",
"'%r is not a day in the month of %s %s'",
")",
"%",
"(",
"_errstr",
"(",
"value",
")",
",",
"ENGLISH_MONTH_NAMES",
"[",
"month",
"-",
"1",
"]",
",",
"year",
")",
",",
"excMsg",
")"
] | Raises ValidationException if value is not a day of the month, from
1 to 28, 29, 30, or 31 depending on the month and year.
Returns value.
* value (str): The value being validated as existing as a numbered day in the given year and month.
* year (int): The given year.
* month (int): The given month. 1 is January, 2 is February, and so on.
* blank (bool): If True, a blank string will be accepted. Defaults to False.
* strip (bool, str, None): If None, whitespace is stripped from value. If a str, the characters in it are stripped from value. If False, nothing is stripped.
* allowlistRegexes (Sequence, None): A sequence of regex str that will explicitly pass validation, even if they aren't numbers.
* blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, response_str) tuples that, if matched, will explicitly fail validation.
* excMsg (str): A custom message to use in the raised ValidationException.
>>> import pysimplevalidate as pysv
>>> pysv.validateDayOfMonth('31', 2019, 10)
31
>>> pysv.validateDayOfMonth('32', 2019, 10)
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '32' is not a day in the month of October 2019
>>> pysv.validateDayOfMonth('29', 2004, 2)
29
>>> pysv.validateDayOfMonth('29', 2005, 2)
Traceback (most recent call last):
...
pysimplevalidate.ValidationException: '29' is not a day in the month of February 2005 | [
"Raises",
"ValidationException",
"if",
"value",
"is",
"not",
"a",
"day",
"of",
"the",
"month",
"from",
"1",
"to",
"28",
"29",
"30",
"or",
"31",
"depending",
"on",
"the",
"month",
"and",
"year",
".",
"Returns",
"value",
"."
] | train | https://github.com/asweigart/pysimplevalidate/blob/3ca27228abb7355d14bbf8abc225c63366379e44/src/pysimplevalidate/__init__.py#L1373-L1411 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/logs.py | get_level | def get_level(level_string):
"""
Returns an appropriate logging level integer from a string name
"""
levels = {'debug': logging.DEBUG, 'info': logging.INFO,
'warning': logging.WARNING, 'error': logging.ERROR,
'critical': logging.CRITICAL}
try:
level = levels[level_string.lower()]
except KeyError:
sys.exit('{0} is not a recognized logging level'.format(level_string))
else:
return level | python | def get_level(level_string):
"""
Returns an appropriate logging level integer from a string name
"""
levels = {'debug': logging.DEBUG, 'info': logging.INFO,
'warning': logging.WARNING, 'error': logging.ERROR,
'critical': logging.CRITICAL}
try:
level = levels[level_string.lower()]
except KeyError:
sys.exit('{0} is not a recognized logging level'.format(level_string))
else:
return level | [
"def",
"get_level",
"(",
"level_string",
")",
":",
"levels",
"=",
"{",
"'debug'",
":",
"logging",
".",
"DEBUG",
",",
"'info'",
":",
"logging",
".",
"INFO",
",",
"'warning'",
":",
"logging",
".",
"WARNING",
",",
"'error'",
":",
"logging",
".",
"ERROR",
",",
"'critical'",
":",
"logging",
".",
"CRITICAL",
"}",
"try",
":",
"level",
"=",
"levels",
"[",
"level_string",
".",
"lower",
"(",
")",
"]",
"except",
"KeyError",
":",
"sys",
".",
"exit",
"(",
"'{0} is not a recognized logging level'",
".",
"format",
"(",
"level_string",
")",
")",
"else",
":",
"return",
"level"
] | Returns an appropriate logging level integer from a string name | [
"Returns",
"an",
"appropriate",
"logging",
"level",
"integer",
"from",
"a",
"string",
"name"
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/logs.py#L15-L27 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/logs.py | config_logging | def config_logging(no_log_file, log_to, log_level, silent, verbosity):
"""
Configures and generates a Logger object, 'openaccess_epub' based on common
parameters used for console interface script execution in OpenAccess_EPUB.
These parameters are:
no_log_file
Boolean. Disables logging to file. If set to True, log_to and
log_level become irrelevant.
log_to
A string name indicating a file path for logging.
log_level
Logging level, one of: 'debug', 'info', 'warning', 'error', 'critical'
silent
Boolean
verbosity
Console logging level, one of: 'debug', 'info', 'warning', 'error',
'critical
This method currently only configures a console StreamHandler with a
message-only Formatter.
"""
log_level = get_level(log_level)
console_level = get_level(verbosity)
#We want to configure our openaccess_epub as the parent log
log = logging.getLogger('openaccess_epub')
log.setLevel(logging.DEBUG) # Don't filter at the log level
standard = logging.Formatter(STANDARD_FORMAT)
message_only = logging.Formatter(MESSAGE_ONLY_FORMAT)
#Only add FileHandler IF it's allowed AND we have a name for it
if not no_log_file and log_to is not None:
fh = logging.FileHandler(filename=log_to)
fh.setLevel(log_level)
fh.setFormatter(standard)
log.addHandler(fh)
#Add on the console StreamHandler at verbosity level if silent not set
if not silent:
sh_echo = logging.StreamHandler(sys.stdout)
sh_echo.setLevel(console_level)
sh_echo.setFormatter(message_only)
log.addHandler(sh_echo) | python | def config_logging(no_log_file, log_to, log_level, silent, verbosity):
"""
Configures and generates a Logger object, 'openaccess_epub' based on common
parameters used for console interface script execution in OpenAccess_EPUB.
These parameters are:
no_log_file
Boolean. Disables logging to file. If set to True, log_to and
log_level become irrelevant.
log_to
A string name indicating a file path for logging.
log_level
Logging level, one of: 'debug', 'info', 'warning', 'error', 'critical'
silent
Boolean
verbosity
Console logging level, one of: 'debug', 'info', 'warning', 'error',
'critical
This method currently only configures a console StreamHandler with a
message-only Formatter.
"""
log_level = get_level(log_level)
console_level = get_level(verbosity)
#We want to configure our openaccess_epub as the parent log
log = logging.getLogger('openaccess_epub')
log.setLevel(logging.DEBUG) # Don't filter at the log level
standard = logging.Formatter(STANDARD_FORMAT)
message_only = logging.Formatter(MESSAGE_ONLY_FORMAT)
#Only add FileHandler IF it's allowed AND we have a name for it
if not no_log_file and log_to is not None:
fh = logging.FileHandler(filename=log_to)
fh.setLevel(log_level)
fh.setFormatter(standard)
log.addHandler(fh)
#Add on the console StreamHandler at verbosity level if silent not set
if not silent:
sh_echo = logging.StreamHandler(sys.stdout)
sh_echo.setLevel(console_level)
sh_echo.setFormatter(message_only)
log.addHandler(sh_echo) | [
"def",
"config_logging",
"(",
"no_log_file",
",",
"log_to",
",",
"log_level",
",",
"silent",
",",
"verbosity",
")",
":",
"log_level",
"=",
"get_level",
"(",
"log_level",
")",
"console_level",
"=",
"get_level",
"(",
"verbosity",
")",
"#We want to configure our openaccess_epub as the parent log",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'openaccess_epub'",
")",
"log",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"# Don't filter at the log level",
"standard",
"=",
"logging",
".",
"Formatter",
"(",
"STANDARD_FORMAT",
")",
"message_only",
"=",
"logging",
".",
"Formatter",
"(",
"MESSAGE_ONLY_FORMAT",
")",
"#Only add FileHandler IF it's allowed AND we have a name for it",
"if",
"not",
"no_log_file",
"and",
"log_to",
"is",
"not",
"None",
":",
"fh",
"=",
"logging",
".",
"FileHandler",
"(",
"filename",
"=",
"log_to",
")",
"fh",
".",
"setLevel",
"(",
"log_level",
")",
"fh",
".",
"setFormatter",
"(",
"standard",
")",
"log",
".",
"addHandler",
"(",
"fh",
")",
"#Add on the console StreamHandler at verbosity level if silent not set",
"if",
"not",
"silent",
":",
"sh_echo",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stdout",
")",
"sh_echo",
".",
"setLevel",
"(",
"console_level",
")",
"sh_echo",
".",
"setFormatter",
"(",
"message_only",
")",
"log",
".",
"addHandler",
"(",
"sh_echo",
")"
] | Configures and generates a Logger object, 'openaccess_epub' based on common
parameters used for console interface script execution in OpenAccess_EPUB.
These parameters are:
no_log_file
Boolean. Disables logging to file. If set to True, log_to and
log_level become irrelevant.
log_to
A string name indicating a file path for logging.
log_level
Logging level, one of: 'debug', 'info', 'warning', 'error', 'critical'
silent
Boolean
verbosity
Console logging level, one of: 'debug', 'info', 'warning', 'error',
'critical
This method currently only configures a console StreamHandler with a
message-only Formatter. | [
"Configures",
"and",
"generates",
"a",
"Logger",
"object",
"openaccess_epub",
"based",
"on",
"common",
"parameters",
"used",
"for",
"console",
"interface",
"script",
"execution",
"in",
"OpenAccess_EPUB",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/logs.py#L38-L82 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/logs.py | replace_filehandler | def replace_filehandler(logname, new_file, level=None, frmt=None):
"""
This utility function will remove a previous Logger FileHandler, if one
exists, and add a new filehandler.
Parameters:
logname
The name of the log to reconfigure, 'openaccess_epub' for example
new_file
The file location for the new FileHandler
level
Optional. Level of FileHandler logging, if not used then the new
FileHandler will have the same level as the old. Pass in name strings,
'INFO' for example
frmt
Optional string format of Formatter for the FileHandler, if not used
then the new FileHandler will inherit the Formatter of the old, pass
in format strings, '%(message)s' for example
It is best practice to use the optional level and frmt arguments to account
for the case where a previous FileHandler does not exist. In the case that
they are not used and a previous FileHandler is not found, then the level
will be set logging.DEBUG and the frmt will be set to
openaccess_epub.utils.logs.STANDARD_FORMAT as a matter of safety.
"""
#Call up the Logger to get reconfigured
log = logging.getLogger(logname)
#Set up defaults and whether explicit for level
if level is not None:
level = get_level(level)
explicit_level = True
else:
level = logging.DEBUG
explicit_level = False
#Set up defaults and whether explicit for frmt
if frmt is not None:
frmt = logging.Formatter(frmt)
explicit_frmt = True
else:
frmt = logging.Formatter(STANDARD_FORMAT)
explicit_frmt = False
#Look for a FileHandler to replace, set level and frmt if not explicit
old_filehandler = None
for handler in log.handlers:
#I think this is an effective method of detecting FileHandler
if type(handler) == logging.FileHandler:
old_filehandler = handler
if not explicit_level:
level = handler.level
if not explicit_frmt:
frmt = handler.formatter
break
#Set up the new FileHandler
new_filehandler = logging.FileHandler(new_file)
new_filehandler.setLevel(level)
new_filehandler.setFormatter(frmt)
#Add the new FileHandler
log.addHandler(new_filehandler)
#Remove the old FileHandler if we found one
if old_filehandler is not None:
old_filehandler.close()
log.removeHandler(old_filehandler) | python | def replace_filehandler(logname, new_file, level=None, frmt=None):
"""
This utility function will remove a previous Logger FileHandler, if one
exists, and add a new filehandler.
Parameters:
logname
The name of the log to reconfigure, 'openaccess_epub' for example
new_file
The file location for the new FileHandler
level
Optional. Level of FileHandler logging, if not used then the new
FileHandler will have the same level as the old. Pass in name strings,
'INFO' for example
frmt
Optional string format of Formatter for the FileHandler, if not used
then the new FileHandler will inherit the Formatter of the old, pass
in format strings, '%(message)s' for example
It is best practice to use the optional level and frmt arguments to account
for the case where a previous FileHandler does not exist. In the case that
they are not used and a previous FileHandler is not found, then the level
will be set logging.DEBUG and the frmt will be set to
openaccess_epub.utils.logs.STANDARD_FORMAT as a matter of safety.
"""
#Call up the Logger to get reconfigured
log = logging.getLogger(logname)
#Set up defaults and whether explicit for level
if level is not None:
level = get_level(level)
explicit_level = True
else:
level = logging.DEBUG
explicit_level = False
#Set up defaults and whether explicit for frmt
if frmt is not None:
frmt = logging.Formatter(frmt)
explicit_frmt = True
else:
frmt = logging.Formatter(STANDARD_FORMAT)
explicit_frmt = False
#Look for a FileHandler to replace, set level and frmt if not explicit
old_filehandler = None
for handler in log.handlers:
#I think this is an effective method of detecting FileHandler
if type(handler) == logging.FileHandler:
old_filehandler = handler
if not explicit_level:
level = handler.level
if not explicit_frmt:
frmt = handler.formatter
break
#Set up the new FileHandler
new_filehandler = logging.FileHandler(new_file)
new_filehandler.setLevel(level)
new_filehandler.setFormatter(frmt)
#Add the new FileHandler
log.addHandler(new_filehandler)
#Remove the old FileHandler if we found one
if old_filehandler is not None:
old_filehandler.close()
log.removeHandler(old_filehandler) | [
"def",
"replace_filehandler",
"(",
"logname",
",",
"new_file",
",",
"level",
"=",
"None",
",",
"frmt",
"=",
"None",
")",
":",
"#Call up the Logger to get reconfigured",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"logname",
")",
"#Set up defaults and whether explicit for level",
"if",
"level",
"is",
"not",
"None",
":",
"level",
"=",
"get_level",
"(",
"level",
")",
"explicit_level",
"=",
"True",
"else",
":",
"level",
"=",
"logging",
".",
"DEBUG",
"explicit_level",
"=",
"False",
"#Set up defaults and whether explicit for frmt",
"if",
"frmt",
"is",
"not",
"None",
":",
"frmt",
"=",
"logging",
".",
"Formatter",
"(",
"frmt",
")",
"explicit_frmt",
"=",
"True",
"else",
":",
"frmt",
"=",
"logging",
".",
"Formatter",
"(",
"STANDARD_FORMAT",
")",
"explicit_frmt",
"=",
"False",
"#Look for a FileHandler to replace, set level and frmt if not explicit",
"old_filehandler",
"=",
"None",
"for",
"handler",
"in",
"log",
".",
"handlers",
":",
"#I think this is an effective method of detecting FileHandler",
"if",
"type",
"(",
"handler",
")",
"==",
"logging",
".",
"FileHandler",
":",
"old_filehandler",
"=",
"handler",
"if",
"not",
"explicit_level",
":",
"level",
"=",
"handler",
".",
"level",
"if",
"not",
"explicit_frmt",
":",
"frmt",
"=",
"handler",
".",
"formatter",
"break",
"#Set up the new FileHandler",
"new_filehandler",
"=",
"logging",
".",
"FileHandler",
"(",
"new_file",
")",
"new_filehandler",
".",
"setLevel",
"(",
"level",
")",
"new_filehandler",
".",
"setFormatter",
"(",
"frmt",
")",
"#Add the new FileHandler",
"log",
".",
"addHandler",
"(",
"new_filehandler",
")",
"#Remove the old FileHandler if we found one",
"if",
"old_filehandler",
"is",
"not",
"None",
":",
"old_filehandler",
".",
"close",
"(",
")",
"log",
".",
"removeHandler",
"(",
"old_filehandler",
")"
] | This utility function will remove a previous Logger FileHandler, if one
exists, and add a new filehandler.
Parameters:
logname
The name of the log to reconfigure, 'openaccess_epub' for example
new_file
The file location for the new FileHandler
level
Optional. Level of FileHandler logging, if not used then the new
FileHandler will have the same level as the old. Pass in name strings,
'INFO' for example
frmt
Optional string format of Formatter for the FileHandler, if not used
then the new FileHandler will inherit the Formatter of the old, pass
in format strings, '%(message)s' for example
It is best practice to use the optional level and frmt arguments to account
for the case where a previous FileHandler does not exist. In the case that
they are not used and a previous FileHandler is not found, then the level
will be set logging.DEBUG and the frmt will be set to
openaccess_epub.utils.logs.STANDARD_FORMAT as a matter of safety. | [
"This",
"utility",
"function",
"will",
"remove",
"a",
"previous",
"Logger",
"FileHandler",
"if",
"one",
"exists",
"and",
"add",
"a",
"new",
"filehandler",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/logs.py#L85-L152 |
MSchnei/pyprf_feature | pyprf_feature/analysis/model_creation_utils.py | rmp_pixel_deg_xys | def rmp_pixel_deg_xys(vecX, vecY, vecPrfSd, tplPngSize,
varExtXmin, varExtXmax, varExtYmin, varExtYmax):
"""Remap x, y, sigma parameters from pixel to degree.
Parameters
----------
vecX : 1D numpy array
Array with possible x parametrs in pixels
vecY : 1D numpy array
Array with possible y parametrs in pixels
vecPrfSd : 1D numpy array
Array with possible sd parametrs in pixels
tplPngSize : tuple, 2
Pixel dimensions of the visual space in pixel (width, height).
varExtXmin : float
Extent of visual space from centre in negative x-direction (width)
varExtXmax : float
Extent of visual space from centre in positive x-direction (width)
varExtYmin : int
Extent of visual space from centre in negative y-direction (height)
varExtYmax : float
Extent of visual space from centre in positive y-direction (height)
Returns
-------
vecX : 1D numpy array
Array with possible x parametrs in degree
vecY : 1D numpy array
Array with possible y parametrs in degree
vecPrfSd : 1D numpy array
Array with possible sd parametrs in degree
"""
# Remap modelled x-positions of the pRFs:
vecXdgr = rmp_rng(vecX, varExtXmin, varExtXmax, varOldThrMin=0.0,
varOldAbsMax=(tplPngSize[0] - 1))
# Remap modelled y-positions of the pRFs:
vecYdgr = rmp_rng(vecY, varExtYmin, varExtYmax, varOldThrMin=0.0,
varOldAbsMax=(tplPngSize[1] - 1))
# We calculate the scaling factor from pixels to degrees of visual angle to
# separately for the x- and the y-directions (the two should be the same).
varPix2DgrX = np.divide((varExtXmax - varExtXmin), tplPngSize[0])
varPix2DgrY = np.divide((varExtYmax - varExtYmin), tplPngSize[1])
# Check whether varDgr2PixX and varDgr2PixY are similar:
strErrMsg = 'ERROR. The ratio of X and Y dimensions in ' + \
'stimulus space (in pixels) do not agree'
assert 0.5 > np.absolute((varPix2DgrX - varPix2DgrY)), strErrMsg
# Convert prf sizes from degrees of visual angles to pixel
vecPrfSdDgr = np.multiply(vecPrfSd, varPix2DgrX)
# Return new values.
return vecXdgr, vecYdgr, vecPrfSdDgr | python | def rmp_pixel_deg_xys(vecX, vecY, vecPrfSd, tplPngSize,
varExtXmin, varExtXmax, varExtYmin, varExtYmax):
"""Remap x, y, sigma parameters from pixel to degree.
Parameters
----------
vecX : 1D numpy array
Array with possible x parametrs in pixels
vecY : 1D numpy array
Array with possible y parametrs in pixels
vecPrfSd : 1D numpy array
Array with possible sd parametrs in pixels
tplPngSize : tuple, 2
Pixel dimensions of the visual space in pixel (width, height).
varExtXmin : float
Extent of visual space from centre in negative x-direction (width)
varExtXmax : float
Extent of visual space from centre in positive x-direction (width)
varExtYmin : int
Extent of visual space from centre in negative y-direction (height)
varExtYmax : float
Extent of visual space from centre in positive y-direction (height)
Returns
-------
vecX : 1D numpy array
Array with possible x parametrs in degree
vecY : 1D numpy array
Array with possible y parametrs in degree
vecPrfSd : 1D numpy array
Array with possible sd parametrs in degree
"""
# Remap modelled x-positions of the pRFs:
vecXdgr = rmp_rng(vecX, varExtXmin, varExtXmax, varOldThrMin=0.0,
varOldAbsMax=(tplPngSize[0] - 1))
# Remap modelled y-positions of the pRFs:
vecYdgr = rmp_rng(vecY, varExtYmin, varExtYmax, varOldThrMin=0.0,
varOldAbsMax=(tplPngSize[1] - 1))
# We calculate the scaling factor from pixels to degrees of visual angle to
# separately for the x- and the y-directions (the two should be the same).
varPix2DgrX = np.divide((varExtXmax - varExtXmin), tplPngSize[0])
varPix2DgrY = np.divide((varExtYmax - varExtYmin), tplPngSize[1])
# Check whether varDgr2PixX and varDgr2PixY are similar:
strErrMsg = 'ERROR. The ratio of X and Y dimensions in ' + \
'stimulus space (in pixels) do not agree'
assert 0.5 > np.absolute((varPix2DgrX - varPix2DgrY)), strErrMsg
# Convert prf sizes from degrees of visual angles to pixel
vecPrfSdDgr = np.multiply(vecPrfSd, varPix2DgrX)
# Return new values.
return vecXdgr, vecYdgr, vecPrfSdDgr | [
"def",
"rmp_pixel_deg_xys",
"(",
"vecX",
",",
"vecY",
",",
"vecPrfSd",
",",
"tplPngSize",
",",
"varExtXmin",
",",
"varExtXmax",
",",
"varExtYmin",
",",
"varExtYmax",
")",
":",
"# Remap modelled x-positions of the pRFs:",
"vecXdgr",
"=",
"rmp_rng",
"(",
"vecX",
",",
"varExtXmin",
",",
"varExtXmax",
",",
"varOldThrMin",
"=",
"0.0",
",",
"varOldAbsMax",
"=",
"(",
"tplPngSize",
"[",
"0",
"]",
"-",
"1",
")",
")",
"# Remap modelled y-positions of the pRFs:",
"vecYdgr",
"=",
"rmp_rng",
"(",
"vecY",
",",
"varExtYmin",
",",
"varExtYmax",
",",
"varOldThrMin",
"=",
"0.0",
",",
"varOldAbsMax",
"=",
"(",
"tplPngSize",
"[",
"1",
"]",
"-",
"1",
")",
")",
"# We calculate the scaling factor from pixels to degrees of visual angle to",
"# separately for the x- and the y-directions (the two should be the same).",
"varPix2DgrX",
"=",
"np",
".",
"divide",
"(",
"(",
"varExtXmax",
"-",
"varExtXmin",
")",
",",
"tplPngSize",
"[",
"0",
"]",
")",
"varPix2DgrY",
"=",
"np",
".",
"divide",
"(",
"(",
"varExtYmax",
"-",
"varExtYmin",
")",
",",
"tplPngSize",
"[",
"1",
"]",
")",
"# Check whether varDgr2PixX and varDgr2PixY are similar:",
"strErrMsg",
"=",
"'ERROR. The ratio of X and Y dimensions in '",
"+",
"'stimulus space (in pixels) do not agree'",
"assert",
"0.5",
">",
"np",
".",
"absolute",
"(",
"(",
"varPix2DgrX",
"-",
"varPix2DgrY",
")",
")",
",",
"strErrMsg",
"# Convert prf sizes from degrees of visual angles to pixel",
"vecPrfSdDgr",
"=",
"np",
".",
"multiply",
"(",
"vecPrfSd",
",",
"varPix2DgrX",
")",
"# Return new values.",
"return",
"vecXdgr",
",",
"vecYdgr",
",",
"vecPrfSdDgr"
] | Remap x, y, sigma parameters from pixel to degree.
Parameters
----------
vecX : 1D numpy array
Array with possible x parametrs in pixels
vecY : 1D numpy array
Array with possible y parametrs in pixels
vecPrfSd : 1D numpy array
Array with possible sd parametrs in pixels
tplPngSize : tuple, 2
Pixel dimensions of the visual space in pixel (width, height).
varExtXmin : float
Extent of visual space from centre in negative x-direction (width)
varExtXmax : float
Extent of visual space from centre in positive x-direction (width)
varExtYmin : int
Extent of visual space from centre in negative y-direction (height)
varExtYmax : float
Extent of visual space from centre in positive y-direction (height)
Returns
-------
vecX : 1D numpy array
Array with possible x parametrs in degree
vecY : 1D numpy array
Array with possible y parametrs in degree
vecPrfSd : 1D numpy array
Array with possible sd parametrs in degree | [
"Remap",
"x",
"y",
"sigma",
"parameters",
"from",
"pixel",
"to",
"degree",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/model_creation_utils.py#L88-L144 |
MSchnei/pyprf_feature | pyprf_feature/analysis/model_creation_utils.py | crt_mdl_prms | def crt_mdl_prms(tplPngSize, varNum1, varExtXmin, varExtXmax, varNum2,
varExtYmin, varExtYmax, varNumPrfSizes, varPrfStdMin,
varPrfStdMax, kwUnt='pix', kwCrd='crt'):
"""Create an array with all possible model parameter combinations
Parameters
----------
tplPngSize : tuple, 2
Pixel dimensions of the visual space (width, height).
varNum1 : int, positive
Number of x-positions to model
varExtXmin : float
Extent of visual space from centre in negative x-direction (width)
varExtXmax : float
Extent of visual space from centre in positive x-direction (width)
varNum2 : float, positive
Number of y-positions to model.
varExtYmin : int
Extent of visual space from centre in negative y-direction (height)
varExtYmax : float
Extent of visual space from centre in positive y-direction (height)
varNumPrfSizes : int, positive
Number of pRF sizes to model.
varPrfStdMin : float, positive
Minimum pRF model size (standard deviation of 2D Gaussian)
varPrfStdMax : float, positive
Maximum pRF model size (standard deviation of 2D Gaussian)
kwUnt: str
Keyword to set the unit for model parameter combinations; model
parameters can be in pixels ["pix"] or degrees of visual angles ["deg"]
kwCrd: str
Keyword to set the coordinate system for model parameter combinations;
parameters can be in cartesian ["crt"] or polar ["pol"] coordinates
Returns
-------
aryMdlParams : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, 3]
Model parameters (x, y, sigma) for all models.
"""
# Number of pRF models to be created (i.e. number of possible
# combinations of x-position, y-position, and standard deviation):
varNumMdls = varNum1 * varNum2 * varNumPrfSizes
# Array for the x-position, y-position, and standard deviations for
# which pRF model time courses are going to be created, where the
# columns correspond to: (1) the x-position, (2) the y-position, and
# (3) the standard deviation. The parameters are in units of the
# upsampled visual space.
aryMdlParams = np.zeros((varNumMdls, 3), dtype=np.float32)
# Counter for parameter array:
varCntMdlPrms = 0
if kwCrd == 'crt':
# Vector with the moddeled x-positions of the pRFs:
vecX = np.linspace(varExtXmin, varExtXmax, varNum1, endpoint=True)
# Vector with the moddeled y-positions of the pRFs:
vecY = np.linspace(varExtYmin, varExtYmax, varNum2, endpoint=True)
# Vector with standard deviations pRF models (in degree of vis angle):
vecPrfSd = np.linspace(varPrfStdMin, varPrfStdMax, varNumPrfSizes,
endpoint=True)
if kwUnt == 'deg':
# since parameters are already in degrees of visual angle,
# we do nothing
pass
elif kwUnt == 'pix':
# convert parameters to pixels
vecX, vecY, vecPrfSd = rmp_deg_pixel_xys(vecX, vecY, vecPrfSd,
tplPngSize, varExtXmin,
varExtXmax, varExtYmin,
varExtYmax)
else:
print('Unknown keyword provided for possible model parameter ' +
'combinations: should be either pix or deg')
# Put all combinations of x-position, y-position, and standard
# deviations into the array:
# Loop through x-positions:
for idxX in range(0, varNum1):
# Loop through y-positions:
for idxY in range(0, varNum2):
# Loop through standard deviations (of Gaussian pRF models):
for idxSd in range(0, varNumPrfSizes):
# Place index and parameters in array:
aryMdlParams[varCntMdlPrms, 0] = vecX[idxX]
aryMdlParams[varCntMdlPrms, 1] = vecY[idxY]
aryMdlParams[varCntMdlPrms, 2] = vecPrfSd[idxSd]
# Increment parameter index:
varCntMdlPrms += 1
elif kwCrd == 'pol':
# Vector with the radial position:
vecRad = np.linspace(0.0, varExtXmax, varNum1, endpoint=True)
# Vector with the angular position:
vecTht = np.linspace(0.0, 2*np.pi, varNum2, endpoint=False)
# Get all possible combinations on the grid, using matrix indexing ij
# of output
aryRad, aryTht = np.meshgrid(vecRad, vecTht, indexing='ij')
# Flatten arrays to be able to combine them with meshgrid
vecRad = aryRad.flatten()
vecTht = aryTht.flatten()
# Convert from polar to cartesian
vecX, vecY = map_pol_to_crt(vecTht, vecRad)
# Vector with standard deviations pRF models (in degree of vis angle):
vecPrfSd = np.linspace(varPrfStdMin, varPrfStdMax, varNumPrfSizes,
endpoint=True)
if kwUnt == 'deg':
# since parameters are already in degrees of visual angle,
# we do nothing
pass
elif kwUnt == 'pix':
# convert parameters to pixels
vecX, vecY, vecPrfSd = rmp_deg_pixel_xys(vecX, vecY, vecPrfSd,
tplPngSize, varExtXmin,
varExtXmax, varExtYmin,
varExtYmax)
# Put all combinations of x-position, y-position, and standard
# deviations into the array:
# Loop through x-positions:
for idxXY in range(0, varNum1*varNum2):
# Loop through standard deviations (of Gaussian pRF models):
for idxSd in range(0, varNumPrfSizes):
# Place index and parameters in array:
aryMdlParams[varCntMdlPrms, 0] = vecX[idxXY]
aryMdlParams[varCntMdlPrms, 1] = vecY[idxXY]
aryMdlParams[varCntMdlPrms, 2] = vecPrfSd[idxSd]
# Increment parameter index:
varCntMdlPrms += 1
else:
print('Unknown keyword provided for coordinate system for model ' +
'parameter combinations: should be either crt or pol')
return aryMdlParams | python | def crt_mdl_prms(tplPngSize, varNum1, varExtXmin, varExtXmax, varNum2,
varExtYmin, varExtYmax, varNumPrfSizes, varPrfStdMin,
varPrfStdMax, kwUnt='pix', kwCrd='crt'):
"""Create an array with all possible model parameter combinations
Parameters
----------
tplPngSize : tuple, 2
Pixel dimensions of the visual space (width, height).
varNum1 : int, positive
Number of x-positions to model
varExtXmin : float
Extent of visual space from centre in negative x-direction (width)
varExtXmax : float
Extent of visual space from centre in positive x-direction (width)
varNum2 : float, positive
Number of y-positions to model.
varExtYmin : int
Extent of visual space from centre in negative y-direction (height)
varExtYmax : float
Extent of visual space from centre in positive y-direction (height)
varNumPrfSizes : int, positive
Number of pRF sizes to model.
varPrfStdMin : float, positive
Minimum pRF model size (standard deviation of 2D Gaussian)
varPrfStdMax : float, positive
Maximum pRF model size (standard deviation of 2D Gaussian)
kwUnt: str
Keyword to set the unit for model parameter combinations; model
parameters can be in pixels ["pix"] or degrees of visual angles ["deg"]
kwCrd: str
Keyword to set the coordinate system for model parameter combinations;
parameters can be in cartesian ["crt"] or polar ["pol"] coordinates
Returns
-------
aryMdlParams : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, 3]
Model parameters (x, y, sigma) for all models.
"""
# Number of pRF models to be created (i.e. number of possible
# combinations of x-position, y-position, and standard deviation):
varNumMdls = varNum1 * varNum2 * varNumPrfSizes
# Array for the x-position, y-position, and standard deviations for
# which pRF model time courses are going to be created, where the
# columns correspond to: (1) the x-position, (2) the y-position, and
# (3) the standard deviation. The parameters are in units of the
# upsampled visual space.
aryMdlParams = np.zeros((varNumMdls, 3), dtype=np.float32)
# Counter for parameter array:
varCntMdlPrms = 0
if kwCrd == 'crt':
# Vector with the moddeled x-positions of the pRFs:
vecX = np.linspace(varExtXmin, varExtXmax, varNum1, endpoint=True)
# Vector with the moddeled y-positions of the pRFs:
vecY = np.linspace(varExtYmin, varExtYmax, varNum2, endpoint=True)
# Vector with standard deviations pRF models (in degree of vis angle):
vecPrfSd = np.linspace(varPrfStdMin, varPrfStdMax, varNumPrfSizes,
endpoint=True)
if kwUnt == 'deg':
# since parameters are already in degrees of visual angle,
# we do nothing
pass
elif kwUnt == 'pix':
# convert parameters to pixels
vecX, vecY, vecPrfSd = rmp_deg_pixel_xys(vecX, vecY, vecPrfSd,
tplPngSize, varExtXmin,
varExtXmax, varExtYmin,
varExtYmax)
else:
print('Unknown keyword provided for possible model parameter ' +
'combinations: should be either pix or deg')
# Put all combinations of x-position, y-position, and standard
# deviations into the array:
# Loop through x-positions:
for idxX in range(0, varNum1):
# Loop through y-positions:
for idxY in range(0, varNum2):
# Loop through standard deviations (of Gaussian pRF models):
for idxSd in range(0, varNumPrfSizes):
# Place index and parameters in array:
aryMdlParams[varCntMdlPrms, 0] = vecX[idxX]
aryMdlParams[varCntMdlPrms, 1] = vecY[idxY]
aryMdlParams[varCntMdlPrms, 2] = vecPrfSd[idxSd]
# Increment parameter index:
varCntMdlPrms += 1
elif kwCrd == 'pol':
# Vector with the radial position:
vecRad = np.linspace(0.0, varExtXmax, varNum1, endpoint=True)
# Vector with the angular position:
vecTht = np.linspace(0.0, 2*np.pi, varNum2, endpoint=False)
# Get all possible combinations on the grid, using matrix indexing ij
# of output
aryRad, aryTht = np.meshgrid(vecRad, vecTht, indexing='ij')
# Flatten arrays to be able to combine them with meshgrid
vecRad = aryRad.flatten()
vecTht = aryTht.flatten()
# Convert from polar to cartesian
vecX, vecY = map_pol_to_crt(vecTht, vecRad)
# Vector with standard deviations pRF models (in degree of vis angle):
vecPrfSd = np.linspace(varPrfStdMin, varPrfStdMax, varNumPrfSizes,
endpoint=True)
if kwUnt == 'deg':
# since parameters are already in degrees of visual angle,
# we do nothing
pass
elif kwUnt == 'pix':
# convert parameters to pixels
vecX, vecY, vecPrfSd = rmp_deg_pixel_xys(vecX, vecY, vecPrfSd,
tplPngSize, varExtXmin,
varExtXmax, varExtYmin,
varExtYmax)
# Put all combinations of x-position, y-position, and standard
# deviations into the array:
# Loop through x-positions:
for idxXY in range(0, varNum1*varNum2):
# Loop through standard deviations (of Gaussian pRF models):
for idxSd in range(0, varNumPrfSizes):
# Place index and parameters in array:
aryMdlParams[varCntMdlPrms, 0] = vecX[idxXY]
aryMdlParams[varCntMdlPrms, 1] = vecY[idxXY]
aryMdlParams[varCntMdlPrms, 2] = vecPrfSd[idxSd]
# Increment parameter index:
varCntMdlPrms += 1
else:
print('Unknown keyword provided for coordinate system for model ' +
'parameter combinations: should be either crt or pol')
return aryMdlParams | [
"def",
"crt_mdl_prms",
"(",
"tplPngSize",
",",
"varNum1",
",",
"varExtXmin",
",",
"varExtXmax",
",",
"varNum2",
",",
"varExtYmin",
",",
"varExtYmax",
",",
"varNumPrfSizes",
",",
"varPrfStdMin",
",",
"varPrfStdMax",
",",
"kwUnt",
"=",
"'pix'",
",",
"kwCrd",
"=",
"'crt'",
")",
":",
"# Number of pRF models to be created (i.e. number of possible",
"# combinations of x-position, y-position, and standard deviation):",
"varNumMdls",
"=",
"varNum1",
"*",
"varNum2",
"*",
"varNumPrfSizes",
"# Array for the x-position, y-position, and standard deviations for",
"# which pRF model time courses are going to be created, where the",
"# columns correspond to: (1) the x-position, (2) the y-position, and",
"# (3) the standard deviation. The parameters are in units of the",
"# upsampled visual space.",
"aryMdlParams",
"=",
"np",
".",
"zeros",
"(",
"(",
"varNumMdls",
",",
"3",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# Counter for parameter array:",
"varCntMdlPrms",
"=",
"0",
"if",
"kwCrd",
"==",
"'crt'",
":",
"# Vector with the moddeled x-positions of the pRFs:",
"vecX",
"=",
"np",
".",
"linspace",
"(",
"varExtXmin",
",",
"varExtXmax",
",",
"varNum1",
",",
"endpoint",
"=",
"True",
")",
"# Vector with the moddeled y-positions of the pRFs:",
"vecY",
"=",
"np",
".",
"linspace",
"(",
"varExtYmin",
",",
"varExtYmax",
",",
"varNum2",
",",
"endpoint",
"=",
"True",
")",
"# Vector with standard deviations pRF models (in degree of vis angle):",
"vecPrfSd",
"=",
"np",
".",
"linspace",
"(",
"varPrfStdMin",
",",
"varPrfStdMax",
",",
"varNumPrfSizes",
",",
"endpoint",
"=",
"True",
")",
"if",
"kwUnt",
"==",
"'deg'",
":",
"# since parameters are already in degrees of visual angle,",
"# we do nothing",
"pass",
"elif",
"kwUnt",
"==",
"'pix'",
":",
"# convert parameters to pixels",
"vecX",
",",
"vecY",
",",
"vecPrfSd",
"=",
"rmp_deg_pixel_xys",
"(",
"vecX",
",",
"vecY",
",",
"vecPrfSd",
",",
"tplPngSize",
",",
"varExtXmin",
",",
"varExtXmax",
",",
"varExtYmin",
",",
"varExtYmax",
")",
"else",
":",
"print",
"(",
"'Unknown keyword provided for possible model parameter '",
"+",
"'combinations: should be either pix or deg'",
")",
"# Put all combinations of x-position, y-position, and standard",
"# deviations into the array:",
"# Loop through x-positions:",
"for",
"idxX",
"in",
"range",
"(",
"0",
",",
"varNum1",
")",
":",
"# Loop through y-positions:",
"for",
"idxY",
"in",
"range",
"(",
"0",
",",
"varNum2",
")",
":",
"# Loop through standard deviations (of Gaussian pRF models):",
"for",
"idxSd",
"in",
"range",
"(",
"0",
",",
"varNumPrfSizes",
")",
":",
"# Place index and parameters in array:",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"0",
"]",
"=",
"vecX",
"[",
"idxX",
"]",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"1",
"]",
"=",
"vecY",
"[",
"idxY",
"]",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"2",
"]",
"=",
"vecPrfSd",
"[",
"idxSd",
"]",
"# Increment parameter index:",
"varCntMdlPrms",
"+=",
"1",
"elif",
"kwCrd",
"==",
"'pol'",
":",
"# Vector with the radial position:",
"vecRad",
"=",
"np",
".",
"linspace",
"(",
"0.0",
",",
"varExtXmax",
",",
"varNum1",
",",
"endpoint",
"=",
"True",
")",
"# Vector with the angular position:",
"vecTht",
"=",
"np",
".",
"linspace",
"(",
"0.0",
",",
"2",
"*",
"np",
".",
"pi",
",",
"varNum2",
",",
"endpoint",
"=",
"False",
")",
"# Get all possible combinations on the grid, using matrix indexing ij",
"# of output",
"aryRad",
",",
"aryTht",
"=",
"np",
".",
"meshgrid",
"(",
"vecRad",
",",
"vecTht",
",",
"indexing",
"=",
"'ij'",
")",
"# Flatten arrays to be able to combine them with meshgrid",
"vecRad",
"=",
"aryRad",
".",
"flatten",
"(",
")",
"vecTht",
"=",
"aryTht",
".",
"flatten",
"(",
")",
"# Convert from polar to cartesian",
"vecX",
",",
"vecY",
"=",
"map_pol_to_crt",
"(",
"vecTht",
",",
"vecRad",
")",
"# Vector with standard deviations pRF models (in degree of vis angle):",
"vecPrfSd",
"=",
"np",
".",
"linspace",
"(",
"varPrfStdMin",
",",
"varPrfStdMax",
",",
"varNumPrfSizes",
",",
"endpoint",
"=",
"True",
")",
"if",
"kwUnt",
"==",
"'deg'",
":",
"# since parameters are already in degrees of visual angle,",
"# we do nothing",
"pass",
"elif",
"kwUnt",
"==",
"'pix'",
":",
"# convert parameters to pixels",
"vecX",
",",
"vecY",
",",
"vecPrfSd",
"=",
"rmp_deg_pixel_xys",
"(",
"vecX",
",",
"vecY",
",",
"vecPrfSd",
",",
"tplPngSize",
",",
"varExtXmin",
",",
"varExtXmax",
",",
"varExtYmin",
",",
"varExtYmax",
")",
"# Put all combinations of x-position, y-position, and standard",
"# deviations into the array:",
"# Loop through x-positions:",
"for",
"idxXY",
"in",
"range",
"(",
"0",
",",
"varNum1",
"*",
"varNum2",
")",
":",
"# Loop through standard deviations (of Gaussian pRF models):",
"for",
"idxSd",
"in",
"range",
"(",
"0",
",",
"varNumPrfSizes",
")",
":",
"# Place index and parameters in array:",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"0",
"]",
"=",
"vecX",
"[",
"idxXY",
"]",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"1",
"]",
"=",
"vecY",
"[",
"idxXY",
"]",
"aryMdlParams",
"[",
"varCntMdlPrms",
",",
"2",
"]",
"=",
"vecPrfSd",
"[",
"idxSd",
"]",
"# Increment parameter index:",
"varCntMdlPrms",
"+=",
"1",
"else",
":",
"print",
"(",
"'Unknown keyword provided for coordinate system for model '",
"+",
"'parameter combinations: should be either crt or pol'",
")",
"return",
"aryMdlParams"
] | Create an array with all possible model parameter combinations
Parameters
----------
tplPngSize : tuple, 2
Pixel dimensions of the visual space (width, height).
varNum1 : int, positive
Number of x-positions to model
varExtXmin : float
Extent of visual space from centre in negative x-direction (width)
varExtXmax : float
Extent of visual space from centre in positive x-direction (width)
varNum2 : float, positive
Number of y-positions to model.
varExtYmin : int
Extent of visual space from centre in negative y-direction (height)
varExtYmax : float
Extent of visual space from centre in positive y-direction (height)
varNumPrfSizes : int, positive
Number of pRF sizes to model.
varPrfStdMin : float, positive
Minimum pRF model size (standard deviation of 2D Gaussian)
varPrfStdMax : float, positive
Maximum pRF model size (standard deviation of 2D Gaussian)
kwUnt: str
Keyword to set the unit for model parameter combinations; model
parameters can be in pixels ["pix"] or degrees of visual angles ["deg"]
kwCrd: str
Keyword to set the coordinate system for model parameter combinations;
parameters can be in cartesian ["crt"] or polar ["pol"] coordinates
Returns
-------
aryMdlParams : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, 3]
Model parameters (x, y, sigma) for all models. | [
"Create",
"an",
"array",
"with",
"all",
"possible",
"model",
"parameter",
"combinations"
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/model_creation_utils.py#L147-L305 |
MSchnei/pyprf_feature | pyprf_feature/analysis/model_creation_utils.py | crt_mdl_rsp | def crt_mdl_rsp(arySptExpInf, tplPngSize, aryMdlParams, varPar, strCrd='crt',
lgcPrint=True):
"""Create responses of 2D Gauss models to spatial conditions.
Parameters
----------
arySptExpInf : 3d numpy array, shape [n_x_pix, n_y_pix, n_conditions]
All spatial conditions stacked along second axis.
tplPngSize : tuple, 2
Pixel dimensions of the visual space (width, height).
aryMdlParams : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, 3]
Model parameters (x, y, sigma) for all models.
varPar : int, positive
Number of cores to parallelize over.
strCrd, string, either 'crt' or 'pol'
Whether model parameters are provided in cartesian or polar coordinates
lgcPrint : boolean
Whether print statements should be executed.
Returns
-------
aryMdlCndRsp : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions.
"""
if varPar == 1:
# if the number of cores requested by the user is equal to 1,
# we save the overhead of multiprocessing by calling aryMdlCndRsp
# directly
aryMdlCndRsp = cnvl_2D_gauss(0, aryMdlParams, arySptExpInf,
tplPngSize, None, strCrd=strCrd)
else:
# The long array with all the combinations of model parameters is put
# into separate chunks for parallelisation, using a list of arrays.
lstMdlParams = np.array_split(aryMdlParams, varPar)
# Create a queue to put the results in:
queOut = mp.Queue()
# Empty list for results from parallel processes (for pRF model
# responses):
lstMdlTc = [None] * varPar
# Empty list for processes:
lstPrcs = [None] * varPar
if lgcPrint:
print('---------Running parallel processes')
# Create processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvl_2D_gauss,
args=(idxPrc, lstMdlParams[idxPrc],
arySptExpInf, tplPngSize, queOut
),
kwargs={'strCrd': strCrd},
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
# Start processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].start()
# Collect results from queue:
for idxPrc in range(0, varPar):
lstMdlTc[idxPrc] = queOut.get(True)
# Join processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].join()
if lgcPrint:
print('---------Collecting results from parallel processes')
# Put output arrays from parallel process into one big array
lstMdlTc = sorted(lstMdlTc)
aryMdlCndRsp = np.empty((0, arySptExpInf.shape[-1]))
for idx in range(0, varPar):
aryMdlCndRsp = np.concatenate((aryMdlCndRsp, lstMdlTc[idx][1]),
axis=0)
# Clean up:
del(lstMdlParams)
del(lstMdlTc)
return aryMdlCndRsp.astype('float16') | python | def crt_mdl_rsp(arySptExpInf, tplPngSize, aryMdlParams, varPar, strCrd='crt',
lgcPrint=True):
"""Create responses of 2D Gauss models to spatial conditions.
Parameters
----------
arySptExpInf : 3d numpy array, shape [n_x_pix, n_y_pix, n_conditions]
All spatial conditions stacked along second axis.
tplPngSize : tuple, 2
Pixel dimensions of the visual space (width, height).
aryMdlParams : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, 3]
Model parameters (x, y, sigma) for all models.
varPar : int, positive
Number of cores to parallelize over.
strCrd, string, either 'crt' or 'pol'
Whether model parameters are provided in cartesian or polar coordinates
lgcPrint : boolean
Whether print statements should be executed.
Returns
-------
aryMdlCndRsp : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions.
"""
if varPar == 1:
# if the number of cores requested by the user is equal to 1,
# we save the overhead of multiprocessing by calling aryMdlCndRsp
# directly
aryMdlCndRsp = cnvl_2D_gauss(0, aryMdlParams, arySptExpInf,
tplPngSize, None, strCrd=strCrd)
else:
# The long array with all the combinations of model parameters is put
# into separate chunks for parallelisation, using a list of arrays.
lstMdlParams = np.array_split(aryMdlParams, varPar)
# Create a queue to put the results in:
queOut = mp.Queue()
# Empty list for results from parallel processes (for pRF model
# responses):
lstMdlTc = [None] * varPar
# Empty list for processes:
lstPrcs = [None] * varPar
if lgcPrint:
print('---------Running parallel processes')
# Create processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvl_2D_gauss,
args=(idxPrc, lstMdlParams[idxPrc],
arySptExpInf, tplPngSize, queOut
),
kwargs={'strCrd': strCrd},
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
# Start processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].start()
# Collect results from queue:
for idxPrc in range(0, varPar):
lstMdlTc[idxPrc] = queOut.get(True)
# Join processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].join()
if lgcPrint:
print('---------Collecting results from parallel processes')
# Put output arrays from parallel process into one big array
lstMdlTc = sorted(lstMdlTc)
aryMdlCndRsp = np.empty((0, arySptExpInf.shape[-1]))
for idx in range(0, varPar):
aryMdlCndRsp = np.concatenate((aryMdlCndRsp, lstMdlTc[idx][1]),
axis=0)
# Clean up:
del(lstMdlParams)
del(lstMdlTc)
return aryMdlCndRsp.astype('float16') | [
"def",
"crt_mdl_rsp",
"(",
"arySptExpInf",
",",
"tplPngSize",
",",
"aryMdlParams",
",",
"varPar",
",",
"strCrd",
"=",
"'crt'",
",",
"lgcPrint",
"=",
"True",
")",
":",
"if",
"varPar",
"==",
"1",
":",
"# if the number of cores requested by the user is equal to 1,",
"# we save the overhead of multiprocessing by calling aryMdlCndRsp",
"# directly",
"aryMdlCndRsp",
"=",
"cnvl_2D_gauss",
"(",
"0",
",",
"aryMdlParams",
",",
"arySptExpInf",
",",
"tplPngSize",
",",
"None",
",",
"strCrd",
"=",
"strCrd",
")",
"else",
":",
"# The long array with all the combinations of model parameters is put",
"# into separate chunks for parallelisation, using a list of arrays.",
"lstMdlParams",
"=",
"np",
".",
"array_split",
"(",
"aryMdlParams",
",",
"varPar",
")",
"# Create a queue to put the results in:",
"queOut",
"=",
"mp",
".",
"Queue",
"(",
")",
"# Empty list for results from parallel processes (for pRF model",
"# responses):",
"lstMdlTc",
"=",
"[",
"None",
"]",
"*",
"varPar",
"# Empty list for processes:",
"lstPrcs",
"=",
"[",
"None",
"]",
"*",
"varPar",
"if",
"lgcPrint",
":",
"print",
"(",
"'---------Running parallel processes'",
")",
"# Create processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
"=",
"mp",
".",
"Process",
"(",
"target",
"=",
"cnvl_2D_gauss",
",",
"args",
"=",
"(",
"idxPrc",
",",
"lstMdlParams",
"[",
"idxPrc",
"]",
",",
"arySptExpInf",
",",
"tplPngSize",
",",
"queOut",
")",
",",
"kwargs",
"=",
"{",
"'strCrd'",
":",
"strCrd",
"}",
",",
")",
"# Daemon (kills processes when exiting):",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"Daemon",
"=",
"True",
"# Start processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"start",
"(",
")",
"# Collect results from queue:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstMdlTc",
"[",
"idxPrc",
"]",
"=",
"queOut",
".",
"get",
"(",
"True",
")",
"# Join processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"join",
"(",
")",
"if",
"lgcPrint",
":",
"print",
"(",
"'---------Collecting results from parallel processes'",
")",
"# Put output arrays from parallel process into one big array",
"lstMdlTc",
"=",
"sorted",
"(",
"lstMdlTc",
")",
"aryMdlCndRsp",
"=",
"np",
".",
"empty",
"(",
"(",
"0",
",",
"arySptExpInf",
".",
"shape",
"[",
"-",
"1",
"]",
")",
")",
"for",
"idx",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"aryMdlCndRsp",
"=",
"np",
".",
"concatenate",
"(",
"(",
"aryMdlCndRsp",
",",
"lstMdlTc",
"[",
"idx",
"]",
"[",
"1",
"]",
")",
",",
"axis",
"=",
"0",
")",
"# Clean up:",
"del",
"(",
"lstMdlParams",
")",
"del",
"(",
"lstMdlTc",
")",
"return",
"aryMdlCndRsp",
".",
"astype",
"(",
"'float16'",
")"
] | Create responses of 2D Gauss models to spatial conditions.
Parameters
----------
arySptExpInf : 3d numpy array, shape [n_x_pix, n_y_pix, n_conditions]
All spatial conditions stacked along second axis.
tplPngSize : tuple, 2
Pixel dimensions of the visual space (width, height).
aryMdlParams : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, 3]
Model parameters (x, y, sigma) for all models.
varPar : int, positive
Number of cores to parallelize over.
strCrd, string, either 'crt' or 'pol'
Whether model parameters are provided in cartesian or polar coordinates
lgcPrint : boolean
Whether print statements should be executed.
Returns
-------
aryMdlCndRsp : 2d numpy array, shape [n_x_pos*n_y_pos*n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions. | [
"Create",
"responses",
"of",
"2D",
"Gauss",
"models",
"to",
"spatial",
"conditions",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/model_creation_utils.py#L308-L396 |
MSchnei/pyprf_feature | pyprf_feature/analysis/model_creation_utils.py | crt_nrl_tc | def crt_nrl_tc(aryMdlRsp, aryCnd, aryOns, aryDrt, varTr, varNumVol,
varTmpOvsmpl, lgcPrint=True):
"""Create temporally upsampled neural time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions.
aryCnd : np.array
1D array with condition identifiers (every condition has its own int)
aryOns : np.array, same len as aryCnd
1D array with condition onset times in seconds.
aryDrt : np.array, same len as aryCnd
1D array with condition durations of different conditions in seconds.
varTr : float, positive
Time to repeat (TR) of the (fMRI) experiment
varNumVol : float, positive
Number of data point (volumes) in the (fMRI) data
varTmpOvsmpl : float, positive
Factor by which the time courses should be temporally upsampled.
lgcPrint: boolean, default True
Should print messages be sent to user?
Returns
-------
aryNrlTc : 2d numpy array,
shape [n_x_pos * n_y_pos * n_sd, varNumVol*varTmpOvsmpl]
Neural time course models in temporally upsampled space
Notes
---------
[1] This function first creates boxcar functions based on the conditions
as they are specified in the temporal experiment information, provided
by the user in the csv file. Second, it then replaces the 1s in the
boxcar function by predicted condition values that were previously
calculated based on the overlap between the assumed 2D Gaussian for the
current model and the presented stimulus aperture for that condition.
Since the 2D Gaussian is normalized, the overlap value will be between
0 and 1.
"""
# adjust the input, if necessary, such that input is 2D
tplInpShp = aryMdlRsp.shape
aryMdlRsp = aryMdlRsp.reshape((-1, aryMdlRsp.shape[-1]))
# the first spatial condition might code the baseline (blank periods) with
# all zeros. If this is the case, remove the first spatial condition, since
# for temporal conditions this is removed automatically below and we need
# temporal and sptial conditions to maych
if np.all(aryMdlRsp[:, 0] == 0):
if lgcPrint:
print('------------Removed first spatial condition (all zeros)')
aryMdlRsp = aryMdlRsp[:, 1:]
# create boxcar functions in temporally upsampled space
aryBxCarTmp = create_boxcar(aryCnd, aryOns, aryDrt, varTr, varNumVol,
aryExclCnd=np.array([0.]),
varTmpOvsmpl=varTmpOvsmpl).T
# Make sure that aryMdlRsp and aryBxCarTmp have the same number of
# conditions
assert aryMdlRsp.shape[-1] == aryBxCarTmp.shape[0]
# pre-allocate pixelwise boxcar array
aryNrlTc = np.zeros((aryMdlRsp.shape[0], aryBxCarTmp.shape[-1]),
dtype='float16')
# loop through boxcar functions of conditions
for ind, vecCndOcc in enumerate(aryBxCarTmp):
# get response predicted by models for this specific spatial condition
rspValPrdByMdl = aryMdlRsp[:, ind]
# insert predicted response value several times using broad-casting
aryNrlTc[..., vecCndOcc.astype('bool')] = rspValPrdByMdl[:, None]
# determine output shape
tplOutShp = tplInpShp[:-1] + (int(varNumVol*varTmpOvsmpl), )
return aryNrlTc.reshape(tplOutShp).astype('float16') | python | def crt_nrl_tc(aryMdlRsp, aryCnd, aryOns, aryDrt, varTr, varNumVol,
varTmpOvsmpl, lgcPrint=True):
"""Create temporally upsampled neural time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions.
aryCnd : np.array
1D array with condition identifiers (every condition has its own int)
aryOns : np.array, same len as aryCnd
1D array with condition onset times in seconds.
aryDrt : np.array, same len as aryCnd
1D array with condition durations of different conditions in seconds.
varTr : float, positive
Time to repeat (TR) of the (fMRI) experiment
varNumVol : float, positive
Number of data point (volumes) in the (fMRI) data
varTmpOvsmpl : float, positive
Factor by which the time courses should be temporally upsampled.
lgcPrint: boolean, default True
Should print messages be sent to user?
Returns
-------
aryNrlTc : 2d numpy array,
shape [n_x_pos * n_y_pos * n_sd, varNumVol*varTmpOvsmpl]
Neural time course models in temporally upsampled space
Notes
---------
[1] This function first creates boxcar functions based on the conditions
as they are specified in the temporal experiment information, provided
by the user in the csv file. Second, it then replaces the 1s in the
boxcar function by predicted condition values that were previously
calculated based on the overlap between the assumed 2D Gaussian for the
current model and the presented stimulus aperture for that condition.
Since the 2D Gaussian is normalized, the overlap value will be between
0 and 1.
"""
# adjust the input, if necessary, such that input is 2D
tplInpShp = aryMdlRsp.shape
aryMdlRsp = aryMdlRsp.reshape((-1, aryMdlRsp.shape[-1]))
# the first spatial condition might code the baseline (blank periods) with
# all zeros. If this is the case, remove the first spatial condition, since
# for temporal conditions this is removed automatically below and we need
# temporal and sptial conditions to maych
if np.all(aryMdlRsp[:, 0] == 0):
if lgcPrint:
print('------------Removed first spatial condition (all zeros)')
aryMdlRsp = aryMdlRsp[:, 1:]
# create boxcar functions in temporally upsampled space
aryBxCarTmp = create_boxcar(aryCnd, aryOns, aryDrt, varTr, varNumVol,
aryExclCnd=np.array([0.]),
varTmpOvsmpl=varTmpOvsmpl).T
# Make sure that aryMdlRsp and aryBxCarTmp have the same number of
# conditions
assert aryMdlRsp.shape[-1] == aryBxCarTmp.shape[0]
# pre-allocate pixelwise boxcar array
aryNrlTc = np.zeros((aryMdlRsp.shape[0], aryBxCarTmp.shape[-1]),
dtype='float16')
# loop through boxcar functions of conditions
for ind, vecCndOcc in enumerate(aryBxCarTmp):
# get response predicted by models for this specific spatial condition
rspValPrdByMdl = aryMdlRsp[:, ind]
# insert predicted response value several times using broad-casting
aryNrlTc[..., vecCndOcc.astype('bool')] = rspValPrdByMdl[:, None]
# determine output shape
tplOutShp = tplInpShp[:-1] + (int(varNumVol*varTmpOvsmpl), )
return aryNrlTc.reshape(tplOutShp).astype('float16') | [
"def",
"crt_nrl_tc",
"(",
"aryMdlRsp",
",",
"aryCnd",
",",
"aryOns",
",",
"aryDrt",
",",
"varTr",
",",
"varNumVol",
",",
"varTmpOvsmpl",
",",
"lgcPrint",
"=",
"True",
")",
":",
"# adjust the input, if necessary, such that input is 2D",
"tplInpShp",
"=",
"aryMdlRsp",
".",
"shape",
"aryMdlRsp",
"=",
"aryMdlRsp",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"aryMdlRsp",
".",
"shape",
"[",
"-",
"1",
"]",
")",
")",
"# the first spatial condition might code the baseline (blank periods) with",
"# all zeros. If this is the case, remove the first spatial condition, since",
"# for temporal conditions this is removed automatically below and we need",
"# temporal and sptial conditions to maych",
"if",
"np",
".",
"all",
"(",
"aryMdlRsp",
"[",
":",
",",
"0",
"]",
"==",
"0",
")",
":",
"if",
"lgcPrint",
":",
"print",
"(",
"'------------Removed first spatial condition (all zeros)'",
")",
"aryMdlRsp",
"=",
"aryMdlRsp",
"[",
":",
",",
"1",
":",
"]",
"# create boxcar functions in temporally upsampled space",
"aryBxCarTmp",
"=",
"create_boxcar",
"(",
"aryCnd",
",",
"aryOns",
",",
"aryDrt",
",",
"varTr",
",",
"varNumVol",
",",
"aryExclCnd",
"=",
"np",
".",
"array",
"(",
"[",
"0.",
"]",
")",
",",
"varTmpOvsmpl",
"=",
"varTmpOvsmpl",
")",
".",
"T",
"# Make sure that aryMdlRsp and aryBxCarTmp have the same number of",
"# conditions",
"assert",
"aryMdlRsp",
".",
"shape",
"[",
"-",
"1",
"]",
"==",
"aryBxCarTmp",
".",
"shape",
"[",
"0",
"]",
"# pre-allocate pixelwise boxcar array",
"aryNrlTc",
"=",
"np",
".",
"zeros",
"(",
"(",
"aryMdlRsp",
".",
"shape",
"[",
"0",
"]",
",",
"aryBxCarTmp",
".",
"shape",
"[",
"-",
"1",
"]",
")",
",",
"dtype",
"=",
"'float16'",
")",
"# loop through boxcar functions of conditions",
"for",
"ind",
",",
"vecCndOcc",
"in",
"enumerate",
"(",
"aryBxCarTmp",
")",
":",
"# get response predicted by models for this specific spatial condition",
"rspValPrdByMdl",
"=",
"aryMdlRsp",
"[",
":",
",",
"ind",
"]",
"# insert predicted response value several times using broad-casting",
"aryNrlTc",
"[",
"...",
",",
"vecCndOcc",
".",
"astype",
"(",
"'bool'",
")",
"]",
"=",
"rspValPrdByMdl",
"[",
":",
",",
"None",
"]",
"# determine output shape",
"tplOutShp",
"=",
"tplInpShp",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"int",
"(",
"varNumVol",
"*",
"varTmpOvsmpl",
")",
",",
")",
"return",
"aryNrlTc",
".",
"reshape",
"(",
"tplOutShp",
")",
".",
"astype",
"(",
"'float16'",
")"
] | Create temporally upsampled neural time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions.
aryCnd : np.array
1D array with condition identifiers (every condition has its own int)
aryOns : np.array, same len as aryCnd
1D array with condition onset times in seconds.
aryDrt : np.array, same len as aryCnd
1D array with condition durations of different conditions in seconds.
varTr : float, positive
Time to repeat (TR) of the (fMRI) experiment
varNumVol : float, positive
Number of data point (volumes) in the (fMRI) data
varTmpOvsmpl : float, positive
Factor by which the time courses should be temporally upsampled.
lgcPrint: boolean, default True
Should print messages be sent to user?
Returns
-------
aryNrlTc : 2d numpy array,
shape [n_x_pos * n_y_pos * n_sd, varNumVol*varTmpOvsmpl]
Neural time course models in temporally upsampled space
Notes
---------
[1] This function first creates boxcar functions based on the conditions
as they are specified in the temporal experiment information, provided
by the user in the csv file. Second, it then replaces the 1s in the
boxcar function by predicted condition values that were previously
calculated based on the overlap between the assumed 2D Gaussian for the
current model and the presented stimulus aperture for that condition.
Since the 2D Gaussian is normalized, the overlap value will be between
0 and 1. | [
"Create",
"temporally",
"upsampled",
"neural",
"time",
"courses",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/model_creation_utils.py#L399-L476 |
MSchnei/pyprf_feature | pyprf_feature/analysis/model_creation_utils.py | crt_prf_tc | def crt_prf_tc(aryNrlTc, varNumVol, varTr, varTmpOvsmpl, switchHrfSet,
tplPngSize, varPar, dctPrm=None, lgcPrint=True):
"""Convolve every neural time course with HRF function.
Parameters
----------
aryNrlTc : 4d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_vol]
Temporally upsampled neural time course models.
varNumVol : float, positive
Number of volumes of the (fMRI) data.
varTr : float, positive
Time to repeat (TR) of the (fMRI) experiment.
varTmpOvsmpl : int, positive
Factor by which the data hs been temporally upsampled.
switchHrfSet : int, (1, 2, 3)
Switch to determine which hrf basis functions are used
tplPngSize : tuple
Pixel dimensions of the visual space (width, height).
varPar : int, positive
Number of cores for multi-processing.
dctPrm : dictionary, default None
Dictionary with customized hrf parameters. If this is None, default
hrf parameters will be used.
lgcPrint: boolean, default True
Should print messages be sent to user?
Returns
-------
aryNrlTcConv : 5d numpy array,
shape [n_x_pos, n_y_pos, n_sd, n_hrf_bases, varNumVol]
Neural time courses convolved with HRF basis functions
"""
# Create hrf time course function:
if switchHrfSet == 3:
lstHrf = [spmt, dspmt, ddspmt]
elif switchHrfSet == 2:
lstHrf = [spmt, dspmt]
elif switchHrfSet == 1:
lstHrf = [spmt]
# If necessary, adjust the input such that input is 2D, with last dim time
tplInpShp = aryNrlTc.shape
aryNrlTc = np.reshape(aryNrlTc, (-1, aryNrlTc.shape[-1]))
if varPar == 1:
# if the number of cores requested by the user is equal to 1,
# we save the overhead of multiprocessing by calling aryMdlCndRsp
# directly
aryNrlTcConv = cnvl_tc(0, aryNrlTc, lstHrf, varTr,
varNumVol, varTmpOvsmpl, None, dctPrm=dctPrm)
else:
# Put input data into chunks:
lstNrlTc = np.array_split(aryNrlTc, varPar)
# Create a queue to put the results in:
queOut = mp.Queue()
# Empty list for processes:
lstPrcs = [None] * varPar
# Empty list for results of parallel processes:
lstConv = [None] * varPar
if lgcPrint:
print('------------Running parallel processes')
# Create processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvl_tc,
args=(idxPrc,
lstNrlTc[idxPrc],
lstHrf,
varTr,
varNumVol,
varTmpOvsmpl,
queOut),
kwargs={'dctPrm': dctPrm},
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
# Start processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].start()
# Collect results from queue:
for idxPrc in range(0, varPar):
lstConv[idxPrc] = queOut.get(True)
# Join processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].join()
if lgcPrint:
print('------------Collecting results from parallel processes')
# Put output into correct order:
lstConv = sorted(lstConv)
# Concatenate convolved pixel time courses (into the same order
aryNrlTcConv = np.zeros((0, switchHrfSet, varNumVol), dtype=np.float32)
for idxRes in range(0, varPar):
aryNrlTcConv = np.concatenate((aryNrlTcConv, lstConv[idxRes][1]),
axis=0)
# clean up
del(aryNrlTc)
del(lstConv)
# Reshape results:
tplOutShp = tplInpShp[:-1] + (len(lstHrf), ) + (varNumVol, )
# Return:
return np.reshape(aryNrlTcConv, tplOutShp).astype(np.float32) | python | def crt_prf_tc(aryNrlTc, varNumVol, varTr, varTmpOvsmpl, switchHrfSet,
tplPngSize, varPar, dctPrm=None, lgcPrint=True):
"""Convolve every neural time course with HRF function.
Parameters
----------
aryNrlTc : 4d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_vol]
Temporally upsampled neural time course models.
varNumVol : float, positive
Number of volumes of the (fMRI) data.
varTr : float, positive
Time to repeat (TR) of the (fMRI) experiment.
varTmpOvsmpl : int, positive
Factor by which the data hs been temporally upsampled.
switchHrfSet : int, (1, 2, 3)
Switch to determine which hrf basis functions are used
tplPngSize : tuple
Pixel dimensions of the visual space (width, height).
varPar : int, positive
Number of cores for multi-processing.
dctPrm : dictionary, default None
Dictionary with customized hrf parameters. If this is None, default
hrf parameters will be used.
lgcPrint: boolean, default True
Should print messages be sent to user?
Returns
-------
aryNrlTcConv : 5d numpy array,
shape [n_x_pos, n_y_pos, n_sd, n_hrf_bases, varNumVol]
Neural time courses convolved with HRF basis functions
"""
# Create hrf time course function:
if switchHrfSet == 3:
lstHrf = [spmt, dspmt, ddspmt]
elif switchHrfSet == 2:
lstHrf = [spmt, dspmt]
elif switchHrfSet == 1:
lstHrf = [spmt]
# If necessary, adjust the input such that input is 2D, with last dim time
tplInpShp = aryNrlTc.shape
aryNrlTc = np.reshape(aryNrlTc, (-1, aryNrlTc.shape[-1]))
if varPar == 1:
# if the number of cores requested by the user is equal to 1,
# we save the overhead of multiprocessing by calling aryMdlCndRsp
# directly
aryNrlTcConv = cnvl_tc(0, aryNrlTc, lstHrf, varTr,
varNumVol, varTmpOvsmpl, None, dctPrm=dctPrm)
else:
# Put input data into chunks:
lstNrlTc = np.array_split(aryNrlTc, varPar)
# Create a queue to put the results in:
queOut = mp.Queue()
# Empty list for processes:
lstPrcs = [None] * varPar
# Empty list for results of parallel processes:
lstConv = [None] * varPar
if lgcPrint:
print('------------Running parallel processes')
# Create processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc] = mp.Process(target=cnvl_tc,
args=(idxPrc,
lstNrlTc[idxPrc],
lstHrf,
varTr,
varNumVol,
varTmpOvsmpl,
queOut),
kwargs={'dctPrm': dctPrm},
)
# Daemon (kills processes when exiting):
lstPrcs[idxPrc].Daemon = True
# Start processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].start()
# Collect results from queue:
for idxPrc in range(0, varPar):
lstConv[idxPrc] = queOut.get(True)
# Join processes:
for idxPrc in range(0, varPar):
lstPrcs[idxPrc].join()
if lgcPrint:
print('------------Collecting results from parallel processes')
# Put output into correct order:
lstConv = sorted(lstConv)
# Concatenate convolved pixel time courses (into the same order
aryNrlTcConv = np.zeros((0, switchHrfSet, varNumVol), dtype=np.float32)
for idxRes in range(0, varPar):
aryNrlTcConv = np.concatenate((aryNrlTcConv, lstConv[idxRes][1]),
axis=0)
# clean up
del(aryNrlTc)
del(lstConv)
# Reshape results:
tplOutShp = tplInpShp[:-1] + (len(lstHrf), ) + (varNumVol, )
# Return:
return np.reshape(aryNrlTcConv, tplOutShp).astype(np.float32) | [
"def",
"crt_prf_tc",
"(",
"aryNrlTc",
",",
"varNumVol",
",",
"varTr",
",",
"varTmpOvsmpl",
",",
"switchHrfSet",
",",
"tplPngSize",
",",
"varPar",
",",
"dctPrm",
"=",
"None",
",",
"lgcPrint",
"=",
"True",
")",
":",
"# Create hrf time course function:",
"if",
"switchHrfSet",
"==",
"3",
":",
"lstHrf",
"=",
"[",
"spmt",
",",
"dspmt",
",",
"ddspmt",
"]",
"elif",
"switchHrfSet",
"==",
"2",
":",
"lstHrf",
"=",
"[",
"spmt",
",",
"dspmt",
"]",
"elif",
"switchHrfSet",
"==",
"1",
":",
"lstHrf",
"=",
"[",
"spmt",
"]",
"# If necessary, adjust the input such that input is 2D, with last dim time",
"tplInpShp",
"=",
"aryNrlTc",
".",
"shape",
"aryNrlTc",
"=",
"np",
".",
"reshape",
"(",
"aryNrlTc",
",",
"(",
"-",
"1",
",",
"aryNrlTc",
".",
"shape",
"[",
"-",
"1",
"]",
")",
")",
"if",
"varPar",
"==",
"1",
":",
"# if the number of cores requested by the user is equal to 1,",
"# we save the overhead of multiprocessing by calling aryMdlCndRsp",
"# directly",
"aryNrlTcConv",
"=",
"cnvl_tc",
"(",
"0",
",",
"aryNrlTc",
",",
"lstHrf",
",",
"varTr",
",",
"varNumVol",
",",
"varTmpOvsmpl",
",",
"None",
",",
"dctPrm",
"=",
"dctPrm",
")",
"else",
":",
"# Put input data into chunks:",
"lstNrlTc",
"=",
"np",
".",
"array_split",
"(",
"aryNrlTc",
",",
"varPar",
")",
"# Create a queue to put the results in:",
"queOut",
"=",
"mp",
".",
"Queue",
"(",
")",
"# Empty list for processes:",
"lstPrcs",
"=",
"[",
"None",
"]",
"*",
"varPar",
"# Empty list for results of parallel processes:",
"lstConv",
"=",
"[",
"None",
"]",
"*",
"varPar",
"if",
"lgcPrint",
":",
"print",
"(",
"'------------Running parallel processes'",
")",
"# Create processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
"=",
"mp",
".",
"Process",
"(",
"target",
"=",
"cnvl_tc",
",",
"args",
"=",
"(",
"idxPrc",
",",
"lstNrlTc",
"[",
"idxPrc",
"]",
",",
"lstHrf",
",",
"varTr",
",",
"varNumVol",
",",
"varTmpOvsmpl",
",",
"queOut",
")",
",",
"kwargs",
"=",
"{",
"'dctPrm'",
":",
"dctPrm",
"}",
",",
")",
"# Daemon (kills processes when exiting):",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"Daemon",
"=",
"True",
"# Start processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"start",
"(",
")",
"# Collect results from queue:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstConv",
"[",
"idxPrc",
"]",
"=",
"queOut",
".",
"get",
"(",
"True",
")",
"# Join processes:",
"for",
"idxPrc",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"lstPrcs",
"[",
"idxPrc",
"]",
".",
"join",
"(",
")",
"if",
"lgcPrint",
":",
"print",
"(",
"'------------Collecting results from parallel processes'",
")",
"# Put output into correct order:",
"lstConv",
"=",
"sorted",
"(",
"lstConv",
")",
"# Concatenate convolved pixel time courses (into the same order",
"aryNrlTcConv",
"=",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"switchHrfSet",
",",
"varNumVol",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"for",
"idxRes",
"in",
"range",
"(",
"0",
",",
"varPar",
")",
":",
"aryNrlTcConv",
"=",
"np",
".",
"concatenate",
"(",
"(",
"aryNrlTcConv",
",",
"lstConv",
"[",
"idxRes",
"]",
"[",
"1",
"]",
")",
",",
"axis",
"=",
"0",
")",
"# clean up",
"del",
"(",
"aryNrlTc",
")",
"del",
"(",
"lstConv",
")",
"# Reshape results:",
"tplOutShp",
"=",
"tplInpShp",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"len",
"(",
"lstHrf",
")",
",",
")",
"+",
"(",
"varNumVol",
",",
")",
"# Return:",
"return",
"np",
".",
"reshape",
"(",
"aryNrlTcConv",
",",
"tplOutShp",
")",
".",
"astype",
"(",
"np",
".",
"float32",
")"
] | Convolve every neural time course with HRF function.
Parameters
----------
aryNrlTc : 4d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_vol]
Temporally upsampled neural time course models.
varNumVol : float, positive
Number of volumes of the (fMRI) data.
varTr : float, positive
Time to repeat (TR) of the (fMRI) experiment.
varTmpOvsmpl : int, positive
Factor by which the data hs been temporally upsampled.
switchHrfSet : int, (1, 2, 3)
Switch to determine which hrf basis functions are used
tplPngSize : tuple
Pixel dimensions of the visual space (width, height).
varPar : int, positive
Number of cores for multi-processing.
dctPrm : dictionary, default None
Dictionary with customized hrf parameters. If this is None, default
hrf parameters will be used.
lgcPrint: boolean, default True
Should print messages be sent to user?
Returns
-------
aryNrlTcConv : 5d numpy array,
shape [n_x_pos, n_y_pos, n_sd, n_hrf_bases, varNumVol]
Neural time courses convolved with HRF basis functions | [
"Convolve",
"every",
"neural",
"time",
"course",
"with",
"HRF",
"function",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/model_creation_utils.py#L479-L591 |
MSchnei/pyprf_feature | pyprf_feature/analysis/model_creation_utils.py | crt_prf_ftr_tc | def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl,
switchHrfSet, tplPngSize, varPar, dctPrm=None,
lgcPrint=True):
"""Create all spatial x feature prf time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions
aryTmpExpInf: 2d numpy array, shape [unknown, 4]
Temporal information about conditions
varNumVol : float, positive
Number of volumes of the (fMRI) data.
varTr : float, positive
Time to repeat (TR) of the (fMRI) experiment.
varTmpOvsmpl : int, positive
Factor by which the data hs been temporally upsampled.
switchHrfSet : int, (1, 2, 3)
Switch to determine which hrf basis functions are used
tplPngSize : tuple
Pixel dimensions of the visual space (width, height).
varPar : int, positive
Description of input 1.
dctPrm : dictionary, default None
Dictionary with customized hrf parameters. If this is None, default
hrf parameters will be used.
lgcPrint: boolean, default True
Should print messages be sent to user?
Returns
-------
aryNrlTcConv : 3d numpy array,
shape [nr of models, nr of unique feautures, varNumVol]
Prf time course models
"""
# Identify number of unique features
vecFeat = np.unique(aryTmpExpInf[:, 3])
vecFeat = vecFeat[np.nonzero(vecFeat)[0]]
# Preallocate the output array
aryPrfTc = np.zeros((aryMdlRsp.shape[0], 0, varNumVol),
dtype=np.float32)
# Loop over unique features
for indFtr, ftr in enumerate(vecFeat):
if lgcPrint:
print('---------Create prf time course model for feature ' +
str(ftr))
# Derive sptial conditions, onsets and durations for this specific
# feature
aryTmpCnd = aryTmpExpInf[aryTmpExpInf[:, 3] == ftr, 0]
aryTmpOns = aryTmpExpInf[aryTmpExpInf[:, 3] == ftr, 1]
aryTmpDrt = aryTmpExpInf[aryTmpExpInf[:, 3] == ftr, 2]
# Create temporally upsampled neural time courses.
aryNrlTcTmp = crt_nrl_tc(aryMdlRsp, aryTmpCnd, aryTmpOns, aryTmpDrt,
varTr, varNumVol, varTmpOvsmpl,
lgcPrint=lgcPrint)
# Convolve with hrf to create model pRF time courses.
aryPrfTcTmp = crt_prf_tc(aryNrlTcTmp, varNumVol, varTr, varTmpOvsmpl,
switchHrfSet, tplPngSize, varPar,
dctPrm=dctPrm, lgcPrint=lgcPrint)
# Add temporal time course to time course that will be returned
aryPrfTc = np.concatenate((aryPrfTc, aryPrfTcTmp), axis=1)
return aryPrfTc | python | def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl,
switchHrfSet, tplPngSize, varPar, dctPrm=None,
lgcPrint=True):
"""Create all spatial x feature prf time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions
aryTmpExpInf: 2d numpy array, shape [unknown, 4]
Temporal information about conditions
varNumVol : float, positive
Number of volumes of the (fMRI) data.
varTr : float, positive
Time to repeat (TR) of the (fMRI) experiment.
varTmpOvsmpl : int, positive
Factor by which the data hs been temporally upsampled.
switchHrfSet : int, (1, 2, 3)
Switch to determine which hrf basis functions are used
tplPngSize : tuple
Pixel dimensions of the visual space (width, height).
varPar : int, positive
Description of input 1.
dctPrm : dictionary, default None
Dictionary with customized hrf parameters. If this is None, default
hrf parameters will be used.
lgcPrint: boolean, default True
Should print messages be sent to user?
Returns
-------
aryNrlTcConv : 3d numpy array,
shape [nr of models, nr of unique feautures, varNumVol]
Prf time course models
"""
# Identify number of unique features
vecFeat = np.unique(aryTmpExpInf[:, 3])
vecFeat = vecFeat[np.nonzero(vecFeat)[0]]
# Preallocate the output array
aryPrfTc = np.zeros((aryMdlRsp.shape[0], 0, varNumVol),
dtype=np.float32)
# Loop over unique features
for indFtr, ftr in enumerate(vecFeat):
if lgcPrint:
print('---------Create prf time course model for feature ' +
str(ftr))
# Derive sptial conditions, onsets and durations for this specific
# feature
aryTmpCnd = aryTmpExpInf[aryTmpExpInf[:, 3] == ftr, 0]
aryTmpOns = aryTmpExpInf[aryTmpExpInf[:, 3] == ftr, 1]
aryTmpDrt = aryTmpExpInf[aryTmpExpInf[:, 3] == ftr, 2]
# Create temporally upsampled neural time courses.
aryNrlTcTmp = crt_nrl_tc(aryMdlRsp, aryTmpCnd, aryTmpOns, aryTmpDrt,
varTr, varNumVol, varTmpOvsmpl,
lgcPrint=lgcPrint)
# Convolve with hrf to create model pRF time courses.
aryPrfTcTmp = crt_prf_tc(aryNrlTcTmp, varNumVol, varTr, varTmpOvsmpl,
switchHrfSet, tplPngSize, varPar,
dctPrm=dctPrm, lgcPrint=lgcPrint)
# Add temporal time course to time course that will be returned
aryPrfTc = np.concatenate((aryPrfTc, aryPrfTcTmp), axis=1)
return aryPrfTc | [
"def",
"crt_prf_ftr_tc",
"(",
"aryMdlRsp",
",",
"aryTmpExpInf",
",",
"varNumVol",
",",
"varTr",
",",
"varTmpOvsmpl",
",",
"switchHrfSet",
",",
"tplPngSize",
",",
"varPar",
",",
"dctPrm",
"=",
"None",
",",
"lgcPrint",
"=",
"True",
")",
":",
"# Identify number of unique features",
"vecFeat",
"=",
"np",
".",
"unique",
"(",
"aryTmpExpInf",
"[",
":",
",",
"3",
"]",
")",
"vecFeat",
"=",
"vecFeat",
"[",
"np",
".",
"nonzero",
"(",
"vecFeat",
")",
"[",
"0",
"]",
"]",
"# Preallocate the output array",
"aryPrfTc",
"=",
"np",
".",
"zeros",
"(",
"(",
"aryMdlRsp",
".",
"shape",
"[",
"0",
"]",
",",
"0",
",",
"varNumVol",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# Loop over unique features",
"for",
"indFtr",
",",
"ftr",
"in",
"enumerate",
"(",
"vecFeat",
")",
":",
"if",
"lgcPrint",
":",
"print",
"(",
"'---------Create prf time course model for feature '",
"+",
"str",
"(",
"ftr",
")",
")",
"# Derive sptial conditions, onsets and durations for this specific",
"# feature",
"aryTmpCnd",
"=",
"aryTmpExpInf",
"[",
"aryTmpExpInf",
"[",
":",
",",
"3",
"]",
"==",
"ftr",
",",
"0",
"]",
"aryTmpOns",
"=",
"aryTmpExpInf",
"[",
"aryTmpExpInf",
"[",
":",
",",
"3",
"]",
"==",
"ftr",
",",
"1",
"]",
"aryTmpDrt",
"=",
"aryTmpExpInf",
"[",
"aryTmpExpInf",
"[",
":",
",",
"3",
"]",
"==",
"ftr",
",",
"2",
"]",
"# Create temporally upsampled neural time courses.",
"aryNrlTcTmp",
"=",
"crt_nrl_tc",
"(",
"aryMdlRsp",
",",
"aryTmpCnd",
",",
"aryTmpOns",
",",
"aryTmpDrt",
",",
"varTr",
",",
"varNumVol",
",",
"varTmpOvsmpl",
",",
"lgcPrint",
"=",
"lgcPrint",
")",
"# Convolve with hrf to create model pRF time courses.",
"aryPrfTcTmp",
"=",
"crt_prf_tc",
"(",
"aryNrlTcTmp",
",",
"varNumVol",
",",
"varTr",
",",
"varTmpOvsmpl",
",",
"switchHrfSet",
",",
"tplPngSize",
",",
"varPar",
",",
"dctPrm",
"=",
"dctPrm",
",",
"lgcPrint",
"=",
"lgcPrint",
")",
"# Add temporal time course to time course that will be returned",
"aryPrfTc",
"=",
"np",
".",
"concatenate",
"(",
"(",
"aryPrfTc",
",",
"aryPrfTcTmp",
")",
",",
"axis",
"=",
"1",
")",
"return",
"aryPrfTc"
] | Create all spatial x feature prf time courses.
Parameters
----------
aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond]
Responses of 2D Gauss models to spatial conditions
aryTmpExpInf: 2d numpy array, shape [unknown, 4]
Temporal information about conditions
varNumVol : float, positive
Number of volumes of the (fMRI) data.
varTr : float, positive
Time to repeat (TR) of the (fMRI) experiment.
varTmpOvsmpl : int, positive
Factor by which the data hs been temporally upsampled.
switchHrfSet : int, (1, 2, 3)
Switch to determine which hrf basis functions are used
tplPngSize : tuple
Pixel dimensions of the visual space (width, height).
varPar : int, positive
Description of input 1.
dctPrm : dictionary, default None
Dictionary with customized hrf parameters. If this is None, default
hrf parameters will be used.
lgcPrint: boolean, default True
Should print messages be sent to user?
Returns
-------
aryNrlTcConv : 3d numpy array,
shape [nr of models, nr of unique feautures, varNumVol]
Prf time course models | [
"Create",
"all",
"spatial",
"x",
"feature",
"prf",
"time",
"courses",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/model_creation_utils.py#L594-L662 |
MSchnei/pyprf_feature | pyprf_feature/analysis/model_creation_utils.py | fnd_unq_rws | def fnd_unq_rws(A, return_index=False, return_inverse=False):
"""Find unique rows in 2D array.
Parameters
----------
A : 2d numpy array
Array for which unique rows should be identified.
return_index : bool
Bool to decide whether I is returned.
return_inverse : bool
Bool to decide whether J is returned.
Returns
-------
B : 1d numpy array,
Unique rows
I: 1d numpy array, only returned if return_index is True
B = A[I,:]
J: 2d numpy array, only returned if return_inverse is True
A = B[J,:]
"""
A = np.require(A, requirements='C')
assert A.ndim == 2, "array must be 2-dim'l"
B = np.unique(A.view([('', A.dtype)]*A.shape[1]),
return_index=return_index,
return_inverse=return_inverse)
if return_index or return_inverse:
return (B[0].view(A.dtype).reshape((-1, A.shape[1]), order='C'),) \
+ B[1:]
else:
return B.view(A.dtype).reshape((-1, A.shape[1]), order='C') | python | def fnd_unq_rws(A, return_index=False, return_inverse=False):
"""Find unique rows in 2D array.
Parameters
----------
A : 2d numpy array
Array for which unique rows should be identified.
return_index : bool
Bool to decide whether I is returned.
return_inverse : bool
Bool to decide whether J is returned.
Returns
-------
B : 1d numpy array,
Unique rows
I: 1d numpy array, only returned if return_index is True
B = A[I,:]
J: 2d numpy array, only returned if return_inverse is True
A = B[J,:]
"""
A = np.require(A, requirements='C')
assert A.ndim == 2, "array must be 2-dim'l"
B = np.unique(A.view([('', A.dtype)]*A.shape[1]),
return_index=return_index,
return_inverse=return_inverse)
if return_index or return_inverse:
return (B[0].view(A.dtype).reshape((-1, A.shape[1]), order='C'),) \
+ B[1:]
else:
return B.view(A.dtype).reshape((-1, A.shape[1]), order='C') | [
"def",
"fnd_unq_rws",
"(",
"A",
",",
"return_index",
"=",
"False",
",",
"return_inverse",
"=",
"False",
")",
":",
"A",
"=",
"np",
".",
"require",
"(",
"A",
",",
"requirements",
"=",
"'C'",
")",
"assert",
"A",
".",
"ndim",
"==",
"2",
",",
"\"array must be 2-dim'l\"",
"B",
"=",
"np",
".",
"unique",
"(",
"A",
".",
"view",
"(",
"[",
"(",
"''",
",",
"A",
".",
"dtype",
")",
"]",
"*",
"A",
".",
"shape",
"[",
"1",
"]",
")",
",",
"return_index",
"=",
"return_index",
",",
"return_inverse",
"=",
"return_inverse",
")",
"if",
"return_index",
"or",
"return_inverse",
":",
"return",
"(",
"B",
"[",
"0",
"]",
".",
"view",
"(",
"A",
".",
"dtype",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"A",
".",
"shape",
"[",
"1",
"]",
")",
",",
"order",
"=",
"'C'",
")",
",",
")",
"+",
"B",
"[",
"1",
":",
"]",
"else",
":",
"return",
"B",
".",
"view",
"(",
"A",
".",
"dtype",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"A",
".",
"shape",
"[",
"1",
"]",
")",
",",
"order",
"=",
"'C'",
")"
] | Find unique rows in 2D array.
Parameters
----------
A : 2d numpy array
Array for which unique rows should be identified.
return_index : bool
Bool to decide whether I is returned.
return_inverse : bool
Bool to decide whether J is returned.
Returns
-------
B : 1d numpy array,
Unique rows
I: 1d numpy array, only returned if return_index is True
B = A[I,:]
J: 2d numpy array, only returned if return_inverse is True
A = B[J,:] | [
"Find",
"unique",
"rows",
"in",
"2D",
"array",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/model_creation_utils.py#L665-L699 |
bachya/pyflunearyou | pyflunearyou/client.py | Client._request | async def _request(
self, method: str, endpoint: str, *, headers: dict = None) -> dict:
"""Make a request against air-matters.com."""
url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint)
if not headers:
headers = {}
headers.update({
'Host': DEFAULT_HOST,
'Origin': DEFAULT_ORIGIN,
'Referer': DEFAULT_ORIGIN,
'User-Agent': DEFAULT_USER_AGENT,
})
async with self._websession.request(
method,
url,
headers=headers,
) as resp:
try:
resp.raise_for_status()
return await resp.json(content_type=None)
except client_exceptions.ClientError as err:
raise RequestError(
'Error requesting data from {0}: {1}'.format(
endpoint, err)) from None | python | async def _request(
self, method: str, endpoint: str, *, headers: dict = None) -> dict:
"""Make a request against air-matters.com."""
url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint)
if not headers:
headers = {}
headers.update({
'Host': DEFAULT_HOST,
'Origin': DEFAULT_ORIGIN,
'Referer': DEFAULT_ORIGIN,
'User-Agent': DEFAULT_USER_AGENT,
})
async with self._websession.request(
method,
url,
headers=headers,
) as resp:
try:
resp.raise_for_status()
return await resp.json(content_type=None)
except client_exceptions.ClientError as err:
raise RequestError(
'Error requesting data from {0}: {1}'.format(
endpoint, err)) from None | [
"async",
"def",
"_request",
"(",
"self",
",",
"method",
":",
"str",
",",
"endpoint",
":",
"str",
",",
"*",
",",
"headers",
":",
"dict",
"=",
"None",
")",
"->",
"dict",
":",
"url",
"=",
"'{0}/{1}'",
".",
"format",
"(",
"API_URL_SCAFFOLD",
",",
"endpoint",
")",
"if",
"not",
"headers",
":",
"headers",
"=",
"{",
"}",
"headers",
".",
"update",
"(",
"{",
"'Host'",
":",
"DEFAULT_HOST",
",",
"'Origin'",
":",
"DEFAULT_ORIGIN",
",",
"'Referer'",
":",
"DEFAULT_ORIGIN",
",",
"'User-Agent'",
":",
"DEFAULT_USER_AGENT",
",",
"}",
")",
"async",
"with",
"self",
".",
"_websession",
".",
"request",
"(",
"method",
",",
"url",
",",
"headers",
"=",
"headers",
",",
")",
"as",
"resp",
":",
"try",
":",
"resp",
".",
"raise_for_status",
"(",
")",
"return",
"await",
"resp",
".",
"json",
"(",
"content_type",
"=",
"None",
")",
"except",
"client_exceptions",
".",
"ClientError",
"as",
"err",
":",
"raise",
"RequestError",
"(",
"'Error requesting data from {0}: {1}'",
".",
"format",
"(",
"endpoint",
",",
"err",
")",
")",
"from",
"None"
] | Make a request against air-matters.com. | [
"Make",
"a",
"request",
"against",
"air",
"-",
"matters",
".",
"com",
"."
] | train | https://github.com/bachya/pyflunearyou/blob/16a2f839c8df851e925e010a6b5c5708386febac/pyflunearyou/client.py#L34-L59 |
olivier-m/rafter | rafter/filters.py | filter_transform_response | def filter_transform_response(get_response, params):
"""
This filter process the returned response. It does 3 things:
- If the response is a ``sanic.response.HTTPResponse`` and not a
:class:`rafter.http.Response`, return it immediately.
- If the response is not a :class:`rafter.http.Response` instance,
turn it to a :class:`rafter.http.Response` instance with the response
as data.
- Then, return the Response instance.
As the Response instance is not immediately serialized, you can still
validate its data without any serialization / de-serialization penalty.
"""
async def decorated_filter(request, *args, **kwargs):
response = await get_response(request, *args, **kwargs)
if isinstance(response, HTTPResponse) and \
not isinstance(response, Response):
return response
if not isinstance(response, Response):
response = Response(response)
return response
return decorated_filter | python | def filter_transform_response(get_response, params):
"""
This filter process the returned response. It does 3 things:
- If the response is a ``sanic.response.HTTPResponse`` and not a
:class:`rafter.http.Response`, return it immediately.
- If the response is not a :class:`rafter.http.Response` instance,
turn it to a :class:`rafter.http.Response` instance with the response
as data.
- Then, return the Response instance.
As the Response instance is not immediately serialized, you can still
validate its data without any serialization / de-serialization penalty.
"""
async def decorated_filter(request, *args, **kwargs):
response = await get_response(request, *args, **kwargs)
if isinstance(response, HTTPResponse) and \
not isinstance(response, Response):
return response
if not isinstance(response, Response):
response = Response(response)
return response
return decorated_filter | [
"def",
"filter_transform_response",
"(",
"get_response",
",",
"params",
")",
":",
"async",
"def",
"decorated_filter",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"await",
"get_response",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"response",
",",
"HTTPResponse",
")",
"and",
"not",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"return",
"response",
"if",
"not",
"isinstance",
"(",
"response",
",",
"Response",
")",
":",
"response",
"=",
"Response",
"(",
"response",
")",
"return",
"response",
"return",
"decorated_filter"
] | This filter process the returned response. It does 3 things:
- If the response is a ``sanic.response.HTTPResponse`` and not a
:class:`rafter.http.Response`, return it immediately.
- If the response is not a :class:`rafter.http.Response` instance,
turn it to a :class:`rafter.http.Response` instance with the response
as data.
- Then, return the Response instance.
As the Response instance is not immediately serialized, you can still
validate its data without any serialization / de-serialization penalty. | [
"This",
"filter",
"process",
"the",
"returned",
"response",
".",
"It",
"does",
"3",
"things",
":"
] | train | https://github.com/olivier-m/rafter/blob/aafcf8fd019f24abcf519307c4484cc6b4697c04/rafter/filters.py#L11-L38 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/article/__init__.py | Article.get_publisher | def get_publisher(self):
"""
This method defines how the Article tries to determine the publisher of
the article.
This method relies on the success of the get_DOI method to fetch the
appropriate full DOI for the article. It then takes the DOI prefix
which corresponds to the publisher and then uses that to attempt to load
the correct publisher-specific code. This may fail; if the DOI is not
mapped to a code file, if the DOI is mapped but the code file could not
be located, or if the mapped code file is malformed then this method
will issue/log an informative error message and return None. This method
will not try to infer the publisher based on any metadata other than the
DOI of the article.
Returns
-------
publisher : Publisher instance or None
"""
#For a detailed explanation of the DOI system, visit:
#http://www.doi.org/hb.html
#The basic syntax of a DOI is this <prefix>/<suffix>
#The <prefix> specifies a unique DOI registrant, in our case, this
#should correspond to the publisher. We use this information to register
#the correct Publisher class with this article
doi_prefix = self.doi.split('/')[0]
#The import_by_doi method should raise ImportError if a problem occurred
try:
publisher_mod = openaccess_epub.publisher.import_by_doi(doi_prefix)
except ImportError as e:
log.exception(e)
return None
#Each publisher module should define an attribute "pub_class" pointing
#to the publisher-specific class extending
#openaccess_epub.publisher.Publisher
return publisher_mod.pub_class(self) | python | def get_publisher(self):
"""
This method defines how the Article tries to determine the publisher of
the article.
This method relies on the success of the get_DOI method to fetch the
appropriate full DOI for the article. It then takes the DOI prefix
which corresponds to the publisher and then uses that to attempt to load
the correct publisher-specific code. This may fail; if the DOI is not
mapped to a code file, if the DOI is mapped but the code file could not
be located, or if the mapped code file is malformed then this method
will issue/log an informative error message and return None. This method
will not try to infer the publisher based on any metadata other than the
DOI of the article.
Returns
-------
publisher : Publisher instance or None
"""
#For a detailed explanation of the DOI system, visit:
#http://www.doi.org/hb.html
#The basic syntax of a DOI is this <prefix>/<suffix>
#The <prefix> specifies a unique DOI registrant, in our case, this
#should correspond to the publisher. We use this information to register
#the correct Publisher class with this article
doi_prefix = self.doi.split('/')[0]
#The import_by_doi method should raise ImportError if a problem occurred
try:
publisher_mod = openaccess_epub.publisher.import_by_doi(doi_prefix)
except ImportError as e:
log.exception(e)
return None
#Each publisher module should define an attribute "pub_class" pointing
#to the publisher-specific class extending
#openaccess_epub.publisher.Publisher
return publisher_mod.pub_class(self) | [
"def",
"get_publisher",
"(",
"self",
")",
":",
"#For a detailed explanation of the DOI system, visit:",
"#http://www.doi.org/hb.html",
"#The basic syntax of a DOI is this <prefix>/<suffix>",
"#The <prefix> specifies a unique DOI registrant, in our case, this",
"#should correspond to the publisher. We use this information to register",
"#the correct Publisher class with this article",
"doi_prefix",
"=",
"self",
".",
"doi",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"#The import_by_doi method should raise ImportError if a problem occurred",
"try",
":",
"publisher_mod",
"=",
"openaccess_epub",
".",
"publisher",
".",
"import_by_doi",
"(",
"doi_prefix",
")",
"except",
"ImportError",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"return",
"None",
"#Each publisher module should define an attribute \"pub_class\" pointing",
"#to the publisher-specific class extending",
"#openaccess_epub.publisher.Publisher",
"return",
"publisher_mod",
".",
"pub_class",
"(",
"self",
")"
] | This method defines how the Article tries to determine the publisher of
the article.
This method relies on the success of the get_DOI method to fetch the
appropriate full DOI for the article. It then takes the DOI prefix
which corresponds to the publisher and then uses that to attempt to load
the correct publisher-specific code. This may fail; if the DOI is not
mapped to a code file, if the DOI is mapped but the code file could not
be located, or if the mapped code file is malformed then this method
will issue/log an informative error message and return None. This method
will not try to infer the publisher based on any metadata other than the
DOI of the article.
Returns
-------
publisher : Publisher instance or None | [
"This",
"method",
"defines",
"how",
"the",
"Article",
"tries",
"to",
"determine",
"the",
"publisher",
"of",
"the",
"article",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/article/__init__.py#L135-L170 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/article/__init__.py | Article.get_DOI | def get_DOI(self):
"""
This method defines how the Article tries to detect the DOI.
It attempts to determine the article DOI string by DTD-appropriate
inspection of the article metadata. This method should be made as
flexible as necessary to properly collect the DOI for any XML
publishing specification.
Returns
-------
doi : str or None
The full (publisher/article) DOI string for the article, or None on
failure.
"""
if self.dtd_name == 'JPTS':
doi = self.root.xpath("./front/article-meta/article-id[@pub-id-type='doi']")
if doi:
return doi[0].text
log.warning('Unable to locate DOI string for this article')
return None
else:
log.warning('Unable to locate DOI string for this article')
return None | python | def get_DOI(self):
"""
This method defines how the Article tries to detect the DOI.
It attempts to determine the article DOI string by DTD-appropriate
inspection of the article metadata. This method should be made as
flexible as necessary to properly collect the DOI for any XML
publishing specification.
Returns
-------
doi : str or None
The full (publisher/article) DOI string for the article, or None on
failure.
"""
if self.dtd_name == 'JPTS':
doi = self.root.xpath("./front/article-meta/article-id[@pub-id-type='doi']")
if doi:
return doi[0].text
log.warning('Unable to locate DOI string for this article')
return None
else:
log.warning('Unable to locate DOI string for this article')
return None | [
"def",
"get_DOI",
"(",
"self",
")",
":",
"if",
"self",
".",
"dtd_name",
"==",
"'JPTS'",
":",
"doi",
"=",
"self",
".",
"root",
".",
"xpath",
"(",
"\"./front/article-meta/article-id[@pub-id-type='doi']\"",
")",
"if",
"doi",
":",
"return",
"doi",
"[",
"0",
"]",
".",
"text",
"log",
".",
"warning",
"(",
"'Unable to locate DOI string for this article'",
")",
"return",
"None",
"else",
":",
"log",
".",
"warning",
"(",
"'Unable to locate DOI string for this article'",
")",
"return",
"None"
] | This method defines how the Article tries to detect the DOI.
It attempts to determine the article DOI string by DTD-appropriate
inspection of the article metadata. This method should be made as
flexible as necessary to properly collect the DOI for any XML
publishing specification.
Returns
-------
doi : str or None
The full (publisher/article) DOI string for the article, or None on
failure. | [
"This",
"method",
"defines",
"how",
"the",
"Article",
"tries",
"to",
"detect",
"the",
"DOI",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/article/__init__.py#L172-L195 |
MSchnei/pyprf_feature | pyprf_feature/analysis/find_prf_utils_np.py | np_lst_sq | def np_lst_sq(vecMdl, aryFuncChnk):
"""Least squares fitting in numpy without cross-validation.
Notes
-----
This is just a wrapper function for np.linalg.lstsq to keep piping
consistent.
"""
aryTmpBts, vecTmpRes = np.linalg.lstsq(vecMdl,
aryFuncChnk,
rcond=-1)[:2]
return aryTmpBts, vecTmpRes | python | def np_lst_sq(vecMdl, aryFuncChnk):
"""Least squares fitting in numpy without cross-validation.
Notes
-----
This is just a wrapper function for np.linalg.lstsq to keep piping
consistent.
"""
aryTmpBts, vecTmpRes = np.linalg.lstsq(vecMdl,
aryFuncChnk,
rcond=-1)[:2]
return aryTmpBts, vecTmpRes | [
"def",
"np_lst_sq",
"(",
"vecMdl",
",",
"aryFuncChnk",
")",
":",
"aryTmpBts",
",",
"vecTmpRes",
"=",
"np",
".",
"linalg",
".",
"lstsq",
"(",
"vecMdl",
",",
"aryFuncChnk",
",",
"rcond",
"=",
"-",
"1",
")",
"[",
":",
"2",
"]",
"return",
"aryTmpBts",
",",
"vecTmpRes"
] | Least squares fitting in numpy without cross-validation.
Notes
-----
This is just a wrapper function for np.linalg.lstsq to keep piping
consistent. | [
"Least",
"squares",
"fitting",
"in",
"numpy",
"without",
"cross",
"-",
"validation",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/find_prf_utils_np.py#L8-L21 |
MSchnei/pyprf_feature | pyprf_feature/analysis/find_prf_utils_np.py | np_lst_sq_xval | def np_lst_sq_xval(vecMdl, aryFuncChnk, aryIdxTrn, aryIdxTst):
"""Least squares fitting in numpy with cross-validation.
"""
varNumXval = aryIdxTrn.shape[-1]
varNumVoxChnk = aryFuncChnk.shape[-1]
# pre-allocate ary to collect cross-validation
# error for every xval fold
aryResXval = np.empty((varNumVoxChnk,
varNumXval),
dtype=np.float32)
# loop over cross-validation folds
for idxXval in range(varNumXval):
# Get pRF time course models for trn and tst:
vecMdlTrn = vecMdl[aryIdxTrn[:, idxXval], :]
vecMdlTst = vecMdl[aryIdxTst[:, idxXval], :]
# Get functional data for trn and tst:
aryFuncChnkTrn = aryFuncChnk[
aryIdxTrn[:, idxXval], :]
aryFuncChnkTst = aryFuncChnk[
aryIdxTst[:, idxXval], :]
# Numpy linalg.lstsq is used to calculate the
# parameter estimates of the current model:
vecTmpPe = np.linalg.lstsq(vecMdlTrn,
aryFuncChnkTrn,
rcond=-1)[0]
# calculate model prediction time course
aryMdlPrdTc = np.dot(vecMdlTst, vecTmpPe)
# calculate residual sum of squares between
# test data and model prediction time course
aryResXval[:, idxXval] = np.sum(
(np.subtract(aryFuncChnkTst,
aryMdlPrdTc))**2, axis=0)
return aryResXval | python | def np_lst_sq_xval(vecMdl, aryFuncChnk, aryIdxTrn, aryIdxTst):
"""Least squares fitting in numpy with cross-validation.
"""
varNumXval = aryIdxTrn.shape[-1]
varNumVoxChnk = aryFuncChnk.shape[-1]
# pre-allocate ary to collect cross-validation
# error for every xval fold
aryResXval = np.empty((varNumVoxChnk,
varNumXval),
dtype=np.float32)
# loop over cross-validation folds
for idxXval in range(varNumXval):
# Get pRF time course models for trn and tst:
vecMdlTrn = vecMdl[aryIdxTrn[:, idxXval], :]
vecMdlTst = vecMdl[aryIdxTst[:, idxXval], :]
# Get functional data for trn and tst:
aryFuncChnkTrn = aryFuncChnk[
aryIdxTrn[:, idxXval], :]
aryFuncChnkTst = aryFuncChnk[
aryIdxTst[:, idxXval], :]
# Numpy linalg.lstsq is used to calculate the
# parameter estimates of the current model:
vecTmpPe = np.linalg.lstsq(vecMdlTrn,
aryFuncChnkTrn,
rcond=-1)[0]
# calculate model prediction time course
aryMdlPrdTc = np.dot(vecMdlTst, vecTmpPe)
# calculate residual sum of squares between
# test data and model prediction time course
aryResXval[:, idxXval] = np.sum(
(np.subtract(aryFuncChnkTst,
aryMdlPrdTc))**2, axis=0)
return aryResXval | [
"def",
"np_lst_sq_xval",
"(",
"vecMdl",
",",
"aryFuncChnk",
",",
"aryIdxTrn",
",",
"aryIdxTst",
")",
":",
"varNumXval",
"=",
"aryIdxTrn",
".",
"shape",
"[",
"-",
"1",
"]",
"varNumVoxChnk",
"=",
"aryFuncChnk",
".",
"shape",
"[",
"-",
"1",
"]",
"# pre-allocate ary to collect cross-validation",
"# error for every xval fold",
"aryResXval",
"=",
"np",
".",
"empty",
"(",
"(",
"varNumVoxChnk",
",",
"varNumXval",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"# loop over cross-validation folds",
"for",
"idxXval",
"in",
"range",
"(",
"varNumXval",
")",
":",
"# Get pRF time course models for trn and tst:",
"vecMdlTrn",
"=",
"vecMdl",
"[",
"aryIdxTrn",
"[",
":",
",",
"idxXval",
"]",
",",
":",
"]",
"vecMdlTst",
"=",
"vecMdl",
"[",
"aryIdxTst",
"[",
":",
",",
"idxXval",
"]",
",",
":",
"]",
"# Get functional data for trn and tst:",
"aryFuncChnkTrn",
"=",
"aryFuncChnk",
"[",
"aryIdxTrn",
"[",
":",
",",
"idxXval",
"]",
",",
":",
"]",
"aryFuncChnkTst",
"=",
"aryFuncChnk",
"[",
"aryIdxTst",
"[",
":",
",",
"idxXval",
"]",
",",
":",
"]",
"# Numpy linalg.lstsq is used to calculate the",
"# parameter estimates of the current model:",
"vecTmpPe",
"=",
"np",
".",
"linalg",
".",
"lstsq",
"(",
"vecMdlTrn",
",",
"aryFuncChnkTrn",
",",
"rcond",
"=",
"-",
"1",
")",
"[",
"0",
"]",
"# calculate model prediction time course",
"aryMdlPrdTc",
"=",
"np",
".",
"dot",
"(",
"vecMdlTst",
",",
"vecTmpPe",
")",
"# calculate residual sum of squares between",
"# test data and model prediction time course",
"aryResXval",
"[",
":",
",",
"idxXval",
"]",
"=",
"np",
".",
"sum",
"(",
"(",
"np",
".",
"subtract",
"(",
"aryFuncChnkTst",
",",
"aryMdlPrdTc",
")",
")",
"**",
"2",
",",
"axis",
"=",
"0",
")",
"return",
"aryResXval"
] | Least squares fitting in numpy with cross-validation. | [
"Least",
"squares",
"fitting",
"in",
"numpy",
"with",
"cross",
"-",
"validation",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/find_prf_utils_np.py#L24-L64 |
bachya/pyflunearyou | pyflunearyou/report.py | Report._raw_user_report_data | async def _raw_user_report_data(self) -> list:
"""Return user report data (if accompanied by latitude/longitude)."""
data = await self._request('get', 'map/markers')
return [
location for location in data
if location['latitude'] and location['longitude']
] | python | async def _raw_user_report_data(self) -> list:
"""Return user report data (if accompanied by latitude/longitude)."""
data = await self._request('get', 'map/markers')
return [
location for location in data
if location['latitude'] and location['longitude']
] | [
"async",
"def",
"_raw_user_report_data",
"(",
"self",
")",
"->",
"list",
":",
"data",
"=",
"await",
"self",
".",
"_request",
"(",
"'get'",
",",
"'map/markers'",
")",
"return",
"[",
"location",
"for",
"location",
"in",
"data",
"if",
"location",
"[",
"'latitude'",
"]",
"and",
"location",
"[",
"'longitude'",
"]",
"]"
] | Return user report data (if accompanied by latitude/longitude). | [
"Return",
"user",
"report",
"data",
"(",
"if",
"accompanied",
"by",
"latitude",
"/",
"longitude",
")",
"."
] | train | https://github.com/bachya/pyflunearyou/blob/16a2f839c8df851e925e010a6b5c5708386febac/pyflunearyou/report.py#L29-L35 |
bachya/pyflunearyou | pyflunearyou/report.py | Report._raw_state_data | async def _raw_state_data(self) -> list:
"""Return a list of states."""
data = await self._request('get', 'states')
return [
location for location in data
if location['name'] != 'United States'
] | python | async def _raw_state_data(self) -> list:
"""Return a list of states."""
data = await self._request('get', 'states')
return [
location for location in data
if location['name'] != 'United States'
] | [
"async",
"def",
"_raw_state_data",
"(",
"self",
")",
"->",
"list",
":",
"data",
"=",
"await",
"self",
".",
"_request",
"(",
"'get'",
",",
"'states'",
")",
"return",
"[",
"location",
"for",
"location",
"in",
"data",
"if",
"location",
"[",
"'name'",
"]",
"!=",
"'United States'",
"]"
] | Return a list of states. | [
"Return",
"a",
"list",
"of",
"states",
"."
] | train | https://github.com/bachya/pyflunearyou/blob/16a2f839c8df851e925e010a6b5c5708386febac/pyflunearyou/report.py#L37-L43 |
bachya/pyflunearyou | pyflunearyou/report.py | Report.nearest_by_coordinates | async def nearest_by_coordinates(
self, latitude: float, longitude: float) -> dict:
"""Get the nearest report (with local and state info) to a lat/lon."""
# Since user data is more granular than state or CDC data, find the
# user report whose coordinates are closest to the provided
# coordinates:
nearest_user_report = get_nearest_by_coordinates(
await self.user_reports(), 'latitude', 'longitude', latitude,
longitude)
try:
# If the user report corresponds to a known state in
# flunearyou.org's database, we can safely assume that's the
# correct state:
nearest_state = next((
state for state in await self.state_data()
if state['place_id'] == nearest_user_report['contained_by']))
except StopIteration:
# If a place ID doesn't exist (e.g., ZIP Code 98012 doesn't have a
# place ID), calculate the nearest state by measuring the distance
# from the provided latitude/longitude to flunearyou.org's
# latitude/longitude that defines each state:
nearest_state = get_nearest_by_coordinates(
await self.state_data(), 'lat', 'lon', latitude, longitude)
return {'local': nearest_user_report, 'state': nearest_state} | python | async def nearest_by_coordinates(
self, latitude: float, longitude: float) -> dict:
"""Get the nearest report (with local and state info) to a lat/lon."""
# Since user data is more granular than state or CDC data, find the
# user report whose coordinates are closest to the provided
# coordinates:
nearest_user_report = get_nearest_by_coordinates(
await self.user_reports(), 'latitude', 'longitude', latitude,
longitude)
try:
# If the user report corresponds to a known state in
# flunearyou.org's database, we can safely assume that's the
# correct state:
nearest_state = next((
state for state in await self.state_data()
if state['place_id'] == nearest_user_report['contained_by']))
except StopIteration:
# If a place ID doesn't exist (e.g., ZIP Code 98012 doesn't have a
# place ID), calculate the nearest state by measuring the distance
# from the provided latitude/longitude to flunearyou.org's
# latitude/longitude that defines each state:
nearest_state = get_nearest_by_coordinates(
await self.state_data(), 'lat', 'lon', latitude, longitude)
return {'local': nearest_user_report, 'state': nearest_state} | [
"async",
"def",
"nearest_by_coordinates",
"(",
"self",
",",
"latitude",
":",
"float",
",",
"longitude",
":",
"float",
")",
"->",
"dict",
":",
"# Since user data is more granular than state or CDC data, find the",
"# user report whose coordinates are closest to the provided",
"# coordinates:",
"nearest_user_report",
"=",
"get_nearest_by_coordinates",
"(",
"await",
"self",
".",
"user_reports",
"(",
")",
",",
"'latitude'",
",",
"'longitude'",
",",
"latitude",
",",
"longitude",
")",
"try",
":",
"# If the user report corresponds to a known state in",
"# flunearyou.org's database, we can safely assume that's the",
"# correct state:",
"nearest_state",
"=",
"next",
"(",
"(",
"state",
"for",
"state",
"in",
"await",
"self",
".",
"state_data",
"(",
")",
"if",
"state",
"[",
"'place_id'",
"]",
"==",
"nearest_user_report",
"[",
"'contained_by'",
"]",
")",
")",
"except",
"StopIteration",
":",
"# If a place ID doesn't exist (e.g., ZIP Code 98012 doesn't have a",
"# place ID), calculate the nearest state by measuring the distance",
"# from the provided latitude/longitude to flunearyou.org's",
"# latitude/longitude that defines each state:",
"nearest_state",
"=",
"get_nearest_by_coordinates",
"(",
"await",
"self",
".",
"state_data",
"(",
")",
",",
"'lat'",
",",
"'lon'",
",",
"latitude",
",",
"longitude",
")",
"return",
"{",
"'local'",
":",
"nearest_user_report",
",",
"'state'",
":",
"nearest_state",
"}"
] | Get the nearest report (with local and state info) to a lat/lon. | [
"Get",
"the",
"nearest",
"report",
"(",
"with",
"local",
"and",
"state",
"info",
")",
"to",
"a",
"lat",
"/",
"lon",
"."
] | train | https://github.com/bachya/pyflunearyou/blob/16a2f839c8df851e925e010a6b5c5708386febac/pyflunearyou/report.py#L45-L70 |
mediawiki-utilities/python-mwreverts | mwreverts/historical_dict.py | HistoricalDict.initialize | def initialize(self, maxsize, history=None):
'''size specifies the maximum amount of history to keep'''
super().__init__()
self.maxsize = int(maxsize)
self.history = deque(maxlen=self.maxsize) # Preserves order history
# If `items` are specified, then initialize with them
if history is not None:
for key, value in history:
self.insert(key, value) | python | def initialize(self, maxsize, history=None):
'''size specifies the maximum amount of history to keep'''
super().__init__()
self.maxsize = int(maxsize)
self.history = deque(maxlen=self.maxsize) # Preserves order history
# If `items` are specified, then initialize with them
if history is not None:
for key, value in history:
self.insert(key, value) | [
"def",
"initialize",
"(",
"self",
",",
"maxsize",
",",
"history",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"maxsize",
"=",
"int",
"(",
"maxsize",
")",
"self",
".",
"history",
"=",
"deque",
"(",
"maxlen",
"=",
"self",
".",
"maxsize",
")",
"# Preserves order history",
"# If `items` are specified, then initialize with them",
"if",
"history",
"is",
"not",
"None",
":",
"for",
"key",
",",
"value",
"in",
"history",
":",
"self",
".",
"insert",
"(",
"key",
",",
"value",
")"
] | size specifies the maximum amount of history to keep | [
"size",
"specifies",
"the",
"maximum",
"amount",
"of",
"history",
"to",
"keep"
] | train | https://github.com/mediawiki-utilities/python-mwreverts/blob/d379ac941e14e235ad82a48bd445a3dfa6cc022e/mwreverts/historical_dict.py#L13-L23 |
mediawiki-utilities/python-mwreverts | mwreverts/historical_dict.py | HistoricalDict.insert | def insert(self, key, value):
'''Adds a new key-value pair. Returns any discarded values.'''
# Add to history and catch expectorate
if len(self.history) == self.maxsize:
expectorate = self.history[0]
else:
expectorate = None
self.history.append((key, value))
# Add to the appropriate list of values
if key in self:
super().__getitem__(key).append(value)
else:
super().__setitem__(key, [value])
# Clean up old values
if expectorate is not None:
old_key, old_value = expectorate
super().__getitem__(old_key).pop(0)
if len(super().__getitem__(old_key)) == 0:
super().__delitem__(old_key)
return (old_key, old_value) | python | def insert(self, key, value):
'''Adds a new key-value pair. Returns any discarded values.'''
# Add to history and catch expectorate
if len(self.history) == self.maxsize:
expectorate = self.history[0]
else:
expectorate = None
self.history.append((key, value))
# Add to the appropriate list of values
if key in self:
super().__getitem__(key).append(value)
else:
super().__setitem__(key, [value])
# Clean up old values
if expectorate is not None:
old_key, old_value = expectorate
super().__getitem__(old_key).pop(0)
if len(super().__getitem__(old_key)) == 0:
super().__delitem__(old_key)
return (old_key, old_value) | [
"def",
"insert",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# Add to history and catch expectorate",
"if",
"len",
"(",
"self",
".",
"history",
")",
"==",
"self",
".",
"maxsize",
":",
"expectorate",
"=",
"self",
".",
"history",
"[",
"0",
"]",
"else",
":",
"expectorate",
"=",
"None",
"self",
".",
"history",
".",
"append",
"(",
"(",
"key",
",",
"value",
")",
")",
"# Add to the appropriate list of values",
"if",
"key",
"in",
"self",
":",
"super",
"(",
")",
".",
"__getitem__",
"(",
"key",
")",
".",
"append",
"(",
"value",
")",
"else",
":",
"super",
"(",
")",
".",
"__setitem__",
"(",
"key",
",",
"[",
"value",
"]",
")",
"# Clean up old values",
"if",
"expectorate",
"is",
"not",
"None",
":",
"old_key",
",",
"old_value",
"=",
"expectorate",
"super",
"(",
")",
".",
"__getitem__",
"(",
"old_key",
")",
".",
"pop",
"(",
"0",
")",
"if",
"len",
"(",
"super",
"(",
")",
".",
"__getitem__",
"(",
"old_key",
")",
")",
"==",
"0",
":",
"super",
"(",
")",
".",
"__delitem__",
"(",
"old_key",
")",
"return",
"(",
"old_key",
",",
"old_value",
")"
] | Adds a new key-value pair. Returns any discarded values. | [
"Adds",
"a",
"new",
"key",
"-",
"value",
"pair",
".",
"Returns",
"any",
"discarded",
"values",
"."
] | train | https://github.com/mediawiki-utilities/python-mwreverts/blob/d379ac941e14e235ad82a48bd445a3dfa6cc022e/mwreverts/historical_dict.py#L28-L52 |
mediawiki-utilities/python-mwreverts | mwreverts/historical_dict.py | HistoricalDict.up_to | def up_to(self, key):
'''Gets the recently inserted values up to a key'''
for okey, ovalue in reversed(self.history):
if okey == key:
break
else:
yield ovalue | python | def up_to(self, key):
'''Gets the recently inserted values up to a key'''
for okey, ovalue in reversed(self.history):
if okey == key:
break
else:
yield ovalue | [
"def",
"up_to",
"(",
"self",
",",
"key",
")",
":",
"for",
"okey",
",",
"ovalue",
"in",
"reversed",
"(",
"self",
".",
"history",
")",
":",
"if",
"okey",
"==",
"key",
":",
"break",
"else",
":",
"yield",
"ovalue"
] | Gets the recently inserted values up to a key | [
"Gets",
"the",
"recently",
"inserted",
"values",
"up",
"to",
"a",
"key"
] | train | https://github.com/mediawiki-utilities/python-mwreverts/blob/d379ac941e14e235ad82a48bd445a3dfa6cc022e/mwreverts/historical_dict.py#L60-L66 |
olivier-m/rafter | rafter/app.py | Rafter.resource | def resource(self, uri, methods=frozenset({'GET'}), **kwargs):
"""
Decorates a function to be registered as a resource route.
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:param host:
:param strict_slashes:
:param stream:
:param version:
:param name: user defined route name for url_for
:param filters: List of callable that will filter request and
response data
:param validators: List of callable added to the filter list.
:return: A decorated function
"""
def decorator(f):
if kwargs.get('stream'):
f.is_stream = kwargs['stream']
self.add_resource(f, uri=uri, methods=methods, **kwargs)
return decorator | python | def resource(self, uri, methods=frozenset({'GET'}), **kwargs):
"""
Decorates a function to be registered as a resource route.
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:param host:
:param strict_slashes:
:param stream:
:param version:
:param name: user defined route name for url_for
:param filters: List of callable that will filter request and
response data
:param validators: List of callable added to the filter list.
:return: A decorated function
"""
def decorator(f):
if kwargs.get('stream'):
f.is_stream = kwargs['stream']
self.add_resource(f, uri=uri, methods=methods, **kwargs)
return decorator | [
"def",
"resource",
"(",
"self",
",",
"uri",
",",
"methods",
"=",
"frozenset",
"(",
"{",
"'GET'",
"}",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'stream'",
")",
":",
"f",
".",
"is_stream",
"=",
"kwargs",
"[",
"'stream'",
"]",
"self",
".",
"add_resource",
"(",
"f",
",",
"uri",
"=",
"uri",
",",
"methods",
"=",
"methods",
",",
"*",
"*",
"kwargs",
")",
"return",
"decorator"
] | Decorates a function to be registered as a resource route.
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:param host:
:param strict_slashes:
:param stream:
:param version:
:param name: user defined route name for url_for
:param filters: List of callable that will filter request and
response data
:param validators: List of callable added to the filter list.
:return: A decorated function | [
"Decorates",
"a",
"function",
"to",
"be",
"registered",
"as",
"a",
"resource",
"route",
"."
] | train | https://github.com/olivier-m/rafter/blob/aafcf8fd019f24abcf519307c4484cc6b4697c04/rafter/app.py#L66-L88 |
olivier-m/rafter | rafter/app.py | Rafter.add_resource | def add_resource(self, handler, uri, methods=frozenset({'GET'}),
**kwargs):
"""
Register a resource route.
:param handler: function or class instance
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:param host:
:param strict_slashes:
:param version:
:param name: user defined route name for url_for
:param filters: List of callable that will filter request and
response data
:param validators: List of callable added to the filter list.
:return: function or class instance
"""
sanic_args = ('host', 'strict_slashes', 'version', 'name')
view_kwargs = dict((k, v) for k, v in kwargs.items()
if k in sanic_args)
filters = kwargs.get('filters', self.default_filters)
validators = kwargs.get('validators', [])
filter_list = list(filters) + list(validators)
filter_options = {
'filter_list': filter_list,
'handler': handler,
'uri': uri,
'methods': methods
}
filter_options.update(kwargs)
handler = self.init_filters(filter_list, filter_options)(handler)
return self.add_route(handler=handler, uri=uri, methods=methods,
**view_kwargs) | python | def add_resource(self, handler, uri, methods=frozenset({'GET'}),
**kwargs):
"""
Register a resource route.
:param handler: function or class instance
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:param host:
:param strict_slashes:
:param version:
:param name: user defined route name for url_for
:param filters: List of callable that will filter request and
response data
:param validators: List of callable added to the filter list.
:return: function or class instance
"""
sanic_args = ('host', 'strict_slashes', 'version', 'name')
view_kwargs = dict((k, v) for k, v in kwargs.items()
if k in sanic_args)
filters = kwargs.get('filters', self.default_filters)
validators = kwargs.get('validators', [])
filter_list = list(filters) + list(validators)
filter_options = {
'filter_list': filter_list,
'handler': handler,
'uri': uri,
'methods': methods
}
filter_options.update(kwargs)
handler = self.init_filters(filter_list, filter_options)(handler)
return self.add_route(handler=handler, uri=uri, methods=methods,
**view_kwargs) | [
"def",
"add_resource",
"(",
"self",
",",
"handler",
",",
"uri",
",",
"methods",
"=",
"frozenset",
"(",
"{",
"'GET'",
"}",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"sanic_args",
"=",
"(",
"'host'",
",",
"'strict_slashes'",
",",
"'version'",
",",
"'name'",
")",
"view_kwargs",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"k",
"in",
"sanic_args",
")",
"filters",
"=",
"kwargs",
".",
"get",
"(",
"'filters'",
",",
"self",
".",
"default_filters",
")",
"validators",
"=",
"kwargs",
".",
"get",
"(",
"'validators'",
",",
"[",
"]",
")",
"filter_list",
"=",
"list",
"(",
"filters",
")",
"+",
"list",
"(",
"validators",
")",
"filter_options",
"=",
"{",
"'filter_list'",
":",
"filter_list",
",",
"'handler'",
":",
"handler",
",",
"'uri'",
":",
"uri",
",",
"'methods'",
":",
"methods",
"}",
"filter_options",
".",
"update",
"(",
"kwargs",
")",
"handler",
"=",
"self",
".",
"init_filters",
"(",
"filter_list",
",",
"filter_options",
")",
"(",
"handler",
")",
"return",
"self",
".",
"add_route",
"(",
"handler",
"=",
"handler",
",",
"uri",
"=",
"uri",
",",
"methods",
"=",
"methods",
",",
"*",
"*",
"view_kwargs",
")"
] | Register a resource route.
:param handler: function or class instance
:param uri: path of the URL
:param methods: list or tuple of methods allowed
:param host:
:param strict_slashes:
:param version:
:param name: user defined route name for url_for
:param filters: List of callable that will filter request and
response data
:param validators: List of callable added to the filter list.
:return: function or class instance | [
"Register",
"a",
"resource",
"route",
"."
] | train | https://github.com/olivier-m/rafter/blob/aafcf8fd019f24abcf519307c4484cc6b4697c04/rafter/app.py#L90-L127 |
mediawiki-utilities/python-mwreverts | mwreverts/api.py | check | def check(session, rev_id, page_id=None, radius=defaults.RADIUS,
before=None, window=None, rvprop=None):
"""
Checks the revert status of a revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Parameters:
session : :class:`mwapi.Session`
An API session to make use of
rev_id : int
the ID of the revision to check
page_id : int
the ID of the page the revision occupies (slower if not provided)
radius : int
a positive integer indicating the maximum number of revisions
that can be reverted
before : :class:`mwtypes.Timestamp`
if set, limits the search for *reverting* revisions to those which
were saved before this timestamp
window : int
if set, limits the search for *reverting* revisions to those which
were saved within `window` seconds after the reverted edit
rvprop : set( str )
a set of properties to include in revisions
:Returns:
A triple :class:`mwreverts.Revert` | `None`
* reverting -- If this edit reverted other edit(s)
* reverted -- If this edit was reverted by another edit
* reverted_to -- If this edit was reverted to by another edit
:Example:
>>> import mwapi
>>> import mwreverts.api
>>>
>>> session = mwapi.Session("https://en.wikipedia.org")
>>>
>>> def print_revert(revert):
... if revert is None:
... print(None)
... else:
... print(revert.reverting['revid'],
... [r['revid'] for r in revert.reverteds],
... revert.reverted_to['revid'])
...
>>> reverting, reverted, reverted_to = \
... mwreverts.api.check(session, 679778587)
>>> print_revert(reverting)
None
>>> print_revert(reverted)
679778743 [679778587] 679742862
>>> print_revert(reverted_to)
None
"""
rev_id = int(rev_id)
radius = int(radius)
if radius < 1:
raise TypeError("invalid radius. Expected a positive integer.")
page_id = int(page_id) if page_id is not None else None
before = Timestamp(before) if before is not None else None
rvprop = set(rvprop) if rvprop is not None else set()
# If we don't have the page_id, we're going to need to look them up
if page_id is None:
page_id = get_page_id(session, rev_id)
# Load history and current rev
current_and_past_revs = list(n_edits_before(
session,
rev_id,
page_id,
n=radius + 1,
rvprop={'ids', 'timestamp', 'sha1'} | rvprop
))
if len(current_and_past_revs) < 1:
raise KeyError("Revision {0} not found in page {1}."
.format(rev_id, page_id))
current_rev, past_revs = (
current_and_past_revs[-1], # Current
current_and_past_revs[:-1] # Past revisions
)
if window is not None and before is None:
before = Timestamp(current_rev['timestamp']) + window
# Load future revisions
future_revs = list(n_edits_after(
session,
rev_id + 1,
page_id,
n=radius,
timestamp=before,
rvprop={'ids', 'timestamp', 'sha1'} | rvprop
))
return build_revert_tuple(
rev_id, past_revs, current_rev, future_revs, radius) | python | def check(session, rev_id, page_id=None, radius=defaults.RADIUS,
before=None, window=None, rvprop=None):
"""
Checks the revert status of a revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Parameters:
session : :class:`mwapi.Session`
An API session to make use of
rev_id : int
the ID of the revision to check
page_id : int
the ID of the page the revision occupies (slower if not provided)
radius : int
a positive integer indicating the maximum number of revisions
that can be reverted
before : :class:`mwtypes.Timestamp`
if set, limits the search for *reverting* revisions to those which
were saved before this timestamp
window : int
if set, limits the search for *reverting* revisions to those which
were saved within `window` seconds after the reverted edit
rvprop : set( str )
a set of properties to include in revisions
:Returns:
A triple :class:`mwreverts.Revert` | `None`
* reverting -- If this edit reverted other edit(s)
* reverted -- If this edit was reverted by another edit
* reverted_to -- If this edit was reverted to by another edit
:Example:
>>> import mwapi
>>> import mwreverts.api
>>>
>>> session = mwapi.Session("https://en.wikipedia.org")
>>>
>>> def print_revert(revert):
... if revert is None:
... print(None)
... else:
... print(revert.reverting['revid'],
... [r['revid'] for r in revert.reverteds],
... revert.reverted_to['revid'])
...
>>> reverting, reverted, reverted_to = \
... mwreverts.api.check(session, 679778587)
>>> print_revert(reverting)
None
>>> print_revert(reverted)
679778743 [679778587] 679742862
>>> print_revert(reverted_to)
None
"""
rev_id = int(rev_id)
radius = int(radius)
if radius < 1:
raise TypeError("invalid radius. Expected a positive integer.")
page_id = int(page_id) if page_id is not None else None
before = Timestamp(before) if before is not None else None
rvprop = set(rvprop) if rvprop is not None else set()
# If we don't have the page_id, we're going to need to look them up
if page_id is None:
page_id = get_page_id(session, rev_id)
# Load history and current rev
current_and_past_revs = list(n_edits_before(
session,
rev_id,
page_id,
n=radius + 1,
rvprop={'ids', 'timestamp', 'sha1'} | rvprop
))
if len(current_and_past_revs) < 1:
raise KeyError("Revision {0} not found in page {1}."
.format(rev_id, page_id))
current_rev, past_revs = (
current_and_past_revs[-1], # Current
current_and_past_revs[:-1] # Past revisions
)
if window is not None and before is None:
before = Timestamp(current_rev['timestamp']) + window
# Load future revisions
future_revs = list(n_edits_after(
session,
rev_id + 1,
page_id,
n=radius,
timestamp=before,
rvprop={'ids', 'timestamp', 'sha1'} | rvprop
))
return build_revert_tuple(
rev_id, past_revs, current_rev, future_revs, radius) | [
"def",
"check",
"(",
"session",
",",
"rev_id",
",",
"page_id",
"=",
"None",
",",
"radius",
"=",
"defaults",
".",
"RADIUS",
",",
"before",
"=",
"None",
",",
"window",
"=",
"None",
",",
"rvprop",
"=",
"None",
")",
":",
"rev_id",
"=",
"int",
"(",
"rev_id",
")",
"radius",
"=",
"int",
"(",
"radius",
")",
"if",
"radius",
"<",
"1",
":",
"raise",
"TypeError",
"(",
"\"invalid radius. Expected a positive integer.\"",
")",
"page_id",
"=",
"int",
"(",
"page_id",
")",
"if",
"page_id",
"is",
"not",
"None",
"else",
"None",
"before",
"=",
"Timestamp",
"(",
"before",
")",
"if",
"before",
"is",
"not",
"None",
"else",
"None",
"rvprop",
"=",
"set",
"(",
"rvprop",
")",
"if",
"rvprop",
"is",
"not",
"None",
"else",
"set",
"(",
")",
"# If we don't have the page_id, we're going to need to look them up",
"if",
"page_id",
"is",
"None",
":",
"page_id",
"=",
"get_page_id",
"(",
"session",
",",
"rev_id",
")",
"# Load history and current rev",
"current_and_past_revs",
"=",
"list",
"(",
"n_edits_before",
"(",
"session",
",",
"rev_id",
",",
"page_id",
",",
"n",
"=",
"radius",
"+",
"1",
",",
"rvprop",
"=",
"{",
"'ids'",
",",
"'timestamp'",
",",
"'sha1'",
"}",
"|",
"rvprop",
")",
")",
"if",
"len",
"(",
"current_and_past_revs",
")",
"<",
"1",
":",
"raise",
"KeyError",
"(",
"\"Revision {0} not found in page {1}.\"",
".",
"format",
"(",
"rev_id",
",",
"page_id",
")",
")",
"current_rev",
",",
"past_revs",
"=",
"(",
"current_and_past_revs",
"[",
"-",
"1",
"]",
",",
"# Current",
"current_and_past_revs",
"[",
":",
"-",
"1",
"]",
"# Past revisions",
")",
"if",
"window",
"is",
"not",
"None",
"and",
"before",
"is",
"None",
":",
"before",
"=",
"Timestamp",
"(",
"current_rev",
"[",
"'timestamp'",
"]",
")",
"+",
"window",
"# Load future revisions",
"future_revs",
"=",
"list",
"(",
"n_edits_after",
"(",
"session",
",",
"rev_id",
"+",
"1",
",",
"page_id",
",",
"n",
"=",
"radius",
",",
"timestamp",
"=",
"before",
",",
"rvprop",
"=",
"{",
"'ids'",
",",
"'timestamp'",
",",
"'sha1'",
"}",
"|",
"rvprop",
")",
")",
"return",
"build_revert_tuple",
"(",
"rev_id",
",",
"past_revs",
",",
"current_rev",
",",
"future_revs",
",",
"radius",
")"
] | Checks the revert status of a revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Parameters:
session : :class:`mwapi.Session`
An API session to make use of
rev_id : int
the ID of the revision to check
page_id : int
the ID of the page the revision occupies (slower if not provided)
radius : int
a positive integer indicating the maximum number of revisions
that can be reverted
before : :class:`mwtypes.Timestamp`
if set, limits the search for *reverting* revisions to those which
were saved before this timestamp
window : int
if set, limits the search for *reverting* revisions to those which
were saved within `window` seconds after the reverted edit
rvprop : set( str )
a set of properties to include in revisions
:Returns:
A triple :class:`mwreverts.Revert` | `None`
* reverting -- If this edit reverted other edit(s)
* reverted -- If this edit was reverted by another edit
* reverted_to -- If this edit was reverted to by another edit
:Example:
>>> import mwapi
>>> import mwreverts.api
>>>
>>> session = mwapi.Session("https://en.wikipedia.org")
>>>
>>> def print_revert(revert):
... if revert is None:
... print(None)
... else:
... print(revert.reverting['revid'],
... [r['revid'] for r in revert.reverteds],
... revert.reverted_to['revid'])
...
>>> reverting, reverted, reverted_to = \
... mwreverts.api.check(session, 679778587)
>>> print_revert(reverting)
None
>>> print_revert(reverted)
679778743 [679778587] 679742862
>>> print_revert(reverted_to)
None | [
"Checks",
"the",
"revert",
"status",
"of",
"a",
"revision",
".",
"With",
"this",
"method",
"you",
"can",
"determine",
"whether",
"an",
"edit",
"is",
"a",
"reverting",
"edit",
"was",
"reverted",
"by",
"another",
"edit",
"and",
"/",
"or",
"was",
"reverted_to",
"by",
"another",
"edit",
"."
] | train | https://github.com/mediawiki-utilities/python-mwreverts/blob/d379ac941e14e235ad82a48bd445a3dfa6cc022e/mwreverts/api.py#L58-L163 |
mediawiki-utilities/python-mwreverts | mwreverts/api.py | check_deleted | def check_deleted(session, rev_id, title=None, timestamp=None,
radius=defaults.RADIUS, before=None, window=None,
rvprop=None):
"""
Checks the revert status of a deleted revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Parameters:
session : :class:`mwapi.Session`
An API session to make use of
rev_id : int
the ID of the revision to check
title : str
the title of the page the revision occupies (slower if not
provided) Note that the MediaWiki API expects the title to
include the namespace prefix (e.g. "User_talk:EpochFail")
radius : int
a positive integer indicating the maximum number of revisions
that can be reverted
before : :class:`mwtypes.Timestamp`
if set, limits the search for *reverting* revisions to those which
were saved before this timestamp
window : int
if set, limits the search for *reverting* revisions to those which
were saved within `window` seconds after the reverted edit
rvprop : set( str )
a set of properties to include in revisions
:Returns:
A triple :class:`mwreverts.Revert` | `None`
* reverting -- If this edit reverted other edit(s)
* reverted -- If this edit was reverted by another edit
* reverted_to -- If this edit was reverted to by another edit
"""
rev_id = int(rev_id)
radius = int(radius)
if radius < 1:
raise TypeError("invalid radius. Expected a positive integer.")
title = str(title) if title is not None else None
before = Timestamp(before) if before is not None else None
rvprop = set(rvprop) if rvprop is not None else set()
# If we don't have the title, we're going to need to look it up
if title is None or timestamp is None:
title, timestamp = get_deleted_title_and_timestamp(session, rev_id)
# Load history and current rev
current_and_past_revs = list(n_deleted_edits_before(
session, rev_id, title, timestamp, n=radius + 1,
rvprop={'ids', 'timestamp', 'sha1'} | rvprop
))
if len(current_and_past_revs) < 1:
raise KeyError("Revision {0} not found in page {1}."
.format(rev_id, title))
current_rev, past_revs = (
current_and_past_revs[-1], # Current
current_and_past_revs[:-1] # Past revisions
)
if window is not None and before is None:
before = Timestamp(current_rev['timestamp']) + window
# Load future revisions
future_revs = list(n_deleted_edits_after(
session, rev_id + 1, title, timestamp, n=radius, before=before,
rvprop={'ids', 'timestamp', 'sha1'} | rvprop
))
return build_revert_tuple(
rev_id, past_revs, current_rev, future_revs, radius) | python | def check_deleted(session, rev_id, title=None, timestamp=None,
radius=defaults.RADIUS, before=None, window=None,
rvprop=None):
"""
Checks the revert status of a deleted revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Parameters:
session : :class:`mwapi.Session`
An API session to make use of
rev_id : int
the ID of the revision to check
title : str
the title of the page the revision occupies (slower if not
provided) Note that the MediaWiki API expects the title to
include the namespace prefix (e.g. "User_talk:EpochFail")
radius : int
a positive integer indicating the maximum number of revisions
that can be reverted
before : :class:`mwtypes.Timestamp`
if set, limits the search for *reverting* revisions to those which
were saved before this timestamp
window : int
if set, limits the search for *reverting* revisions to those which
were saved within `window` seconds after the reverted edit
rvprop : set( str )
a set of properties to include in revisions
:Returns:
A triple :class:`mwreverts.Revert` | `None`
* reverting -- If this edit reverted other edit(s)
* reverted -- If this edit was reverted by another edit
* reverted_to -- If this edit was reverted to by another edit
"""
rev_id = int(rev_id)
radius = int(radius)
if radius < 1:
raise TypeError("invalid radius. Expected a positive integer.")
title = str(title) if title is not None else None
before = Timestamp(before) if before is not None else None
rvprop = set(rvprop) if rvprop is not None else set()
# If we don't have the title, we're going to need to look it up
if title is None or timestamp is None:
title, timestamp = get_deleted_title_and_timestamp(session, rev_id)
# Load history and current rev
current_and_past_revs = list(n_deleted_edits_before(
session, rev_id, title, timestamp, n=radius + 1,
rvprop={'ids', 'timestamp', 'sha1'} | rvprop
))
if len(current_and_past_revs) < 1:
raise KeyError("Revision {0} not found in page {1}."
.format(rev_id, title))
current_rev, past_revs = (
current_and_past_revs[-1], # Current
current_and_past_revs[:-1] # Past revisions
)
if window is not None and before is None:
before = Timestamp(current_rev['timestamp']) + window
# Load future revisions
future_revs = list(n_deleted_edits_after(
session, rev_id + 1, title, timestamp, n=radius, before=before,
rvprop={'ids', 'timestamp', 'sha1'} | rvprop
))
return build_revert_tuple(
rev_id, past_revs, current_rev, future_revs, radius) | [
"def",
"check_deleted",
"(",
"session",
",",
"rev_id",
",",
"title",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"radius",
"=",
"defaults",
".",
"RADIUS",
",",
"before",
"=",
"None",
",",
"window",
"=",
"None",
",",
"rvprop",
"=",
"None",
")",
":",
"rev_id",
"=",
"int",
"(",
"rev_id",
")",
"radius",
"=",
"int",
"(",
"radius",
")",
"if",
"radius",
"<",
"1",
":",
"raise",
"TypeError",
"(",
"\"invalid radius. Expected a positive integer.\"",
")",
"title",
"=",
"str",
"(",
"title",
")",
"if",
"title",
"is",
"not",
"None",
"else",
"None",
"before",
"=",
"Timestamp",
"(",
"before",
")",
"if",
"before",
"is",
"not",
"None",
"else",
"None",
"rvprop",
"=",
"set",
"(",
"rvprop",
")",
"if",
"rvprop",
"is",
"not",
"None",
"else",
"set",
"(",
")",
"# If we don't have the title, we're going to need to look it up",
"if",
"title",
"is",
"None",
"or",
"timestamp",
"is",
"None",
":",
"title",
",",
"timestamp",
"=",
"get_deleted_title_and_timestamp",
"(",
"session",
",",
"rev_id",
")",
"# Load history and current rev",
"current_and_past_revs",
"=",
"list",
"(",
"n_deleted_edits_before",
"(",
"session",
",",
"rev_id",
",",
"title",
",",
"timestamp",
",",
"n",
"=",
"radius",
"+",
"1",
",",
"rvprop",
"=",
"{",
"'ids'",
",",
"'timestamp'",
",",
"'sha1'",
"}",
"|",
"rvprop",
")",
")",
"if",
"len",
"(",
"current_and_past_revs",
")",
"<",
"1",
":",
"raise",
"KeyError",
"(",
"\"Revision {0} not found in page {1}.\"",
".",
"format",
"(",
"rev_id",
",",
"title",
")",
")",
"current_rev",
",",
"past_revs",
"=",
"(",
"current_and_past_revs",
"[",
"-",
"1",
"]",
",",
"# Current",
"current_and_past_revs",
"[",
":",
"-",
"1",
"]",
"# Past revisions",
")",
"if",
"window",
"is",
"not",
"None",
"and",
"before",
"is",
"None",
":",
"before",
"=",
"Timestamp",
"(",
"current_rev",
"[",
"'timestamp'",
"]",
")",
"+",
"window",
"# Load future revisions",
"future_revs",
"=",
"list",
"(",
"n_deleted_edits_after",
"(",
"session",
",",
"rev_id",
"+",
"1",
",",
"title",
",",
"timestamp",
",",
"n",
"=",
"radius",
",",
"before",
"=",
"before",
",",
"rvprop",
"=",
"{",
"'ids'",
",",
"'timestamp'",
",",
"'sha1'",
"}",
"|",
"rvprop",
")",
")",
"return",
"build_revert_tuple",
"(",
"rev_id",
",",
"past_revs",
",",
"current_rev",
",",
"future_revs",
",",
"radius",
")"
] | Checks the revert status of a deleted revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Parameters:
session : :class:`mwapi.Session`
An API session to make use of
rev_id : int
the ID of the revision to check
title : str
the title of the page the revision occupies (slower if not
provided) Note that the MediaWiki API expects the title to
include the namespace prefix (e.g. "User_talk:EpochFail")
radius : int
a positive integer indicating the maximum number of revisions
that can be reverted
before : :class:`mwtypes.Timestamp`
if set, limits the search for *reverting* revisions to those which
were saved before this timestamp
window : int
if set, limits the search for *reverting* revisions to those which
were saved within `window` seconds after the reverted edit
rvprop : set( str )
a set of properties to include in revisions
:Returns:
A triple :class:`mwreverts.Revert` | `None`
* reverting -- If this edit reverted other edit(s)
* reverted -- If this edit was reverted by another edit
* reverted_to -- If this edit was reverted to by another edit | [
"Checks",
"the",
"revert",
"status",
"of",
"a",
"deleted",
"revision",
".",
"With",
"this",
"method",
"you",
"can",
"determine",
"whether",
"an",
"edit",
"is",
"a",
"reverting",
"edit",
"was",
"reverted",
"by",
"another",
"edit",
"and",
"/",
"or",
"was",
"reverted_to",
"by",
"another",
"edit",
"."
] | train | https://github.com/mediawiki-utilities/python-mwreverts/blob/d379ac941e14e235ad82a48bd445a3dfa6cc022e/mwreverts/api.py#L210-L286 |
rcbops/osa_differ | osa_differ/osa_differ.py | get_commits | def get_commits(repo_dir, old_commit, new_commit, hide_merges=True):
"""Find all commits between two commit SHAs."""
repo = Repo(repo_dir)
commits = repo.iter_commits(rev="{0}..{1}".format(old_commit, new_commit))
if hide_merges:
return [x for x in commits if not x.summary.startswith("Merge ")]
else:
return list(commits) | python | def get_commits(repo_dir, old_commit, new_commit, hide_merges=True):
"""Find all commits between two commit SHAs."""
repo = Repo(repo_dir)
commits = repo.iter_commits(rev="{0}..{1}".format(old_commit, new_commit))
if hide_merges:
return [x for x in commits if not x.summary.startswith("Merge ")]
else:
return list(commits) | [
"def",
"get_commits",
"(",
"repo_dir",
",",
"old_commit",
",",
"new_commit",
",",
"hide_merges",
"=",
"True",
")",
":",
"repo",
"=",
"Repo",
"(",
"repo_dir",
")",
"commits",
"=",
"repo",
".",
"iter_commits",
"(",
"rev",
"=",
"\"{0}..{1}\"",
".",
"format",
"(",
"old_commit",
",",
"new_commit",
")",
")",
"if",
"hide_merges",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"commits",
"if",
"not",
"x",
".",
"summary",
".",
"startswith",
"(",
"\"Merge \"",
")",
"]",
"else",
":",
"return",
"list",
"(",
"commits",
")"
] | Find all commits between two commit SHAs. | [
"Find",
"all",
"commits",
"between",
"two",
"commit",
"SHAs",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L181-L188 |
rcbops/osa_differ | osa_differ/osa_differ.py | get_commit_url | def get_commit_url(repo_url):
"""Determine URL to view commits for repo."""
if "github.com" in repo_url:
return repo_url[:-4] if repo_url.endswith(".git") else repo_url
if "git.openstack.org" in repo_url:
uri = '/'.join(repo_url.split('/')[-2:])
return "https://github.com/{0}".format(uri)
# If it didn't match these conditions, just return it.
return repo_url | python | def get_commit_url(repo_url):
"""Determine URL to view commits for repo."""
if "github.com" in repo_url:
return repo_url[:-4] if repo_url.endswith(".git") else repo_url
if "git.openstack.org" in repo_url:
uri = '/'.join(repo_url.split('/')[-2:])
return "https://github.com/{0}".format(uri)
# If it didn't match these conditions, just return it.
return repo_url | [
"def",
"get_commit_url",
"(",
"repo_url",
")",
":",
"if",
"\"github.com\"",
"in",
"repo_url",
":",
"return",
"repo_url",
"[",
":",
"-",
"4",
"]",
"if",
"repo_url",
".",
"endswith",
"(",
"\".git\"",
")",
"else",
"repo_url",
"if",
"\"git.openstack.org\"",
"in",
"repo_url",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"repo_url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"2",
":",
"]",
")",
"return",
"\"https://github.com/{0}\"",
".",
"format",
"(",
"uri",
")",
"# If it didn't match these conditions, just return it.",
"return",
"repo_url"
] | Determine URL to view commits for repo. | [
"Determine",
"URL",
"to",
"view",
"commits",
"for",
"repo",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L191-L200 |
rcbops/osa_differ | osa_differ/osa_differ.py | get_projects | def get_projects(osa_repo_dir, commit):
"""Get all projects from multiple YAML files."""
# Check out the correct commit SHA from the repository
repo = Repo(osa_repo_dir)
checkout(repo, commit)
yaml_files = glob.glob(
'{0}/playbooks/defaults/repo_packages/*.yml'.format(osa_repo_dir)
)
yaml_parsed = []
for yaml_file in yaml_files:
with open(yaml_file, 'r') as f:
yaml_parsed.append(yaml.load(f))
merged_dicts = {k: v for d in yaml_parsed for k, v in d.items()}
return normalize_yaml(merged_dicts) | python | def get_projects(osa_repo_dir, commit):
"""Get all projects from multiple YAML files."""
# Check out the correct commit SHA from the repository
repo = Repo(osa_repo_dir)
checkout(repo, commit)
yaml_files = glob.glob(
'{0}/playbooks/defaults/repo_packages/*.yml'.format(osa_repo_dir)
)
yaml_parsed = []
for yaml_file in yaml_files:
with open(yaml_file, 'r') as f:
yaml_parsed.append(yaml.load(f))
merged_dicts = {k: v for d in yaml_parsed for k, v in d.items()}
return normalize_yaml(merged_dicts) | [
"def",
"get_projects",
"(",
"osa_repo_dir",
",",
"commit",
")",
":",
"# Check out the correct commit SHA from the repository",
"repo",
"=",
"Repo",
"(",
"osa_repo_dir",
")",
"checkout",
"(",
"repo",
",",
"commit",
")",
"yaml_files",
"=",
"glob",
".",
"glob",
"(",
"'{0}/playbooks/defaults/repo_packages/*.yml'",
".",
"format",
"(",
"osa_repo_dir",
")",
")",
"yaml_parsed",
"=",
"[",
"]",
"for",
"yaml_file",
"in",
"yaml_files",
":",
"with",
"open",
"(",
"yaml_file",
",",
"'r'",
")",
"as",
"f",
":",
"yaml_parsed",
".",
"append",
"(",
"yaml",
".",
"load",
"(",
"f",
")",
")",
"merged_dicts",
"=",
"{",
"k",
":",
"v",
"for",
"d",
"in",
"yaml_parsed",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
"}",
"return",
"normalize_yaml",
"(",
"merged_dicts",
")"
] | Get all projects from multiple YAML files. | [
"Get",
"all",
"projects",
"from",
"multiple",
"YAML",
"files",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L203-L219 |
rcbops/osa_differ | osa_differ/osa_differ.py | checkout | def checkout(repo, ref):
"""Checkout a repoself."""
# Delete local branch if it exists, remote branch will be tracked
# automatically. This prevents stale local branches from causing problems.
# It also avoids problems with appending origin/ to refs as that doesn't
# work with tags, SHAs, and upstreams not called origin.
if ref in repo.branches:
# eg delete master but leave origin/master
log.warn("Removing local branch {b} for repo {r}".format(b=ref,
r=repo))
# Can't delete currently checked out branch, so make sure head is
# detached before deleting.
repo.head.reset(index=True, working_tree=True)
repo.git.checkout(repo.head.commit.hexsha)
repo.delete_head(ref, '--force')
log.info("Checkout out repo {repo} to ref {ref}".format(repo=repo,
ref=ref))
repo.head.reset(index=True, working_tree=True)
repo.git.checkout(ref)
repo.head.reset(index=True, working_tree=True)
sha = repo.head.commit.hexsha
log.info("Current SHA for repo {repo} is {sha}".format(repo=repo, sha=sha)) | python | def checkout(repo, ref):
"""Checkout a repoself."""
# Delete local branch if it exists, remote branch will be tracked
# automatically. This prevents stale local branches from causing problems.
# It also avoids problems with appending origin/ to refs as that doesn't
# work with tags, SHAs, and upstreams not called origin.
if ref in repo.branches:
# eg delete master but leave origin/master
log.warn("Removing local branch {b} for repo {r}".format(b=ref,
r=repo))
# Can't delete currently checked out branch, so make sure head is
# detached before deleting.
repo.head.reset(index=True, working_tree=True)
repo.git.checkout(repo.head.commit.hexsha)
repo.delete_head(ref, '--force')
log.info("Checkout out repo {repo} to ref {ref}".format(repo=repo,
ref=ref))
repo.head.reset(index=True, working_tree=True)
repo.git.checkout(ref)
repo.head.reset(index=True, working_tree=True)
sha = repo.head.commit.hexsha
log.info("Current SHA for repo {repo} is {sha}".format(repo=repo, sha=sha)) | [
"def",
"checkout",
"(",
"repo",
",",
"ref",
")",
":",
"# Delete local branch if it exists, remote branch will be tracked",
"# automatically. This prevents stale local branches from causing problems.",
"# It also avoids problems with appending origin/ to refs as that doesn't",
"# work with tags, SHAs, and upstreams not called origin.",
"if",
"ref",
"in",
"repo",
".",
"branches",
":",
"# eg delete master but leave origin/master",
"log",
".",
"warn",
"(",
"\"Removing local branch {b} for repo {r}\"",
".",
"format",
"(",
"b",
"=",
"ref",
",",
"r",
"=",
"repo",
")",
")",
"# Can't delete currently checked out branch, so make sure head is",
"# detached before deleting.",
"repo",
".",
"head",
".",
"reset",
"(",
"index",
"=",
"True",
",",
"working_tree",
"=",
"True",
")",
"repo",
".",
"git",
".",
"checkout",
"(",
"repo",
".",
"head",
".",
"commit",
".",
"hexsha",
")",
"repo",
".",
"delete_head",
"(",
"ref",
",",
"'--force'",
")",
"log",
".",
"info",
"(",
"\"Checkout out repo {repo} to ref {ref}\"",
".",
"format",
"(",
"repo",
"=",
"repo",
",",
"ref",
"=",
"ref",
")",
")",
"repo",
".",
"head",
".",
"reset",
"(",
"index",
"=",
"True",
",",
"working_tree",
"=",
"True",
")",
"repo",
".",
"git",
".",
"checkout",
"(",
"ref",
")",
"repo",
".",
"head",
".",
"reset",
"(",
"index",
"=",
"True",
",",
"working_tree",
"=",
"True",
")",
"sha",
"=",
"repo",
".",
"head",
".",
"commit",
".",
"hexsha",
"log",
".",
"info",
"(",
"\"Current SHA for repo {repo} is {sha}\"",
".",
"format",
"(",
"repo",
"=",
"repo",
",",
"sha",
"=",
"sha",
")",
")"
] | Checkout a repoself. | [
"Checkout",
"a",
"repoself",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L222-L245 |
rcbops/osa_differ | osa_differ/osa_differ.py | get_roles | def get_roles(osa_repo_dir, commit, role_requirements):
"""Read OSA role information at a particular commit."""
repo = Repo(osa_repo_dir)
checkout(repo, commit)
log.info("Looking for file {f} in repo {r}".format(r=osa_repo_dir,
f=role_requirements))
filename = "{0}/{1}".format(osa_repo_dir, role_requirements)
with open(filename, 'r') as f:
roles_yaml = yaml.load(f)
return normalize_yaml(roles_yaml) | python | def get_roles(osa_repo_dir, commit, role_requirements):
"""Read OSA role information at a particular commit."""
repo = Repo(osa_repo_dir)
checkout(repo, commit)
log.info("Looking for file {f} in repo {r}".format(r=osa_repo_dir,
f=role_requirements))
filename = "{0}/{1}".format(osa_repo_dir, role_requirements)
with open(filename, 'r') as f:
roles_yaml = yaml.load(f)
return normalize_yaml(roles_yaml) | [
"def",
"get_roles",
"(",
"osa_repo_dir",
",",
"commit",
",",
"role_requirements",
")",
":",
"repo",
"=",
"Repo",
"(",
"osa_repo_dir",
")",
"checkout",
"(",
"repo",
",",
"commit",
")",
"log",
".",
"info",
"(",
"\"Looking for file {f} in repo {r}\"",
".",
"format",
"(",
"r",
"=",
"osa_repo_dir",
",",
"f",
"=",
"role_requirements",
")",
")",
"filename",
"=",
"\"{0}/{1}\"",
".",
"format",
"(",
"osa_repo_dir",
",",
"role_requirements",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"roles_yaml",
"=",
"yaml",
".",
"load",
"(",
"f",
")",
"return",
"normalize_yaml",
"(",
"roles_yaml",
")"
] | Read OSA role information at a particular commit. | [
"Read",
"OSA",
"role",
"information",
"at",
"a",
"particular",
"commit",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L248-L260 |
rcbops/osa_differ | osa_differ/osa_differ.py | make_osa_report | def make_osa_report(repo_dir, old_commit, new_commit,
args):
"""Create initial RST report header for OpenStack-Ansible."""
update_repo(repo_dir, args.osa_repo_url, args.update)
# Are these commits valid?
validate_commits(repo_dir, [old_commit, new_commit])
# Do we have a valid commit range?
validate_commit_range(repo_dir, old_commit, new_commit)
# Get the commits in the range
commits = get_commits(repo_dir, old_commit, new_commit)
# Start off our report with a header and our OpenStack-Ansible commits.
template_vars = {
'args': args,
'repo': 'openstack-ansible',
'commits': commits,
'commit_base_url': get_commit_url(args.osa_repo_url),
'old_sha': old_commit,
'new_sha': new_commit
}
return render_template('offline-header.j2', template_vars) | python | def make_osa_report(repo_dir, old_commit, new_commit,
args):
"""Create initial RST report header for OpenStack-Ansible."""
update_repo(repo_dir, args.osa_repo_url, args.update)
# Are these commits valid?
validate_commits(repo_dir, [old_commit, new_commit])
# Do we have a valid commit range?
validate_commit_range(repo_dir, old_commit, new_commit)
# Get the commits in the range
commits = get_commits(repo_dir, old_commit, new_commit)
# Start off our report with a header and our OpenStack-Ansible commits.
template_vars = {
'args': args,
'repo': 'openstack-ansible',
'commits': commits,
'commit_base_url': get_commit_url(args.osa_repo_url),
'old_sha': old_commit,
'new_sha': new_commit
}
return render_template('offline-header.j2', template_vars) | [
"def",
"make_osa_report",
"(",
"repo_dir",
",",
"old_commit",
",",
"new_commit",
",",
"args",
")",
":",
"update_repo",
"(",
"repo_dir",
",",
"args",
".",
"osa_repo_url",
",",
"args",
".",
"update",
")",
"# Are these commits valid?",
"validate_commits",
"(",
"repo_dir",
",",
"[",
"old_commit",
",",
"new_commit",
"]",
")",
"# Do we have a valid commit range?",
"validate_commit_range",
"(",
"repo_dir",
",",
"old_commit",
",",
"new_commit",
")",
"# Get the commits in the range",
"commits",
"=",
"get_commits",
"(",
"repo_dir",
",",
"old_commit",
",",
"new_commit",
")",
"# Start off our report with a header and our OpenStack-Ansible commits.",
"template_vars",
"=",
"{",
"'args'",
":",
"args",
",",
"'repo'",
":",
"'openstack-ansible'",
",",
"'commits'",
":",
"commits",
",",
"'commit_base_url'",
":",
"get_commit_url",
"(",
"args",
".",
"osa_repo_url",
")",
",",
"'old_sha'",
":",
"old_commit",
",",
"'new_sha'",
":",
"new_commit",
"}",
"return",
"render_template",
"(",
"'offline-header.j2'",
",",
"template_vars",
")"
] | Create initial RST report header for OpenStack-Ansible. | [
"Create",
"initial",
"RST",
"report",
"header",
"for",
"OpenStack",
"-",
"Ansible",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L263-L286 |
rcbops/osa_differ | osa_differ/osa_differ.py | make_report | def make_report(storage_directory, old_pins, new_pins, do_update=False,
version_mappings=None):
"""Create RST report from a list of projects/roles."""
report = ""
version_mappings = version_mappings or {}
for new_pin in new_pins:
repo_name, repo_url, commit_sha = new_pin
commit_sha = version_mappings.get(repo_name, {}
).get(commit_sha, commit_sha)
# Prepare our repo directory and clone the repo if needed. Only pull
# if the user requests it.
repo_dir = "{0}/{1}".format(storage_directory, repo_name)
update_repo(repo_dir, repo_url, do_update)
# Get the old SHA from the previous pins. If this pin didn't exist
# in the previous OSA revision, skip it. This could happen with newly-
# added projects and roles.
try:
commit_sha_old = next(x[2] for x in old_pins if x[0] == repo_name)
except Exception:
continue
else:
commit_sha_old = version_mappings.get(repo_name, {}
).get(commit_sha_old,
commit_sha_old)
# Loop through the commits and render our template.
validate_commits(repo_dir, [commit_sha_old, commit_sha])
commits = get_commits(repo_dir, commit_sha_old, commit_sha)
template_vars = {
'repo': repo_name,
'commits': commits,
'commit_base_url': get_commit_url(repo_url),
'old_sha': commit_sha_old,
'new_sha': commit_sha
}
rst = render_template('offline-repo-changes.j2', template_vars)
report += rst
return report | python | def make_report(storage_directory, old_pins, new_pins, do_update=False,
version_mappings=None):
"""Create RST report from a list of projects/roles."""
report = ""
version_mappings = version_mappings or {}
for new_pin in new_pins:
repo_name, repo_url, commit_sha = new_pin
commit_sha = version_mappings.get(repo_name, {}
).get(commit_sha, commit_sha)
# Prepare our repo directory and clone the repo if needed. Only pull
# if the user requests it.
repo_dir = "{0}/{1}".format(storage_directory, repo_name)
update_repo(repo_dir, repo_url, do_update)
# Get the old SHA from the previous pins. If this pin didn't exist
# in the previous OSA revision, skip it. This could happen with newly-
# added projects and roles.
try:
commit_sha_old = next(x[2] for x in old_pins if x[0] == repo_name)
except Exception:
continue
else:
commit_sha_old = version_mappings.get(repo_name, {}
).get(commit_sha_old,
commit_sha_old)
# Loop through the commits and render our template.
validate_commits(repo_dir, [commit_sha_old, commit_sha])
commits = get_commits(repo_dir, commit_sha_old, commit_sha)
template_vars = {
'repo': repo_name,
'commits': commits,
'commit_base_url': get_commit_url(repo_url),
'old_sha': commit_sha_old,
'new_sha': commit_sha
}
rst = render_template('offline-repo-changes.j2', template_vars)
report += rst
return report | [
"def",
"make_report",
"(",
"storage_directory",
",",
"old_pins",
",",
"new_pins",
",",
"do_update",
"=",
"False",
",",
"version_mappings",
"=",
"None",
")",
":",
"report",
"=",
"\"\"",
"version_mappings",
"=",
"version_mappings",
"or",
"{",
"}",
"for",
"new_pin",
"in",
"new_pins",
":",
"repo_name",
",",
"repo_url",
",",
"commit_sha",
"=",
"new_pin",
"commit_sha",
"=",
"version_mappings",
".",
"get",
"(",
"repo_name",
",",
"{",
"}",
")",
".",
"get",
"(",
"commit_sha",
",",
"commit_sha",
")",
"# Prepare our repo directory and clone the repo if needed. Only pull",
"# if the user requests it.",
"repo_dir",
"=",
"\"{0}/{1}\"",
".",
"format",
"(",
"storage_directory",
",",
"repo_name",
")",
"update_repo",
"(",
"repo_dir",
",",
"repo_url",
",",
"do_update",
")",
"# Get the old SHA from the previous pins. If this pin didn't exist",
"# in the previous OSA revision, skip it. This could happen with newly-",
"# added projects and roles.",
"try",
":",
"commit_sha_old",
"=",
"next",
"(",
"x",
"[",
"2",
"]",
"for",
"x",
"in",
"old_pins",
"if",
"x",
"[",
"0",
"]",
"==",
"repo_name",
")",
"except",
"Exception",
":",
"continue",
"else",
":",
"commit_sha_old",
"=",
"version_mappings",
".",
"get",
"(",
"repo_name",
",",
"{",
"}",
")",
".",
"get",
"(",
"commit_sha_old",
",",
"commit_sha_old",
")",
"# Loop through the commits and render our template.",
"validate_commits",
"(",
"repo_dir",
",",
"[",
"commit_sha_old",
",",
"commit_sha",
"]",
")",
"commits",
"=",
"get_commits",
"(",
"repo_dir",
",",
"commit_sha_old",
",",
"commit_sha",
")",
"template_vars",
"=",
"{",
"'repo'",
":",
"repo_name",
",",
"'commits'",
":",
"commits",
",",
"'commit_base_url'",
":",
"get_commit_url",
"(",
"repo_url",
")",
",",
"'old_sha'",
":",
"commit_sha_old",
",",
"'new_sha'",
":",
"commit_sha",
"}",
"rst",
"=",
"render_template",
"(",
"'offline-repo-changes.j2'",
",",
"template_vars",
")",
"report",
"+=",
"rst",
"return",
"report"
] | Create RST report from a list of projects/roles. | [
"Create",
"RST",
"report",
"from",
"a",
"list",
"of",
"projects",
"/",
"roles",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L289-L329 |
rcbops/osa_differ | osa_differ/osa_differ.py | normalize_yaml | def normalize_yaml(yaml):
"""Normalize the YAML from project and role lookups.
These are returned as a list of tuples.
"""
if isinstance(yaml, list):
# Normalize the roles YAML data
normalized_yaml = [(x['name'], x['src'], x.get('version', 'HEAD'))
for x in yaml]
else:
# Extract the project names from the roles YAML and create a list of
# tuples.
projects = [x[:-9] for x in yaml.keys() if x.endswith('git_repo')]
normalized_yaml = []
for project in projects:
repo_url = yaml['{0}_git_repo'.format(project)]
commit_sha = yaml['{0}_git_install_branch'.format(project)]
normalized_yaml.append((project, repo_url, commit_sha))
return normalized_yaml | python | def normalize_yaml(yaml):
"""Normalize the YAML from project and role lookups.
These are returned as a list of tuples.
"""
if isinstance(yaml, list):
# Normalize the roles YAML data
normalized_yaml = [(x['name'], x['src'], x.get('version', 'HEAD'))
for x in yaml]
else:
# Extract the project names from the roles YAML and create a list of
# tuples.
projects = [x[:-9] for x in yaml.keys() if x.endswith('git_repo')]
normalized_yaml = []
for project in projects:
repo_url = yaml['{0}_git_repo'.format(project)]
commit_sha = yaml['{0}_git_install_branch'.format(project)]
normalized_yaml.append((project, repo_url, commit_sha))
return normalized_yaml | [
"def",
"normalize_yaml",
"(",
"yaml",
")",
":",
"if",
"isinstance",
"(",
"yaml",
",",
"list",
")",
":",
"# Normalize the roles YAML data",
"normalized_yaml",
"=",
"[",
"(",
"x",
"[",
"'name'",
"]",
",",
"x",
"[",
"'src'",
"]",
",",
"x",
".",
"get",
"(",
"'version'",
",",
"'HEAD'",
")",
")",
"for",
"x",
"in",
"yaml",
"]",
"else",
":",
"# Extract the project names from the roles YAML and create a list of",
"# tuples.",
"projects",
"=",
"[",
"x",
"[",
":",
"-",
"9",
"]",
"for",
"x",
"in",
"yaml",
".",
"keys",
"(",
")",
"if",
"x",
".",
"endswith",
"(",
"'git_repo'",
")",
"]",
"normalized_yaml",
"=",
"[",
"]",
"for",
"project",
"in",
"projects",
":",
"repo_url",
"=",
"yaml",
"[",
"'{0}_git_repo'",
".",
"format",
"(",
"project",
")",
"]",
"commit_sha",
"=",
"yaml",
"[",
"'{0}_git_install_branch'",
".",
"format",
"(",
"project",
")",
"]",
"normalized_yaml",
".",
"append",
"(",
"(",
"project",
",",
"repo_url",
",",
"commit_sha",
")",
")",
"return",
"normalized_yaml"
] | Normalize the YAML from project and role lookups.
These are returned as a list of tuples. | [
"Normalize",
"the",
"YAML",
"from",
"project",
"and",
"role",
"lookups",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L332-L351 |
rcbops/osa_differ | osa_differ/osa_differ.py | post_gist | def post_gist(report_data, old_sha, new_sha):
"""Post the report to a GitHub Gist and return the URL of the gist."""
payload = {
"description": ("Changes in OpenStack-Ansible between "
"{0} and {1}".format(old_sha, new_sha)),
"public": True,
"files": {
"osa-diff-{0}-{1}.rst".format(old_sha, new_sha): {
"content": report_data
}
}
}
url = "https://api.github.com/gists"
r = requests.post(url, data=json.dumps(payload))
response = r.json()
return response['html_url'] | python | def post_gist(report_data, old_sha, new_sha):
"""Post the report to a GitHub Gist and return the URL of the gist."""
payload = {
"description": ("Changes in OpenStack-Ansible between "
"{0} and {1}".format(old_sha, new_sha)),
"public": True,
"files": {
"osa-diff-{0}-{1}.rst".format(old_sha, new_sha): {
"content": report_data
}
}
}
url = "https://api.github.com/gists"
r = requests.post(url, data=json.dumps(payload))
response = r.json()
return response['html_url'] | [
"def",
"post_gist",
"(",
"report_data",
",",
"old_sha",
",",
"new_sha",
")",
":",
"payload",
"=",
"{",
"\"description\"",
":",
"(",
"\"Changes in OpenStack-Ansible between \"",
"\"{0} and {1}\"",
".",
"format",
"(",
"old_sha",
",",
"new_sha",
")",
")",
",",
"\"public\"",
":",
"True",
",",
"\"files\"",
":",
"{",
"\"osa-diff-{0}-{1}.rst\"",
".",
"format",
"(",
"old_sha",
",",
"new_sha",
")",
":",
"{",
"\"content\"",
":",
"report_data",
"}",
"}",
"}",
"url",
"=",
"\"https://api.github.com/gists\"",
"r",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
")",
"response",
"=",
"r",
".",
"json",
"(",
")",
"return",
"response",
"[",
"'html_url'",
"]"
] | Post the report to a GitHub Gist and return the URL of the gist. | [
"Post",
"the",
"report",
"to",
"a",
"GitHub",
"Gist",
"and",
"return",
"the",
"URL",
"of",
"the",
"gist",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L361-L376 |
rcbops/osa_differ | osa_differ/osa_differ.py | prepare_storage_dir | def prepare_storage_dir(storage_directory):
"""Prepare the storage directory."""
storage_directory = os.path.expanduser(storage_directory)
if not os.path.exists(storage_directory):
os.mkdir(storage_directory)
return storage_directory | python | def prepare_storage_dir(storage_directory):
"""Prepare the storage directory."""
storage_directory = os.path.expanduser(storage_directory)
if not os.path.exists(storage_directory):
os.mkdir(storage_directory)
return storage_directory | [
"def",
"prepare_storage_dir",
"(",
"storage_directory",
")",
":",
"storage_directory",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"storage_directory",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"storage_directory",
")",
":",
"os",
".",
"mkdir",
"(",
"storage_directory",
")",
"return",
"storage_directory"
] | Prepare the storage directory. | [
"Prepare",
"the",
"storage",
"directory",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L399-L405 |
rcbops/osa_differ | osa_differ/osa_differ.py | render_template | def render_template(template_file, template_vars):
"""Render a jinja template."""
# Load our Jinja templates
template_dir = "{0}/templates".format(
os.path.dirname(os.path.abspath(__file__))
)
jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir),
trim_blocks=True
)
rendered = jinja_env.get_template(template_file).render(template_vars)
return rendered | python | def render_template(template_file, template_vars):
"""Render a jinja template."""
# Load our Jinja templates
template_dir = "{0}/templates".format(
os.path.dirname(os.path.abspath(__file__))
)
jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir),
trim_blocks=True
)
rendered = jinja_env.get_template(template_file).render(template_vars)
return rendered | [
"def",
"render_template",
"(",
"template_file",
",",
"template_vars",
")",
":",
"# Load our Jinja templates",
"template_dir",
"=",
"\"{0}/templates\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
")",
"jinja_env",
"=",
"jinja2",
".",
"Environment",
"(",
"loader",
"=",
"jinja2",
".",
"FileSystemLoader",
"(",
"template_dir",
")",
",",
"trim_blocks",
"=",
"True",
")",
"rendered",
"=",
"jinja_env",
".",
"get_template",
"(",
"template_file",
")",
".",
"render",
"(",
"template_vars",
")",
"return",
"rendered"
] | Render a jinja template. | [
"Render",
"a",
"jinja",
"template",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L408-L420 |
rcbops/osa_differ | osa_differ/osa_differ.py | repo_pull | def repo_pull(repo_dir, repo_url, fetch=False):
"""Reset repository and optionally update it."""
# Make sure the repository is reset to the master branch.
repo = Repo(repo_dir)
repo.git.clean("-df")
repo.git.reset("--hard")
repo.git.checkout("master")
repo.head.reset(index=True, working_tree=True)
# Compile the refspec appropriately to ensure
# that if the repo is from github it includes
# all the refs needed, including PR's.
refspec_list = [
"+refs/heads/*:refs/remotes/origin/*",
"+refs/heads/*:refs/heads/*",
"+refs/tags/*:refs/tags/*"
]
if "github.com" in repo_url:
refspec_list.extend([
"+refs/pull/*:refs/remotes/origin/pr/*",
"+refs/heads/*:refs/remotes/origin/*"])
# Only get the latest updates if requested.
if fetch:
repo.git.fetch(["-u", "-v", "-f",
repo_url,
refspec_list])
return repo | python | def repo_pull(repo_dir, repo_url, fetch=False):
"""Reset repository and optionally update it."""
# Make sure the repository is reset to the master branch.
repo = Repo(repo_dir)
repo.git.clean("-df")
repo.git.reset("--hard")
repo.git.checkout("master")
repo.head.reset(index=True, working_tree=True)
# Compile the refspec appropriately to ensure
# that if the repo is from github it includes
# all the refs needed, including PR's.
refspec_list = [
"+refs/heads/*:refs/remotes/origin/*",
"+refs/heads/*:refs/heads/*",
"+refs/tags/*:refs/tags/*"
]
if "github.com" in repo_url:
refspec_list.extend([
"+refs/pull/*:refs/remotes/origin/pr/*",
"+refs/heads/*:refs/remotes/origin/*"])
# Only get the latest updates if requested.
if fetch:
repo.git.fetch(["-u", "-v", "-f",
repo_url,
refspec_list])
return repo | [
"def",
"repo_pull",
"(",
"repo_dir",
",",
"repo_url",
",",
"fetch",
"=",
"False",
")",
":",
"# Make sure the repository is reset to the master branch.",
"repo",
"=",
"Repo",
"(",
"repo_dir",
")",
"repo",
".",
"git",
".",
"clean",
"(",
"\"-df\"",
")",
"repo",
".",
"git",
".",
"reset",
"(",
"\"--hard\"",
")",
"repo",
".",
"git",
".",
"checkout",
"(",
"\"master\"",
")",
"repo",
".",
"head",
".",
"reset",
"(",
"index",
"=",
"True",
",",
"working_tree",
"=",
"True",
")",
"# Compile the refspec appropriately to ensure",
"# that if the repo is from github it includes",
"# all the refs needed, including PR's.",
"refspec_list",
"=",
"[",
"\"+refs/heads/*:refs/remotes/origin/*\"",
",",
"\"+refs/heads/*:refs/heads/*\"",
",",
"\"+refs/tags/*:refs/tags/*\"",
"]",
"if",
"\"github.com\"",
"in",
"repo_url",
":",
"refspec_list",
".",
"extend",
"(",
"[",
"\"+refs/pull/*:refs/remotes/origin/pr/*\"",
",",
"\"+refs/heads/*:refs/remotes/origin/*\"",
"]",
")",
"# Only get the latest updates if requested.",
"if",
"fetch",
":",
"repo",
".",
"git",
".",
"fetch",
"(",
"[",
"\"-u\"",
",",
"\"-v\"",
",",
"\"-f\"",
",",
"repo_url",
",",
"refspec_list",
"]",
")",
"return",
"repo"
] | Reset repository and optionally update it. | [
"Reset",
"repository",
"and",
"optionally",
"update",
"it",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L429-L456 |
rcbops/osa_differ | osa_differ/osa_differ.py | update_repo | def update_repo(repo_dir, repo_url, fetch=False):
"""Clone the repo if it doesn't exist already, otherwise update it."""
repo_exists = os.path.exists(repo_dir)
if not repo_exists:
log.info("Cloning repo {}".format(repo_url))
repo = repo_clone(repo_dir, repo_url)
# Make sure the repo is properly prepared
# and has all the refs required
log.info("Fetching repo {} (fetch: {})".format(repo_url, fetch))
repo = repo_pull(repo_dir, repo_url, fetch)
return repo | python | def update_repo(repo_dir, repo_url, fetch=False):
"""Clone the repo if it doesn't exist already, otherwise update it."""
repo_exists = os.path.exists(repo_dir)
if not repo_exists:
log.info("Cloning repo {}".format(repo_url))
repo = repo_clone(repo_dir, repo_url)
# Make sure the repo is properly prepared
# and has all the refs required
log.info("Fetching repo {} (fetch: {})".format(repo_url, fetch))
repo = repo_pull(repo_dir, repo_url, fetch)
return repo | [
"def",
"update_repo",
"(",
"repo_dir",
",",
"repo_url",
",",
"fetch",
"=",
"False",
")",
":",
"repo_exists",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"repo_dir",
")",
"if",
"not",
"repo_exists",
":",
"log",
".",
"info",
"(",
"\"Cloning repo {}\"",
".",
"format",
"(",
"repo_url",
")",
")",
"repo",
"=",
"repo_clone",
"(",
"repo_dir",
",",
"repo_url",
")",
"# Make sure the repo is properly prepared",
"# and has all the refs required",
"log",
".",
"info",
"(",
"\"Fetching repo {} (fetch: {})\"",
".",
"format",
"(",
"repo_url",
",",
"fetch",
")",
")",
"repo",
"=",
"repo_pull",
"(",
"repo_dir",
",",
"repo_url",
",",
"fetch",
")",
"return",
"repo"
] | Clone the repo if it doesn't exist already, otherwise update it. | [
"Clone",
"the",
"repo",
"if",
"it",
"doesn",
"t",
"exist",
"already",
"otherwise",
"update",
"it",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L459-L471 |
rcbops/osa_differ | osa_differ/osa_differ.py | validate_commits | def validate_commits(repo_dir, commits):
"""Test if a commit is valid for the repository."""
log.debug("Validating {c} exist in {r}".format(c=commits, r=repo_dir))
repo = Repo(repo_dir)
for commit in commits:
try:
commit = repo.commit(commit)
except Exception:
msg = ("Commit {commit} could not be found in repo {repo}. "
"You may need to pass --update to fetch the latest "
"updates to the git repositories stored on "
"your local computer.".format(repo=repo_dir, commit=commit))
raise exceptions.InvalidCommitException(msg)
return True | python | def validate_commits(repo_dir, commits):
"""Test if a commit is valid for the repository."""
log.debug("Validating {c} exist in {r}".format(c=commits, r=repo_dir))
repo = Repo(repo_dir)
for commit in commits:
try:
commit = repo.commit(commit)
except Exception:
msg = ("Commit {commit} could not be found in repo {repo}. "
"You may need to pass --update to fetch the latest "
"updates to the git repositories stored on "
"your local computer.".format(repo=repo_dir, commit=commit))
raise exceptions.InvalidCommitException(msg)
return True | [
"def",
"validate_commits",
"(",
"repo_dir",
",",
"commits",
")",
":",
"log",
".",
"debug",
"(",
"\"Validating {c} exist in {r}\"",
".",
"format",
"(",
"c",
"=",
"commits",
",",
"r",
"=",
"repo_dir",
")",
")",
"repo",
"=",
"Repo",
"(",
"repo_dir",
")",
"for",
"commit",
"in",
"commits",
":",
"try",
":",
"commit",
"=",
"repo",
".",
"commit",
"(",
"commit",
")",
"except",
"Exception",
":",
"msg",
"=",
"(",
"\"Commit {commit} could not be found in repo {repo}. \"",
"\"You may need to pass --update to fetch the latest \"",
"\"updates to the git repositories stored on \"",
"\"your local computer.\"",
".",
"format",
"(",
"repo",
"=",
"repo_dir",
",",
"commit",
"=",
"commit",
")",
")",
"raise",
"exceptions",
".",
"InvalidCommitException",
"(",
"msg",
")",
"return",
"True"
] | Test if a commit is valid for the repository. | [
"Test",
"if",
"a",
"commit",
"is",
"valid",
"for",
"the",
"repository",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L474-L488 |
rcbops/osa_differ | osa_differ/osa_differ.py | validate_commit_range | def validate_commit_range(repo_dir, old_commit, new_commit):
"""Check if commit range is valid. Flip it if needed."""
# Are there any commits between the two commits that were provided?
try:
commits = get_commits(repo_dir, old_commit, new_commit)
except Exception:
commits = []
if len(commits) == 0:
# The user might have gotten their commits out of order. Let's flip
# the order of the commits and try again.
try:
commits = get_commits(repo_dir, new_commit, old_commit)
except Exception:
commits = []
if len(commits) == 0:
# Okay, so there really are no commits between the two commits
# provided by the user. :)
msg = ("The commit range {0}..{1} is invalid for {2}."
"You may need to use the --update option to fetch the "
"latest updates to the git repositories stored on your "
"local computer.".format(old_commit, new_commit, repo_dir))
raise exceptions.InvalidCommitRangeException(msg)
else:
return 'flip'
return True | python | def validate_commit_range(repo_dir, old_commit, new_commit):
"""Check if commit range is valid. Flip it if needed."""
# Are there any commits between the two commits that were provided?
try:
commits = get_commits(repo_dir, old_commit, new_commit)
except Exception:
commits = []
if len(commits) == 0:
# The user might have gotten their commits out of order. Let's flip
# the order of the commits and try again.
try:
commits = get_commits(repo_dir, new_commit, old_commit)
except Exception:
commits = []
if len(commits) == 0:
# Okay, so there really are no commits between the two commits
# provided by the user. :)
msg = ("The commit range {0}..{1} is invalid for {2}."
"You may need to use the --update option to fetch the "
"latest updates to the git repositories stored on your "
"local computer.".format(old_commit, new_commit, repo_dir))
raise exceptions.InvalidCommitRangeException(msg)
else:
return 'flip'
return True | [
"def",
"validate_commit_range",
"(",
"repo_dir",
",",
"old_commit",
",",
"new_commit",
")",
":",
"# Are there any commits between the two commits that were provided?",
"try",
":",
"commits",
"=",
"get_commits",
"(",
"repo_dir",
",",
"old_commit",
",",
"new_commit",
")",
"except",
"Exception",
":",
"commits",
"=",
"[",
"]",
"if",
"len",
"(",
"commits",
")",
"==",
"0",
":",
"# The user might have gotten their commits out of order. Let's flip",
"# the order of the commits and try again.",
"try",
":",
"commits",
"=",
"get_commits",
"(",
"repo_dir",
",",
"new_commit",
",",
"old_commit",
")",
"except",
"Exception",
":",
"commits",
"=",
"[",
"]",
"if",
"len",
"(",
"commits",
")",
"==",
"0",
":",
"# Okay, so there really are no commits between the two commits",
"# provided by the user. :)",
"msg",
"=",
"(",
"\"The commit range {0}..{1} is invalid for {2}.\"",
"\"You may need to use the --update option to fetch the \"",
"\"latest updates to the git repositories stored on your \"",
"\"local computer.\"",
".",
"format",
"(",
"old_commit",
",",
"new_commit",
",",
"repo_dir",
")",
")",
"raise",
"exceptions",
".",
"InvalidCommitRangeException",
"(",
"msg",
")",
"else",
":",
"return",
"'flip'",
"return",
"True"
] | Check if commit range is valid. Flip it if needed. | [
"Check",
"if",
"commit",
"range",
"is",
"valid",
".",
"Flip",
"it",
"if",
"needed",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L491-L516 |
rcbops/osa_differ | osa_differ/osa_differ.py | get_release_notes | def get_release_notes(osa_repo_dir, osa_old_commit, osa_new_commit):
"""Get release notes between the two revisions."""
repo = Repo(osa_repo_dir)
# Get a list of tags, sorted
tags = repo.git.tag().split('\n')
tags = sorted(tags, key=LooseVersion)
# Currently major tags are being printed after rc and
# b tags. We need to fix the list so that major
# tags are printed before rc and b releases
tags = _fix_tags_list(tags)
# Find the closest tag from a given SHA
# The tag found here is the tag that was cut
# either on or before the given SHA
checkout(repo, osa_old_commit)
old_tag = repo.git.describe()
# If the SHA given is between two release tags, then
# 'git describe' will return a tag in form of
# <tag>-<commitNum>-<sha>. For example:
# 14.0.2-3-g6931e26
# Since reno does not support this format, we need to
# strip away the commit number and sha bits.
if '-' in old_tag:
old_tag = old_tag[0:old_tag.index('-')]
# Get the nearest tag associated with the new commit
checkout(repo, osa_new_commit)
new_tag = repo.git.describe()
if '-' in new_tag:
nearest_new_tag = new_tag[0:new_tag.index('-')]
else:
nearest_new_tag = new_tag
# Truncate the tags list to only include versions
# between old_sha and new_sha. The latest release
# is not included in this list. That version will be
# printed separately in the following step.
tags = tags[tags.index(old_tag):tags.index(nearest_new_tag)]
release_notes = ""
# Checkout the new commit, then run reno to get the latest
# releasenotes that have been created or updated between
# the latest release and this new commit.
repo.git.checkout(osa_new_commit, '-f')
reno_report_command = ['reno',
'report',
'--earliest-version',
nearest_new_tag]
reno_report_p = subprocess.Popen(reno_report_command,
cwd=osa_repo_dir,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
reno_output = reno_report_p.communicate()[0].decode('UTF-8')
release_notes += reno_output
# We want to start with the latest packaged release first, so
# the tags list is reversed
for version in reversed(tags):
# If version is an rc or b tag, and it has a major
# release tag, then skip it. There is no need to print
# release notes for an rc or b release unless we are
# comparing shas between two rc or b releases.
repo.git.checkout(version, '-f')
# We are outputing one version at a time here
reno_report_command = ['reno',
'report',
'--branch',
version,
'--earliest-version',
version]
reno_report_p = subprocess.Popen(reno_report_command,
cwd=osa_repo_dir,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
reno_output = reno_report_p.communicate()[0].decode('UTF-8')
# We need to ensure the output includes the version we are concerned
# about.
# This is due to https://bugs.launchpad.net/reno/+bug/1670173
if version in reno_output:
release_notes += reno_output
# Clean up "Release Notes" title. We don't need this title for
# each tagged release.
release_notes = release_notes.replace(
"=============\nRelease Notes\n=============",
""
)
# Replace headers that contain '=' with '~' to comply with osa-differ's
# formatting
release_notes = re.sub('===+', _equal_to_tilde, release_notes)
# Replace headers that contain '-' with '#' to comply with osa-differ's
# formatting
release_notes = re.sub('---+', _dash_to_num, release_notes)
return release_notes | python | def get_release_notes(osa_repo_dir, osa_old_commit, osa_new_commit):
"""Get release notes between the two revisions."""
repo = Repo(osa_repo_dir)
# Get a list of tags, sorted
tags = repo.git.tag().split('\n')
tags = sorted(tags, key=LooseVersion)
# Currently major tags are being printed after rc and
# b tags. We need to fix the list so that major
# tags are printed before rc and b releases
tags = _fix_tags_list(tags)
# Find the closest tag from a given SHA
# The tag found here is the tag that was cut
# either on or before the given SHA
checkout(repo, osa_old_commit)
old_tag = repo.git.describe()
# If the SHA given is between two release tags, then
# 'git describe' will return a tag in form of
# <tag>-<commitNum>-<sha>. For example:
# 14.0.2-3-g6931e26
# Since reno does not support this format, we need to
# strip away the commit number and sha bits.
if '-' in old_tag:
old_tag = old_tag[0:old_tag.index('-')]
# Get the nearest tag associated with the new commit
checkout(repo, osa_new_commit)
new_tag = repo.git.describe()
if '-' in new_tag:
nearest_new_tag = new_tag[0:new_tag.index('-')]
else:
nearest_new_tag = new_tag
# Truncate the tags list to only include versions
# between old_sha and new_sha. The latest release
# is not included in this list. That version will be
# printed separately in the following step.
tags = tags[tags.index(old_tag):tags.index(nearest_new_tag)]
release_notes = ""
# Checkout the new commit, then run reno to get the latest
# releasenotes that have been created or updated between
# the latest release and this new commit.
repo.git.checkout(osa_new_commit, '-f')
reno_report_command = ['reno',
'report',
'--earliest-version',
nearest_new_tag]
reno_report_p = subprocess.Popen(reno_report_command,
cwd=osa_repo_dir,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
reno_output = reno_report_p.communicate()[0].decode('UTF-8')
release_notes += reno_output
# We want to start with the latest packaged release first, so
# the tags list is reversed
for version in reversed(tags):
# If version is an rc or b tag, and it has a major
# release tag, then skip it. There is no need to print
# release notes for an rc or b release unless we are
# comparing shas between two rc or b releases.
repo.git.checkout(version, '-f')
# We are outputing one version at a time here
reno_report_command = ['reno',
'report',
'--branch',
version,
'--earliest-version',
version]
reno_report_p = subprocess.Popen(reno_report_command,
cwd=osa_repo_dir,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
reno_output = reno_report_p.communicate()[0].decode('UTF-8')
# We need to ensure the output includes the version we are concerned
# about.
# This is due to https://bugs.launchpad.net/reno/+bug/1670173
if version in reno_output:
release_notes += reno_output
# Clean up "Release Notes" title. We don't need this title for
# each tagged release.
release_notes = release_notes.replace(
"=============\nRelease Notes\n=============",
""
)
# Replace headers that contain '=' with '~' to comply with osa-differ's
# formatting
release_notes = re.sub('===+', _equal_to_tilde, release_notes)
# Replace headers that contain '-' with '#' to comply with osa-differ's
# formatting
release_notes = re.sub('---+', _dash_to_num, release_notes)
return release_notes | [
"def",
"get_release_notes",
"(",
"osa_repo_dir",
",",
"osa_old_commit",
",",
"osa_new_commit",
")",
":",
"repo",
"=",
"Repo",
"(",
"osa_repo_dir",
")",
"# Get a list of tags, sorted",
"tags",
"=",
"repo",
".",
"git",
".",
"tag",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"tags",
"=",
"sorted",
"(",
"tags",
",",
"key",
"=",
"LooseVersion",
")",
"# Currently major tags are being printed after rc and",
"# b tags. We need to fix the list so that major",
"# tags are printed before rc and b releases",
"tags",
"=",
"_fix_tags_list",
"(",
"tags",
")",
"# Find the closest tag from a given SHA",
"# The tag found here is the tag that was cut",
"# either on or before the given SHA",
"checkout",
"(",
"repo",
",",
"osa_old_commit",
")",
"old_tag",
"=",
"repo",
".",
"git",
".",
"describe",
"(",
")",
"# If the SHA given is between two release tags, then",
"# 'git describe' will return a tag in form of",
"# <tag>-<commitNum>-<sha>. For example:",
"# 14.0.2-3-g6931e26",
"# Since reno does not support this format, we need to",
"# strip away the commit number and sha bits.",
"if",
"'-'",
"in",
"old_tag",
":",
"old_tag",
"=",
"old_tag",
"[",
"0",
":",
"old_tag",
".",
"index",
"(",
"'-'",
")",
"]",
"# Get the nearest tag associated with the new commit",
"checkout",
"(",
"repo",
",",
"osa_new_commit",
")",
"new_tag",
"=",
"repo",
".",
"git",
".",
"describe",
"(",
")",
"if",
"'-'",
"in",
"new_tag",
":",
"nearest_new_tag",
"=",
"new_tag",
"[",
"0",
":",
"new_tag",
".",
"index",
"(",
"'-'",
")",
"]",
"else",
":",
"nearest_new_tag",
"=",
"new_tag",
"# Truncate the tags list to only include versions",
"# between old_sha and new_sha. The latest release",
"# is not included in this list. That version will be",
"# printed separately in the following step.",
"tags",
"=",
"tags",
"[",
"tags",
".",
"index",
"(",
"old_tag",
")",
":",
"tags",
".",
"index",
"(",
"nearest_new_tag",
")",
"]",
"release_notes",
"=",
"\"\"",
"# Checkout the new commit, then run reno to get the latest",
"# releasenotes that have been created or updated between",
"# the latest release and this new commit.",
"repo",
".",
"git",
".",
"checkout",
"(",
"osa_new_commit",
",",
"'-f'",
")",
"reno_report_command",
"=",
"[",
"'reno'",
",",
"'report'",
",",
"'--earliest-version'",
",",
"nearest_new_tag",
"]",
"reno_report_p",
"=",
"subprocess",
".",
"Popen",
"(",
"reno_report_command",
",",
"cwd",
"=",
"osa_repo_dir",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"reno_output",
"=",
"reno_report_p",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"decode",
"(",
"'UTF-8'",
")",
"release_notes",
"+=",
"reno_output",
"# We want to start with the latest packaged release first, so",
"# the tags list is reversed",
"for",
"version",
"in",
"reversed",
"(",
"tags",
")",
":",
"# If version is an rc or b tag, and it has a major",
"# release tag, then skip it. There is no need to print",
"# release notes for an rc or b release unless we are",
"# comparing shas between two rc or b releases.",
"repo",
".",
"git",
".",
"checkout",
"(",
"version",
",",
"'-f'",
")",
"# We are outputing one version at a time here",
"reno_report_command",
"=",
"[",
"'reno'",
",",
"'report'",
",",
"'--branch'",
",",
"version",
",",
"'--earliest-version'",
",",
"version",
"]",
"reno_report_p",
"=",
"subprocess",
".",
"Popen",
"(",
"reno_report_command",
",",
"cwd",
"=",
"osa_repo_dir",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"reno_output",
"=",
"reno_report_p",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
".",
"decode",
"(",
"'UTF-8'",
")",
"# We need to ensure the output includes the version we are concerned",
"# about.",
"# This is due to https://bugs.launchpad.net/reno/+bug/1670173",
"if",
"version",
"in",
"reno_output",
":",
"release_notes",
"+=",
"reno_output",
"# Clean up \"Release Notes\" title. We don't need this title for",
"# each tagged release.",
"release_notes",
"=",
"release_notes",
".",
"replace",
"(",
"\"=============\\nRelease Notes\\n=============\"",
",",
"\"\"",
")",
"# Replace headers that contain '=' with '~' to comply with osa-differ's",
"# formatting",
"release_notes",
"=",
"re",
".",
"sub",
"(",
"'===+'",
",",
"_equal_to_tilde",
",",
"release_notes",
")",
"# Replace headers that contain '-' with '#' to comply with osa-differ's",
"# formatting",
"release_notes",
"=",
"re",
".",
"sub",
"(",
"'---+'",
",",
"_dash_to_num",
",",
"release_notes",
")",
"return",
"release_notes"
] | Get release notes between the two revisions. | [
"Get",
"release",
"notes",
"between",
"the",
"two",
"revisions",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L519-L614 |
rcbops/osa_differ | osa_differ/osa_differ.py | run_osa_differ | def run_osa_differ():
"""Start here."""
# Get our arguments from the command line
args = parse_arguments()
# Set up DEBUG logging if needed
if args.debug:
log.setLevel(logging.DEBUG)
elif args.verbose:
log.setLevel(logging.INFO)
# Create the storage directory if it doesn't exist already.
try:
storage_directory = prepare_storage_dir(args.directory)
except OSError:
print("ERROR: Couldn't create the storage directory {0}. "
"Please create it manually.".format(args.directory))
sys.exit(1)
# Assemble some variables for the OSA repository.
osa_old_commit = args.old_commit[0]
osa_new_commit = args.new_commit[0]
osa_repo_dir = "{0}/openstack-ansible".format(storage_directory)
# Generate OpenStack-Ansible report header.
report_rst = make_osa_report(osa_repo_dir,
osa_old_commit,
osa_new_commit,
args)
# Get OpenStack-Ansible Reno release notes for the packaged
# releases between the two commits.
if args.release_notes:
report_rst += ("\nRelease Notes\n"
"-------------")
report_rst += get_release_notes(osa_repo_dir,
osa_old_commit,
osa_new_commit)
# Get the list of OpenStack roles from the newer and older commits.
role_yaml = get_roles(osa_repo_dir,
osa_old_commit,
args.role_requirements)
role_yaml_latest = get_roles(osa_repo_dir,
osa_new_commit,
args.role_requirements)
if not args.skip_roles:
# Generate the role report.
report_rst += ("\nOpenStack-Ansible Roles\n"
"-----------------------")
report_rst += make_report(storage_directory,
role_yaml,
role_yaml_latest,
args.update,
args.version_mappings)
if not args.skip_projects:
# Get the list of OpenStack projects from newer commit and older
# commit.
project_yaml = get_projects(osa_repo_dir, osa_old_commit)
project_yaml_latest = get_projects(osa_repo_dir,
osa_new_commit)
# Generate the project report.
report_rst += ("\nOpenStack Projects\n"
"------------------")
report_rst += make_report(storage_directory,
project_yaml,
project_yaml_latest,
args.update)
# Publish report according to the user's request.
output = publish_report(report_rst, args, osa_old_commit, osa_new_commit)
print(output) | python | def run_osa_differ():
"""Start here."""
# Get our arguments from the command line
args = parse_arguments()
# Set up DEBUG logging if needed
if args.debug:
log.setLevel(logging.DEBUG)
elif args.verbose:
log.setLevel(logging.INFO)
# Create the storage directory if it doesn't exist already.
try:
storage_directory = prepare_storage_dir(args.directory)
except OSError:
print("ERROR: Couldn't create the storage directory {0}. "
"Please create it manually.".format(args.directory))
sys.exit(1)
# Assemble some variables for the OSA repository.
osa_old_commit = args.old_commit[0]
osa_new_commit = args.new_commit[0]
osa_repo_dir = "{0}/openstack-ansible".format(storage_directory)
# Generate OpenStack-Ansible report header.
report_rst = make_osa_report(osa_repo_dir,
osa_old_commit,
osa_new_commit,
args)
# Get OpenStack-Ansible Reno release notes for the packaged
# releases between the two commits.
if args.release_notes:
report_rst += ("\nRelease Notes\n"
"-------------")
report_rst += get_release_notes(osa_repo_dir,
osa_old_commit,
osa_new_commit)
# Get the list of OpenStack roles from the newer and older commits.
role_yaml = get_roles(osa_repo_dir,
osa_old_commit,
args.role_requirements)
role_yaml_latest = get_roles(osa_repo_dir,
osa_new_commit,
args.role_requirements)
if not args.skip_roles:
# Generate the role report.
report_rst += ("\nOpenStack-Ansible Roles\n"
"-----------------------")
report_rst += make_report(storage_directory,
role_yaml,
role_yaml_latest,
args.update,
args.version_mappings)
if not args.skip_projects:
# Get the list of OpenStack projects from newer commit and older
# commit.
project_yaml = get_projects(osa_repo_dir, osa_old_commit)
project_yaml_latest = get_projects(osa_repo_dir,
osa_new_commit)
# Generate the project report.
report_rst += ("\nOpenStack Projects\n"
"------------------")
report_rst += make_report(storage_directory,
project_yaml,
project_yaml_latest,
args.update)
# Publish report according to the user's request.
output = publish_report(report_rst, args, osa_old_commit, osa_new_commit)
print(output) | [
"def",
"run_osa_differ",
"(",
")",
":",
"# Get our arguments from the command line",
"args",
"=",
"parse_arguments",
"(",
")",
"# Set up DEBUG logging if needed",
"if",
"args",
".",
"debug",
":",
"log",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"elif",
"args",
".",
"verbose",
":",
"log",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"# Create the storage directory if it doesn't exist already.",
"try",
":",
"storage_directory",
"=",
"prepare_storage_dir",
"(",
"args",
".",
"directory",
")",
"except",
"OSError",
":",
"print",
"(",
"\"ERROR: Couldn't create the storage directory {0}. \"",
"\"Please create it manually.\"",
".",
"format",
"(",
"args",
".",
"directory",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"# Assemble some variables for the OSA repository.",
"osa_old_commit",
"=",
"args",
".",
"old_commit",
"[",
"0",
"]",
"osa_new_commit",
"=",
"args",
".",
"new_commit",
"[",
"0",
"]",
"osa_repo_dir",
"=",
"\"{0}/openstack-ansible\"",
".",
"format",
"(",
"storage_directory",
")",
"# Generate OpenStack-Ansible report header.",
"report_rst",
"=",
"make_osa_report",
"(",
"osa_repo_dir",
",",
"osa_old_commit",
",",
"osa_new_commit",
",",
"args",
")",
"# Get OpenStack-Ansible Reno release notes for the packaged",
"# releases between the two commits.",
"if",
"args",
".",
"release_notes",
":",
"report_rst",
"+=",
"(",
"\"\\nRelease Notes\\n\"",
"\"-------------\"",
")",
"report_rst",
"+=",
"get_release_notes",
"(",
"osa_repo_dir",
",",
"osa_old_commit",
",",
"osa_new_commit",
")",
"# Get the list of OpenStack roles from the newer and older commits.",
"role_yaml",
"=",
"get_roles",
"(",
"osa_repo_dir",
",",
"osa_old_commit",
",",
"args",
".",
"role_requirements",
")",
"role_yaml_latest",
"=",
"get_roles",
"(",
"osa_repo_dir",
",",
"osa_new_commit",
",",
"args",
".",
"role_requirements",
")",
"if",
"not",
"args",
".",
"skip_roles",
":",
"# Generate the role report.",
"report_rst",
"+=",
"(",
"\"\\nOpenStack-Ansible Roles\\n\"",
"\"-----------------------\"",
")",
"report_rst",
"+=",
"make_report",
"(",
"storage_directory",
",",
"role_yaml",
",",
"role_yaml_latest",
",",
"args",
".",
"update",
",",
"args",
".",
"version_mappings",
")",
"if",
"not",
"args",
".",
"skip_projects",
":",
"# Get the list of OpenStack projects from newer commit and older",
"# commit.",
"project_yaml",
"=",
"get_projects",
"(",
"osa_repo_dir",
",",
"osa_old_commit",
")",
"project_yaml_latest",
"=",
"get_projects",
"(",
"osa_repo_dir",
",",
"osa_new_commit",
")",
"# Generate the project report.",
"report_rst",
"+=",
"(",
"\"\\nOpenStack Projects\\n\"",
"\"------------------\"",
")",
"report_rst",
"+=",
"make_report",
"(",
"storage_directory",
",",
"project_yaml",
",",
"project_yaml_latest",
",",
"args",
".",
"update",
")",
"# Publish report according to the user's request.",
"output",
"=",
"publish_report",
"(",
"report_rst",
",",
"args",
",",
"osa_old_commit",
",",
"osa_new_commit",
")",
"print",
"(",
"output",
")"
] | Start here. | [
"Start",
"here",
"."
] | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L646-L720 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | append_new_text | def append_new_text(destination, text, join_str=None):
"""
This method provides the functionality of adding text appropriately
underneath the destination node. This will be either to the destination's
text attribute or to the tail attribute of the last child.
"""
if join_str is None:
join_str = ' '
if len(destination) > 0: # Destination has children
last = destination[-1]
if last.tail is None: # Last child has no tail
last.tail = text
else: # Last child has a tail
last.tail = join_str.join([last.tail, text])
else: # Destination has no children
if destination.text is None: # Destination has no text
destination.text = text
else: # Destination has a text
destination.text = join_str.join([destination.text, text]) | python | def append_new_text(destination, text, join_str=None):
"""
This method provides the functionality of adding text appropriately
underneath the destination node. This will be either to the destination's
text attribute or to the tail attribute of the last child.
"""
if join_str is None:
join_str = ' '
if len(destination) > 0: # Destination has children
last = destination[-1]
if last.tail is None: # Last child has no tail
last.tail = text
else: # Last child has a tail
last.tail = join_str.join([last.tail, text])
else: # Destination has no children
if destination.text is None: # Destination has no text
destination.text = text
else: # Destination has a text
destination.text = join_str.join([destination.text, text]) | [
"def",
"append_new_text",
"(",
"destination",
",",
"text",
",",
"join_str",
"=",
"None",
")",
":",
"if",
"join_str",
"is",
"None",
":",
"join_str",
"=",
"' '",
"if",
"len",
"(",
"destination",
")",
">",
"0",
":",
"# Destination has children",
"last",
"=",
"destination",
"[",
"-",
"1",
"]",
"if",
"last",
".",
"tail",
"is",
"None",
":",
"# Last child has no tail",
"last",
".",
"tail",
"=",
"text",
"else",
":",
"# Last child has a tail",
"last",
".",
"tail",
"=",
"join_str",
".",
"join",
"(",
"[",
"last",
".",
"tail",
",",
"text",
"]",
")",
"else",
":",
"# Destination has no children",
"if",
"destination",
".",
"text",
"is",
"None",
":",
"# Destination has no text",
"destination",
".",
"text",
"=",
"text",
"else",
":",
"# Destination has a text",
"destination",
".",
"text",
"=",
"join_str",
".",
"join",
"(",
"[",
"destination",
".",
"text",
",",
"text",
"]",
")"
] | This method provides the functionality of adding text appropriately
underneath the destination node. This will be either to the destination's
text attribute or to the tail attribute of the last child. | [
"This",
"method",
"provides",
"the",
"functionality",
"of",
"adding",
"text",
"appropriately",
"underneath",
"the",
"destination",
"node",
".",
"This",
"will",
"be",
"either",
"to",
"the",
"destination",
"s",
"text",
"attribute",
"or",
"to",
"the",
"tail",
"attribute",
"of",
"the",
"last",
"child",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L24-L42 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | append_all_below | def append_all_below(destination, source, join_str=None):
"""
Compared to xml.dom.minidom, lxml's treatment of text as .text and .tail
attributes of elements is an oddity. It can even be a little frustrating
when one is attempting to copy everything underneath some element to
another element; one has to write in extra code to handle the text. This
method provides the functionality of adding everything underneath the
source element, in preserved order, to the destination element.
"""
if join_str is None:
join_str = ' '
if source.text is not None: # If source has text
if len(destination) == 0: # Destination has no children
if destination.text is None: # Destination has no text
destination.text = source.text
else: # Destination has a text
destination.text = join_str.join([destination.text, source.text])
else: # Destination has children
#Select last child
last = destination[-1]
if last.tail is None: # Last child has no tail
last.tail = source.text
else: # Last child has a tail
last.tail = join_str.join([last.tail, source.text])
for each_child in source:
destination.append(deepcopy(each_child)) | python | def append_all_below(destination, source, join_str=None):
"""
Compared to xml.dom.minidom, lxml's treatment of text as .text and .tail
attributes of elements is an oddity. It can even be a little frustrating
when one is attempting to copy everything underneath some element to
another element; one has to write in extra code to handle the text. This
method provides the functionality of adding everything underneath the
source element, in preserved order, to the destination element.
"""
if join_str is None:
join_str = ' '
if source.text is not None: # If source has text
if len(destination) == 0: # Destination has no children
if destination.text is None: # Destination has no text
destination.text = source.text
else: # Destination has a text
destination.text = join_str.join([destination.text, source.text])
else: # Destination has children
#Select last child
last = destination[-1]
if last.tail is None: # Last child has no tail
last.tail = source.text
else: # Last child has a tail
last.tail = join_str.join([last.tail, source.text])
for each_child in source:
destination.append(deepcopy(each_child)) | [
"def",
"append_all_below",
"(",
"destination",
",",
"source",
",",
"join_str",
"=",
"None",
")",
":",
"if",
"join_str",
"is",
"None",
":",
"join_str",
"=",
"' '",
"if",
"source",
".",
"text",
"is",
"not",
"None",
":",
"# If source has text",
"if",
"len",
"(",
"destination",
")",
"==",
"0",
":",
"# Destination has no children",
"if",
"destination",
".",
"text",
"is",
"None",
":",
"# Destination has no text",
"destination",
".",
"text",
"=",
"source",
".",
"text",
"else",
":",
"# Destination has a text",
"destination",
".",
"text",
"=",
"join_str",
".",
"join",
"(",
"[",
"destination",
".",
"text",
",",
"source",
".",
"text",
"]",
")",
"else",
":",
"# Destination has children",
"#Select last child",
"last",
"=",
"destination",
"[",
"-",
"1",
"]",
"if",
"last",
".",
"tail",
"is",
"None",
":",
"# Last child has no tail",
"last",
".",
"tail",
"=",
"source",
".",
"text",
"else",
":",
"# Last child has a tail",
"last",
".",
"tail",
"=",
"join_str",
".",
"join",
"(",
"[",
"last",
".",
"tail",
",",
"source",
".",
"text",
"]",
")",
"for",
"each_child",
"in",
"source",
":",
"destination",
".",
"append",
"(",
"deepcopy",
"(",
"each_child",
")",
")"
] | Compared to xml.dom.minidom, lxml's treatment of text as .text and .tail
attributes of elements is an oddity. It can even be a little frustrating
when one is attempting to copy everything underneath some element to
another element; one has to write in extra code to handle the text. This
method provides the functionality of adding everything underneath the
source element, in preserved order, to the destination element. | [
"Compared",
"to",
"xml",
".",
"dom",
".",
"minidom",
"lxml",
"s",
"treatment",
"of",
"text",
"as",
".",
"text",
"and",
".",
"tail",
"attributes",
"of",
"elements",
"is",
"an",
"oddity",
".",
"It",
"can",
"even",
"be",
"a",
"little",
"frustrating",
"when",
"one",
"is",
"attempting",
"to",
"copy",
"everything",
"underneath",
"some",
"element",
"to",
"another",
"element",
";",
"one",
"has",
"to",
"write",
"in",
"extra",
"code",
"to",
"handle",
"the",
"text",
".",
"This",
"method",
"provides",
"the",
"functionality",
"of",
"adding",
"everything",
"underneath",
"the",
"source",
"element",
"in",
"preserved",
"order",
"to",
"the",
"destination",
"element",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L45-L70 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | all_text | def all_text(element):
"""
A method for extending lxml's functionality, this will find and concatenate
all text data that exists one level immediately underneath the given
element. Unlike etree.tostring(element, method='text'), this will not
recursively walk the entire underlying tree. It merely combines the element
text attribute with the tail attribute of each child.
"""
if element.text is None:
text = []
else:
text = [element.text]
tails = [child.tail for child in element if child.tail is not None]
tails = [tail.strip() for tail in tails if tail.strip()]
return ' '.join(text + tails) | python | def all_text(element):
"""
A method for extending lxml's functionality, this will find and concatenate
all text data that exists one level immediately underneath the given
element. Unlike etree.tostring(element, method='text'), this will not
recursively walk the entire underlying tree. It merely combines the element
text attribute with the tail attribute of each child.
"""
if element.text is None:
text = []
else:
text = [element.text]
tails = [child.tail for child in element if child.tail is not None]
tails = [tail.strip() for tail in tails if tail.strip()]
return ' '.join(text + tails) | [
"def",
"all_text",
"(",
"element",
")",
":",
"if",
"element",
".",
"text",
"is",
"None",
":",
"text",
"=",
"[",
"]",
"else",
":",
"text",
"=",
"[",
"element",
".",
"text",
"]",
"tails",
"=",
"[",
"child",
".",
"tail",
"for",
"child",
"in",
"element",
"if",
"child",
".",
"tail",
"is",
"not",
"None",
"]",
"tails",
"=",
"[",
"tail",
".",
"strip",
"(",
")",
"for",
"tail",
"in",
"tails",
"if",
"tail",
".",
"strip",
"(",
")",
"]",
"return",
"' '",
".",
"join",
"(",
"text",
"+",
"tails",
")"
] | A method for extending lxml's functionality, this will find and concatenate
all text data that exists one level immediately underneath the given
element. Unlike etree.tostring(element, method='text'), this will not
recursively walk the entire underlying tree. It merely combines the element
text attribute with the tail attribute of each child. | [
"A",
"method",
"for",
"extending",
"lxml",
"s",
"functionality",
"this",
"will",
"find",
"and",
"concatenate",
"all",
"text",
"data",
"that",
"exists",
"one",
"level",
"immediately",
"underneath",
"the",
"given",
"element",
".",
"Unlike",
"etree",
".",
"tostring",
"(",
"element",
"method",
"=",
"text",
")",
"this",
"will",
"not",
"recursively",
"walk",
"the",
"entire",
"underlying",
"tree",
".",
"It",
"merely",
"combines",
"the",
"element",
"text",
"attribute",
"with",
"the",
"tail",
"attribute",
"of",
"each",
"child",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L73-L87 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | remove_all_attributes | def remove_all_attributes(element, exclude=None):
"""
This method will remove all attributes of any provided element.
A list of strings may be passed to the keyward-argument "exclude", which
will serve as a list of attributes which will not be removed.
"""
if exclude is None:
exclude = []
for k in element.attrib.keys():
if k not in exclude:
element.attrib.pop(k) | python | def remove_all_attributes(element, exclude=None):
"""
This method will remove all attributes of any provided element.
A list of strings may be passed to the keyward-argument "exclude", which
will serve as a list of attributes which will not be removed.
"""
if exclude is None:
exclude = []
for k in element.attrib.keys():
if k not in exclude:
element.attrib.pop(k) | [
"def",
"remove_all_attributes",
"(",
"element",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"[",
"]",
"for",
"k",
"in",
"element",
".",
"attrib",
".",
"keys",
"(",
")",
":",
"if",
"k",
"not",
"in",
"exclude",
":",
"element",
".",
"attrib",
".",
"pop",
"(",
"k",
")"
] | This method will remove all attributes of any provided element.
A list of strings may be passed to the keyward-argument "exclude", which
will serve as a list of attributes which will not be removed. | [
"This",
"method",
"will",
"remove",
"all",
"attributes",
"of",
"any",
"provided",
"element",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L90-L101 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | ns_format | def ns_format(element, namespaced_string):
"""
Provides a convenient method for adapting a tag or attribute name to
use lxml's format. Use this for tags like ops:switch or attributes like
xlink:href.
"""
if ':' not in namespaced_string:
print('This name contains no namespace, returning it unmodified: ' + namespaced_string)
return namespaced_string
namespace, name = namespaced_string.split(':')
return '{' + element.nsmap[namespace] + '}' + name | python | def ns_format(element, namespaced_string):
"""
Provides a convenient method for adapting a tag or attribute name to
use lxml's format. Use this for tags like ops:switch or attributes like
xlink:href.
"""
if ':' not in namespaced_string:
print('This name contains no namespace, returning it unmodified: ' + namespaced_string)
return namespaced_string
namespace, name = namespaced_string.split(':')
return '{' + element.nsmap[namespace] + '}' + name | [
"def",
"ns_format",
"(",
"element",
",",
"namespaced_string",
")",
":",
"if",
"':'",
"not",
"in",
"namespaced_string",
":",
"print",
"(",
"'This name contains no namespace, returning it unmodified: '",
"+",
"namespaced_string",
")",
"return",
"namespaced_string",
"namespace",
",",
"name",
"=",
"namespaced_string",
".",
"split",
"(",
"':'",
")",
"return",
"'{'",
"+",
"element",
".",
"nsmap",
"[",
"namespace",
"]",
"+",
"'}'",
"+",
"name"
] | Provides a convenient method for adapting a tag or attribute name to
use lxml's format. Use this for tags like ops:switch or attributes like
xlink:href. | [
"Provides",
"a",
"convenient",
"method",
"for",
"adapting",
"a",
"tag",
"or",
"attribute",
"name",
"to",
"use",
"lxml",
"s",
"format",
".",
"Use",
"this",
"for",
"tags",
"like",
"ops",
":",
"switch",
"or",
"attributes",
"like",
"xlink",
":",
"href",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L136-L146 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | rename_attributes | def rename_attributes(element, attrs):
"""
Renames the attributes of the element. Accepts the element and a dictionary
of string values. The keys are the original names, and their values will be
the altered names. This method treats all attributes as optional and will
not fail on missing attributes.
"""
for name in attrs.keys():
if name not in element.attrib:
continue
else:
element.attrib[attrs[name]] = element.attrib.pop(name) | python | def rename_attributes(element, attrs):
"""
Renames the attributes of the element. Accepts the element and a dictionary
of string values. The keys are the original names, and their values will be
the altered names. This method treats all attributes as optional and will
not fail on missing attributes.
"""
for name in attrs.keys():
if name not in element.attrib:
continue
else:
element.attrib[attrs[name]] = element.attrib.pop(name) | [
"def",
"rename_attributes",
"(",
"element",
",",
"attrs",
")",
":",
"for",
"name",
"in",
"attrs",
".",
"keys",
"(",
")",
":",
"if",
"name",
"not",
"in",
"element",
".",
"attrib",
":",
"continue",
"else",
":",
"element",
".",
"attrib",
"[",
"attrs",
"[",
"name",
"]",
"]",
"=",
"element",
".",
"attrib",
".",
"pop",
"(",
"name",
")"
] | Renames the attributes of the element. Accepts the element and a dictionary
of string values. The keys are the original names, and their values will be
the altered names. This method treats all attributes as optional and will
not fail on missing attributes. | [
"Renames",
"the",
"attributes",
"of",
"the",
"element",
".",
"Accepts",
"the",
"element",
"and",
"a",
"dictionary",
"of",
"string",
"values",
".",
"The",
"keys",
"are",
"the",
"original",
"names",
"and",
"their",
"values",
"will",
"be",
"the",
"altered",
"names",
".",
"This",
"method",
"treats",
"all",
"attributes",
"as",
"optional",
"and",
"will",
"not",
"fail",
"on",
"missing",
"attributes",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L149-L160 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | elevate_element | def elevate_element(node, adopt_name=None, adopt_attrs=None):
"""
This method serves a specialized function. It comes up most often when
working with block level elements that may not be contained within
paragraph elements, which are presented in the source document as
inline elements (inside a paragraph element).
It would be inappropriate to merely insert the block element at the
level of the parent, since this disorders the document by placing
the child out of place with its siblings. So this method will elevate
the node to the parent level and also create a new parent to adopt all
of the siblings after the elevated child.
The adopting parent node will have identical attributes and tag name
as the original parent unless specified otherwise.
"""
#These must be collected before modifying the xml
parent = node.getparent()
grandparent = parent.getparent()
child_index = parent.index(node)
parent_index = grandparent.index(parent)
#Get a list of the siblings
siblings = list(parent)[child_index+1:]
#Insert the node after the parent
grandparent.insert(parent_index+1, node)
#Only create the adoptive parent if there are siblings
if len(siblings) > 0 or node.tail is not None:
#Create the adoptive parent
if adopt_name is None:
adopt = etree.Element(parent.tag)
else:
adopt = etree.Element(adopt_name)
if adopt_attrs is None:
for key in parent.attrib.keys():
adopt.attrib[key] = parent.attrib[key]
else:
for key in adopt_attrs.keys():
adopt.attrib[key] = adopt_attrs[key]
#Insert the adoptive parent after the elevated child
grandparent.insert(grandparent.index(node)+1, adopt)
#Transfer the siblings to the adoptive parent
for sibling in siblings:
adopt.append(sibling)
#lxml's element.tail attribute presents a slight problem, requiring the
#following oddity
#Set the adoptive parent's text to the node.tail
if node.tail is not None:
adopt.text = node.tail
node.tail = None | python | def elevate_element(node, adopt_name=None, adopt_attrs=None):
"""
This method serves a specialized function. It comes up most often when
working with block level elements that may not be contained within
paragraph elements, which are presented in the source document as
inline elements (inside a paragraph element).
It would be inappropriate to merely insert the block element at the
level of the parent, since this disorders the document by placing
the child out of place with its siblings. So this method will elevate
the node to the parent level and also create a new parent to adopt all
of the siblings after the elevated child.
The adopting parent node will have identical attributes and tag name
as the original parent unless specified otherwise.
"""
#These must be collected before modifying the xml
parent = node.getparent()
grandparent = parent.getparent()
child_index = parent.index(node)
parent_index = grandparent.index(parent)
#Get a list of the siblings
siblings = list(parent)[child_index+1:]
#Insert the node after the parent
grandparent.insert(parent_index+1, node)
#Only create the adoptive parent if there are siblings
if len(siblings) > 0 or node.tail is not None:
#Create the adoptive parent
if adopt_name is None:
adopt = etree.Element(parent.tag)
else:
adopt = etree.Element(adopt_name)
if adopt_attrs is None:
for key in parent.attrib.keys():
adopt.attrib[key] = parent.attrib[key]
else:
for key in adopt_attrs.keys():
adopt.attrib[key] = adopt_attrs[key]
#Insert the adoptive parent after the elevated child
grandparent.insert(grandparent.index(node)+1, adopt)
#Transfer the siblings to the adoptive parent
for sibling in siblings:
adopt.append(sibling)
#lxml's element.tail attribute presents a slight problem, requiring the
#following oddity
#Set the adoptive parent's text to the node.tail
if node.tail is not None:
adopt.text = node.tail
node.tail = None | [
"def",
"elevate_element",
"(",
"node",
",",
"adopt_name",
"=",
"None",
",",
"adopt_attrs",
"=",
"None",
")",
":",
"#These must be collected before modifying the xml",
"parent",
"=",
"node",
".",
"getparent",
"(",
")",
"grandparent",
"=",
"parent",
".",
"getparent",
"(",
")",
"child_index",
"=",
"parent",
".",
"index",
"(",
"node",
")",
"parent_index",
"=",
"grandparent",
".",
"index",
"(",
"parent",
")",
"#Get a list of the siblings",
"siblings",
"=",
"list",
"(",
"parent",
")",
"[",
"child_index",
"+",
"1",
":",
"]",
"#Insert the node after the parent",
"grandparent",
".",
"insert",
"(",
"parent_index",
"+",
"1",
",",
"node",
")",
"#Only create the adoptive parent if there are siblings",
"if",
"len",
"(",
"siblings",
")",
">",
"0",
"or",
"node",
".",
"tail",
"is",
"not",
"None",
":",
"#Create the adoptive parent",
"if",
"adopt_name",
"is",
"None",
":",
"adopt",
"=",
"etree",
".",
"Element",
"(",
"parent",
".",
"tag",
")",
"else",
":",
"adopt",
"=",
"etree",
".",
"Element",
"(",
"adopt_name",
")",
"if",
"adopt_attrs",
"is",
"None",
":",
"for",
"key",
"in",
"parent",
".",
"attrib",
".",
"keys",
"(",
")",
":",
"adopt",
".",
"attrib",
"[",
"key",
"]",
"=",
"parent",
".",
"attrib",
"[",
"key",
"]",
"else",
":",
"for",
"key",
"in",
"adopt_attrs",
".",
"keys",
"(",
")",
":",
"adopt",
".",
"attrib",
"[",
"key",
"]",
"=",
"adopt_attrs",
"[",
"key",
"]",
"#Insert the adoptive parent after the elevated child",
"grandparent",
".",
"insert",
"(",
"grandparent",
".",
"index",
"(",
"node",
")",
"+",
"1",
",",
"adopt",
")",
"#Transfer the siblings to the adoptive parent",
"for",
"sibling",
"in",
"siblings",
":",
"adopt",
".",
"append",
"(",
"sibling",
")",
"#lxml's element.tail attribute presents a slight problem, requiring the",
"#following oddity",
"#Set the adoptive parent's text to the node.tail",
"if",
"node",
".",
"tail",
"is",
"not",
"None",
":",
"adopt",
".",
"text",
"=",
"node",
".",
"tail",
"node",
".",
"tail",
"=",
"None"
] | This method serves a specialized function. It comes up most often when
working with block level elements that may not be contained within
paragraph elements, which are presented in the source document as
inline elements (inside a paragraph element).
It would be inappropriate to merely insert the block element at the
level of the parent, since this disorders the document by placing
the child out of place with its siblings. So this method will elevate
the node to the parent level and also create a new parent to adopt all
of the siblings after the elevated child.
The adopting parent node will have identical attributes and tag name
as the original parent unless specified otherwise. | [
"This",
"method",
"serves",
"a",
"specialized",
"function",
".",
"It",
"comes",
"up",
"most",
"often",
"when",
"working",
"with",
"block",
"level",
"elements",
"that",
"may",
"not",
"be",
"contained",
"within",
"paragraph",
"elements",
"which",
"are",
"presented",
"in",
"the",
"source",
"document",
"as",
"inline",
"elements",
"(",
"inside",
"a",
"paragraph",
"element",
")",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L163-L212 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | replace | def replace(old, new):
"""
A simple way to replace one element node with another.
"""
parent = old.getparent()
parent.replace(old, new) | python | def replace(old, new):
"""
A simple way to replace one element node with another.
"""
parent = old.getparent()
parent.replace(old, new) | [
"def",
"replace",
"(",
"old",
",",
"new",
")",
":",
"parent",
"=",
"old",
".",
"getparent",
"(",
")",
"parent",
".",
"replace",
"(",
"old",
",",
"new",
")"
] | A simple way to replace one element node with another. | [
"A",
"simple",
"way",
"to",
"replace",
"one",
"element",
"node",
"with",
"another",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L223-L228 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | insert_before | def insert_before(old, new):
"""
A simple way to insert a new element node before the old element node among
its siblings.
"""
parent = old.getparent()
parent.insert(parent.index(old), new) | python | def insert_before(old, new):
"""
A simple way to insert a new element node before the old element node among
its siblings.
"""
parent = old.getparent()
parent.insert(parent.index(old), new) | [
"def",
"insert_before",
"(",
"old",
",",
"new",
")",
":",
"parent",
"=",
"old",
".",
"getparent",
"(",
")",
"parent",
".",
"insert",
"(",
"parent",
".",
"index",
"(",
"old",
")",
",",
"new",
")"
] | A simple way to insert a new element node before the old element node among
its siblings. | [
"A",
"simple",
"way",
"to",
"insert",
"a",
"new",
"element",
"node",
"before",
"the",
"old",
"element",
"node",
"among",
"its",
"siblings",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L231-L237 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | comment | def comment(node):
"""
Converts the node received to a comment, in place, and will also return the
comment element.
"""
parent = node.parentNode
comment = node.ownerDocument.createComment(node.toxml())
parent.replaceChild(comment, node)
return comment | python | def comment(node):
"""
Converts the node received to a comment, in place, and will also return the
comment element.
"""
parent = node.parentNode
comment = node.ownerDocument.createComment(node.toxml())
parent.replaceChild(comment, node)
return comment | [
"def",
"comment",
"(",
"node",
")",
":",
"parent",
"=",
"node",
".",
"parentNode",
"comment",
"=",
"node",
".",
"ownerDocument",
".",
"createComment",
"(",
"node",
".",
"toxml",
"(",
")",
")",
"parent",
".",
"replaceChild",
"(",
"comment",
",",
"node",
")",
"return",
"comment"
] | Converts the node received to a comment, in place, and will also return the
comment element. | [
"Converts",
"the",
"node",
"received",
"to",
"a",
"comment",
"in",
"place",
"and",
"will",
"also",
"return",
"the",
"comment",
"element",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L240-L248 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | uncomment | def uncomment(comment):
"""
Converts the comment node received to a non-commented element, in place,
and will return the new node.
This may fail, primarily due to special characters within the comment that
the xml parser is unable to handle. If it fails, this method will log an
error and return None
"""
parent = comment.parentNode
h = html.parser.HTMLParser()
data = h.unescape(comment.data)
try:
node = minidom.parseString(data).firstChild
except xml.parsers.expat.ExpatError: # Could not parse!
log.error('Could not uncomment node due to parsing error!')
return None
else:
parent.replaceChild(node, comment)
return node | python | def uncomment(comment):
"""
Converts the comment node received to a non-commented element, in place,
and will return the new node.
This may fail, primarily due to special characters within the comment that
the xml parser is unable to handle. If it fails, this method will log an
error and return None
"""
parent = comment.parentNode
h = html.parser.HTMLParser()
data = h.unescape(comment.data)
try:
node = minidom.parseString(data).firstChild
except xml.parsers.expat.ExpatError: # Could not parse!
log.error('Could not uncomment node due to parsing error!')
return None
else:
parent.replaceChild(node, comment)
return node | [
"def",
"uncomment",
"(",
"comment",
")",
":",
"parent",
"=",
"comment",
".",
"parentNode",
"h",
"=",
"html",
".",
"parser",
".",
"HTMLParser",
"(",
")",
"data",
"=",
"h",
".",
"unescape",
"(",
"comment",
".",
"data",
")",
"try",
":",
"node",
"=",
"minidom",
".",
"parseString",
"(",
"data",
")",
".",
"firstChild",
"except",
"xml",
".",
"parsers",
".",
"expat",
".",
"ExpatError",
":",
"# Could not parse!",
"log",
".",
"error",
"(",
"'Could not uncomment node due to parsing error!'",
")",
"return",
"None",
"else",
":",
"parent",
".",
"replaceChild",
"(",
"node",
",",
"comment",
")",
"return",
"node"
] | Converts the comment node received to a non-commented element, in place,
and will return the new node.
This may fail, primarily due to special characters within the comment that
the xml parser is unable to handle. If it fails, this method will log an
error and return None | [
"Converts",
"the",
"comment",
"node",
"received",
"to",
"a",
"non",
"-",
"commented",
"element",
"in",
"place",
"and",
"will",
"return",
"the",
"new",
"node",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L251-L270 |
SavinaRoja/OpenAccess_EPUB | src/openaccess_epub/utils/element_methods.py | serialize | def serialize(element, strip=False):
"""
A handy way to serialize an element to text.
"""
text = etree.tostring(element, method='text', encoding='utf-8')
if strip:
text = text.strip()
return str(text, encoding='utf-8') | python | def serialize(element, strip=False):
"""
A handy way to serialize an element to text.
"""
text = etree.tostring(element, method='text', encoding='utf-8')
if strip:
text = text.strip()
return str(text, encoding='utf-8') | [
"def",
"serialize",
"(",
"element",
",",
"strip",
"=",
"False",
")",
":",
"text",
"=",
"etree",
".",
"tostring",
"(",
"element",
",",
"method",
"=",
"'text'",
",",
"encoding",
"=",
"'utf-8'",
")",
"if",
"strip",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"return",
"str",
"(",
"text",
",",
"encoding",
"=",
"'utf-8'",
")"
] | A handy way to serialize an element to text. | [
"A",
"handy",
"way",
"to",
"serialize",
"an",
"element",
"to",
"text",
"."
] | train | https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/utils/element_methods.py#L273-L280 |
MSchnei/pyprf_feature | pyprf_feature/analysis/pyprf_opt_ep.py | get_arg_parse | def get_arg_parse():
"""Parses the Command Line Arguments using argparse."""
# Create parser object:
objParser = argparse.ArgumentParser()
# Add argument to namespace -config file path:
objParser.add_argument('-config', required=True,
metavar='/path/to/config.csv',
help='Absolute file path of config file with \
parameters for pRF analysis. Ignored if in \
testing mode.'
)
# Add argument to namespace -prior results file path:
objParser.add_argument('-strPthPrior', required=True,
metavar='/path/to/my_prior_res',
help='Absolute file path of prior pRF results. \
Ignored if in testing mode.'
)
# Add argument to namespace -varNumOpt1 flag:
objParser.add_argument('-varNumOpt1', required=True, type=int,
metavar='N1',
help='Number of radial positions.'
)
# Add argument to namespace -varNumOpt2 flag:
objParser.add_argument('-varNumOpt2', required=True, type=int,
metavar='N2',
help='Number of angular positions.'
)
# Add argument to namespace -varNumOpt3 flag:
objParser.add_argument('-varNumOpt3', default=None, metavar='N3',
help='Max displacement in radial direction.'
)
# Add argument to namespace -lgcRstrCentre flag:
objParser.add_argument('-lgcRstrCentre', dest='lgcRstrCentre',
action='store_true', default=False,
help='Restrict fitted models to stimulated area.')
objParser.add_argument('-strPathHrf', default=None, required=False,
metavar='/path/to/custom_hrf_parameter.npy',
help='Path to npy file with custom hrf parameters. \
Ignored if in testing mode.')
objParser.add_argument('-supsur', nargs='+',
help='List of floats that represent the ratio of \
size neg surround to size pos center.',
type=float, default=None)
# Namespace object containign arguments and values:
objNspc = objParser.parse_args()
return objNspc | python | def get_arg_parse():
"""Parses the Command Line Arguments using argparse."""
# Create parser object:
objParser = argparse.ArgumentParser()
# Add argument to namespace -config file path:
objParser.add_argument('-config', required=True,
metavar='/path/to/config.csv',
help='Absolute file path of config file with \
parameters for pRF analysis. Ignored if in \
testing mode.'
)
# Add argument to namespace -prior results file path:
objParser.add_argument('-strPthPrior', required=True,
metavar='/path/to/my_prior_res',
help='Absolute file path of prior pRF results. \
Ignored if in testing mode.'
)
# Add argument to namespace -varNumOpt1 flag:
objParser.add_argument('-varNumOpt1', required=True, type=int,
metavar='N1',
help='Number of radial positions.'
)
# Add argument to namespace -varNumOpt2 flag:
objParser.add_argument('-varNumOpt2', required=True, type=int,
metavar='N2',
help='Number of angular positions.'
)
# Add argument to namespace -varNumOpt3 flag:
objParser.add_argument('-varNumOpt3', default=None, metavar='N3',
help='Max displacement in radial direction.'
)
# Add argument to namespace -lgcRstrCentre flag:
objParser.add_argument('-lgcRstrCentre', dest='lgcRstrCentre',
action='store_true', default=False,
help='Restrict fitted models to stimulated area.')
objParser.add_argument('-strPathHrf', default=None, required=False,
metavar='/path/to/custom_hrf_parameter.npy',
help='Path to npy file with custom hrf parameters. \
Ignored if in testing mode.')
objParser.add_argument('-supsur', nargs='+',
help='List of floats that represent the ratio of \
size neg surround to size pos center.',
type=float, default=None)
# Namespace object containign arguments and values:
objNspc = objParser.parse_args()
return objNspc | [
"def",
"get_arg_parse",
"(",
")",
":",
"# Create parser object:",
"objParser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"# Add argument to namespace -config file path:",
"objParser",
".",
"add_argument",
"(",
"'-config'",
",",
"required",
"=",
"True",
",",
"metavar",
"=",
"'/path/to/config.csv'",
",",
"help",
"=",
"'Absolute file path of config file with \\\n parameters for pRF analysis. Ignored if in \\\n testing mode.'",
")",
"# Add argument to namespace -prior results file path:",
"objParser",
".",
"add_argument",
"(",
"'-strPthPrior'",
",",
"required",
"=",
"True",
",",
"metavar",
"=",
"'/path/to/my_prior_res'",
",",
"help",
"=",
"'Absolute file path of prior pRF results. \\\n Ignored if in testing mode.'",
")",
"# Add argument to namespace -varNumOpt1 flag:",
"objParser",
".",
"add_argument",
"(",
"'-varNumOpt1'",
",",
"required",
"=",
"True",
",",
"type",
"=",
"int",
",",
"metavar",
"=",
"'N1'",
",",
"help",
"=",
"'Number of radial positions.'",
")",
"# Add argument to namespace -varNumOpt2 flag:",
"objParser",
".",
"add_argument",
"(",
"'-varNumOpt2'",
",",
"required",
"=",
"True",
",",
"type",
"=",
"int",
",",
"metavar",
"=",
"'N2'",
",",
"help",
"=",
"'Number of angular positions.'",
")",
"# Add argument to namespace -varNumOpt3 flag:",
"objParser",
".",
"add_argument",
"(",
"'-varNumOpt3'",
",",
"default",
"=",
"None",
",",
"metavar",
"=",
"'N3'",
",",
"help",
"=",
"'Max displacement in radial direction.'",
")",
"# Add argument to namespace -lgcRstrCentre flag:",
"objParser",
".",
"add_argument",
"(",
"'-lgcRstrCentre'",
",",
"dest",
"=",
"'lgcRstrCentre'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'Restrict fitted models to stimulated area.'",
")",
"objParser",
".",
"add_argument",
"(",
"'-strPathHrf'",
",",
"default",
"=",
"None",
",",
"required",
"=",
"False",
",",
"metavar",
"=",
"'/path/to/custom_hrf_parameter.npy'",
",",
"help",
"=",
"'Path to npy file with custom hrf parameters. \\\n Ignored if in testing mode.'",
")",
"objParser",
".",
"add_argument",
"(",
"'-supsur'",
",",
"nargs",
"=",
"'+'",
",",
"help",
"=",
"'List of floats that represent the ratio of \\\n size neg surround to size pos center.'",
",",
"type",
"=",
"float",
",",
"default",
"=",
"None",
")",
"# Namespace object containign arguments and values:",
"objNspc",
"=",
"objParser",
".",
"parse_args",
"(",
")",
"return",
"objNspc"
] | Parses the Command Line Arguments using argparse. | [
"Parses",
"the",
"Command",
"Line",
"Arguments",
"using",
"argparse",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/pyprf_opt_ep.py#L16-L71 |
MSchnei/pyprf_feature | pyprf_feature/analysis/pyprf_opt_ep.py | main | def main():
"""pyprf_opt_brute entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
# input arguments, but since we use 'argparse' it is redundant.
# lstArgs = sys.argv[1:]
strWelcome = 'pyprf_opt_brute ' + __version__
strDec = '=' * len(strWelcome)
print(strDec + '\n' + strWelcome + '\n' + strDec)
objNspc = get_arg_parse()
# Print info if no config argument is provided.
if any(item is None for item in [objNspc.config, objNspc.strPthPrior,
objNspc.varNumOpt1, objNspc.varNumOpt2]):
print('Please provide the necessary input arguments, i.e.:')
print('-strCsvCnfg -strPthPrior -varNumOpt1 and -varNumOpt2')
else:
# Signal non-test mode to lower functions (needed for pytest):
lgcTest = False
# Perform pRF fitting without suppressive surround
if objNspc.supsur is None:
print('***Mode: Fit pRF models, no suppressive surround***')
# Call to main function, to invoke pRF analysis:
pyprf_opt_brute(objNspc.config, objNspc, lgcTest=lgcTest,
strPathHrf=objNspc.strPathHrf, varRat=None)
# Perform pRF fitting with suppressive surround
else:
print('***Mode: Fit pRF models, suppressive surround***')
# Load config parameters from csv file into dictionary:
dicCnfg = load_config(objNspc.config, lgcTest=lgcTest,
lgcPrint=False)
# Load config parameters from dictionary into namespace.
# We do this on every loop so we have a fresh start in case
# variables are redefined during the prf analysis
cfg = cls_set_config(dicCnfg)
# Make sure that lgcCrteMdl is set to True since we will need
# to loop iteratively over pyprf_feature with different ratios
# for size surround to size center. On every loop models,
# reflecting the new ratio, need to be created from scratch
errorMsg = 'lgcCrteMdl needs to be set to True for -supsur.'
assert cfg.lgcCrteMdl, errorMsg
# Make sure that switchHrf is set to 1. It would not make sense
# to find the negative surround for the hrf deriavtive function
errorMsg = 'switchHrfSet needs to be set to 1 for -supsur.'
assert cfg.switchHrfSet == 1, errorMsg
# Get list with size ratios
lstRat = objNspc.supsur
# Make sure that all ratios are larger than 1.0
errorMsg = 'All provided ratios need to be larger than 1.0'
assert np.all(np.greater(np.array(lstRat), 1.0)), errorMsg
# Append None as the first entry, so fitting without surround
# is performed once as well
lstRat.insert(0, None)
# Loop over ratios and find best pRF
for varRat in lstRat:
# Print to command line, so the user knows which exponent
# is used
print('---Ratio surround to center: ' + str(varRat))
# Call to main function, to invoke pRF analysis:
pyprf_opt_brute(objNspc.config, objNspc, lgcTest=lgcTest,
strPathHrf=objNspc.strPathHrf, varRat=varRat)
# List with name suffices of output images:
lstNiiNames = ['_x_pos',
'_y_pos',
'_SD',
'_R2',
'_polar_angle',
'_eccentricity',
'_Betas']
# Compare results for the different ratios, export nii files
# based on the results of the comparison and delete in-between
# results
# Replace first entry (None) with 1, so it can be saved to nii
lstRat[0] = 1.0
# Append 'hrf' to cfg.strPathOut, if fitting was done with
# custom hrf
if objNspc.strPathHrf is not None:
cfg.strPathOut = cfg.strPathOut + '_hrf'
cmp_res_R2(lstRat, lstNiiNames, cfg.strPathOut, cfg.strPathMdl,
lgcDel=True, lgcSveMdlTc=False, strNmeExt='_brute') | python | def main():
"""pyprf_opt_brute entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
# input arguments, but since we use 'argparse' it is redundant.
# lstArgs = sys.argv[1:]
strWelcome = 'pyprf_opt_brute ' + __version__
strDec = '=' * len(strWelcome)
print(strDec + '\n' + strWelcome + '\n' + strDec)
objNspc = get_arg_parse()
# Print info if no config argument is provided.
if any(item is None for item in [objNspc.config, objNspc.strPthPrior,
objNspc.varNumOpt1, objNspc.varNumOpt2]):
print('Please provide the necessary input arguments, i.e.:')
print('-strCsvCnfg -strPthPrior -varNumOpt1 and -varNumOpt2')
else:
# Signal non-test mode to lower functions (needed for pytest):
lgcTest = False
# Perform pRF fitting without suppressive surround
if objNspc.supsur is None:
print('***Mode: Fit pRF models, no suppressive surround***')
# Call to main function, to invoke pRF analysis:
pyprf_opt_brute(objNspc.config, objNspc, lgcTest=lgcTest,
strPathHrf=objNspc.strPathHrf, varRat=None)
# Perform pRF fitting with suppressive surround
else:
print('***Mode: Fit pRF models, suppressive surround***')
# Load config parameters from csv file into dictionary:
dicCnfg = load_config(objNspc.config, lgcTest=lgcTest,
lgcPrint=False)
# Load config parameters from dictionary into namespace.
# We do this on every loop so we have a fresh start in case
# variables are redefined during the prf analysis
cfg = cls_set_config(dicCnfg)
# Make sure that lgcCrteMdl is set to True since we will need
# to loop iteratively over pyprf_feature with different ratios
# for size surround to size center. On every loop models,
# reflecting the new ratio, need to be created from scratch
errorMsg = 'lgcCrteMdl needs to be set to True for -supsur.'
assert cfg.lgcCrteMdl, errorMsg
# Make sure that switchHrf is set to 1. It would not make sense
# to find the negative surround for the hrf deriavtive function
errorMsg = 'switchHrfSet needs to be set to 1 for -supsur.'
assert cfg.switchHrfSet == 1, errorMsg
# Get list with size ratios
lstRat = objNspc.supsur
# Make sure that all ratios are larger than 1.0
errorMsg = 'All provided ratios need to be larger than 1.0'
assert np.all(np.greater(np.array(lstRat), 1.0)), errorMsg
# Append None as the first entry, so fitting without surround
# is performed once as well
lstRat.insert(0, None)
# Loop over ratios and find best pRF
for varRat in lstRat:
# Print to command line, so the user knows which exponent
# is used
print('---Ratio surround to center: ' + str(varRat))
# Call to main function, to invoke pRF analysis:
pyprf_opt_brute(objNspc.config, objNspc, lgcTest=lgcTest,
strPathHrf=objNspc.strPathHrf, varRat=varRat)
# List with name suffices of output images:
lstNiiNames = ['_x_pos',
'_y_pos',
'_SD',
'_R2',
'_polar_angle',
'_eccentricity',
'_Betas']
# Compare results for the different ratios, export nii files
# based on the results of the comparison and delete in-between
# results
# Replace first entry (None) with 1, so it can be saved to nii
lstRat[0] = 1.0
# Append 'hrf' to cfg.strPathOut, if fitting was done with
# custom hrf
if objNspc.strPathHrf is not None:
cfg.strPathOut = cfg.strPathOut + '_hrf'
cmp_res_R2(lstRat, lstNiiNames, cfg.strPathOut, cfg.strPathMdl,
lgcDel=True, lgcSveMdlTc=False, strNmeExt='_brute') | [
"def",
"main",
"(",
")",
":",
"# Get list of input arguments (without first one, which is the path to the",
"# function that is called): --NOTE: This is another way of accessing",
"# input arguments, but since we use 'argparse' it is redundant.",
"# lstArgs = sys.argv[1:]",
"strWelcome",
"=",
"'pyprf_opt_brute '",
"+",
"__version__",
"strDec",
"=",
"'='",
"*",
"len",
"(",
"strWelcome",
")",
"print",
"(",
"strDec",
"+",
"'\\n'",
"+",
"strWelcome",
"+",
"'\\n'",
"+",
"strDec",
")",
"objNspc",
"=",
"get_arg_parse",
"(",
")",
"# Print info if no config argument is provided.",
"if",
"any",
"(",
"item",
"is",
"None",
"for",
"item",
"in",
"[",
"objNspc",
".",
"config",
",",
"objNspc",
".",
"strPthPrior",
",",
"objNspc",
".",
"varNumOpt1",
",",
"objNspc",
".",
"varNumOpt2",
"]",
")",
":",
"print",
"(",
"'Please provide the necessary input arguments, i.e.:'",
")",
"print",
"(",
"'-strCsvCnfg -strPthPrior -varNumOpt1 and -varNumOpt2'",
")",
"else",
":",
"# Signal non-test mode to lower functions (needed for pytest):",
"lgcTest",
"=",
"False",
"# Perform pRF fitting without suppressive surround",
"if",
"objNspc",
".",
"supsur",
"is",
"None",
":",
"print",
"(",
"'***Mode: Fit pRF models, no suppressive surround***'",
")",
"# Call to main function, to invoke pRF analysis:",
"pyprf_opt_brute",
"(",
"objNspc",
".",
"config",
",",
"objNspc",
",",
"lgcTest",
"=",
"lgcTest",
",",
"strPathHrf",
"=",
"objNspc",
".",
"strPathHrf",
",",
"varRat",
"=",
"None",
")",
"# Perform pRF fitting with suppressive surround",
"else",
":",
"print",
"(",
"'***Mode: Fit pRF models, suppressive surround***'",
")",
"# Load config parameters from csv file into dictionary:",
"dicCnfg",
"=",
"load_config",
"(",
"objNspc",
".",
"config",
",",
"lgcTest",
"=",
"lgcTest",
",",
"lgcPrint",
"=",
"False",
")",
"# Load config parameters from dictionary into namespace.",
"# We do this on every loop so we have a fresh start in case",
"# variables are redefined during the prf analysis",
"cfg",
"=",
"cls_set_config",
"(",
"dicCnfg",
")",
"# Make sure that lgcCrteMdl is set to True since we will need",
"# to loop iteratively over pyprf_feature with different ratios",
"# for size surround to size center. On every loop models,",
"# reflecting the new ratio, need to be created from scratch",
"errorMsg",
"=",
"'lgcCrteMdl needs to be set to True for -supsur.'",
"assert",
"cfg",
".",
"lgcCrteMdl",
",",
"errorMsg",
"# Make sure that switchHrf is set to 1. It would not make sense",
"# to find the negative surround for the hrf deriavtive function",
"errorMsg",
"=",
"'switchHrfSet needs to be set to 1 for -supsur.'",
"assert",
"cfg",
".",
"switchHrfSet",
"==",
"1",
",",
"errorMsg",
"# Get list with size ratios",
"lstRat",
"=",
"objNspc",
".",
"supsur",
"# Make sure that all ratios are larger than 1.0",
"errorMsg",
"=",
"'All provided ratios need to be larger than 1.0'",
"assert",
"np",
".",
"all",
"(",
"np",
".",
"greater",
"(",
"np",
".",
"array",
"(",
"lstRat",
")",
",",
"1.0",
")",
")",
",",
"errorMsg",
"# Append None as the first entry, so fitting without surround",
"# is performed once as well",
"lstRat",
".",
"insert",
"(",
"0",
",",
"None",
")",
"# Loop over ratios and find best pRF",
"for",
"varRat",
"in",
"lstRat",
":",
"# Print to command line, so the user knows which exponent",
"# is used",
"print",
"(",
"'---Ratio surround to center: '",
"+",
"str",
"(",
"varRat",
")",
")",
"# Call to main function, to invoke pRF analysis:",
"pyprf_opt_brute",
"(",
"objNspc",
".",
"config",
",",
"objNspc",
",",
"lgcTest",
"=",
"lgcTest",
",",
"strPathHrf",
"=",
"objNspc",
".",
"strPathHrf",
",",
"varRat",
"=",
"varRat",
")",
"# List with name suffices of output images:",
"lstNiiNames",
"=",
"[",
"'_x_pos'",
",",
"'_y_pos'",
",",
"'_SD'",
",",
"'_R2'",
",",
"'_polar_angle'",
",",
"'_eccentricity'",
",",
"'_Betas'",
"]",
"# Compare results for the different ratios, export nii files",
"# based on the results of the comparison and delete in-between",
"# results",
"# Replace first entry (None) with 1, so it can be saved to nii",
"lstRat",
"[",
"0",
"]",
"=",
"1.0",
"# Append 'hrf' to cfg.strPathOut, if fitting was done with",
"# custom hrf",
"if",
"objNspc",
".",
"strPathHrf",
"is",
"not",
"None",
":",
"cfg",
".",
"strPathOut",
"=",
"cfg",
".",
"strPathOut",
"+",
"'_hrf'",
"cmp_res_R2",
"(",
"lstRat",
",",
"lstNiiNames",
",",
"cfg",
".",
"strPathOut",
",",
"cfg",
".",
"strPathMdl",
",",
"lgcDel",
"=",
"True",
",",
"lgcSveMdlTc",
"=",
"False",
",",
"strNmeExt",
"=",
"'_brute'",
")"
] | pyprf_opt_brute entry point. | [
"pyprf_opt_brute",
"entry",
"point",
"."
] | train | https://github.com/MSchnei/pyprf_feature/blob/49004ede7ae1ddee07a30afe9ce3e2776750805c/pyprf_feature/analysis/pyprf_opt_ep.py#L74-L171 |
pmacosta/pcsv | pcsv/csv_file.py | _homogenize_data_filter | def _homogenize_data_filter(dfilter):
"""
Make data filter definition consistent.
Create a tuple where first element is the row filter and the second element
is the column filter
"""
if isinstance(dfilter, tuple) and (len(dfilter) == 1):
dfilter = (dfilter[0], None)
if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None,)):
dfilter = (None, None)
elif isinstance(dfilter, dict):
dfilter = (dfilter, None)
elif isinstance(dfilter, (list, str)) or (
isinstance(dfilter, int) and (not isinstance(dfilter, bool))
):
dfilter = (None, dfilter if isinstance(dfilter, list) else [dfilter])
elif isinstance(dfilter[0], dict) or (
(dfilter[0] is None) and (not isinstance(dfilter[1], dict))
):
pass
else:
dfilter = (dfilter[1], dfilter[0])
return dfilter | python | def _homogenize_data_filter(dfilter):
"""
Make data filter definition consistent.
Create a tuple where first element is the row filter and the second element
is the column filter
"""
if isinstance(dfilter, tuple) and (len(dfilter) == 1):
dfilter = (dfilter[0], None)
if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None,)):
dfilter = (None, None)
elif isinstance(dfilter, dict):
dfilter = (dfilter, None)
elif isinstance(dfilter, (list, str)) or (
isinstance(dfilter, int) and (not isinstance(dfilter, bool))
):
dfilter = (None, dfilter if isinstance(dfilter, list) else [dfilter])
elif isinstance(dfilter[0], dict) or (
(dfilter[0] is None) and (not isinstance(dfilter[1], dict))
):
pass
else:
dfilter = (dfilter[1], dfilter[0])
return dfilter | [
"def",
"_homogenize_data_filter",
"(",
"dfilter",
")",
":",
"if",
"isinstance",
"(",
"dfilter",
",",
"tuple",
")",
"and",
"(",
"len",
"(",
"dfilter",
")",
"==",
"1",
")",
":",
"dfilter",
"=",
"(",
"dfilter",
"[",
"0",
"]",
",",
"None",
")",
"if",
"(",
"dfilter",
"is",
"None",
")",
"or",
"(",
"dfilter",
"==",
"(",
"None",
",",
"None",
")",
")",
"or",
"(",
"dfilter",
"==",
"(",
"None",
",",
")",
")",
":",
"dfilter",
"=",
"(",
"None",
",",
"None",
")",
"elif",
"isinstance",
"(",
"dfilter",
",",
"dict",
")",
":",
"dfilter",
"=",
"(",
"dfilter",
",",
"None",
")",
"elif",
"isinstance",
"(",
"dfilter",
",",
"(",
"list",
",",
"str",
")",
")",
"or",
"(",
"isinstance",
"(",
"dfilter",
",",
"int",
")",
"and",
"(",
"not",
"isinstance",
"(",
"dfilter",
",",
"bool",
")",
")",
")",
":",
"dfilter",
"=",
"(",
"None",
",",
"dfilter",
"if",
"isinstance",
"(",
"dfilter",
",",
"list",
")",
"else",
"[",
"dfilter",
"]",
")",
"elif",
"isinstance",
"(",
"dfilter",
"[",
"0",
"]",
",",
"dict",
")",
"or",
"(",
"(",
"dfilter",
"[",
"0",
"]",
"is",
"None",
")",
"and",
"(",
"not",
"isinstance",
"(",
"dfilter",
"[",
"1",
"]",
",",
"dict",
")",
")",
")",
":",
"pass",
"else",
":",
"dfilter",
"=",
"(",
"dfilter",
"[",
"1",
"]",
",",
"dfilter",
"[",
"0",
"]",
")",
"return",
"dfilter"
] | Make data filter definition consistent.
Create a tuple where first element is the row filter and the second element
is the column filter | [
"Make",
"data",
"filter",
"definition",
"consistent",
"."
] | train | https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/csv_file.py#L38-L61 |
pmacosta/pcsv | pcsv/csv_file.py | _tofloat | def _tofloat(obj):
"""Convert to float if object is a float string."""
if "inf" in obj.lower().strip():
return obj
try:
return int(obj)
except ValueError:
try:
return float(obj)
except ValueError:
return obj | python | def _tofloat(obj):
"""Convert to float if object is a float string."""
if "inf" in obj.lower().strip():
return obj
try:
return int(obj)
except ValueError:
try:
return float(obj)
except ValueError:
return obj | [
"def",
"_tofloat",
"(",
"obj",
")",
":",
"if",
"\"inf\"",
"in",
"obj",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
":",
"return",
"obj",
"try",
":",
"return",
"int",
"(",
"obj",
")",
"except",
"ValueError",
":",
"try",
":",
"return",
"float",
"(",
"obj",
")",
"except",
"ValueError",
":",
"return",
"obj"
] | Convert to float if object is a float string. | [
"Convert",
"to",
"float",
"if",
"object",
"is",
"a",
"float",
"string",
"."
] | train | https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/csv_file.py#L64-L74 |
pmacosta/pcsv | pcsv/csv_file.py | CsvFile._in_header | def _in_header(self, col):
"""Validate column identifier(s)."""
# pylint: disable=R1704
if not self._has_header:
# Conditionally register exceptions so that they do not appear
# in situations where has_header is always True. In this way
# they are not auto-documented by default
icol_ex = pexdoc.exh.addex(RuntimeError, "Invalid column specification")
hnf_ex = pexdoc.exh.addex(ValueError, "Column *[column_identifier]* not found")
col_list = [col] if isinstance(col, (str, int)) else col
for col in col_list:
edata = {"field": "column_identifier", "value": col}
if not self._has_header:
# Condition not subsumed in raise_exception_if
# so that calls that always have has_header=True
# do not pick up this exception
icol_ex(not isinstance(col, int))
hnf_ex((col < 0) or (col > len(self._header) - 1), edata)
else:
hnf_ex(
(isinstance(col, int) and ((col < 0) or (col > self._data_cols)))
or (
isinstance(col, str) and (col.upper() not in self._header_upper)
),
edata,
)
return col_list | python | def _in_header(self, col):
"""Validate column identifier(s)."""
# pylint: disable=R1704
if not self._has_header:
# Conditionally register exceptions so that they do not appear
# in situations where has_header is always True. In this way
# they are not auto-documented by default
icol_ex = pexdoc.exh.addex(RuntimeError, "Invalid column specification")
hnf_ex = pexdoc.exh.addex(ValueError, "Column *[column_identifier]* not found")
col_list = [col] if isinstance(col, (str, int)) else col
for col in col_list:
edata = {"field": "column_identifier", "value": col}
if not self._has_header:
# Condition not subsumed in raise_exception_if
# so that calls that always have has_header=True
# do not pick up this exception
icol_ex(not isinstance(col, int))
hnf_ex((col < 0) or (col > len(self._header) - 1), edata)
else:
hnf_ex(
(isinstance(col, int) and ((col < 0) or (col > self._data_cols)))
or (
isinstance(col, str) and (col.upper() not in self._header_upper)
),
edata,
)
return col_list | [
"def",
"_in_header",
"(",
"self",
",",
"col",
")",
":",
"# pylint: disable=R1704",
"if",
"not",
"self",
".",
"_has_header",
":",
"# Conditionally register exceptions so that they do not appear",
"# in situations where has_header is always True. In this way",
"# they are not auto-documented by default",
"icol_ex",
"=",
"pexdoc",
".",
"exh",
".",
"addex",
"(",
"RuntimeError",
",",
"\"Invalid column specification\"",
")",
"hnf_ex",
"=",
"pexdoc",
".",
"exh",
".",
"addex",
"(",
"ValueError",
",",
"\"Column *[column_identifier]* not found\"",
")",
"col_list",
"=",
"[",
"col",
"]",
"if",
"isinstance",
"(",
"col",
",",
"(",
"str",
",",
"int",
")",
")",
"else",
"col",
"for",
"col",
"in",
"col_list",
":",
"edata",
"=",
"{",
"\"field\"",
":",
"\"column_identifier\"",
",",
"\"value\"",
":",
"col",
"}",
"if",
"not",
"self",
".",
"_has_header",
":",
"# Condition not subsumed in raise_exception_if",
"# so that calls that always have has_header=True",
"# do not pick up this exception",
"icol_ex",
"(",
"not",
"isinstance",
"(",
"col",
",",
"int",
")",
")",
"hnf_ex",
"(",
"(",
"col",
"<",
"0",
")",
"or",
"(",
"col",
">",
"len",
"(",
"self",
".",
"_header",
")",
"-",
"1",
")",
",",
"edata",
")",
"else",
":",
"hnf_ex",
"(",
"(",
"isinstance",
"(",
"col",
",",
"int",
")",
"and",
"(",
"(",
"col",
"<",
"0",
")",
"or",
"(",
"col",
">",
"self",
".",
"_data_cols",
")",
")",
")",
"or",
"(",
"isinstance",
"(",
"col",
",",
"str",
")",
"and",
"(",
"col",
".",
"upper",
"(",
")",
"not",
"in",
"self",
".",
"_header_upper",
")",
")",
",",
"edata",
",",
")",
"return",
"col_list"
] | Validate column identifier(s). | [
"Validate",
"column",
"identifier",
"(",
"s",
")",
"."
] | train | https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/csv_file.py#L367-L393 |
pmacosta/pcsv | pcsv/csv_file.py | CsvFile._validate_frow | def _validate_frow(self, frow):
"""Validate frow argument."""
is_int = isinstance(frow, int) and (not isinstance(frow, bool))
pexdoc.exh.addai("frow", not (is_int and (frow >= 0)))
return frow | python | def _validate_frow(self, frow):
"""Validate frow argument."""
is_int = isinstance(frow, int) and (not isinstance(frow, bool))
pexdoc.exh.addai("frow", not (is_int and (frow >= 0)))
return frow | [
"def",
"_validate_frow",
"(",
"self",
",",
"frow",
")",
":",
"is_int",
"=",
"isinstance",
"(",
"frow",
",",
"int",
")",
"and",
"(",
"not",
"isinstance",
"(",
"frow",
",",
"bool",
")",
")",
"pexdoc",
".",
"exh",
".",
"addai",
"(",
"\"frow\"",
",",
"not",
"(",
"is_int",
"and",
"(",
"frow",
">=",
"0",
")",
")",
")",
"return",
"frow"
] | Validate frow argument. | [
"Validate",
"frow",
"argument",
"."
] | train | https://github.com/pmacosta/pcsv/blob/cd1588c19b0cd58c38bc672e396db940f88ffbd7/pcsv/csv_file.py#L489-L493 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.