id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
6,900
bsmurphy/PyKrige
pykrige/core.py
_adjust_for_anisotropy
def _adjust_for_anisotropy(X, center, scaling, angle): """Adjusts data coordinates to take into account anisotropy. Can also be used to take into account data scaling. Angles are CCW about specified axes. Scaling is applied in rotated coordinate system. Parameters ---------- X : ndarray float array [n_samples, n_dim], the input array of coordinates center : ndarray float array [n_dim], the coordinate of centers scaling : ndarray float array [n_dim - 1], the scaling of last two dimensions angle : ndarray float array [2*n_dim - 3], the anisotropy angle (degrees) Returns ------- X_adj : ndarray float array [n_samples, n_dim], the X array adjusted for anisotropy. """ center = np.asarray(center)[None, :] angle = np.asarray(angle)*np.pi/180 X -= center Ndim = X.shape[1] if Ndim == 1: raise NotImplementedError('Not implemnented yet?') elif Ndim == 2: stretch = np.array([[1, 0], [0, scaling[0]]]) rot_tot = np.array([[np.cos(-angle[0]), -np.sin(-angle[0])], [np.sin(-angle[0]), np.cos(-angle[0])]]) elif Ndim == 3: stretch = np.array([[1., 0., 0.], [0., scaling[0], 0.], [0., 0., scaling[1]]]) rotate_x = np.array([[1., 0., 0.], [0., np.cos(-angle[0]), -np.sin(-angle[0])], [0., np.sin(-angle[0]), np.cos(-angle[0])]]) rotate_y = np.array([[np.cos(-angle[1]), 0., np.sin(-angle[1])], [0., 1., 0.], [-np.sin(-angle[1]), 0., np.cos(-angle[1])]]) rotate_z = np.array([[np.cos(-angle[2]), -np.sin(-angle[2]), 0.], [np.sin(-angle[2]), np.cos(-angle[2]), 0.], [0., 0., 1.]]) rot_tot = np.dot(rotate_z, np.dot(rotate_y, rotate_x)) else: raise ValueError("Adjust for anisotropy function doesn't " "support ND spaces where N>3") X_adj = np.dot(stretch, np.dot(rot_tot, X.T)).T X_adj += center return X_adj
python
def _adjust_for_anisotropy(X, center, scaling, angle): """Adjusts data coordinates to take into account anisotropy. Can also be used to take into account data scaling. Angles are CCW about specified axes. Scaling is applied in rotated coordinate system. Parameters ---------- X : ndarray float array [n_samples, n_dim], the input array of coordinates center : ndarray float array [n_dim], the coordinate of centers scaling : ndarray float array [n_dim - 1], the scaling of last two dimensions angle : ndarray float array [2*n_dim - 3], the anisotropy angle (degrees) Returns ------- X_adj : ndarray float array [n_samples, n_dim], the X array adjusted for anisotropy. """ center = np.asarray(center)[None, :] angle = np.asarray(angle)*np.pi/180 X -= center Ndim = X.shape[1] if Ndim == 1: raise NotImplementedError('Not implemnented yet?') elif Ndim == 2: stretch = np.array([[1, 0], [0, scaling[0]]]) rot_tot = np.array([[np.cos(-angle[0]), -np.sin(-angle[0])], [np.sin(-angle[0]), np.cos(-angle[0])]]) elif Ndim == 3: stretch = np.array([[1., 0., 0.], [0., scaling[0], 0.], [0., 0., scaling[1]]]) rotate_x = np.array([[1., 0., 0.], [0., np.cos(-angle[0]), -np.sin(-angle[0])], [0., np.sin(-angle[0]), np.cos(-angle[0])]]) rotate_y = np.array([[np.cos(-angle[1]), 0., np.sin(-angle[1])], [0., 1., 0.], [-np.sin(-angle[1]), 0., np.cos(-angle[1])]]) rotate_z = np.array([[np.cos(-angle[2]), -np.sin(-angle[2]), 0.], [np.sin(-angle[2]), np.cos(-angle[2]), 0.], [0., 0., 1.]]) rot_tot = np.dot(rotate_z, np.dot(rotate_y, rotate_x)) else: raise ValueError("Adjust for anisotropy function doesn't " "support ND spaces where N>3") X_adj = np.dot(stretch, np.dot(rot_tot, X.T)).T X_adj += center return X_adj
[ "def", "_adjust_for_anisotropy", "(", "X", ",", "center", ",", "scaling", ",", "angle", ")", ":", "center", "=", "np", ".", "asarray", "(", "center", ")", "[", "None", ",", ":", "]", "angle", "=", "np", ".", "asarray", "(", "angle", ")", "*", "np", ".", "pi", "/", "180", "X", "-=", "center", "Ndim", "=", "X", ".", "shape", "[", "1", "]", "if", "Ndim", "==", "1", ":", "raise", "NotImplementedError", "(", "'Not implemnented yet?'", ")", "elif", "Ndim", "==", "2", ":", "stretch", "=", "np", ".", "array", "(", "[", "[", "1", ",", "0", "]", ",", "[", "0", ",", "scaling", "[", "0", "]", "]", "]", ")", "rot_tot", "=", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "-", "angle", "[", "0", "]", ")", ",", "-", "np", ".", "sin", "(", "-", "angle", "[", "0", "]", ")", "]", ",", "[", "np", ".", "sin", "(", "-", "angle", "[", "0", "]", ")", ",", "np", ".", "cos", "(", "-", "angle", "[", "0", "]", ")", "]", "]", ")", "elif", "Ndim", "==", "3", ":", "stretch", "=", "np", ".", "array", "(", "[", "[", "1.", ",", "0.", ",", "0.", "]", ",", "[", "0.", ",", "scaling", "[", "0", "]", ",", "0.", "]", ",", "[", "0.", ",", "0.", ",", "scaling", "[", "1", "]", "]", "]", ")", "rotate_x", "=", "np", ".", "array", "(", "[", "[", "1.", ",", "0.", ",", "0.", "]", ",", "[", "0.", ",", "np", ".", "cos", "(", "-", "angle", "[", "0", "]", ")", ",", "-", "np", ".", "sin", "(", "-", "angle", "[", "0", "]", ")", "]", ",", "[", "0.", ",", "np", ".", "sin", "(", "-", "angle", "[", "0", "]", ")", ",", "np", ".", "cos", "(", "-", "angle", "[", "0", "]", ")", "]", "]", ")", "rotate_y", "=", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "-", "angle", "[", "1", "]", ")", ",", "0.", ",", "np", ".", "sin", "(", "-", "angle", "[", "1", "]", ")", "]", ",", "[", "0.", ",", "1.", ",", "0.", "]", ",", "[", "-", "np", ".", "sin", "(", "-", "angle", "[", "1", "]", ")", ",", "0.", ",", "np", ".", "cos", "(", "-", "angle", "[", "1", "]", ")", "]", "]", ")", "rotate_z", "=", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "-", "angle", "[", "2", "]", ")", ",", "-", "np", ".", "sin", "(", "-", "angle", "[", "2", "]", ")", ",", "0.", "]", ",", "[", "np", ".", "sin", "(", "-", "angle", "[", "2", "]", ")", ",", "np", ".", "cos", "(", "-", "angle", "[", "2", "]", ")", ",", "0.", "]", ",", "[", "0.", ",", "0.", ",", "1.", "]", "]", ")", "rot_tot", "=", "np", ".", "dot", "(", "rotate_z", ",", "np", ".", "dot", "(", "rotate_y", ",", "rotate_x", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Adjust for anisotropy function doesn't \"", "\"support ND spaces where N>3\"", ")", "X_adj", "=", "np", ".", "dot", "(", "stretch", ",", "np", ".", "dot", "(", "rot_tot", ",", "X", ".", "T", ")", ")", ".", "T", "X_adj", "+=", "center", "return", "X_adj" ]
Adjusts data coordinates to take into account anisotropy. Can also be used to take into account data scaling. Angles are CCW about specified axes. Scaling is applied in rotated coordinate system. Parameters ---------- X : ndarray float array [n_samples, n_dim], the input array of coordinates center : ndarray float array [n_dim], the coordinate of centers scaling : ndarray float array [n_dim - 1], the scaling of last two dimensions angle : ndarray float array [2*n_dim - 3], the anisotropy angle (degrees) Returns ------- X_adj : ndarray float array [n_samples, n_dim], the X array adjusted for anisotropy.
[ "Adjusts", "data", "coordinates", "to", "take", "into", "account", "anisotropy", ".", "Can", "also", "be", "used", "to", "take", "into", "account", "data", "scaling", ".", "Angles", "are", "CCW", "about", "specified", "axes", ".", "Scaling", "is", "applied", "in", "rotated", "coordinate", "system", "." ]
a4db3003b0b5688658c12faeb95a5a8b2b14b433
https://github.com/bsmurphy/PyKrige/blob/a4db3003b0b5688658c12faeb95a5a8b2b14b433/pykrige/core.py#L113-L167
6,901
bsmurphy/PyKrige
pykrige/core.py
_calculate_variogram_model
def _calculate_variogram_model(lags, semivariance, variogram_model, variogram_function, weight): """Function that fits a variogram model when parameters are not specified. Returns variogram model parameters that minimize the RMSE between the specified variogram function and the actual calculated variogram points. Parameters ---------- lags: 1d array binned lags/distances to use for variogram model parameter estimation semivariance: 1d array binned/averaged experimental semivariances to use for variogram model parameter estimation variogram_model: str/unicode specified variogram model to use for parameter estimation variogram_function: callable the actual funtion that evaluates the model variogram weight: bool flag for implementing the crude weighting routine, used in order to fit smaller lags better this is passed on to the residual calculation cfunction, where weighting is actually applied... Returns ------- res: list list of estimated variogram model parameters NOTE that the estimation routine works in terms of the partial sill (psill = sill - nugget) -- setting bounds such that psill > 0 ensures that the sill will always be greater than the nugget... """ if variogram_model == 'linear': x0 = [(np.amax(semivariance) - np.amin(semivariance)) / (np.amax(lags) - np.amin(lags)), np.amin(semivariance)] bnds = ([0., 0.], [np.inf, np.amax(semivariance)]) elif variogram_model == 'power': x0 = [(np.amax(semivariance) - np.amin(semivariance)) / (np.amax(lags) - np.amin(lags)), 1.1, np.amin(semivariance)] bnds = ([0., 0.001, 0.], [np.inf, 1.999, np.amax(semivariance)]) else: x0 = [np.amax(semivariance) - np.amin(semivariance), 0.25*np.amax(lags), np.amin(semivariance)] bnds = ([0., 0., 0.], [10.*np.amax(semivariance), np.amax(lags), np.amax(semivariance)]) # use 'soft' L1-norm minimization in order to buffer against # potential outliers (weird/skewed points) res = least_squares(_variogram_residuals, x0, bounds=bnds, loss='soft_l1', args=(lags, semivariance, variogram_function, weight)) return res.x
python
def _calculate_variogram_model(lags, semivariance, variogram_model, variogram_function, weight): """Function that fits a variogram model when parameters are not specified. Returns variogram model parameters that minimize the RMSE between the specified variogram function and the actual calculated variogram points. Parameters ---------- lags: 1d array binned lags/distances to use for variogram model parameter estimation semivariance: 1d array binned/averaged experimental semivariances to use for variogram model parameter estimation variogram_model: str/unicode specified variogram model to use for parameter estimation variogram_function: callable the actual funtion that evaluates the model variogram weight: bool flag for implementing the crude weighting routine, used in order to fit smaller lags better this is passed on to the residual calculation cfunction, where weighting is actually applied... Returns ------- res: list list of estimated variogram model parameters NOTE that the estimation routine works in terms of the partial sill (psill = sill - nugget) -- setting bounds such that psill > 0 ensures that the sill will always be greater than the nugget... """ if variogram_model == 'linear': x0 = [(np.amax(semivariance) - np.amin(semivariance)) / (np.amax(lags) - np.amin(lags)), np.amin(semivariance)] bnds = ([0., 0.], [np.inf, np.amax(semivariance)]) elif variogram_model == 'power': x0 = [(np.amax(semivariance) - np.amin(semivariance)) / (np.amax(lags) - np.amin(lags)), 1.1, np.amin(semivariance)] bnds = ([0., 0.001, 0.], [np.inf, 1.999, np.amax(semivariance)]) else: x0 = [np.amax(semivariance) - np.amin(semivariance), 0.25*np.amax(lags), np.amin(semivariance)] bnds = ([0., 0., 0.], [10.*np.amax(semivariance), np.amax(lags), np.amax(semivariance)]) # use 'soft' L1-norm minimization in order to buffer against # potential outliers (weird/skewed points) res = least_squares(_variogram_residuals, x0, bounds=bnds, loss='soft_l1', args=(lags, semivariance, variogram_function, weight)) return res.x
[ "def", "_calculate_variogram_model", "(", "lags", ",", "semivariance", ",", "variogram_model", ",", "variogram_function", ",", "weight", ")", ":", "if", "variogram_model", "==", "'linear'", ":", "x0", "=", "[", "(", "np", ".", "amax", "(", "semivariance", ")", "-", "np", ".", "amin", "(", "semivariance", ")", ")", "/", "(", "np", ".", "amax", "(", "lags", ")", "-", "np", ".", "amin", "(", "lags", ")", ")", ",", "np", ".", "amin", "(", "semivariance", ")", "]", "bnds", "=", "(", "[", "0.", ",", "0.", "]", ",", "[", "np", ".", "inf", ",", "np", ".", "amax", "(", "semivariance", ")", "]", ")", "elif", "variogram_model", "==", "'power'", ":", "x0", "=", "[", "(", "np", ".", "amax", "(", "semivariance", ")", "-", "np", ".", "amin", "(", "semivariance", ")", ")", "/", "(", "np", ".", "amax", "(", "lags", ")", "-", "np", ".", "amin", "(", "lags", ")", ")", ",", "1.1", ",", "np", ".", "amin", "(", "semivariance", ")", "]", "bnds", "=", "(", "[", "0.", ",", "0.001", ",", "0.", "]", ",", "[", "np", ".", "inf", ",", "1.999", ",", "np", ".", "amax", "(", "semivariance", ")", "]", ")", "else", ":", "x0", "=", "[", "np", ".", "amax", "(", "semivariance", ")", "-", "np", ".", "amin", "(", "semivariance", ")", ",", "0.25", "*", "np", ".", "amax", "(", "lags", ")", ",", "np", ".", "amin", "(", "semivariance", ")", "]", "bnds", "=", "(", "[", "0.", ",", "0.", ",", "0.", "]", ",", "[", "10.", "*", "np", ".", "amax", "(", "semivariance", ")", ",", "np", ".", "amax", "(", "lags", ")", ",", "np", ".", "amax", "(", "semivariance", ")", "]", ")", "# use 'soft' L1-norm minimization in order to buffer against", "# potential outliers (weird/skewed points)", "res", "=", "least_squares", "(", "_variogram_residuals", ",", "x0", ",", "bounds", "=", "bnds", ",", "loss", "=", "'soft_l1'", ",", "args", "=", "(", "lags", ",", "semivariance", ",", "variogram_function", ",", "weight", ")", ")", "return", "res", ".", "x" ]
Function that fits a variogram model when parameters are not specified. Returns variogram model parameters that minimize the RMSE between the specified variogram function and the actual calculated variogram points. Parameters ---------- lags: 1d array binned lags/distances to use for variogram model parameter estimation semivariance: 1d array binned/averaged experimental semivariances to use for variogram model parameter estimation variogram_model: str/unicode specified variogram model to use for parameter estimation variogram_function: callable the actual funtion that evaluates the model variogram weight: bool flag for implementing the crude weighting routine, used in order to fit smaller lags better this is passed on to the residual calculation cfunction, where weighting is actually applied... Returns ------- res: list list of estimated variogram model parameters NOTE that the estimation routine works in terms of the partial sill (psill = sill - nugget) -- setting bounds such that psill > 0 ensures that the sill will always be greater than the nugget...
[ "Function", "that", "fits", "a", "variogram", "model", "when", "parameters", "are", "not", "specified", ".", "Returns", "variogram", "model", "parameters", "that", "minimize", "the", "RMSE", "between", "the", "specified", "variogram", "function", "and", "the", "actual", "calculated", "variogram", "points", "." ]
a4db3003b0b5688658c12faeb95a5a8b2b14b433
https://github.com/bsmurphy/PyKrige/blob/a4db3003b0b5688658c12faeb95a5a8b2b14b433/pykrige/core.py#L531-L582
6,902
bsmurphy/PyKrige
pykrige/core.py
_krige
def _krige(X, y, coords, variogram_function, variogram_model_parameters, coordinates_type): """Sets up and solves the ordinary kriging system for the given coordinate pair. This function is only used for the statistics calculations. Parameters ---------- X: ndarray float array [n_samples, n_dim], the input array of coordinates y: ndarray float array [n_samples], the input array of measurement values coords: ndarray float array [1, n_dim], point at which to evaluate the kriging system variogram_function: callable function that will be called to evaluate variogram model variogram_model_parameters: list user-specified parameters for variogram model coordinates_type: str type of coordinates in X array, can be 'euclidean' for standard rectangular coordinates or 'geographic' if the coordinates are lat/lon Returns ------- zinterp: float kriging estimate at the specified point sigmasq: float mean square error of the kriging estimate """ zero_index = None zero_value = False # calculate distance between points... need a square distance matrix # of inter-measurement-point distances and a vector of distances between # measurement points (X) and the kriging point (coords) if coordinates_type == 'euclidean': d = squareform(pdist(X, metric='euclidean')) bd = np.squeeze(cdist(X, coords[None, :], metric='euclidean')) # geographic coordinate distances still calculated in the old way... # assume X[:, 0] ('x') => lon, X[:, 1] ('y') => lat # also assume problem is 2D; check done earlier in initializing variogram elif coordinates_type == 'geographic': x1, x2 = np.meshgrid(X[:, 0], X[:, 0], sparse=True) y1, y2 = np.meshgrid(X[:, 1], X[:, 1], sparse=True) d = great_circle_distance(x1, y1, x2, y2) bd = great_circle_distance(X[:, 0], X[:, 1], coords[0] * np.ones(X.shape[0]), coords[1] * np.ones(X.shape[0])) # this check is done when initializing variogram, but kept here anyways... else: raise ValueError("Specified coordinate type '%s' " "is not supported." % coordinates_type) # check if kriging point overlaps with measurement point if np.any(np.absolute(bd) <= 1e-10): zero_value = True zero_index = np.where(bd <= 1e-10)[0][0] # set up kriging matrix n = X.shape[0] a = np.zeros((n+1, n+1)) a[:n, :n] = - variogram_function(variogram_model_parameters, d) np.fill_diagonal(a, 0.0) a[n, :] = 1.0 a[:, n] = 1.0 a[n, n] = 0.0 # set up RHS b = np.zeros((n+1, 1)) b[:n, 0] = - variogram_function(variogram_model_parameters, bd) if zero_value: b[zero_index, 0] = 0.0 b[n, 0] = 1.0 # solve res = np.linalg.solve(a, b) zinterp = np.sum(res[:n, 0] * y) sigmasq = np.sum(res[:, 0] * -b[:, 0]) return zinterp, sigmasq
python
def _krige(X, y, coords, variogram_function, variogram_model_parameters, coordinates_type): """Sets up and solves the ordinary kriging system for the given coordinate pair. This function is only used for the statistics calculations. Parameters ---------- X: ndarray float array [n_samples, n_dim], the input array of coordinates y: ndarray float array [n_samples], the input array of measurement values coords: ndarray float array [1, n_dim], point at which to evaluate the kriging system variogram_function: callable function that will be called to evaluate variogram model variogram_model_parameters: list user-specified parameters for variogram model coordinates_type: str type of coordinates in X array, can be 'euclidean' for standard rectangular coordinates or 'geographic' if the coordinates are lat/lon Returns ------- zinterp: float kriging estimate at the specified point sigmasq: float mean square error of the kriging estimate """ zero_index = None zero_value = False # calculate distance between points... need a square distance matrix # of inter-measurement-point distances and a vector of distances between # measurement points (X) and the kriging point (coords) if coordinates_type == 'euclidean': d = squareform(pdist(X, metric='euclidean')) bd = np.squeeze(cdist(X, coords[None, :], metric='euclidean')) # geographic coordinate distances still calculated in the old way... # assume X[:, 0] ('x') => lon, X[:, 1] ('y') => lat # also assume problem is 2D; check done earlier in initializing variogram elif coordinates_type == 'geographic': x1, x2 = np.meshgrid(X[:, 0], X[:, 0], sparse=True) y1, y2 = np.meshgrid(X[:, 1], X[:, 1], sparse=True) d = great_circle_distance(x1, y1, x2, y2) bd = great_circle_distance(X[:, 0], X[:, 1], coords[0] * np.ones(X.shape[0]), coords[1] * np.ones(X.shape[0])) # this check is done when initializing variogram, but kept here anyways... else: raise ValueError("Specified coordinate type '%s' " "is not supported." % coordinates_type) # check if kriging point overlaps with measurement point if np.any(np.absolute(bd) <= 1e-10): zero_value = True zero_index = np.where(bd <= 1e-10)[0][0] # set up kriging matrix n = X.shape[0] a = np.zeros((n+1, n+1)) a[:n, :n] = - variogram_function(variogram_model_parameters, d) np.fill_diagonal(a, 0.0) a[n, :] = 1.0 a[:, n] = 1.0 a[n, n] = 0.0 # set up RHS b = np.zeros((n+1, 1)) b[:n, 0] = - variogram_function(variogram_model_parameters, bd) if zero_value: b[zero_index, 0] = 0.0 b[n, 0] = 1.0 # solve res = np.linalg.solve(a, b) zinterp = np.sum(res[:n, 0] * y) sigmasq = np.sum(res[:, 0] * -b[:, 0]) return zinterp, sigmasq
[ "def", "_krige", "(", "X", ",", "y", ",", "coords", ",", "variogram_function", ",", "variogram_model_parameters", ",", "coordinates_type", ")", ":", "zero_index", "=", "None", "zero_value", "=", "False", "# calculate distance between points... need a square distance matrix", "# of inter-measurement-point distances and a vector of distances between", "# measurement points (X) and the kriging point (coords)", "if", "coordinates_type", "==", "'euclidean'", ":", "d", "=", "squareform", "(", "pdist", "(", "X", ",", "metric", "=", "'euclidean'", ")", ")", "bd", "=", "np", ".", "squeeze", "(", "cdist", "(", "X", ",", "coords", "[", "None", ",", ":", "]", ",", "metric", "=", "'euclidean'", ")", ")", "# geographic coordinate distances still calculated in the old way...", "# assume X[:, 0] ('x') => lon, X[:, 1] ('y') => lat", "# also assume problem is 2D; check done earlier in initializing variogram", "elif", "coordinates_type", "==", "'geographic'", ":", "x1", ",", "x2", "=", "np", ".", "meshgrid", "(", "X", "[", ":", ",", "0", "]", ",", "X", "[", ":", ",", "0", "]", ",", "sparse", "=", "True", ")", "y1", ",", "y2", "=", "np", ".", "meshgrid", "(", "X", "[", ":", ",", "1", "]", ",", "X", "[", ":", ",", "1", "]", ",", "sparse", "=", "True", ")", "d", "=", "great_circle_distance", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", "bd", "=", "great_circle_distance", "(", "X", "[", ":", ",", "0", "]", ",", "X", "[", ":", ",", "1", "]", ",", "coords", "[", "0", "]", "*", "np", ".", "ones", "(", "X", ".", "shape", "[", "0", "]", ")", ",", "coords", "[", "1", "]", "*", "np", ".", "ones", "(", "X", ".", "shape", "[", "0", "]", ")", ")", "# this check is done when initializing variogram, but kept here anyways...", "else", ":", "raise", "ValueError", "(", "\"Specified coordinate type '%s' \"", "\"is not supported.\"", "%", "coordinates_type", ")", "# check if kriging point overlaps with measurement point", "if", "np", ".", "any", "(", "np", ".", "absolute", "(", "bd", ")", "<=", "1e-10", ")", ":", "zero_value", "=", "True", "zero_index", "=", "np", ".", "where", "(", "bd", "<=", "1e-10", ")", "[", "0", "]", "[", "0", "]", "# set up kriging matrix", "n", "=", "X", ".", "shape", "[", "0", "]", "a", "=", "np", ".", "zeros", "(", "(", "n", "+", "1", ",", "n", "+", "1", ")", ")", "a", "[", ":", "n", ",", ":", "n", "]", "=", "-", "variogram_function", "(", "variogram_model_parameters", ",", "d", ")", "np", ".", "fill_diagonal", "(", "a", ",", "0.0", ")", "a", "[", "n", ",", ":", "]", "=", "1.0", "a", "[", ":", ",", "n", "]", "=", "1.0", "a", "[", "n", ",", "n", "]", "=", "0.0", "# set up RHS", "b", "=", "np", ".", "zeros", "(", "(", "n", "+", "1", ",", "1", ")", ")", "b", "[", ":", "n", ",", "0", "]", "=", "-", "variogram_function", "(", "variogram_model_parameters", ",", "bd", ")", "if", "zero_value", ":", "b", "[", "zero_index", ",", "0", "]", "=", "0.0", "b", "[", "n", ",", "0", "]", "=", "1.0", "# solve", "res", "=", "np", ".", "linalg", ".", "solve", "(", "a", ",", "b", ")", "zinterp", "=", "np", ".", "sum", "(", "res", "[", ":", "n", ",", "0", "]", "*", "y", ")", "sigmasq", "=", "np", ".", "sum", "(", "res", "[", ":", ",", "0", "]", "*", "-", "b", "[", ":", ",", "0", "]", ")", "return", "zinterp", ",", "sigmasq" ]
Sets up and solves the ordinary kriging system for the given coordinate pair. This function is only used for the statistics calculations. Parameters ---------- X: ndarray float array [n_samples, n_dim], the input array of coordinates y: ndarray float array [n_samples], the input array of measurement values coords: ndarray float array [1, n_dim], point at which to evaluate the kriging system variogram_function: callable function that will be called to evaluate variogram model variogram_model_parameters: list user-specified parameters for variogram model coordinates_type: str type of coordinates in X array, can be 'euclidean' for standard rectangular coordinates or 'geographic' if the coordinates are lat/lon Returns ------- zinterp: float kriging estimate at the specified point sigmasq: float mean square error of the kriging estimate
[ "Sets", "up", "and", "solves", "the", "ordinary", "kriging", "system", "for", "the", "given", "coordinate", "pair", ".", "This", "function", "is", "only", "used", "for", "the", "statistics", "calculations", "." ]
a4db3003b0b5688658c12faeb95a5a8b2b14b433
https://github.com/bsmurphy/PyKrige/blob/a4db3003b0b5688658c12faeb95a5a8b2b14b433/pykrige/core.py#L585-L666
6,903
bsmurphy/PyKrige
pykrige/core.py
_find_statistics
def _find_statistics(X, y, variogram_function, variogram_model_parameters, coordinates_type): """Calculates variogram fit statistics. Returns the delta, sigma, and epsilon values for the variogram fit. These arrays are used for statistics calculations. Parameters ---------- X: ndarray float array [n_samples, n_dim], the input array of coordinates y: ndarray float array [n_samples], the input array of measurement values variogram_function: callable function that will be called to evaluate variogram model variogram_model_parameters: list user-specified parameters for variogram model coordinates_type: str type of coordinates in X array, can be 'euclidean' for standard rectangular coordinates or 'geographic' if the coordinates are lat/lon Returns ------- delta: ndarray residuals between observed values and kriged estimates for those values sigma: ndarray mean error in kriging estimates epsilon: ndarray residuals normalized by their mean error """ delta = np.zeros(y.shape) sigma = np.zeros(y.shape) for i in range(y.shape[0]): # skip the first value in the kriging problem if i == 0: continue else: k, ss = _krige(X[:i, :], y[:i], X[i, :], variogram_function, variogram_model_parameters, coordinates_type) # if the estimation error is zero, it's probably because # the evaluation point X[i, :] is really close to one of the # kriging system points in X[:i, :]... # in the case of zero estimation error, the results are not stored if np.absolute(ss) < eps: continue delta[i] = y[i] - k sigma[i] = np.sqrt(ss) # only use non-zero entries in these arrays... sigma is used to pull out # non-zero entries in both cases because it is guaranteed to be positive, # whereas delta can be either positive or negative delta = delta[sigma > eps] sigma = sigma[sigma > eps] epsilon = delta/sigma return delta, sigma, epsilon
python
def _find_statistics(X, y, variogram_function, variogram_model_parameters, coordinates_type): """Calculates variogram fit statistics. Returns the delta, sigma, and epsilon values for the variogram fit. These arrays are used for statistics calculations. Parameters ---------- X: ndarray float array [n_samples, n_dim], the input array of coordinates y: ndarray float array [n_samples], the input array of measurement values variogram_function: callable function that will be called to evaluate variogram model variogram_model_parameters: list user-specified parameters for variogram model coordinates_type: str type of coordinates in X array, can be 'euclidean' for standard rectangular coordinates or 'geographic' if the coordinates are lat/lon Returns ------- delta: ndarray residuals between observed values and kriged estimates for those values sigma: ndarray mean error in kriging estimates epsilon: ndarray residuals normalized by their mean error """ delta = np.zeros(y.shape) sigma = np.zeros(y.shape) for i in range(y.shape[0]): # skip the first value in the kriging problem if i == 0: continue else: k, ss = _krige(X[:i, :], y[:i], X[i, :], variogram_function, variogram_model_parameters, coordinates_type) # if the estimation error is zero, it's probably because # the evaluation point X[i, :] is really close to one of the # kriging system points in X[:i, :]... # in the case of zero estimation error, the results are not stored if np.absolute(ss) < eps: continue delta[i] = y[i] - k sigma[i] = np.sqrt(ss) # only use non-zero entries in these arrays... sigma is used to pull out # non-zero entries in both cases because it is guaranteed to be positive, # whereas delta can be either positive or negative delta = delta[sigma > eps] sigma = sigma[sigma > eps] epsilon = delta/sigma return delta, sigma, epsilon
[ "def", "_find_statistics", "(", "X", ",", "y", ",", "variogram_function", ",", "variogram_model_parameters", ",", "coordinates_type", ")", ":", "delta", "=", "np", ".", "zeros", "(", "y", ".", "shape", ")", "sigma", "=", "np", ".", "zeros", "(", "y", ".", "shape", ")", "for", "i", "in", "range", "(", "y", ".", "shape", "[", "0", "]", ")", ":", "# skip the first value in the kriging problem", "if", "i", "==", "0", ":", "continue", "else", ":", "k", ",", "ss", "=", "_krige", "(", "X", "[", ":", "i", ",", ":", "]", ",", "y", "[", ":", "i", "]", ",", "X", "[", "i", ",", ":", "]", ",", "variogram_function", ",", "variogram_model_parameters", ",", "coordinates_type", ")", "# if the estimation error is zero, it's probably because", "# the evaluation point X[i, :] is really close to one of the", "# kriging system points in X[:i, :]...", "# in the case of zero estimation error, the results are not stored", "if", "np", ".", "absolute", "(", "ss", ")", "<", "eps", ":", "continue", "delta", "[", "i", "]", "=", "y", "[", "i", "]", "-", "k", "sigma", "[", "i", "]", "=", "np", ".", "sqrt", "(", "ss", ")", "# only use non-zero entries in these arrays... sigma is used to pull out", "# non-zero entries in both cases because it is guaranteed to be positive,", "# whereas delta can be either positive or negative", "delta", "=", "delta", "[", "sigma", ">", "eps", "]", "sigma", "=", "sigma", "[", "sigma", ">", "eps", "]", "epsilon", "=", "delta", "/", "sigma", "return", "delta", ",", "sigma", ",", "epsilon" ]
Calculates variogram fit statistics. Returns the delta, sigma, and epsilon values for the variogram fit. These arrays are used for statistics calculations. Parameters ---------- X: ndarray float array [n_samples, n_dim], the input array of coordinates y: ndarray float array [n_samples], the input array of measurement values variogram_function: callable function that will be called to evaluate variogram model variogram_model_parameters: list user-specified parameters for variogram model coordinates_type: str type of coordinates in X array, can be 'euclidean' for standard rectangular coordinates or 'geographic' if the coordinates are lat/lon Returns ------- delta: ndarray residuals between observed values and kriged estimates for those values sigma: ndarray mean error in kriging estimates epsilon: ndarray residuals normalized by their mean error
[ "Calculates", "variogram", "fit", "statistics", ".", "Returns", "the", "delta", "sigma", "and", "epsilon", "values", "for", "the", "variogram", "fit", ".", "These", "arrays", "are", "used", "for", "statistics", "calculations", "." ]
a4db3003b0b5688658c12faeb95a5a8b2b14b433
https://github.com/bsmurphy/PyKrige/blob/a4db3003b0b5688658c12faeb95a5a8b2b14b433/pykrige/core.py#L669-L729
6,904
bsmurphy/PyKrige
pykrige/rk.py
RegressionKriging.fit
def fit(self, p, x, y): """ fit the regression method and also Krige the residual Parameters ---------- p: ndarray (Ns, d) array of predictor variables (Ns samples, d dimensions) for regression x: ndarray ndarray of (x, y) points. Needs to be a (Ns, 2) array corresponding to the lon/lat, for example 2d regression kriging. array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging y: ndarray array of targets (Ns, ) """ self.regression_model.fit(p, y) ml_pred = self.regression_model.predict(p) print('Finished learning regression model') # residual=y-ml_pred self.krige.fit(x=x, y=y - ml_pred) print('Finished kriging residuals')
python
def fit(self, p, x, y): """ fit the regression method and also Krige the residual Parameters ---------- p: ndarray (Ns, d) array of predictor variables (Ns samples, d dimensions) for regression x: ndarray ndarray of (x, y) points. Needs to be a (Ns, 2) array corresponding to the lon/lat, for example 2d regression kriging. array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging y: ndarray array of targets (Ns, ) """ self.regression_model.fit(p, y) ml_pred = self.regression_model.predict(p) print('Finished learning regression model') # residual=y-ml_pred self.krige.fit(x=x, y=y - ml_pred) print('Finished kriging residuals')
[ "def", "fit", "(", "self", ",", "p", ",", "x", ",", "y", ")", ":", "self", ".", "regression_model", ".", "fit", "(", "p", ",", "y", ")", "ml_pred", "=", "self", ".", "regression_model", ".", "predict", "(", "p", ")", "print", "(", "'Finished learning regression model'", ")", "# residual=y-ml_pred", "self", ".", "krige", ".", "fit", "(", "x", "=", "x", ",", "y", "=", "y", "-", "ml_pred", ")", "print", "(", "'Finished kriging residuals'", ")" ]
fit the regression method and also Krige the residual Parameters ---------- p: ndarray (Ns, d) array of predictor variables (Ns samples, d dimensions) for regression x: ndarray ndarray of (x, y) points. Needs to be a (Ns, 2) array corresponding to the lon/lat, for example 2d regression kriging. array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging y: ndarray array of targets (Ns, )
[ "fit", "the", "regression", "method", "and", "also", "Krige", "the", "residual" ]
a4db3003b0b5688658c12faeb95a5a8b2b14b433
https://github.com/bsmurphy/PyKrige/blob/a4db3003b0b5688658c12faeb95a5a8b2b14b433/pykrige/rk.py#L195-L216
6,905
bsmurphy/PyKrige
pykrige/rk.py
RegressionKriging.score
def score(self, p, x, y, sample_weight=None): """ Overloading default regression score method Parameters ---------- p: ndarray (Ns, d) array of predictor variables (Ns samples, d dimensions) for regression x: ndarray ndarray of (x, y) points. Needs to be a (Ns, 2) array corresponding to the lon/lat, for example. array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging y: ndarray array of targets (Ns, ) """ return r2_score(y_pred=self.predict(p, x), y_true=y, sample_weight=sample_weight)
python
def score(self, p, x, y, sample_weight=None): """ Overloading default regression score method Parameters ---------- p: ndarray (Ns, d) array of predictor variables (Ns samples, d dimensions) for regression x: ndarray ndarray of (x, y) points. Needs to be a (Ns, 2) array corresponding to the lon/lat, for example. array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging y: ndarray array of targets (Ns, ) """ return r2_score(y_pred=self.predict(p, x), y_true=y, sample_weight=sample_weight)
[ "def", "score", "(", "self", ",", "p", ",", "x", ",", "y", ",", "sample_weight", "=", "None", ")", ":", "return", "r2_score", "(", "y_pred", "=", "self", ".", "predict", "(", "p", ",", "x", ")", ",", "y_true", "=", "y", ",", "sample_weight", "=", "sample_weight", ")" ]
Overloading default regression score method Parameters ---------- p: ndarray (Ns, d) array of predictor variables (Ns samples, d dimensions) for regression x: ndarray ndarray of (x, y) points. Needs to be a (Ns, 2) array corresponding to the lon/lat, for example. array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging y: ndarray array of targets (Ns, )
[ "Overloading", "default", "regression", "score", "method" ]
a4db3003b0b5688658c12faeb95a5a8b2b14b433
https://github.com/bsmurphy/PyKrige/blob/a4db3003b0b5688658c12faeb95a5a8b2b14b433/pykrige/rk.py#L254-L273
6,906
bsmurphy/PyKrige
pykrige/ok3d.py
OrdinaryKriging3D._exec_loop_moving_window
def _exec_loop_moving_window(self, a_all, bd_all, mask, bd_idx): """Solves the kriging system by looping over all specified points. Uses only a certain number of closest points. Not very memory intensive, but the loop is done in pure Python. """ import scipy.linalg.lapack npt = bd_all.shape[0] n = bd_idx.shape[1] kvalues = np.zeros(npt) sigmasq = np.zeros(npt) for i in np.nonzero(~mask)[0]: b_selector = bd_idx[i] bd = bd_all[i] a_selector = np.concatenate((b_selector, np.array([a_all.shape[0] - 1]))) a = a_all[a_selector[:, None], a_selector] if np.any(np.absolute(bd) <= self.eps): zero_value = True zero_index = np.where(np.absolute(bd) <= self.eps) else: zero_value = False zero_index = None b = np.zeros((n+1, 1)) b[:n, 0] = - self.variogram_function(self.variogram_model_parameters, bd) if zero_value: b[zero_index[0], 0] = 0.0 b[n, 0] = 1.0 x = scipy.linalg.solve(a, b) kvalues[i] = x[:n, 0].dot(self.VALUES[b_selector]) sigmasq[i] = - x[:, 0].dot(b[:, 0]) return kvalues, sigmasq
python
def _exec_loop_moving_window(self, a_all, bd_all, mask, bd_idx): """Solves the kriging system by looping over all specified points. Uses only a certain number of closest points. Not very memory intensive, but the loop is done in pure Python. """ import scipy.linalg.lapack npt = bd_all.shape[0] n = bd_idx.shape[1] kvalues = np.zeros(npt) sigmasq = np.zeros(npt) for i in np.nonzero(~mask)[0]: b_selector = bd_idx[i] bd = bd_all[i] a_selector = np.concatenate((b_selector, np.array([a_all.shape[0] - 1]))) a = a_all[a_selector[:, None], a_selector] if np.any(np.absolute(bd) <= self.eps): zero_value = True zero_index = np.where(np.absolute(bd) <= self.eps) else: zero_value = False zero_index = None b = np.zeros((n+1, 1)) b[:n, 0] = - self.variogram_function(self.variogram_model_parameters, bd) if zero_value: b[zero_index[0], 0] = 0.0 b[n, 0] = 1.0 x = scipy.linalg.solve(a, b) kvalues[i] = x[:n, 0].dot(self.VALUES[b_selector]) sigmasq[i] = - x[:, 0].dot(b[:, 0]) return kvalues, sigmasq
[ "def", "_exec_loop_moving_window", "(", "self", ",", "a_all", ",", "bd_all", ",", "mask", ",", "bd_idx", ")", ":", "import", "scipy", ".", "linalg", ".", "lapack", "npt", "=", "bd_all", ".", "shape", "[", "0", "]", "n", "=", "bd_idx", ".", "shape", "[", "1", "]", "kvalues", "=", "np", ".", "zeros", "(", "npt", ")", "sigmasq", "=", "np", ".", "zeros", "(", "npt", ")", "for", "i", "in", "np", ".", "nonzero", "(", "~", "mask", ")", "[", "0", "]", ":", "b_selector", "=", "bd_idx", "[", "i", "]", "bd", "=", "bd_all", "[", "i", "]", "a_selector", "=", "np", ".", "concatenate", "(", "(", "b_selector", ",", "np", ".", "array", "(", "[", "a_all", ".", "shape", "[", "0", "]", "-", "1", "]", ")", ")", ")", "a", "=", "a_all", "[", "a_selector", "[", ":", ",", "None", "]", ",", "a_selector", "]", "if", "np", ".", "any", "(", "np", ".", "absolute", "(", "bd", ")", "<=", "self", ".", "eps", ")", ":", "zero_value", "=", "True", "zero_index", "=", "np", ".", "where", "(", "np", ".", "absolute", "(", "bd", ")", "<=", "self", ".", "eps", ")", "else", ":", "zero_value", "=", "False", "zero_index", "=", "None", "b", "=", "np", ".", "zeros", "(", "(", "n", "+", "1", ",", "1", ")", ")", "b", "[", ":", "n", ",", "0", "]", "=", "-", "self", ".", "variogram_function", "(", "self", ".", "variogram_model_parameters", ",", "bd", ")", "if", "zero_value", ":", "b", "[", "zero_index", "[", "0", "]", ",", "0", "]", "=", "0.0", "b", "[", "n", ",", "0", "]", "=", "1.0", "x", "=", "scipy", ".", "linalg", ".", "solve", "(", "a", ",", "b", ")", "kvalues", "[", "i", "]", "=", "x", "[", ":", "n", ",", "0", "]", ".", "dot", "(", "self", ".", "VALUES", "[", "b_selector", "]", ")", "sigmasq", "[", "i", "]", "=", "-", "x", "[", ":", ",", "0", "]", ".", "dot", "(", "b", "[", ":", ",", "0", "]", ")", "return", "kvalues", ",", "sigmasq" ]
Solves the kriging system by looping over all specified points. Uses only a certain number of closest points. Not very memory intensive, but the loop is done in pure Python.
[ "Solves", "the", "kriging", "system", "by", "looping", "over", "all", "specified", "points", ".", "Uses", "only", "a", "certain", "number", "of", "closest", "points", ".", "Not", "very", "memory", "intensive", "but", "the", "loop", "is", "done", "in", "pure", "Python", "." ]
a4db3003b0b5688658c12faeb95a5a8b2b14b433
https://github.com/bsmurphy/PyKrige/blob/a4db3003b0b5688658c12faeb95a5a8b2b14b433/pykrige/ok3d.py#L524-L560
6,907
limodou/uliweb
uliweb/lib/werkzeug/debug/util.py
get_frame_info
def get_frame_info(tb, context_lines=7, simple=False): """ Return a dict of information about a given traceback. """ # line numbers / function / variables lineno = tb.tb_lineno function = tb.tb_frame.f_code.co_name variables = tb.tb_frame.f_locals files = {} # get filename if simple: fn = tb.tb_frame.f_code.co_filename else: fn = tb.tb_frame.f_globals.get('__file__') if not fn: fn = os.path.realpath(inspect.getsourcefile(tb) or inspect.getfile(tb)) if fn[-4:] in ('.pyc', '.pyo'): fn = fn[:-1] #if filename is existed, then just read the file # get loader loader = None if not os.path.exists(fn): loader = tb.tb_frame.f_globals.get('__loader__') while not loader and tb.tb_next: tb = tb.tb_next loader = tb.tb_frame.f_globals.get('__loader__') # sourcecode source = '' pre_context, post_context = [], [] context_line = raw_context_line = context_lineno = None try: if loader: source = loader.get_source(fn) else: if not fn in files: source = open(fn).read() files[fn] = source else: source = files[fn] except: pass else: try: raw_context_line = source.splitlines()[lineno - 1].strip() except IndexError: pass if not simple: parsed_source = highlight_python(source) lbound = max(0, lineno - context_lines - 1) ubound = lineno + context_lines try: context_line = parsed_source[lineno - 1] pre_context = parsed_source[lbound:lineno - 1] post_context = parsed_source[lineno:ubound] except IndexError as e: pass context_lineno = lbound if isinstance(fn, unicode): fn = fn.encode('utf-8') return { 'tb': tb, 'filename': fn, 'basename': os.path.basename(fn), 'loader': loader, 'function': function, 'lineno': lineno, 'vars': variables, 'pre_context': pre_context, 'context_line': context_line, 'raw_context_line': raw_context_line, 'post_context': post_context, 'context_lineno': context_lineno, 'source': source }
python
def get_frame_info(tb, context_lines=7, simple=False): """ Return a dict of information about a given traceback. """ # line numbers / function / variables lineno = tb.tb_lineno function = tb.tb_frame.f_code.co_name variables = tb.tb_frame.f_locals files = {} # get filename if simple: fn = tb.tb_frame.f_code.co_filename else: fn = tb.tb_frame.f_globals.get('__file__') if not fn: fn = os.path.realpath(inspect.getsourcefile(tb) or inspect.getfile(tb)) if fn[-4:] in ('.pyc', '.pyo'): fn = fn[:-1] #if filename is existed, then just read the file # get loader loader = None if not os.path.exists(fn): loader = tb.tb_frame.f_globals.get('__loader__') while not loader and tb.tb_next: tb = tb.tb_next loader = tb.tb_frame.f_globals.get('__loader__') # sourcecode source = '' pre_context, post_context = [], [] context_line = raw_context_line = context_lineno = None try: if loader: source = loader.get_source(fn) else: if not fn in files: source = open(fn).read() files[fn] = source else: source = files[fn] except: pass else: try: raw_context_line = source.splitlines()[lineno - 1].strip() except IndexError: pass if not simple: parsed_source = highlight_python(source) lbound = max(0, lineno - context_lines - 1) ubound = lineno + context_lines try: context_line = parsed_source[lineno - 1] pre_context = parsed_source[lbound:lineno - 1] post_context = parsed_source[lineno:ubound] except IndexError as e: pass context_lineno = lbound if isinstance(fn, unicode): fn = fn.encode('utf-8') return { 'tb': tb, 'filename': fn, 'basename': os.path.basename(fn), 'loader': loader, 'function': function, 'lineno': lineno, 'vars': variables, 'pre_context': pre_context, 'context_line': context_line, 'raw_context_line': raw_context_line, 'post_context': post_context, 'context_lineno': context_lineno, 'source': source }
[ "def", "get_frame_info", "(", "tb", ",", "context_lines", "=", "7", ",", "simple", "=", "False", ")", ":", "# line numbers / function / variables", "lineno", "=", "tb", ".", "tb_lineno", "function", "=", "tb", ".", "tb_frame", ".", "f_code", ".", "co_name", "variables", "=", "tb", ".", "tb_frame", ".", "f_locals", "files", "=", "{", "}", "# get filename", "if", "simple", ":", "fn", "=", "tb", ".", "tb_frame", ".", "f_code", ".", "co_filename", "else", ":", "fn", "=", "tb", ".", "tb_frame", ".", "f_globals", ".", "get", "(", "'__file__'", ")", "if", "not", "fn", ":", "fn", "=", "os", ".", "path", ".", "realpath", "(", "inspect", ".", "getsourcefile", "(", "tb", ")", "or", "inspect", ".", "getfile", "(", "tb", ")", ")", "if", "fn", "[", "-", "4", ":", "]", "in", "(", "'.pyc'", ",", "'.pyo'", ")", ":", "fn", "=", "fn", "[", ":", "-", "1", "]", "#if filename is existed, then just read the file", "# get loader", "loader", "=", "None", "if", "not", "os", ".", "path", ".", "exists", "(", "fn", ")", ":", "loader", "=", "tb", ".", "tb_frame", ".", "f_globals", ".", "get", "(", "'__loader__'", ")", "while", "not", "loader", "and", "tb", ".", "tb_next", ":", "tb", "=", "tb", ".", "tb_next", "loader", "=", "tb", ".", "tb_frame", ".", "f_globals", ".", "get", "(", "'__loader__'", ")", "# sourcecode", "source", "=", "''", "pre_context", ",", "post_context", "=", "[", "]", ",", "[", "]", "context_line", "=", "raw_context_line", "=", "context_lineno", "=", "None", "try", ":", "if", "loader", ":", "source", "=", "loader", ".", "get_source", "(", "fn", ")", "else", ":", "if", "not", "fn", "in", "files", ":", "source", "=", "open", "(", "fn", ")", ".", "read", "(", ")", "files", "[", "fn", "]", "=", "source", "else", ":", "source", "=", "files", "[", "fn", "]", "except", ":", "pass", "else", ":", "try", ":", "raw_context_line", "=", "source", ".", "splitlines", "(", ")", "[", "lineno", "-", "1", "]", ".", "strip", "(", ")", "except", "IndexError", ":", "pass", "if", "not", "simple", ":", "parsed_source", "=", "highlight_python", "(", "source", ")", "lbound", "=", "max", "(", "0", ",", "lineno", "-", "context_lines", "-", "1", ")", "ubound", "=", "lineno", "+", "context_lines", "try", ":", "context_line", "=", "parsed_source", "[", "lineno", "-", "1", "]", "pre_context", "=", "parsed_source", "[", "lbound", ":", "lineno", "-", "1", "]", "post_context", "=", "parsed_source", "[", "lineno", ":", "ubound", "]", "except", "IndexError", "as", "e", ":", "pass", "context_lineno", "=", "lbound", "if", "isinstance", "(", "fn", ",", "unicode", ")", ":", "fn", "=", "fn", ".", "encode", "(", "'utf-8'", ")", "return", "{", "'tb'", ":", "tb", ",", "'filename'", ":", "fn", ",", "'basename'", ":", "os", ".", "path", ".", "basename", "(", "fn", ")", ",", "'loader'", ":", "loader", ",", "'function'", ":", "function", ",", "'lineno'", ":", "lineno", ",", "'vars'", ":", "variables", ",", "'pre_context'", ":", "pre_context", ",", "'context_line'", ":", "context_line", ",", "'raw_context_line'", ":", "raw_context_line", ",", "'post_context'", ":", "post_context", ",", "'context_lineno'", ":", "context_lineno", ",", "'source'", ":", "source", "}" ]
Return a dict of information about a given traceback.
[ "Return", "a", "dict", "of", "information", "about", "a", "given", "traceback", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/debug/util.py#L204-L284
6,908
limodou/uliweb
uliweb/lib/werkzeug/debug/util.py
PythonParser.get_html_output
def get_html_output(self): """ Return line generator. """ def html_splitlines(lines): # this cool function was taken from trac. # http://projects.edgewall.com/trac/ open_tag_re = re.compile(r'<(\w+)(\s.*)?[^/]?>') close_tag_re = re.compile(r'</(\w+)>') open_tags = [] for line in lines: for tag in open_tags: line = tag.group(0) + line open_tags = [] for tag in open_tag_re.finditer(line): open_tags.append(tag) open_tags.reverse() for ctag in close_tag_re.finditer(line): for otag in open_tags: if otag.group(1) == ctag.group(1): open_tags.remove(otag) break for tag in open_tags: line += '</%s>' % tag.group(1) yield line if self.error: return escape(self.raw).splitlines() return list(html_splitlines(self.out.getvalue().splitlines()))
python
def get_html_output(self): """ Return line generator. """ def html_splitlines(lines): # this cool function was taken from trac. # http://projects.edgewall.com/trac/ open_tag_re = re.compile(r'<(\w+)(\s.*)?[^/]?>') close_tag_re = re.compile(r'</(\w+)>') open_tags = [] for line in lines: for tag in open_tags: line = tag.group(0) + line open_tags = [] for tag in open_tag_re.finditer(line): open_tags.append(tag) open_tags.reverse() for ctag in close_tag_re.finditer(line): for otag in open_tags: if otag.group(1) == ctag.group(1): open_tags.remove(otag) break for tag in open_tags: line += '</%s>' % tag.group(1) yield line if self.error: return escape(self.raw).splitlines() return list(html_splitlines(self.out.getvalue().splitlines()))
[ "def", "get_html_output", "(", "self", ")", ":", "def", "html_splitlines", "(", "lines", ")", ":", "# this cool function was taken from trac.", "# http://projects.edgewall.com/trac/", "open_tag_re", "=", "re", ".", "compile", "(", "r'<(\\w+)(\\s.*)?[^/]?>'", ")", "close_tag_re", "=", "re", ".", "compile", "(", "r'</(\\w+)>'", ")", "open_tags", "=", "[", "]", "for", "line", "in", "lines", ":", "for", "tag", "in", "open_tags", ":", "line", "=", "tag", ".", "group", "(", "0", ")", "+", "line", "open_tags", "=", "[", "]", "for", "tag", "in", "open_tag_re", ".", "finditer", "(", "line", ")", ":", "open_tags", ".", "append", "(", "tag", ")", "open_tags", ".", "reverse", "(", ")", "for", "ctag", "in", "close_tag_re", ".", "finditer", "(", "line", ")", ":", "for", "otag", "in", "open_tags", ":", "if", "otag", ".", "group", "(", "1", ")", "==", "ctag", ".", "group", "(", "1", ")", ":", "open_tags", ".", "remove", "(", "otag", ")", "break", "for", "tag", "in", "open_tags", ":", "line", "+=", "'</%s>'", "%", "tag", ".", "group", "(", "1", ")", "yield", "line", "if", "self", ".", "error", ":", "return", "escape", "(", "self", ".", "raw", ")", ".", "splitlines", "(", ")", "return", "list", "(", "html_splitlines", "(", "self", ".", "out", ".", "getvalue", "(", ")", ".", "splitlines", "(", ")", ")", ")" ]
Return line generator.
[ "Return", "line", "generator", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/debug/util.py#L148-L174
6,909
limodou/uliweb
uliweb/utils/generic.py
get_columns
def get_columns(model=None, fields=None, meta=None): """ Get model columns list """ if model: M = get_model(model) else: M = None if fields is not None: f = fields if M: if meta and hasattr(M, meta): m = getattr(model, meta) if hasattr(m, 'fields'): f = m.fields else: f = M._fields_list else: f = M._fields_list columns = [] for x in f: if isinstance(x, str): # so x is field_name field_name = x elif isinstance(x, dict): field_name = x['name'] else: raise UliwebError("Field definition is not right, it should be just like str or {'name':xxx}") if '.' in field_name: model_name, field_name = field_name.split('.') M = get_model(model_name) if not M: raise UliwebError("Model can't be empty, because field name not has `model.` prefix") if field_name in M.c: columns.append(M.c[field_name]) return columns
python
def get_columns(model=None, fields=None, meta=None): """ Get model columns list """ if model: M = get_model(model) else: M = None if fields is not None: f = fields if M: if meta and hasattr(M, meta): m = getattr(model, meta) if hasattr(m, 'fields'): f = m.fields else: f = M._fields_list else: f = M._fields_list columns = [] for x in f: if isinstance(x, str): # so x is field_name field_name = x elif isinstance(x, dict): field_name = x['name'] else: raise UliwebError("Field definition is not right, it should be just like str or {'name':xxx}") if '.' in field_name: model_name, field_name = field_name.split('.') M = get_model(model_name) if not M: raise UliwebError("Model can't be empty, because field name not has `model.` prefix") if field_name in M.c: columns.append(M.c[field_name]) return columns
[ "def", "get_columns", "(", "model", "=", "None", ",", "fields", "=", "None", ",", "meta", "=", "None", ")", ":", "if", "model", ":", "M", "=", "get_model", "(", "model", ")", "else", ":", "M", "=", "None", "if", "fields", "is", "not", "None", ":", "f", "=", "fields", "if", "M", ":", "if", "meta", "and", "hasattr", "(", "M", ",", "meta", ")", ":", "m", "=", "getattr", "(", "model", ",", "meta", ")", "if", "hasattr", "(", "m", ",", "'fields'", ")", ":", "f", "=", "m", ".", "fields", "else", ":", "f", "=", "M", ".", "_fields_list", "else", ":", "f", "=", "M", ".", "_fields_list", "columns", "=", "[", "]", "for", "x", "in", "f", ":", "if", "isinstance", "(", "x", ",", "str", ")", ":", "# so x is field_name\r", "field_name", "=", "x", "elif", "isinstance", "(", "x", ",", "dict", ")", ":", "field_name", "=", "x", "[", "'name'", "]", "else", ":", "raise", "UliwebError", "(", "\"Field definition is not right, it should be just like str or {'name':xxx}\"", ")", "if", "'.'", "in", "field_name", ":", "model_name", ",", "field_name", "=", "field_name", ".", "split", "(", "'.'", ")", "M", "=", "get_model", "(", "model_name", ")", "if", "not", "M", ":", "raise", "UliwebError", "(", "\"Model can't be empty, because field name not has `model.` prefix\"", ")", "if", "field_name", "in", "M", ".", "c", ":", "columns", ".", "append", "(", "M", ".", "c", "[", "field_name", "]", ")", "return", "columns" ]
Get model columns list
[ "Get", "model", "columns", "list" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L381-L421
6,910
limodou/uliweb
uliweb/utils/generic.py
get_field
def get_field(name, model=None): """ get model field according to name, the name can be like `model.column` """ if '.' in name: m, name = name.split('.') model = get_model(m) if model: return getattr(model, name, None)
python
def get_field(name, model=None): """ get model field according to name, the name can be like `model.column` """ if '.' in name: m, name = name.split('.') model = get_model(m) if model: return getattr(model, name, None)
[ "def", "get_field", "(", "name", ",", "model", "=", "None", ")", ":", "if", "'.'", "in", "name", ":", "m", ",", "name", "=", "name", ".", "split", "(", "'.'", ")", "model", "=", "get_model", "(", "m", ")", "if", "model", ":", "return", "getattr", "(", "model", ",", "name", ",", "None", ")" ]
get model field according to name, the name can be like `model.column`
[ "get", "model", "field", "according", "to", "name", "the", "name", "can", "be", "like", "model", ".", "column" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L497-L506
6,911
limodou/uliweb
uliweb/utils/generic.py
get_column
def get_column(name, model=None): """ get table column according to name, the name can be like `model.column` """ if '.' in name: m, name = name.split('.') model = get_model(m) if model: return model.c.get(name)
python
def get_column(name, model=None): """ get table column according to name, the name can be like `model.column` """ if '.' in name: m, name = name.split('.') model = get_model(m) if model: return model.c.get(name)
[ "def", "get_column", "(", "name", ",", "model", "=", "None", ")", ":", "if", "'.'", "in", "name", ":", "m", ",", "name", "=", "name", ".", "split", "(", "'.'", ")", "model", "=", "get_model", "(", "m", ")", "if", "model", ":", "return", "model", ".", "c", ".", "get", "(", "name", ")" ]
get table column according to name, the name can be like `model.column`
[ "get", "table", "column", "according", "to", "name", "the", "name", "can", "be", "like", "model", ".", "column" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L508-L517
6,912
limodou/uliweb
uliweb/utils/generic.py
AddView._process_file
def _process_file(self, obj, fobj, field): """ obj is record object fobj is data field is FileField instance """ from uliweb import settings paths = [] upload_to = self.upload_to or self._get_upload_path(field, 'upload_to', obj) if upload_to: self.fileserving.to_path = upload_to upload_to_sub = self.upload_to_sub or self._get_upload_path(field, 'upload_to_sub', obj) if upload_to_sub: paths.append(upload_to_sub) paths.append(fobj['filename']) return self.fileserving.save_file(os.path.join(*paths), fobj['file'], replace=self.file_replace, convert=self.file_convert)
python
def _process_file(self, obj, fobj, field): """ obj is record object fobj is data field is FileField instance """ from uliweb import settings paths = [] upload_to = self.upload_to or self._get_upload_path(field, 'upload_to', obj) if upload_to: self.fileserving.to_path = upload_to upload_to_sub = self.upload_to_sub or self._get_upload_path(field, 'upload_to_sub', obj) if upload_to_sub: paths.append(upload_to_sub) paths.append(fobj['filename']) return self.fileserving.save_file(os.path.join(*paths), fobj['file'], replace=self.file_replace, convert=self.file_convert)
[ "def", "_process_file", "(", "self", ",", "obj", ",", "fobj", ",", "field", ")", ":", "from", "uliweb", "import", "settings", "paths", "=", "[", "]", "upload_to", "=", "self", ".", "upload_to", "or", "self", ".", "_get_upload_path", "(", "field", ",", "'upload_to'", ",", "obj", ")", "if", "upload_to", ":", "self", ".", "fileserving", ".", "to_path", "=", "upload_to", "upload_to_sub", "=", "self", ".", "upload_to_sub", "or", "self", ".", "_get_upload_path", "(", "field", ",", "'upload_to_sub'", ",", "obj", ")", "if", "upload_to_sub", ":", "paths", ".", "append", "(", "upload_to_sub", ")", "paths", ".", "append", "(", "fobj", "[", "'filename'", "]", ")", "return", "self", ".", "fileserving", ".", "save_file", "(", "os", ".", "path", ".", "join", "(", "*", "paths", ")", ",", "fobj", "[", "'file'", "]", ",", "replace", "=", "self", ".", "file_replace", ",", "convert", "=", "self", ".", "file_convert", ")" ]
obj is record object fobj is data field is FileField instance
[ "obj", "is", "record", "object", "fobj", "is", "data", "field", "is", "FileField", "instance" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L1060-L1079
6,913
limodou/uliweb
uliweb/utils/generic.py
SimpleListView.count
def count(self, query): """ If query is Select object, this function will try to get count of select """ if self.manual: return self.total if isinstance(query, Select): q = query.with_only_columns([func.count()]).order_by(None).limit(None).offset(None) return do_(q).scalar() return query.count()
python
def count(self, query): """ If query is Select object, this function will try to get count of select """ if self.manual: return self.total if isinstance(query, Select): q = query.with_only_columns([func.count()]).order_by(None).limit(None).offset(None) return do_(q).scalar() return query.count()
[ "def", "count", "(", "self", ",", "query", ")", ":", "if", "self", ".", "manual", ":", "return", "self", ".", "total", "if", "isinstance", "(", "query", ",", "Select", ")", ":", "q", "=", "query", ".", "with_only_columns", "(", "[", "func", ".", "count", "(", ")", "]", ")", ".", "order_by", "(", "None", ")", ".", "limit", "(", "None", ")", ".", "offset", "(", "None", ")", "return", "do_", "(", "q", ")", ".", "scalar", "(", ")", "return", "query", ".", "count", "(", ")" ]
If query is Select object, this function will try to get count of select
[ "If", "query", "is", "Select", "object", "this", "function", "will", "try", "to", "get", "count", "of", "select" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L1967-L1978
6,914
limodou/uliweb
uliweb/utils/generic.py
SimpleListView.get_data
def get_data(self, query, fields_convert_map, encoding='utf-8', auto_convert=True, include_hidden=False, header=None): """ If convert=True, will convert field value """ fields_convert_map = fields_convert_map or {} d = self.fields_convert_map.copy() d.update(fields_convert_map) if isinstance(query, Select): query = do_(query) # def get_value(name, value, record): # convert = d.get(name) # if convert: # value = convert(value, record) # return safe_unicode(value, encoding) for record in query: self._cal_sum(record) row = [] record = self._get_record(record) if self.before_record_render: self.before_record_render(record) if isinstance(record, orm.Model): model = record.__class__ else: model = None for i, x in enumerate(self.table_info['fields_list']): field = get_field(x['name'], model) if not field: field = {'name':x['name']} else: field = {'name':x['name'], 'prop':field} if not include_hidden and x.get('hidden'): continue if isinstance(record, orm.Model): v = make_view_field(field, record, fields_convert_map=d, auto_convert=auto_convert) else: v = make_view_field(field, record, fields_convert_map=d, auto_convert=auto_convert, value=record[x['name']]) value = v['display'] #value = safe_unicode(v['display'], encoding) row.append(value) if header: ret = dict(zip(header, row)) else: ret = row yield ret total = self._get_sum() if total: row = [] for x in total: v = x if isinstance(x, str): v = safe_unicode(x, encoding) row.append(v) if header: ret = dict(zip(header, row)) else: ret = row yield ret
python
def get_data(self, query, fields_convert_map, encoding='utf-8', auto_convert=True, include_hidden=False, header=None): """ If convert=True, will convert field value """ fields_convert_map = fields_convert_map or {} d = self.fields_convert_map.copy() d.update(fields_convert_map) if isinstance(query, Select): query = do_(query) # def get_value(name, value, record): # convert = d.get(name) # if convert: # value = convert(value, record) # return safe_unicode(value, encoding) for record in query: self._cal_sum(record) row = [] record = self._get_record(record) if self.before_record_render: self.before_record_render(record) if isinstance(record, orm.Model): model = record.__class__ else: model = None for i, x in enumerate(self.table_info['fields_list']): field = get_field(x['name'], model) if not field: field = {'name':x['name']} else: field = {'name':x['name'], 'prop':field} if not include_hidden and x.get('hidden'): continue if isinstance(record, orm.Model): v = make_view_field(field, record, fields_convert_map=d, auto_convert=auto_convert) else: v = make_view_field(field, record, fields_convert_map=d, auto_convert=auto_convert, value=record[x['name']]) value = v['display'] #value = safe_unicode(v['display'], encoding) row.append(value) if header: ret = dict(zip(header, row)) else: ret = row yield ret total = self._get_sum() if total: row = [] for x in total: v = x if isinstance(x, str): v = safe_unicode(x, encoding) row.append(v) if header: ret = dict(zip(header, row)) else: ret = row yield ret
[ "def", "get_data", "(", "self", ",", "query", ",", "fields_convert_map", ",", "encoding", "=", "'utf-8'", ",", "auto_convert", "=", "True", ",", "include_hidden", "=", "False", ",", "header", "=", "None", ")", ":", "fields_convert_map", "=", "fields_convert_map", "or", "{", "}", "d", "=", "self", ".", "fields_convert_map", ".", "copy", "(", ")", "d", ".", "update", "(", "fields_convert_map", ")", "if", "isinstance", "(", "query", ",", "Select", ")", ":", "query", "=", "do_", "(", "query", ")", "# def get_value(name, value, record):\r", "# convert = d.get(name)\r", "# if convert:\r", "# value = convert(value, record)\r", "# return safe_unicode(value, encoding)\r", "for", "record", "in", "query", ":", "self", ".", "_cal_sum", "(", "record", ")", "row", "=", "[", "]", "record", "=", "self", ".", "_get_record", "(", "record", ")", "if", "self", ".", "before_record_render", ":", "self", ".", "before_record_render", "(", "record", ")", "if", "isinstance", "(", "record", ",", "orm", ".", "Model", ")", ":", "model", "=", "record", ".", "__class__", "else", ":", "model", "=", "None", "for", "i", ",", "x", "in", "enumerate", "(", "self", ".", "table_info", "[", "'fields_list'", "]", ")", ":", "field", "=", "get_field", "(", "x", "[", "'name'", "]", ",", "model", ")", "if", "not", "field", ":", "field", "=", "{", "'name'", ":", "x", "[", "'name'", "]", "}", "else", ":", "field", "=", "{", "'name'", ":", "x", "[", "'name'", "]", ",", "'prop'", ":", "field", "}", "if", "not", "include_hidden", "and", "x", ".", "get", "(", "'hidden'", ")", ":", "continue", "if", "isinstance", "(", "record", ",", "orm", ".", "Model", ")", ":", "v", "=", "make_view_field", "(", "field", ",", "record", ",", "fields_convert_map", "=", "d", ",", "auto_convert", "=", "auto_convert", ")", "else", ":", "v", "=", "make_view_field", "(", "field", ",", "record", ",", "fields_convert_map", "=", "d", ",", "auto_convert", "=", "auto_convert", ",", "value", "=", "record", "[", "x", "[", "'name'", "]", "]", ")", "value", "=", "v", "[", "'display'", "]", "#value = safe_unicode(v['display'], encoding)\r", "row", ".", "append", "(", "value", ")", "if", "header", ":", "ret", "=", "dict", "(", "zip", "(", "header", ",", "row", ")", ")", "else", ":", "ret", "=", "row", "yield", "ret", "total", "=", "self", ".", "_get_sum", "(", ")", "if", "total", ":", "row", "=", "[", "]", "for", "x", "in", "total", ":", "v", "=", "x", "if", "isinstance", "(", "x", ",", "str", ")", ":", "v", "=", "safe_unicode", "(", "x", ",", "encoding", ")", "row", ".", "append", "(", "v", ")", "if", "header", ":", "ret", "=", "dict", "(", "zip", "(", "header", ",", "row", ")", ")", "else", ":", "ret", "=", "row", "yield", "ret" ]
If convert=True, will convert field value
[ "If", "convert", "=", "True", "will", "convert", "field", "value" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L2070-L2135
6,915
limodou/uliweb
uliweb/utils/generic.py
SimpleListView.objects
def objects(self, json_result=False): """ Return a generator of all processed data, it just like render but it'll not return a table or json format data but just data. And the data will be processed by fields_convert_map if passed. """ self.rows_num = 0 query = self.query() if not isinstance(query, (orm.Result, list, dict)): query = do_(query) for record in query: self.rows_num += 1 r = self.object(record, json_result) self._cal_sum(record) yield r total = self._render_sum(True) if total: yield total
python
def objects(self, json_result=False): """ Return a generator of all processed data, it just like render but it'll not return a table or json format data but just data. And the data will be processed by fields_convert_map if passed. """ self.rows_num = 0 query = self.query() if not isinstance(query, (orm.Result, list, dict)): query = do_(query) for record in query: self.rows_num += 1 r = self.object(record, json_result) self._cal_sum(record) yield r total = self._render_sum(True) if total: yield total
[ "def", "objects", "(", "self", ",", "json_result", "=", "False", ")", ":", "self", ".", "rows_num", "=", "0", "query", "=", "self", ".", "query", "(", ")", "if", "not", "isinstance", "(", "query", ",", "(", "orm", ".", "Result", ",", "list", ",", "dict", ")", ")", ":", "query", "=", "do_", "(", "query", ")", "for", "record", "in", "query", ":", "self", ".", "rows_num", "+=", "1", "r", "=", "self", ".", "object", "(", "record", ",", "json_result", ")", "self", ".", "_cal_sum", "(", "record", ")", "yield", "r", "total", "=", "self", ".", "_render_sum", "(", "True", ")", "if", "total", ":", "yield", "total" ]
Return a generator of all processed data, it just like render but it'll not return a table or json format data but just data. And the data will be processed by fields_convert_map if passed.
[ "Return", "a", "generator", "of", "all", "processed", "data", "it", "just", "like", "render", "but", "it", "ll", "not", "return", "a", "table", "or", "json", "format", "data", "but", "just", "data", ".", "And", "the", "data", "will", "be", "processed", "by", "fields_convert_map", "if", "passed", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L2275-L2292
6,916
limodou/uliweb
uliweb/utils/generic.py
ListView.query_all
def query_all(self): """ Query all records without limit and offset. """ return self.query_model(self.model, self.condition, order_by=self.order_by, group_by=self.group_by, having=self.having)
python
def query_all(self): """ Query all records without limit and offset. """ return self.query_model(self.model, self.condition, order_by=self.order_by, group_by=self.group_by, having=self.having)
[ "def", "query_all", "(", "self", ")", ":", "return", "self", ".", "query_model", "(", "self", ".", "model", ",", "self", ".", "condition", ",", "order_by", "=", "self", ".", "order_by", ",", "group_by", "=", "self", ".", "group_by", ",", "having", "=", "self", ".", "having", ")" ]
Query all records without limit and offset.
[ "Query", "all", "records", "without", "limit", "and", "offset", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/generic.py#L2636-L2641
6,917
limodou/uliweb
uliweb/lib/werkzeug/contrib/sessions.py
ModificationTrackingDict.copy
def copy(self): """Create a flat copy of the dict.""" missing = object() result = object.__new__(self.__class__) for name in self.__slots__: val = getattr(self, name, missing) if val is not missing: setattr(result, name, val) return result
python
def copy(self): """Create a flat copy of the dict.""" missing = object() result = object.__new__(self.__class__) for name in self.__slots__: val = getattr(self, name, missing) if val is not missing: setattr(result, name, val) return result
[ "def", "copy", "(", "self", ")", ":", "missing", "=", "object", "(", ")", "result", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "for", "name", "in", "self", ".", "__slots__", ":", "val", "=", "getattr", "(", "self", ",", "name", ",", "missing", ")", "if", "val", "is", "not", "missing", ":", "setattr", "(", "result", ",", "name", ",", "val", ")", "return", "result" ]
Create a flat copy of the dict.
[ "Create", "a", "flat", "copy", "of", "the", "dict", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/sessions.py#L100-L108
6,918
limodou/uliweb
uliweb/lib/werkzeug/contrib/sessions.py
FilesystemSessionStore.list
def list(self): """Lists all sessions in the store. .. versionadded:: 0.6 """ before, after = self.filename_template.split('%s', 1) filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before), re.escape(after))) result = [] for filename in os.listdir(self.path): #: this is a session that is still being saved. if filename.endswith(_fs_transaction_suffix): continue match = filename_re.match(filename) if match is not None: result.append(match.group(1)) return result
python
def list(self): """Lists all sessions in the store. .. versionadded:: 0.6 """ before, after = self.filename_template.split('%s', 1) filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before), re.escape(after))) result = [] for filename in os.listdir(self.path): #: this is a session that is still being saved. if filename.endswith(_fs_transaction_suffix): continue match = filename_re.match(filename) if match is not None: result.append(match.group(1)) return result
[ "def", "list", "(", "self", ")", ":", "before", ",", "after", "=", "self", ".", "filename_template", ".", "split", "(", "'%s'", ",", "1", ")", "filename_re", "=", "re", ".", "compile", "(", "r'%s(.{5,})%s$'", "%", "(", "re", ".", "escape", "(", "before", ")", ",", "re", ".", "escape", "(", "after", ")", ")", ")", "result", "=", "[", "]", "for", "filename", "in", "os", ".", "listdir", "(", "self", ".", "path", ")", ":", "#: this is a session that is still being saved.", "if", "filename", ".", "endswith", "(", "_fs_transaction_suffix", ")", ":", "continue", "match", "=", "filename_re", ".", "match", "(", "filename", ")", "if", "match", "is", "not", "None", ":", "result", ".", "append", "(", "match", ".", "group", "(", "1", ")", ")", "return", "result" ]
Lists all sessions in the store. .. versionadded:: 0.6
[ "Lists", "all", "sessions", "in", "the", "store", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/sessions.py#L279-L295
6,919
limodou/uliweb
uliweb/utils/date.py
to_timezone
def to_timezone(dt, tzinfo=None): """ Convert a datetime to timezone """ if not dt: return dt tz = pick_timezone(tzinfo, __timezone__) if not tz: return dt dttz = getattr(dt, 'tzinfo', None) if not dttz: return dt.replace(tzinfo=tz) else: return dt.astimezone(tz)
python
def to_timezone(dt, tzinfo=None): """ Convert a datetime to timezone """ if not dt: return dt tz = pick_timezone(tzinfo, __timezone__) if not tz: return dt dttz = getattr(dt, 'tzinfo', None) if not dttz: return dt.replace(tzinfo=tz) else: return dt.astimezone(tz)
[ "def", "to_timezone", "(", "dt", ",", "tzinfo", "=", "None", ")", ":", "if", "not", "dt", ":", "return", "dt", "tz", "=", "pick_timezone", "(", "tzinfo", ",", "__timezone__", ")", "if", "not", "tz", ":", "return", "dt", "dttz", "=", "getattr", "(", "dt", ",", "'tzinfo'", ",", "None", ")", "if", "not", "dttz", ":", "return", "dt", ".", "replace", "(", "tzinfo", "=", "tz", ")", "else", ":", "return", "dt", ".", "astimezone", "(", "tz", ")" ]
Convert a datetime to timezone
[ "Convert", "a", "datetime", "to", "timezone" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/date.py#L146-L159
6,920
limodou/uliweb
uliweb/utils/date.py
to_date
def to_date(dt, tzinfo=None, format=None): """ Convert a datetime to date with tzinfo """ d = to_datetime(dt, tzinfo, format) if not d: return d return date(d.year, d.month, d.day)
python
def to_date(dt, tzinfo=None, format=None): """ Convert a datetime to date with tzinfo """ d = to_datetime(dt, tzinfo, format) if not d: return d return date(d.year, d.month, d.day)
[ "def", "to_date", "(", "dt", ",", "tzinfo", "=", "None", ",", "format", "=", "None", ")", ":", "d", "=", "to_datetime", "(", "dt", ",", "tzinfo", ",", "format", ")", "if", "not", "d", ":", "return", "d", "return", "date", "(", "d", ".", "year", ",", "d", ".", "month", ",", "d", ".", "day", ")" ]
Convert a datetime to date with tzinfo
[ "Convert", "a", "datetime", "to", "date", "with", "tzinfo" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/date.py#L161-L168
6,921
limodou/uliweb
uliweb/utils/date.py
to_time
def to_time(dt, tzinfo=None, format=None): """ Convert a datetime to time with tzinfo """ d = to_datetime(dt, tzinfo, format) if not d: return d return time_(d.hour, d.minute, d.second, d.microsecond, tzinfo=d.tzinfo)
python
def to_time(dt, tzinfo=None, format=None): """ Convert a datetime to time with tzinfo """ d = to_datetime(dt, tzinfo, format) if not d: return d return time_(d.hour, d.minute, d.second, d.microsecond, tzinfo=d.tzinfo)
[ "def", "to_time", "(", "dt", ",", "tzinfo", "=", "None", ",", "format", "=", "None", ")", ":", "d", "=", "to_datetime", "(", "dt", ",", "tzinfo", ",", "format", ")", "if", "not", "d", ":", "return", "d", "return", "time_", "(", "d", ".", "hour", ",", "d", ".", "minute", ",", "d", ".", "second", ",", "d", ".", "microsecond", ",", "tzinfo", "=", "d", ".", "tzinfo", ")" ]
Convert a datetime to time with tzinfo
[ "Convert", "a", "datetime", "to", "time", "with", "tzinfo" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/date.py#L170-L177
6,922
limodou/uliweb
uliweb/utils/date.py
to_datetime
def to_datetime(dt, tzinfo=None, format=None): """ Convert a date or time to datetime with tzinfo """ if not dt: return dt tz = pick_timezone(tzinfo, __timezone__) if isinstance(dt, (str, unicode)): if not format: formats = DEFAULT_DATETIME_INPUT_FORMATS else: formats = list(format) d = None for fmt in formats: try: d = datetime.strptime(dt, fmt) except ValueError: continue if not d: return None d = d.replace(tzinfo=tz) else: d = datetime(getattr(dt, 'year', 1970), getattr(dt, 'month', 1), getattr(dt, 'day', 1), getattr(dt, 'hour', 0), getattr(dt, 'minute', 0), getattr(dt, 'second', 0), getattr(dt, 'microsecond', 0)) if not getattr(dt, 'tzinfo', None): d = d.replace(tzinfo=tz) else: d = d.replace(tzinfo=dt.tzinfo) return to_timezone(d, tzinfo)
python
def to_datetime(dt, tzinfo=None, format=None): """ Convert a date or time to datetime with tzinfo """ if not dt: return dt tz = pick_timezone(tzinfo, __timezone__) if isinstance(dt, (str, unicode)): if not format: formats = DEFAULT_DATETIME_INPUT_FORMATS else: formats = list(format) d = None for fmt in formats: try: d = datetime.strptime(dt, fmt) except ValueError: continue if not d: return None d = d.replace(tzinfo=tz) else: d = datetime(getattr(dt, 'year', 1970), getattr(dt, 'month', 1), getattr(dt, 'day', 1), getattr(dt, 'hour', 0), getattr(dt, 'minute', 0), getattr(dt, 'second', 0), getattr(dt, 'microsecond', 0)) if not getattr(dt, 'tzinfo', None): d = d.replace(tzinfo=tz) else: d = d.replace(tzinfo=dt.tzinfo) return to_timezone(d, tzinfo)
[ "def", "to_datetime", "(", "dt", ",", "tzinfo", "=", "None", ",", "format", "=", "None", ")", ":", "if", "not", "dt", ":", "return", "dt", "tz", "=", "pick_timezone", "(", "tzinfo", ",", "__timezone__", ")", "if", "isinstance", "(", "dt", ",", "(", "str", ",", "unicode", ")", ")", ":", "if", "not", "format", ":", "formats", "=", "DEFAULT_DATETIME_INPUT_FORMATS", "else", ":", "formats", "=", "list", "(", "format", ")", "d", "=", "None", "for", "fmt", "in", "formats", ":", "try", ":", "d", "=", "datetime", ".", "strptime", "(", "dt", ",", "fmt", ")", "except", "ValueError", ":", "continue", "if", "not", "d", ":", "return", "None", "d", "=", "d", ".", "replace", "(", "tzinfo", "=", "tz", ")", "else", ":", "d", "=", "datetime", "(", "getattr", "(", "dt", ",", "'year'", ",", "1970", ")", ",", "getattr", "(", "dt", ",", "'month'", ",", "1", ")", ",", "getattr", "(", "dt", ",", "'day'", ",", "1", ")", ",", "getattr", "(", "dt", ",", "'hour'", ",", "0", ")", ",", "getattr", "(", "dt", ",", "'minute'", ",", "0", ")", ",", "getattr", "(", "dt", ",", "'second'", ",", "0", ")", ",", "getattr", "(", "dt", ",", "'microsecond'", ",", "0", ")", ")", "if", "not", "getattr", "(", "dt", ",", "'tzinfo'", ",", "None", ")", ":", "d", "=", "d", ".", "replace", "(", "tzinfo", "=", "tz", ")", "else", ":", "d", "=", "d", ".", "replace", "(", "tzinfo", "=", "dt", ".", "tzinfo", ")", "return", "to_timezone", "(", "d", ",", "tzinfo", ")" ]
Convert a date or time to datetime with tzinfo
[ "Convert", "a", "date", "or", "time", "to", "datetime", "with", "tzinfo" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/date.py#L179-L210
6,923
limodou/uliweb
uliweb/utils/date.py
parse_time
def parse_time(t): """ Parse string time format to microsecond """ if isinstance(t, (str, unicode)): b = re_time.match(t) if b: v, unit = int(b.group(1)), b.group(2) if unit == 's': return v*1000 elif unit == 'm': return v*60*1000 elif unit == 'h': return v*60*60*1000 else: return v else: raise TimeFormatError(t) elif isinstance(t, (int, long)): return t else: raise TimeFormatError(t)
python
def parse_time(t): """ Parse string time format to microsecond """ if isinstance(t, (str, unicode)): b = re_time.match(t) if b: v, unit = int(b.group(1)), b.group(2) if unit == 's': return v*1000 elif unit == 'm': return v*60*1000 elif unit == 'h': return v*60*60*1000 else: return v else: raise TimeFormatError(t) elif isinstance(t, (int, long)): return t else: raise TimeFormatError(t)
[ "def", "parse_time", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "(", "str", ",", "unicode", ")", ")", ":", "b", "=", "re_time", ".", "match", "(", "t", ")", "if", "b", ":", "v", ",", "unit", "=", "int", "(", "b", ".", "group", "(", "1", ")", ")", ",", "b", ".", "group", "(", "2", ")", "if", "unit", "==", "'s'", ":", "return", "v", "*", "1000", "elif", "unit", "==", "'m'", ":", "return", "v", "*", "60", "*", "1000", "elif", "unit", "==", "'h'", ":", "return", "v", "*", "60", "*", "60", "*", "1000", "else", ":", "return", "v", "else", ":", "raise", "TimeFormatError", "(", "t", ")", "elif", "isinstance", "(", "t", ",", "(", "int", ",", "long", ")", ")", ":", "return", "t", "else", ":", "raise", "TimeFormatError", "(", "t", ")" ]
Parse string time format to microsecond
[ "Parse", "string", "time", "format", "to", "microsecond" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/date.py#L233-L254
6,924
limodou/uliweb
uliweb/contrib/session/middle_session.py
SessionMiddle.process_exception
def process_exception(self, request, e): """ Still process session data when specially Exception """ if isinstance(e, RedirectException): response = e.get_response() self.process_response(request, response)
python
def process_exception(self, request, e): """ Still process session data when specially Exception """ if isinstance(e, RedirectException): response = e.get_response() self.process_response(request, response)
[ "def", "process_exception", "(", "self", ",", "request", ",", "e", ")", ":", "if", "isinstance", "(", "e", ",", "RedirectException", ")", ":", "response", "=", "e", ".", "get_response", "(", ")", "self", ".", "process_response", "(", "request", ",", "response", ")" ]
Still process session data when specially Exception
[ "Still", "process", "session", "data", "when", "specially", "Exception" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/session/middle_session.py#L68-L74
6,925
limodou/uliweb
uliweb/core/SimpleFrame.py
jsonp
def jsonp(data, **json_kwargs): """ jsonp is callback key name """ from uliweb import request if 'jsonp' in json_kwargs: cb = json_kwargs.pop('jsonp') else: cb = 'callback' begin = str(request.GET.get(cb)) if not begin: raise BadRequest("Can't found %s parameter in request's query_string" % cb) if not r_callback.match(begin): raise BadRequest("The callback name is not right, it can be alphabetic, number and underscore only") if callable(data): @wraps(data) def f(*arg, **kwargs): ret = data(*arg, **kwargs) return Response(begin + '(' + json_dumps(ret) + ');', **json_kwargs) return f else: return Response(begin + '(' + json_dumps(data) + ');', **json_kwargs)
python
def jsonp(data, **json_kwargs): """ jsonp is callback key name """ from uliweb import request if 'jsonp' in json_kwargs: cb = json_kwargs.pop('jsonp') else: cb = 'callback' begin = str(request.GET.get(cb)) if not begin: raise BadRequest("Can't found %s parameter in request's query_string" % cb) if not r_callback.match(begin): raise BadRequest("The callback name is not right, it can be alphabetic, number and underscore only") if callable(data): @wraps(data) def f(*arg, **kwargs): ret = data(*arg, **kwargs) return Response(begin + '(' + json_dumps(ret) + ');', **json_kwargs) return f else: return Response(begin + '(' + json_dumps(data) + ');', **json_kwargs)
[ "def", "jsonp", "(", "data", ",", "*", "*", "json_kwargs", ")", ":", "from", "uliweb", "import", "request", "if", "'jsonp'", "in", "json_kwargs", ":", "cb", "=", "json_kwargs", ".", "pop", "(", "'jsonp'", ")", "else", ":", "cb", "=", "'callback'", "begin", "=", "str", "(", "request", ".", "GET", ".", "get", "(", "cb", ")", ")", "if", "not", "begin", ":", "raise", "BadRequest", "(", "\"Can't found %s parameter in request's query_string\"", "%", "cb", ")", "if", "not", "r_callback", ".", "match", "(", "begin", ")", ":", "raise", "BadRequest", "(", "\"The callback name is not right, it can be alphabetic, number and underscore only\"", ")", "if", "callable", "(", "data", ")", ":", "@", "wraps", "(", "data", ")", "def", "f", "(", "*", "arg", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "data", "(", "*", "arg", ",", "*", "*", "kwargs", ")", "return", "Response", "(", "begin", "+", "'('", "+", "json_dumps", "(", "ret", ")", "+", "');'", ",", "*", "*", "json_kwargs", ")", "return", "f", "else", ":", "return", "Response", "(", "begin", "+", "'('", "+", "json_dumps", "(", "data", ")", "+", "');'", ",", "*", "*", "json_kwargs", ")" ]
jsonp is callback key name
[ "jsonp", "is", "callback", "key", "name" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/SimpleFrame.py#L195-L219
6,926
limodou/uliweb
uliweb/core/SimpleFrame.py
get_url_adapter
def get_url_adapter(_domain_name): """ Fetch a domain url_adapter object, and bind it to according domain """ from werkzeug._compat import wsgi_decoding_dance domain = application.domains.get(_domain_name, {}) server_name = None if domain.get('domain', ''): server_name = domain['domain'] try: env = {} environ = request.environ env['url_scheme'] = environ['wsgi.url_scheme'] env['default_method'] = environ['REQUEST_METHOD'] def _get_wsgi_string(name): val = environ.get(name) if val is not None: return wsgi_decoding_dance(val, "utf-8") env['script_name'] = _get_wsgi_string('SCRIPT_NAME') env['path_info'] = _get_wsgi_string('PATH_INFO') env['query_args'] = _get_wsgi_string('QUERY_STRING') except: env = {} adapter = url_map.bind(server_name, **env) else: try: env = request.environ except: #this env if for testing only env = { 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;' 'q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch', 'HTTP_ACCEPT_LANGUAGE': 'uk,en-US;q=0.8,en;q=0.6', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'keep-alive', # 'HTTP_HOST': 'localhost:8080', 'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux i686)', # 'PATH_INFO': '/', # 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'REQUEST_URI': '/', 'SCRIPT_NAME': '', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.errors': None, 'wsgi.file_wrapper': None, # 'wsgi.input': BytesIO(ntob('', 'utf-8')), 'wsgi.multiprocess': False, 'wsgi.multithread': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), } adapter = url_map.bind_to_environ(env) return adapter
python
def get_url_adapter(_domain_name): """ Fetch a domain url_adapter object, and bind it to according domain """ from werkzeug._compat import wsgi_decoding_dance domain = application.domains.get(_domain_name, {}) server_name = None if domain.get('domain', ''): server_name = domain['domain'] try: env = {} environ = request.environ env['url_scheme'] = environ['wsgi.url_scheme'] env['default_method'] = environ['REQUEST_METHOD'] def _get_wsgi_string(name): val = environ.get(name) if val is not None: return wsgi_decoding_dance(val, "utf-8") env['script_name'] = _get_wsgi_string('SCRIPT_NAME') env['path_info'] = _get_wsgi_string('PATH_INFO') env['query_args'] = _get_wsgi_string('QUERY_STRING') except: env = {} adapter = url_map.bind(server_name, **env) else: try: env = request.environ except: #this env if for testing only env = { 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;' 'q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch', 'HTTP_ACCEPT_LANGUAGE': 'uk,en-US;q=0.8,en;q=0.6', 'HTTP_CACHE_CONTROL': 'max-age=0', 'HTTP_CONNECTION': 'keep-alive', # 'HTTP_HOST': 'localhost:8080', 'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux i686)', # 'PATH_INFO': '/', # 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REQUEST_METHOD': 'GET', 'REQUEST_URI': '/', 'SCRIPT_NAME': '', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '8080', 'SERVER_PROTOCOL': 'HTTP/1.1', 'wsgi.errors': None, 'wsgi.file_wrapper': None, # 'wsgi.input': BytesIO(ntob('', 'utf-8')), 'wsgi.multiprocess': False, 'wsgi.multithread': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0), } adapter = url_map.bind_to_environ(env) return adapter
[ "def", "get_url_adapter", "(", "_domain_name", ")", ":", "from", "werkzeug", ".", "_compat", "import", "wsgi_decoding_dance", "domain", "=", "application", ".", "domains", ".", "get", "(", "_domain_name", ",", "{", "}", ")", "server_name", "=", "None", "if", "domain", ".", "get", "(", "'domain'", ",", "''", ")", ":", "server_name", "=", "domain", "[", "'domain'", "]", "try", ":", "env", "=", "{", "}", "environ", "=", "request", ".", "environ", "env", "[", "'url_scheme'", "]", "=", "environ", "[", "'wsgi.url_scheme'", "]", "env", "[", "'default_method'", "]", "=", "environ", "[", "'REQUEST_METHOD'", "]", "def", "_get_wsgi_string", "(", "name", ")", ":", "val", "=", "environ", ".", "get", "(", "name", ")", "if", "val", "is", "not", "None", ":", "return", "wsgi_decoding_dance", "(", "val", ",", "\"utf-8\"", ")", "env", "[", "'script_name'", "]", "=", "_get_wsgi_string", "(", "'SCRIPT_NAME'", ")", "env", "[", "'path_info'", "]", "=", "_get_wsgi_string", "(", "'PATH_INFO'", ")", "env", "[", "'query_args'", "]", "=", "_get_wsgi_string", "(", "'QUERY_STRING'", ")", "except", ":", "env", "=", "{", "}", "adapter", "=", "url_map", ".", "bind", "(", "server_name", ",", "*", "*", "env", ")", "else", ":", "try", ":", "env", "=", "request", ".", "environ", "except", ":", "#this env if for testing only", "env", "=", "{", "'HTTP_ACCEPT'", ":", "'text/html,application/xhtml+xml,application/xml;'", "'q=0.9,*/*;q=0.8'", ",", "'HTTP_ACCEPT_CHARSET'", ":", "'ISO-8859-1,utf-8;q=0.7,*;q=0.3'", ",", "'HTTP_ACCEPT_ENCODING'", ":", "'gzip,deflate,sdch'", ",", "'HTTP_ACCEPT_LANGUAGE'", ":", "'uk,en-US;q=0.8,en;q=0.6'", ",", "'HTTP_CACHE_CONTROL'", ":", "'max-age=0'", ",", "'HTTP_CONNECTION'", ":", "'keep-alive'", ",", "# 'HTTP_HOST': 'localhost:8080',", "'HTTP_USER_AGENT'", ":", "'Mozilla/5.0 (X11; Linux i686)'", ",", "# 'PATH_INFO': '/',", "# 'QUERY_STRING': '',", "'REMOTE_ADDR'", ":", "'127.0.0.1'", ",", "'REQUEST_METHOD'", ":", "'GET'", ",", "'REQUEST_URI'", ":", "'/'", ",", "'SCRIPT_NAME'", ":", "''", ",", "'SERVER_NAME'", ":", "'localhost'", ",", "'SERVER_PORT'", ":", "'8080'", ",", "'SERVER_PROTOCOL'", ":", "'HTTP/1.1'", ",", "'wsgi.errors'", ":", "None", ",", "'wsgi.file_wrapper'", ":", "None", ",", "# 'wsgi.input': BytesIO(ntob('', 'utf-8')),", "'wsgi.multiprocess'", ":", "False", ",", "'wsgi.multithread'", ":", "False", ",", "'wsgi.run_once'", ":", "False", ",", "'wsgi.url_scheme'", ":", "'http'", ",", "'wsgi.version'", ":", "(", "1", ",", "0", ")", ",", "}", "adapter", "=", "url_map", ".", "bind_to_environ", "(", "env", ")", "return", "adapter" ]
Fetch a domain url_adapter object, and bind it to according domain
[ "Fetch", "a", "domain", "url_adapter", "object", "and", "bind", "it", "to", "according", "domain" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/SimpleFrame.py#L278-L339
6,927
limodou/uliweb
uliweb/core/SimpleFrame.py
get_app_dir
def get_app_dir(app): """ Get an app's directory """ path = __app_dirs__.get(app) if path is not None: return path else: p = app.split('.') try: path = pkg.resource_filename(p[0], '') except ImportError as e: log.error("Can't import app %s" % app) log.exception(e) path = '' if len(p) > 1: path = os.path.join(path, *p[1:]) __app_dirs__[app] = path return path
python
def get_app_dir(app): """ Get an app's directory """ path = __app_dirs__.get(app) if path is not None: return path else: p = app.split('.') try: path = pkg.resource_filename(p[0], '') except ImportError as e: log.error("Can't import app %s" % app) log.exception(e) path = '' if len(p) > 1: path = os.path.join(path, *p[1:]) __app_dirs__[app] = path return path
[ "def", "get_app_dir", "(", "app", ")", ":", "path", "=", "__app_dirs__", ".", "get", "(", "app", ")", "if", "path", "is", "not", "None", ":", "return", "path", "else", ":", "p", "=", "app", ".", "split", "(", "'.'", ")", "try", ":", "path", "=", "pkg", ".", "resource_filename", "(", "p", "[", "0", "]", ",", "''", ")", "except", "ImportError", "as", "e", ":", "log", ".", "error", "(", "\"Can't import app %s\"", "%", "app", ")", "log", ".", "exception", "(", "e", ")", "path", "=", "''", "if", "len", "(", "p", ")", ">", "1", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "*", "p", "[", "1", ":", "]", ")", "__app_dirs__", "[", "app", "]", "=", "path", "return", "path" ]
Get an app's directory
[ "Get", "an", "app", "s", "directory" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/SimpleFrame.py#L405-L424
6,928
limodou/uliweb
uliweb/core/SimpleFrame.py
Dispatcher.get_file
def get_file(self, filename, dir='static'): """ get_file will search from apps directory """ if os.path.exists(filename): return filename dirs = self.apps if dir: fname = os.path.join(dir, filename) else: fname = filename for d in reversed(dirs): path = pkg.resource_filename(d, fname) if os.path.exists(path): return path return None
python
def get_file(self, filename, dir='static'): """ get_file will search from apps directory """ if os.path.exists(filename): return filename dirs = self.apps if dir: fname = os.path.join(dir, filename) else: fname = filename for d in reversed(dirs): path = pkg.resource_filename(d, fname) if os.path.exists(path): return path return None
[ "def", "get_file", "(", "self", ",", "filename", ",", "dir", "=", "'static'", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "filename", "dirs", "=", "self", ".", "apps", "if", "dir", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "dir", ",", "filename", ")", "else", ":", "fname", "=", "filename", "for", "d", "in", "reversed", "(", "dirs", ")", ":", "path", "=", "pkg", ".", "resource_filename", "(", "d", ",", "fname", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "return", "None" ]
get_file will search from apps directory
[ "get_file", "will", "search", "from", "apps", "directory" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/SimpleFrame.py#L842-L857
6,929
limodou/uliweb
uliweb/core/SimpleFrame.py
Dispatcher.get_template_dirs
def get_template_dirs(self): """ Get templates directory from apps, but in reversed order, so the same named template file will be overrided by latter defined app """ def if_not_empty(dir): if not os.path.exists(dir): return for root, dirs, files in os.walk(dir): if dirs: return True for f in files: if f != 'readme.txt': return True template_dirs = [os.path.join(self.project_dir, x) for x in settings.GLOBAL.TEMPLATE_DIRS or []] taglibs_dirs = [] for p in reversed(self.apps): app_path = get_app_dir(p) path = os.path.join(app_path, 'templates') if if_not_empty(path): template_dirs.append(path) path = os.path.join(app_path, 'taglibs') if if_not_empty(path): taglibs_dirs.append(path) Dispatcher.template_dirs = template_dirs Dispatcher.taglibs_dirs = taglibs_dirs
python
def get_template_dirs(self): """ Get templates directory from apps, but in reversed order, so the same named template file will be overrided by latter defined app """ def if_not_empty(dir): if not os.path.exists(dir): return for root, dirs, files in os.walk(dir): if dirs: return True for f in files: if f != 'readme.txt': return True template_dirs = [os.path.join(self.project_dir, x) for x in settings.GLOBAL.TEMPLATE_DIRS or []] taglibs_dirs = [] for p in reversed(self.apps): app_path = get_app_dir(p) path = os.path.join(app_path, 'templates') if if_not_empty(path): template_dirs.append(path) path = os.path.join(app_path, 'taglibs') if if_not_empty(path): taglibs_dirs.append(path) Dispatcher.template_dirs = template_dirs Dispatcher.taglibs_dirs = taglibs_dirs
[ "def", "get_template_dirs", "(", "self", ")", ":", "def", "if_not_empty", "(", "dir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dir", ")", ":", "return", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "dir", ")", ":", "if", "dirs", ":", "return", "True", "for", "f", "in", "files", ":", "if", "f", "!=", "'readme.txt'", ":", "return", "True", "template_dirs", "=", "[", "os", ".", "path", ".", "join", "(", "self", ".", "project_dir", ",", "x", ")", "for", "x", "in", "settings", ".", "GLOBAL", ".", "TEMPLATE_DIRS", "or", "[", "]", "]", "taglibs_dirs", "=", "[", "]", "for", "p", "in", "reversed", "(", "self", ".", "apps", ")", ":", "app_path", "=", "get_app_dir", "(", "p", ")", "path", "=", "os", ".", "path", ".", "join", "(", "app_path", ",", "'templates'", ")", "if", "if_not_empty", "(", "path", ")", ":", "template_dirs", ".", "append", "(", "path", ")", "path", "=", "os", ".", "path", ".", "join", "(", "app_path", ",", "'taglibs'", ")", "if", "if_not_empty", "(", "path", ")", ":", "taglibs_dirs", ".", "append", "(", "path", ")", "Dispatcher", ".", "template_dirs", "=", "template_dirs", "Dispatcher", ".", "taglibs_dirs", "=", "taglibs_dirs" ]
Get templates directory from apps, but in reversed order, so the same named template file will be overrided by latter defined app
[ "Get", "templates", "directory", "from", "apps", "but", "in", "reversed", "order", "so", "the", "same", "named", "template", "file", "will", "be", "overrided", "by", "latter", "defined", "app" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/SimpleFrame.py#L1406-L1434
6,930
limodou/uliweb
uliweb/contrib/redis_cli/__init__.py
get_lock
def get_lock(key, value=None, expiry_time=60): """Get a distribute lock""" from uliweb.utils.common import get_uuid redis = get_redis() value = value or get_uuid() return redis.set(key, value, ex=expiry_time, nx=True)
python
def get_lock(key, value=None, expiry_time=60): """Get a distribute lock""" from uliweb.utils.common import get_uuid redis = get_redis() value = value or get_uuid() return redis.set(key, value, ex=expiry_time, nx=True)
[ "def", "get_lock", "(", "key", ",", "value", "=", "None", ",", "expiry_time", "=", "60", ")", ":", "from", "uliweb", ".", "utils", ".", "common", "import", "get_uuid", "redis", "=", "get_redis", "(", ")", "value", "=", "value", "or", "get_uuid", "(", ")", "return", "redis", ".", "set", "(", "key", ",", "value", ",", "ex", "=", "expiry_time", ",", "nx", "=", "True", ")" ]
Get a distribute lock
[ "Get", "a", "distribute", "lock" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/redis_cli/__init__.py#L40-L46
6,931
limodou/uliweb
uliweb/contrib/redis_cli/__init__.py
set_lock
def set_lock(key, value=None, expiry_time=60): """Force to set a distribute lock""" from uliweb.utils.common import get_uuid redis = get_redis() value = value or get_uuid() return redis.set(key, value, ex=expiry_time, xx=True)
python
def set_lock(key, value=None, expiry_time=60): """Force to set a distribute lock""" from uliweb.utils.common import get_uuid redis = get_redis() value = value or get_uuid() return redis.set(key, value, ex=expiry_time, xx=True)
[ "def", "set_lock", "(", "key", ",", "value", "=", "None", ",", "expiry_time", "=", "60", ")", ":", "from", "uliweb", ".", "utils", ".", "common", "import", "get_uuid", "redis", "=", "get_redis", "(", ")", "value", "=", "value", "or", "get_uuid", "(", ")", "return", "redis", ".", "set", "(", "key", ",", "value", ",", "ex", "=", "expiry_time", ",", "xx", "=", "True", ")" ]
Force to set a distribute lock
[ "Force", "to", "set", "a", "distribute", "lock" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/redis_cli/__init__.py#L48-L54
6,932
limodou/uliweb
uliweb/contrib/redis_cli/__init__.py
after_init_apps
def after_init_apps(sender): """ Check redis version """ from uliweb import settings from uliweb.utils.common import log check = settings.get_var('REDIS/check_version') if check: client = get_redis() try: info = client.info() except Exception as e: log.exception(e) log.error('Redis is not started!') return redis_version = info['redis_version'] version = tuple(map(int, redis_version.split('.'))) op = re_compare_op.search(check) if op: _op = op.group() _v = check[op.end()+1:].strip() else: _op = '=' _v = check nv = tuple(map(int, _v.split('.'))) if _op == '=': flag = version[:len(nv)] == nv elif _op == '>=': flag = version >= nv elif _op == '>': flag = version > nv elif _op == '<=': flag = version <= nv elif _op == '<': flag = version < nv else: log.error("Can't support operator %s when check redis version" % _op) if not flag: log.error("Redis version %s is not matched what you want %s" % (redis_version, _v))
python
def after_init_apps(sender): """ Check redis version """ from uliweb import settings from uliweb.utils.common import log check = settings.get_var('REDIS/check_version') if check: client = get_redis() try: info = client.info() except Exception as e: log.exception(e) log.error('Redis is not started!') return redis_version = info['redis_version'] version = tuple(map(int, redis_version.split('.'))) op = re_compare_op.search(check) if op: _op = op.group() _v = check[op.end()+1:].strip() else: _op = '=' _v = check nv = tuple(map(int, _v.split('.'))) if _op == '=': flag = version[:len(nv)] == nv elif _op == '>=': flag = version >= nv elif _op == '>': flag = version > nv elif _op == '<=': flag = version <= nv elif _op == '<': flag = version < nv else: log.error("Can't support operator %s when check redis version" % _op) if not flag: log.error("Redis version %s is not matched what you want %s" % (redis_version, _v))
[ "def", "after_init_apps", "(", "sender", ")", ":", "from", "uliweb", "import", "settings", "from", "uliweb", ".", "utils", ".", "common", "import", "log", "check", "=", "settings", ".", "get_var", "(", "'REDIS/check_version'", ")", "if", "check", ":", "client", "=", "get_redis", "(", ")", "try", ":", "info", "=", "client", ".", "info", "(", ")", "except", "Exception", "as", "e", ":", "log", ".", "exception", "(", "e", ")", "log", ".", "error", "(", "'Redis is not started!'", ")", "return", "redis_version", "=", "info", "[", "'redis_version'", "]", "version", "=", "tuple", "(", "map", "(", "int", ",", "redis_version", ".", "split", "(", "'.'", ")", ")", ")", "op", "=", "re_compare_op", ".", "search", "(", "check", ")", "if", "op", ":", "_op", "=", "op", ".", "group", "(", ")", "_v", "=", "check", "[", "op", ".", "end", "(", ")", "+", "1", ":", "]", ".", "strip", "(", ")", "else", ":", "_op", "=", "'='", "_v", "=", "check", "nv", "=", "tuple", "(", "map", "(", "int", ",", "_v", ".", "split", "(", "'.'", ")", ")", ")", "if", "_op", "==", "'='", ":", "flag", "=", "version", "[", ":", "len", "(", "nv", ")", "]", "==", "nv", "elif", "_op", "==", "'>='", ":", "flag", "=", "version", ">=", "nv", "elif", "_op", "==", "'>'", ":", "flag", "=", "version", ">", "nv", "elif", "_op", "==", "'<='", ":", "flag", "=", "version", "<=", "nv", "elif", "_op", "==", "'<'", ":", "flag", "=", "version", "<", "nv", "else", ":", "log", ".", "error", "(", "\"Can't support operator %s when check redis version\"", "%", "_op", ")", "if", "not", "flag", ":", "log", ".", "error", "(", "\"Redis version %s is not matched what you want %s\"", "%", "(", "redis_version", ",", "_v", ")", ")" ]
Check redis version
[ "Check", "redis", "version" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/redis_cli/__init__.py#L57-L97
6,933
limodou/uliweb
uliweb/lib/werkzeug/contrib/atom.py
_make_text_block
def _make_text_block(name, content, content_type=None): """Helper function for the builder that creates an XML text block.""" if content_type == 'xhtml': return u'<%s type="xhtml"><div xmlns="%s">%s</div></%s>\n' % \ (name, XHTML_NAMESPACE, content, name) if not content_type: return u'<%s>%s</%s>\n' % (name, escape(content), name) return u'<%s type="%s">%s</%s>\n' % (name, content_type, escape(content), name)
python
def _make_text_block(name, content, content_type=None): """Helper function for the builder that creates an XML text block.""" if content_type == 'xhtml': return u'<%s type="xhtml"><div xmlns="%s">%s</div></%s>\n' % \ (name, XHTML_NAMESPACE, content, name) if not content_type: return u'<%s>%s</%s>\n' % (name, escape(content), name) return u'<%s type="%s">%s</%s>\n' % (name, content_type, escape(content), name)
[ "def", "_make_text_block", "(", "name", ",", "content", ",", "content_type", "=", "None", ")", ":", "if", "content_type", "==", "'xhtml'", ":", "return", "u'<%s type=\"xhtml\"><div xmlns=\"%s\">%s</div></%s>\\n'", "%", "(", "name", ",", "XHTML_NAMESPACE", ",", "content", ",", "name", ")", "if", "not", "content_type", ":", "return", "u'<%s>%s</%s>\\n'", "%", "(", "name", ",", "escape", "(", "content", ")", ",", "name", ")", "return", "u'<%s type=\"%s\">%s</%s>\\n'", "%", "(", "name", ",", "content_type", ",", "escape", "(", "content", ")", ",", "name", ")" ]
Helper function for the builder that creates an XML text block.
[ "Helper", "function", "for", "the", "builder", "that", "creates", "an", "XML", "text", "block", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/atom.py#L34-L42
6,934
limodou/uliweb
uliweb/utils/xltools.py
SimpleWriter._style_range
def _style_range(self, cell, cell_range, border=None, fill=None, font=None, alignment=None): """ Apply styles to a range of cells as if they were a single cell. :param ws: Excel worksheet instance :param range: An excel range to style (e.g. A1:F20) :param border: An openpyxl Border :param fill: An openpyxl PatternFill or GradientFill :param font: An openpyxl Font object """ from openpyxl.styles import Border, Side top = left = right = bottom = Side(border_style='thin', color=self.border_color) def border_add(border, top=None, right=None, left=None, bottom=None): top = top or border.top left = left or border.left right = right or border.right bottom = bottom or border.bottom return Border(top=top, left=left, right=right, bottom=bottom) cell.alignment = alignment cell.fill = fill rows = list(self.sheet[cell_range]) for cell in rows[0]: cell.border = border_add(cell.border, top=top) for cell in rows[-1]: cell.border = border_add(cell.border, bottom=bottom) for row in rows: l = row[0] r = row[-1] l.border = border_add(l.border, left=left) r.border = border_add(r.border, right=right)
python
def _style_range(self, cell, cell_range, border=None, fill=None, font=None, alignment=None): """ Apply styles to a range of cells as if they were a single cell. :param ws: Excel worksheet instance :param range: An excel range to style (e.g. A1:F20) :param border: An openpyxl Border :param fill: An openpyxl PatternFill or GradientFill :param font: An openpyxl Font object """ from openpyxl.styles import Border, Side top = left = right = bottom = Side(border_style='thin', color=self.border_color) def border_add(border, top=None, right=None, left=None, bottom=None): top = top or border.top left = left or border.left right = right or border.right bottom = bottom or border.bottom return Border(top=top, left=left, right=right, bottom=bottom) cell.alignment = alignment cell.fill = fill rows = list(self.sheet[cell_range]) for cell in rows[0]: cell.border = border_add(cell.border, top=top) for cell in rows[-1]: cell.border = border_add(cell.border, bottom=bottom) for row in rows: l = row[0] r = row[-1] l.border = border_add(l.border, left=left) r.border = border_add(r.border, right=right)
[ "def", "_style_range", "(", "self", ",", "cell", ",", "cell_range", ",", "border", "=", "None", ",", "fill", "=", "None", ",", "font", "=", "None", ",", "alignment", "=", "None", ")", ":", "from", "openpyxl", ".", "styles", "import", "Border", ",", "Side", "top", "=", "left", "=", "right", "=", "bottom", "=", "Side", "(", "border_style", "=", "'thin'", ",", "color", "=", "self", ".", "border_color", ")", "def", "border_add", "(", "border", ",", "top", "=", "None", ",", "right", "=", "None", ",", "left", "=", "None", ",", "bottom", "=", "None", ")", ":", "top", "=", "top", "or", "border", ".", "top", "left", "=", "left", "or", "border", ".", "left", "right", "=", "right", "or", "border", ".", "right", "bottom", "=", "bottom", "or", "border", ".", "bottom", "return", "Border", "(", "top", "=", "top", ",", "left", "=", "left", ",", "right", "=", "right", ",", "bottom", "=", "bottom", ")", "cell", ".", "alignment", "=", "alignment", "cell", ".", "fill", "=", "fill", "rows", "=", "list", "(", "self", ".", "sheet", "[", "cell_range", "]", ")", "for", "cell", "in", "rows", "[", "0", "]", ":", "cell", ".", "border", "=", "border_add", "(", "cell", ".", "border", ",", "top", "=", "top", ")", "for", "cell", "in", "rows", "[", "-", "1", "]", ":", "cell", ".", "border", "=", "border_add", "(", "cell", ".", "border", ",", "bottom", "=", "bottom", ")", "for", "row", "in", "rows", ":", "l", "=", "row", "[", "0", "]", "r", "=", "row", "[", "-", "1", "]", "l", ".", "border", "=", "border_add", "(", "l", ".", "border", ",", "left", "=", "left", ")", "r", ".", "border", "=", "border_add", "(", "r", ".", "border", ",", "right", "=", "right", ")" ]
Apply styles to a range of cells as if they were a single cell. :param ws: Excel worksheet instance :param range: An excel range to style (e.g. A1:F20) :param border: An openpyxl Border :param fill: An openpyxl PatternFill or GradientFill :param font: An openpyxl Font object
[ "Apply", "styles", "to", "a", "range", "of", "cells", "as", "if", "they", "were", "a", "single", "cell", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/xltools.py#L326-L362
6,935
limodou/uliweb
uliweb/lib/werkzeug/urls.py
url_unquote
def url_unquote(string, charset='utf-8', errors='replace', unsafe=''): """URL decode a single string with a given encoding. If the charset is set to `None` no unicode decoding is performed and raw bytes are returned. :param s: the string to unquote. :param charset: the charset of the query string. If set to `None` no unicode decoding will take place. :param errors: the error handling for the charset decoding. """ rv = _unquote_to_bytes(string, unsafe) if charset is not None: rv = rv.decode(charset, errors) return rv
python
def url_unquote(string, charset='utf-8', errors='replace', unsafe=''): """URL decode a single string with a given encoding. If the charset is set to `None` no unicode decoding is performed and raw bytes are returned. :param s: the string to unquote. :param charset: the charset of the query string. If set to `None` no unicode decoding will take place. :param errors: the error handling for the charset decoding. """ rv = _unquote_to_bytes(string, unsafe) if charset is not None: rv = rv.decode(charset, errors) return rv
[ "def", "url_unquote", "(", "string", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'replace'", ",", "unsafe", "=", "''", ")", ":", "rv", "=", "_unquote_to_bytes", "(", "string", ",", "unsafe", ")", "if", "charset", "is", "not", "None", ":", "rv", "=", "rv", ".", "decode", "(", "charset", ",", "errors", ")", "return", "rv" ]
URL decode a single string with a given encoding. If the charset is set to `None` no unicode decoding is performed and raw bytes are returned. :param s: the string to unquote. :param charset: the charset of the query string. If set to `None` no unicode decoding will take place. :param errors: the error handling for the charset decoding.
[ "URL", "decode", "a", "single", "string", "with", "a", "given", "encoding", ".", "If", "the", "charset", "is", "set", "to", "None", "no", "unicode", "decoding", "is", "performed", "and", "raw", "bytes", "are", "returned", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/urls.py#L439-L452
6,936
limodou/uliweb
uliweb/lib/werkzeug/urls.py
_URLMixin.decode_netloc
def decode_netloc(self): """Decodes the netloc part into a string.""" rv = _decode_idna(self.host or '') if ':' in rv: rv = '[%s]' % rv port = self.port if port is not None: rv = '%s:%d' % (rv, port) auth = ':'.join(filter(None, [ _url_unquote_legacy(self.raw_username or '', '/:%@'), _url_unquote_legacy(self.raw_password or '', '/:%@'), ])) if auth: rv = '%s@%s' % (auth, rv) return rv
python
def decode_netloc(self): """Decodes the netloc part into a string.""" rv = _decode_idna(self.host or '') if ':' in rv: rv = '[%s]' % rv port = self.port if port is not None: rv = '%s:%d' % (rv, port) auth = ':'.join(filter(None, [ _url_unquote_legacy(self.raw_username or '', '/:%@'), _url_unquote_legacy(self.raw_password or '', '/:%@'), ])) if auth: rv = '%s@%s' % (auth, rv) return rv
[ "def", "decode_netloc", "(", "self", ")", ":", "rv", "=", "_decode_idna", "(", "self", ".", "host", "or", "''", ")", "if", "':'", "in", "rv", ":", "rv", "=", "'[%s]'", "%", "rv", "port", "=", "self", ".", "port", "if", "port", "is", "not", "None", ":", "rv", "=", "'%s:%d'", "%", "(", "rv", ",", "port", ")", "auth", "=", "':'", ".", "join", "(", "filter", "(", "None", ",", "[", "_url_unquote_legacy", "(", "self", ".", "raw_username", "or", "''", ",", "'/:%@'", ")", ",", "_url_unquote_legacy", "(", "self", ".", "raw_password", "or", "''", ",", "'/:%@'", ")", ",", "]", ")", ")", "if", "auth", ":", "rv", "=", "'%s@%s'", "%", "(", "auth", ",", "rv", ")", "return", "rv" ]
Decodes the netloc part into a string.
[ "Decodes", "the", "netloc", "part", "into", "a", "string", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/urls.py#L139-L154
6,937
limodou/uliweb
uliweb/lib/werkzeug/urls.py
BytesURL.decode
def decode(self, charset='utf-8', errors='replace'): """Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment. """ return URL( self.scheme.decode('ascii'), self.decode_netloc(), self.path.decode(charset, errors), self.query.decode(charset, errors), self.fragment.decode(charset, errors) )
python
def decode(self, charset='utf-8', errors='replace'): """Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment. """ return URL( self.scheme.decode('ascii'), self.decode_netloc(), self.path.decode(charset, errors), self.query.decode(charset, errors), self.fragment.decode(charset, errors) )
[ "def", "decode", "(", "self", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'replace'", ")", ":", "return", "URL", "(", "self", ".", "scheme", ".", "decode", "(", "'ascii'", ")", ",", "self", ".", "decode_netloc", "(", ")", ",", "self", ".", "path", ".", "decode", "(", "charset", ",", "errors", ")", ",", "self", ".", "query", ".", "decode", "(", "charset", ",", "errors", ")", ",", "self", ".", "fragment", ".", "decode", "(", "charset", ",", "errors", ")", ")" ]
Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment.
[ "Decodes", "the", "URL", "to", "a", "tuple", "made", "out", "of", "strings", ".", "The", "charset", "is", "only", "being", "used", "for", "the", "path", "query", "and", "fragment", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/urls.py#L270-L280
6,938
limodou/uliweb
uliweb/lib/werkzeug/contrib/iterio.py
_mixed_join
def _mixed_join(iterable, sentinel): """concatenate any string type in an intelligent way.""" iterator = iter(iterable) first_item = next(iterator, sentinel) if isinstance(first_item, bytes): return first_item + b''.join(iterator) return first_item + u''.join(iterator)
python
def _mixed_join(iterable, sentinel): """concatenate any string type in an intelligent way.""" iterator = iter(iterable) first_item = next(iterator, sentinel) if isinstance(first_item, bytes): return first_item + b''.join(iterator) return first_item + u''.join(iterator)
[ "def", "_mixed_join", "(", "iterable", ",", "sentinel", ")", ":", "iterator", "=", "iter", "(", "iterable", ")", "first_item", "=", "next", "(", "iterator", ",", "sentinel", ")", "if", "isinstance", "(", "first_item", ",", "bytes", ")", ":", "return", "first_item", "+", "b''", ".", "join", "(", "iterator", ")", "return", "first_item", "+", "u''", ".", "join", "(", "iterator", ")" ]
concatenate any string type in an intelligent way.
[ "concatenate", "any", "string", "type", "in", "an", "intelligent", "way", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/iterio.py#L50-L56
6,939
limodou/uliweb
uliweb/lib/werkzeug/contrib/iterio.py
IterO._buf_append
def _buf_append(self, string): '''Replace string directly without appending to an empty string, avoiding type issues.''' if not self._buf: self._buf = string else: self._buf += string
python
def _buf_append(self, string): '''Replace string directly without appending to an empty string, avoiding type issues.''' if not self._buf: self._buf = string else: self._buf += string
[ "def", "_buf_append", "(", "self", ",", "string", ")", ":", "if", "not", "self", ".", "_buf", ":", "self", ".", "_buf", "=", "string", "else", ":", "self", ".", "_buf", "+=", "string" ]
Replace string directly without appending to an empty string, avoiding type issues.
[ "Replace", "string", "directly", "without", "appending", "to", "an", "empty", "string", "avoiding", "type", "issues", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/iterio.py#L231-L237
6,940
limodou/uliweb
uliweb/lib/werkzeug/http.py
quote_etag
def quote_etag(etag, weak=False): """Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak". """ if '"' in etag: raise ValueError('invalid etag') etag = '"%s"' % etag if weak: etag = 'w/' + etag return etag
python
def quote_etag(etag, weak=False): """Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak". """ if '"' in etag: raise ValueError('invalid etag') etag = '"%s"' % etag if weak: etag = 'w/' + etag return etag
[ "def", "quote_etag", "(", "etag", ",", "weak", "=", "False", ")", ":", "if", "'\"'", "in", "etag", ":", "raise", "ValueError", "(", "'invalid etag'", ")", "etag", "=", "'\"%s\"'", "%", "etag", "if", "weak", ":", "etag", "=", "'w/'", "+", "etag", "return", "etag" ]
Quote an etag. :param etag: the etag to quote. :param weak: set to `True` to tag it "weak".
[ "Quote", "an", "etag", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/http.py#L582-L593
6,941
limodou/uliweb
uliweb/lib/werkzeug/http.py
parse_etags
def parse_etags(value): """Parse an etag header. :param value: the tag header to parse :return: an :class:`~werkzeug.datastructures.ETags` object. """ if not value: return ETags() strong = [] weak = [] end = len(value) pos = 0 while pos < end: match = _etag_re.match(value, pos) if match is None: break is_weak, quoted, raw = match.groups() if raw == '*': return ETags(star_tag=True) elif quoted: raw = quoted if is_weak: weak.append(raw) else: strong.append(raw) pos = match.end() return ETags(strong, weak)
python
def parse_etags(value): """Parse an etag header. :param value: the tag header to parse :return: an :class:`~werkzeug.datastructures.ETags` object. """ if not value: return ETags() strong = [] weak = [] end = len(value) pos = 0 while pos < end: match = _etag_re.match(value, pos) if match is None: break is_weak, quoted, raw = match.groups() if raw == '*': return ETags(star_tag=True) elif quoted: raw = quoted if is_weak: weak.append(raw) else: strong.append(raw) pos = match.end() return ETags(strong, weak)
[ "def", "parse_etags", "(", "value", ")", ":", "if", "not", "value", ":", "return", "ETags", "(", ")", "strong", "=", "[", "]", "weak", "=", "[", "]", "end", "=", "len", "(", "value", ")", "pos", "=", "0", "while", "pos", "<", "end", ":", "match", "=", "_etag_re", ".", "match", "(", "value", ",", "pos", ")", "if", "match", "is", "None", ":", "break", "is_weak", ",", "quoted", ",", "raw", "=", "match", ".", "groups", "(", ")", "if", "raw", "==", "'*'", ":", "return", "ETags", "(", "star_tag", "=", "True", ")", "elif", "quoted", ":", "raw", "=", "quoted", "if", "is_weak", ":", "weak", ".", "append", "(", "raw", ")", "else", ":", "strong", ".", "append", "(", "raw", ")", "pos", "=", "match", ".", "end", "(", ")", "return", "ETags", "(", "strong", ",", "weak", ")" ]
Parse an etag header. :param value: the tag header to parse :return: an :class:`~werkzeug.datastructures.ETags` object.
[ "Parse", "an", "etag", "header", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/http.py#L619-L645
6,942
limodou/uliweb
uliweb/utils/process.py
wait_pid
def wait_pid(pid, timeout=None, callback=None): """Wait for process with pid 'pid' to terminate and return its exit status code as an integer. If pid is not a children of os.getpid() (current process) just waits until the process disappears and return None. If pid does not exist at all return None immediately. Raise TimeoutExpired on timeout expired (if specified). """ def check_timeout(delay): if timeout is not None: if time.time() >= stop_at: if callback: callback(pid) else: raise TimeoutExpired time.sleep(delay) return min(delay * 2, 0.04) if timeout is not None: waitcall = lambda: os.waitpid(pid, os.WNOHANG) stop_at = time.time() + timeout else: waitcall = lambda: os.waitpid(pid, 0) delay = 0.0001 while 1: try: retpid, status = waitcall() except OSError as err: if err.errno == errno.EINTR: delay = check_timeout(delay) continue elif err.errno == errno.ECHILD: # This has two meanings: # - pid is not a child of os.getpid() in which case # we keep polling until it's gone # - pid never existed in the first place # In both cases we'll eventually return None as we # can't determine its exit status code. while 1: if pid_exists(pid): delay = check_timeout(delay) else: return else: raise else: if retpid == 0: # WNOHANG was used, pid is still running delay = check_timeout(delay) continue # process exited due to a signal; return the integer of # that signal if os.WIFSIGNALED(status): return os.WTERMSIG(status) # process exited using exit(2) system call; return the # integer exit(2) system call has been called with elif os.WIFEXITED(status): return os.WEXITSTATUS(status) else: # should never happen raise RuntimeError("unknown process exit status")
python
def wait_pid(pid, timeout=None, callback=None): """Wait for process with pid 'pid' to terminate and return its exit status code as an integer. If pid is not a children of os.getpid() (current process) just waits until the process disappears and return None. If pid does not exist at all return None immediately. Raise TimeoutExpired on timeout expired (if specified). """ def check_timeout(delay): if timeout is not None: if time.time() >= stop_at: if callback: callback(pid) else: raise TimeoutExpired time.sleep(delay) return min(delay * 2, 0.04) if timeout is not None: waitcall = lambda: os.waitpid(pid, os.WNOHANG) stop_at = time.time() + timeout else: waitcall = lambda: os.waitpid(pid, 0) delay = 0.0001 while 1: try: retpid, status = waitcall() except OSError as err: if err.errno == errno.EINTR: delay = check_timeout(delay) continue elif err.errno == errno.ECHILD: # This has two meanings: # - pid is not a child of os.getpid() in which case # we keep polling until it's gone # - pid never existed in the first place # In both cases we'll eventually return None as we # can't determine its exit status code. while 1: if pid_exists(pid): delay = check_timeout(delay) else: return else: raise else: if retpid == 0: # WNOHANG was used, pid is still running delay = check_timeout(delay) continue # process exited due to a signal; return the integer of # that signal if os.WIFSIGNALED(status): return os.WTERMSIG(status) # process exited using exit(2) system call; return the # integer exit(2) system call has been called with elif os.WIFEXITED(status): return os.WEXITSTATUS(status) else: # should never happen raise RuntimeError("unknown process exit status")
[ "def", "wait_pid", "(", "pid", ",", "timeout", "=", "None", ",", "callback", "=", "None", ")", ":", "def", "check_timeout", "(", "delay", ")", ":", "if", "timeout", "is", "not", "None", ":", "if", "time", ".", "time", "(", ")", ">=", "stop_at", ":", "if", "callback", ":", "callback", "(", "pid", ")", "else", ":", "raise", "TimeoutExpired", "time", ".", "sleep", "(", "delay", ")", "return", "min", "(", "delay", "*", "2", ",", "0.04", ")", "if", "timeout", "is", "not", "None", ":", "waitcall", "=", "lambda", ":", "os", ".", "waitpid", "(", "pid", ",", "os", ".", "WNOHANG", ")", "stop_at", "=", "time", ".", "time", "(", ")", "+", "timeout", "else", ":", "waitcall", "=", "lambda", ":", "os", ".", "waitpid", "(", "pid", ",", "0", ")", "delay", "=", "0.0001", "while", "1", ":", "try", ":", "retpid", ",", "status", "=", "waitcall", "(", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "==", "errno", ".", "EINTR", ":", "delay", "=", "check_timeout", "(", "delay", ")", "continue", "elif", "err", ".", "errno", "==", "errno", ".", "ECHILD", ":", "# This has two meanings:", "# - pid is not a child of os.getpid() in which case", "# we keep polling until it's gone", "# - pid never existed in the first place", "# In both cases we'll eventually return None as we", "# can't determine its exit status code.", "while", "1", ":", "if", "pid_exists", "(", "pid", ")", ":", "delay", "=", "check_timeout", "(", "delay", ")", "else", ":", "return", "else", ":", "raise", "else", ":", "if", "retpid", "==", "0", ":", "# WNOHANG was used, pid is still running", "delay", "=", "check_timeout", "(", "delay", ")", "continue", "# process exited due to a signal; return the integer of", "# that signal", "if", "os", ".", "WIFSIGNALED", "(", "status", ")", ":", "return", "os", ".", "WTERMSIG", "(", "status", ")", "# process exited using exit(2) system call; return the", "# integer exit(2) system call has been called with", "elif", "os", ".", "WIFEXITED", "(", "status", ")", ":", "return", "os", ".", "WEXITSTATUS", "(", "status", ")", "else", ":", "# should never happen", "raise", "RuntimeError", "(", "\"unknown process exit status\"", ")" ]
Wait for process with pid 'pid' to terminate and return its exit status code as an integer. If pid is not a children of os.getpid() (current process) just waits until the process disappears and return None. If pid does not exist at all return None immediately. Raise TimeoutExpired on timeout expired (if specified).
[ "Wait", "for", "process", "with", "pid", "pid", "to", "terminate", "and", "return", "its", "exit", "status", "code", "as", "an", "integer", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/process.py#L30-L94
6,943
limodou/uliweb
uliweb/contrib/upload/__init__.py
FileServing.get_filename
def get_filename(self, filename, filesystem=False, convert=False, subpath=''): """ Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class @param subpath: sub folder in to_path """ from uliweb.utils.common import safe_unicode #make sure the filename is unicode s = settings.GLOBAL if convert: _p, _f = os.path.split(filename) _filename = os.path.join(_p, self.filename_convert(_f)) else: _filename = filename nfile = safe_unicode(_filename, s.HTMLPAGE_ENCODING) if subpath: paths = [application_path(self.to_path), subpath, nfile] else: paths = [application_path(self.to_path), nfile] f = os.path.normpath(os.path.join(*paths)).replace('\\', '/') if filesystem: return files.encode_filename(f, to_encoding=s.FILESYSTEM_ENCODING) return f
python
def get_filename(self, filename, filesystem=False, convert=False, subpath=''): """ Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class @param subpath: sub folder in to_path """ from uliweb.utils.common import safe_unicode #make sure the filename is unicode s = settings.GLOBAL if convert: _p, _f = os.path.split(filename) _filename = os.path.join(_p, self.filename_convert(_f)) else: _filename = filename nfile = safe_unicode(_filename, s.HTMLPAGE_ENCODING) if subpath: paths = [application_path(self.to_path), subpath, nfile] else: paths = [application_path(self.to_path), nfile] f = os.path.normpath(os.path.join(*paths)).replace('\\', '/') if filesystem: return files.encode_filename(f, to_encoding=s.FILESYSTEM_ENCODING) return f
[ "def", "get_filename", "(", "self", ",", "filename", ",", "filesystem", "=", "False", ",", "convert", "=", "False", ",", "subpath", "=", "''", ")", ":", "from", "uliweb", ".", "utils", ".", "common", "import", "safe_unicode", "#make sure the filename is unicode\r", "s", "=", "settings", ".", "GLOBAL", "if", "convert", ":", "_p", ",", "_f", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "_filename", "=", "os", ".", "path", ".", "join", "(", "_p", ",", "self", ".", "filename_convert", "(", "_f", ")", ")", "else", ":", "_filename", "=", "filename", "nfile", "=", "safe_unicode", "(", "_filename", ",", "s", ".", "HTMLPAGE_ENCODING", ")", "if", "subpath", ":", "paths", "=", "[", "application_path", "(", "self", ".", "to_path", ")", ",", "subpath", ",", "nfile", "]", "else", ":", "paths", "=", "[", "application_path", "(", "self", ".", "to_path", ")", ",", "nfile", "]", "f", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "*", "paths", ")", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "filesystem", ":", "return", "files", ".", "encode_filename", "(", "f", ",", "to_encoding", "=", "s", ".", "FILESYSTEM_ENCODING", ")", "return", "f" ]
Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class @param subpath: sub folder in to_path
[ "Get", "the", "filename", "according", "to", "self", ".", "to_path", "and", "if", "filesystem", "is", "False", "then", "return", "unicode", "filename", "otherwise", "return", "filesystem", "encoded", "filename" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/upload/__init__.py#L82-L111
6,944
limodou/uliweb
uliweb/contrib/upload/__init__.py
FileServing.download
def download(self, filename, action='download', x_filename='', x_sendfile=None, real_filename=''): """ action will be "download", "inline" and if the request.GET has 'action', then the action will be replaced by it. """ from uliweb import request from uliweb.utils.common import safe_str from uliweb.utils.filedown import filedown s = settings.GLOBAL action = request.GET.get('action', action) if not real_filename: real_filename = self.get_filename(filename, True, convert=False) else: real_filename = files.encode_filename(real_filename, to_encoding=s.FILESYSTEM_ENCODING) if not x_filename: x_filename = safe_str(filename, s.FILESYSTEM_ENCODING) if self.x_file_prefix: x_filename = os.path.normpath(os.path.join(self.x_file_prefix, x_filename)).replace('\\', '/') xsend_flag = bool(self.x_sendfile) if x_sendfile is None else x_sendfile return filedown(request.environ, filename, action=action, x_sendfile=xsend_flag, x_header_name=self.x_header_name, x_filename=x_filename, real_filename=real_filename)
python
def download(self, filename, action='download', x_filename='', x_sendfile=None, real_filename=''): """ action will be "download", "inline" and if the request.GET has 'action', then the action will be replaced by it. """ from uliweb import request from uliweb.utils.common import safe_str from uliweb.utils.filedown import filedown s = settings.GLOBAL action = request.GET.get('action', action) if not real_filename: real_filename = self.get_filename(filename, True, convert=False) else: real_filename = files.encode_filename(real_filename, to_encoding=s.FILESYSTEM_ENCODING) if not x_filename: x_filename = safe_str(filename, s.FILESYSTEM_ENCODING) if self.x_file_prefix: x_filename = os.path.normpath(os.path.join(self.x_file_prefix, x_filename)).replace('\\', '/') xsend_flag = bool(self.x_sendfile) if x_sendfile is None else x_sendfile return filedown(request.environ, filename, action=action, x_sendfile=xsend_flag, x_header_name=self.x_header_name, x_filename=x_filename, real_filename=real_filename)
[ "def", "download", "(", "self", ",", "filename", ",", "action", "=", "'download'", ",", "x_filename", "=", "''", ",", "x_sendfile", "=", "None", ",", "real_filename", "=", "''", ")", ":", "from", "uliweb", "import", "request", "from", "uliweb", ".", "utils", ".", "common", "import", "safe_str", "from", "uliweb", ".", "utils", ".", "filedown", "import", "filedown", "s", "=", "settings", ".", "GLOBAL", "action", "=", "request", ".", "GET", ".", "get", "(", "'action'", ",", "action", ")", "if", "not", "real_filename", ":", "real_filename", "=", "self", ".", "get_filename", "(", "filename", ",", "True", ",", "convert", "=", "False", ")", "else", ":", "real_filename", "=", "files", ".", "encode_filename", "(", "real_filename", ",", "to_encoding", "=", "s", ".", "FILESYSTEM_ENCODING", ")", "if", "not", "x_filename", ":", "x_filename", "=", "safe_str", "(", "filename", ",", "s", ".", "FILESYSTEM_ENCODING", ")", "if", "self", ".", "x_file_prefix", ":", "x_filename", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "x_file_prefix", ",", "x_filename", ")", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "xsend_flag", "=", "bool", "(", "self", ".", "x_sendfile", ")", "if", "x_sendfile", "is", "None", "else", "x_sendfile", "return", "filedown", "(", "request", ".", "environ", ",", "filename", ",", "action", "=", "action", ",", "x_sendfile", "=", "xsend_flag", ",", "x_header_name", "=", "self", ".", "x_header_name", ",", "x_filename", "=", "x_filename", ",", "real_filename", "=", "real_filename", ")" ]
action will be "download", "inline" and if the request.GET has 'action', then the action will be replaced by it.
[ "action", "will", "be", "download", "inline", "and", "if", "the", "request", ".", "GET", "has", "action", "then", "the", "action", "will", "be", "replaced", "by", "it", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/upload/__init__.py#L113-L139
6,945
limodou/uliweb
uliweb/contrib/auth/__init__.py
logout
def logout(): """ Remove the authenticated user's ID from the request. """ from uliweb import request delete_user_session() request.session.delete() request.user = None return True
python
def logout(): """ Remove the authenticated user's ID from the request. """ from uliweb import request delete_user_session() request.session.delete() request.user = None return True
[ "def", "logout", "(", ")", ":", "from", "uliweb", "import", "request", "delete_user_session", "(", ")", "request", ".", "session", ".", "delete", "(", ")", "request", ".", "user", "=", "None", "return", "True" ]
Remove the authenticated user's ID from the request.
[ "Remove", "the", "authenticated", "user", "s", "ID", "from", "the", "request", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/auth/__init__.py#L241-L250
6,946
limodou/uliweb
uliweb/lib/weto/backends/memcache_storage.py
Storage.get
def get(self, key): """ because memcached does not provide a function to check if a key is existed so here is a heck way, if the value is None, then raise Exception """ if isinstance(key, unicode): key = key.encode('utf-8') v = self.client.get(key) if v is None: raise KeyError("Cache key [%s] not found" % key) else: return v
python
def get(self, key): """ because memcached does not provide a function to check if a key is existed so here is a heck way, if the value is None, then raise Exception """ if isinstance(key, unicode): key = key.encode('utf-8') v = self.client.get(key) if v is None: raise KeyError("Cache key [%s] not found" % key) else: return v
[ "def", "get", "(", "self", ",", "key", ")", ":", "if", "isinstance", "(", "key", ",", "unicode", ")", ":", "key", "=", "key", ".", "encode", "(", "'utf-8'", ")", "v", "=", "self", ".", "client", ".", "get", "(", "key", ")", "if", "v", "is", "None", ":", "raise", "KeyError", "(", "\"Cache key [%s] not found\"", "%", "key", ")", "else", ":", "return", "v" ]
because memcached does not provide a function to check if a key is existed so here is a heck way, if the value is None, then raise Exception
[ "because", "memcached", "does", "not", "provide", "a", "function", "to", "check", "if", "a", "key", "is", "existed", "so", "here", "is", "a", "heck", "way", "if", "the", "value", "is", "None", "then", "raise", "Exception" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/weto/backends/memcache_storage.py#L20-L31
6,947
limodou/uliweb
uliweb/core/commands.py
get_commands
def get_commands(mod): """ Find commands from a module """ import inspect import types commands = {} def check(c): return (inspect.isclass(c) and issubclass(c, Command) and c is not Command and not issubclass(c, CommandManager)) for name in dir(mod): c = getattr(mod, name) if check(c): commands[c.name] = c return commands
python
def get_commands(mod): """ Find commands from a module """ import inspect import types commands = {} def check(c): return (inspect.isclass(c) and issubclass(c, Command) and c is not Command and not issubclass(c, CommandManager)) for name in dir(mod): c = getattr(mod, name) if check(c): commands[c.name] = c return commands
[ "def", "get_commands", "(", "mod", ")", ":", "import", "inspect", "import", "types", "commands", "=", "{", "}", "def", "check", "(", "c", ")", ":", "return", "(", "inspect", ".", "isclass", "(", "c", ")", "and", "issubclass", "(", "c", ",", "Command", ")", "and", "c", "is", "not", "Command", "and", "not", "issubclass", "(", "c", ",", "CommandManager", ")", ")", "for", "name", "in", "dir", "(", "mod", ")", ":", "c", "=", "getattr", "(", "mod", ",", "name", ")", "if", "check", "(", "c", ")", ":", "commands", "[", "c", ".", "name", "]", "=", "c", "return", "commands" ]
Find commands from a module
[ "Find", "commands", "from", "a", "module" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/commands.py#L53-L71
6,948
limodou/uliweb
uliweb/core/commands.py
Command.usage
def usage(self, subcommand): """ Return a brief description of how to use this command, by default from the attribute ``self.help``. """ if len(self.option_list) > 0: usage = '%%prog %s [options] %s' % (subcommand, self.args) else: usage = '%%prog %s %s' % (subcommand, self.args) if self.help: return '%s\n\n%s' % (usage, self.help) else: return usage
python
def usage(self, subcommand): """ Return a brief description of how to use this command, by default from the attribute ``self.help``. """ if len(self.option_list) > 0: usage = '%%prog %s [options] %s' % (subcommand, self.args) else: usage = '%%prog %s %s' % (subcommand, self.args) if self.help: return '%s\n\n%s' % (usage, self.help) else: return usage
[ "def", "usage", "(", "self", ",", "subcommand", ")", ":", "if", "len", "(", "self", ".", "option_list", ")", ">", "0", ":", "usage", "=", "'%%prog %s [options] %s'", "%", "(", "subcommand", ",", "self", ".", "args", ")", "else", ":", "usage", "=", "'%%prog %s %s'", "%", "(", "subcommand", ",", "self", ".", "args", ")", "if", "self", ".", "help", ":", "return", "'%s\\n\\n%s'", "%", "(", "usage", ",", "self", ".", "help", ")", "else", ":", "return", "usage" ]
Return a brief description of how to use this command, by default from the attribute ``self.help``.
[ "Return", "a", "brief", "description", "of", "how", "to", "use", "this", "command", "by", "default", "from", "the", "attribute", "self", ".", "help", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/commands.py#L128-L141
6,949
limodou/uliweb
uliweb/contrib/orm/commands.py
show_table
def show_table(name, table, i, total): """ Display table info, name is tablename table is table object i is current Index total is total of tables """ return '[%d/%d, %s] %s' % (i+1, total, table.__appname__, name)
python
def show_table(name, table, i, total): """ Display table info, name is tablename table is table object i is current Index total is total of tables """ return '[%d/%d, %s] %s' % (i+1, total, table.__appname__, name)
[ "def", "show_table", "(", "name", ",", "table", ",", "i", ",", "total", ")", ":", "return", "'[%d/%d, %s] %s'", "%", "(", "i", "+", "1", ",", "total", ",", "table", ".", "__appname__", ",", "name", ")" ]
Display table info, name is tablename table is table object i is current Index total is total of tables
[ "Display", "table", "info", "name", "is", "tablename", "table", "is", "table", "object", "i", "is", "current", "Index", "total", "is", "total", "of", "tables" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/orm/commands.py#L303-L311
6,950
limodou/uliweb
uliweb/lib/werkzeug/contrib/kickstart.py
TemplateLoader.get_template
def get_template(self, name): """Get a template from a given name.""" filename = path.join(self.search_path, *[p for p in name.split('/') if p and p[0] != '.']) if not path.exists(filename): raise TemplateNotFound(name) return Template.from_file(filename, self.encoding)
python
def get_template(self, name): """Get a template from a given name.""" filename = path.join(self.search_path, *[p for p in name.split('/') if p and p[0] != '.']) if not path.exists(filename): raise TemplateNotFound(name) return Template.from_file(filename, self.encoding)
[ "def", "get_template", "(", "self", ",", "name", ")", ":", "filename", "=", "path", ".", "join", "(", "self", ".", "search_path", ",", "*", "[", "p", "for", "p", "in", "name", ".", "split", "(", "'/'", ")", "if", "p", "and", "p", "[", "0", "]", "!=", "'.'", "]", ")", "if", "not", "path", ".", "exists", "(", "filename", ")", ":", "raise", "TemplateNotFound", "(", "name", ")", "return", "Template", ".", "from_file", "(", "filename", ",", "self", ".", "encoding", ")" ]
Get a template from a given name.
[ "Get", "a", "template", "from", "a", "given", "name", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/kickstart.py#L218-L224
6,951
limodou/uliweb
uliweb/lib/werkzeug/contrib/kickstart.py
TemplateLoader.render_to_string
def render_to_string(self, *args, **kwargs): """Load and render a template into a unicode string.""" try: template_name, args = args[0], args[1:] except IndexError: raise TypeError('name of template required') return self.get_template(template_name).render(*args, **kwargs)
python
def render_to_string(self, *args, **kwargs): """Load and render a template into a unicode string.""" try: template_name, args = args[0], args[1:] except IndexError: raise TypeError('name of template required') return self.get_template(template_name).render(*args, **kwargs)
[ "def", "render_to_string", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "template_name", ",", "args", "=", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", "except", "IndexError", ":", "raise", "TypeError", "(", "'name of template required'", ")", "return", "self", ".", "get_template", "(", "template_name", ")", ".", "render", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Load and render a template into a unicode string.
[ "Load", "and", "render", "a", "template", "into", "a", "unicode", "string", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/kickstart.py#L230-L236
6,952
limodou/uliweb
uliweb/lib/werkzeug/contrib/kickstart.py
GenshiTemplateLoader.get_template
def get_template(self, template_name): """Get the template which is at the given name""" try: return self.loader.load(template_name, encoding=self.encoding) except self.not_found_exception, e: # catch the exception raised by Genshi, convert it into a werkzeug # exception (for the sake of consistency) raise TemplateNotFound(template_name)
python
def get_template(self, template_name): """Get the template which is at the given name""" try: return self.loader.load(template_name, encoding=self.encoding) except self.not_found_exception, e: # catch the exception raised by Genshi, convert it into a werkzeug # exception (for the sake of consistency) raise TemplateNotFound(template_name)
[ "def", "get_template", "(", "self", ",", "template_name", ")", ":", "try", ":", "return", "self", ".", "loader", ".", "load", "(", "template_name", ",", "encoding", "=", "self", ".", "encoding", ")", "except", "self", ".", "not_found_exception", ",", "e", ":", "# catch the exception raised by Genshi, convert it into a werkzeug", "# exception (for the sake of consistency)", "raise", "TemplateNotFound", "(", "template_name", ")" ]
Get the template which is at the given name
[ "Get", "the", "template", "which", "is", "at", "the", "given", "name" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/kickstart.py#L271-L278
6,953
limodou/uliweb
uliweb/lib/werkzeug/contrib/kickstart.py
GenshiTemplateLoader.render_to_string
def render_to_string(self, template_name, context=None): """Load and render a template into an unicode string""" # create an empty context if no context was specified context = context or {} tmpl = self.get_template(template_name) # render the template into a unicode string (None means unicode) return tmpl. \ generate(**context). \ render(self.output_type, encoding=None)
python
def render_to_string(self, template_name, context=None): """Load and render a template into an unicode string""" # create an empty context if no context was specified context = context or {} tmpl = self.get_template(template_name) # render the template into a unicode string (None means unicode) return tmpl. \ generate(**context). \ render(self.output_type, encoding=None)
[ "def", "render_to_string", "(", "self", ",", "template_name", ",", "context", "=", "None", ")", ":", "# create an empty context if no context was specified", "context", "=", "context", "or", "{", "}", "tmpl", "=", "self", ".", "get_template", "(", "template_name", ")", "# render the template into a unicode string (None means unicode)", "return", "tmpl", ".", "generate", "(", "*", "*", "context", ")", ".", "render", "(", "self", ".", "output_type", ",", "encoding", "=", "None", ")" ]
Load and render a template into an unicode string
[ "Load", "and", "render", "a", "template", "into", "an", "unicode", "string" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/kickstart.py#L280-L288
6,954
limodou/uliweb
uliweb/contrib/rbac/dbinit.py
process_permission_roles
def process_permission_roles(perm, v): """ v is roles """ if isinstance(v, (tuple, list)): roles = v else: roles = [v] for r in roles: if isinstance(r, (tuple, list)): role_name, role_props = r else: role_name, role_props = r, '' role = Role.get(Role.c.name == role_name) if not role: raise Exception, 'Role [%s] not found.' % r rel = Rel.get((Rel.c.role==role.id) & (Rel.c.permission==perm.id)) if not rel: rel = Rel(role=role, permission=perm, props=role_props) msg = 'Add Relation(Permision=%s, Role=%s)...' % (name, role_name) else: rel.update(props=role_props) msg = 'Update Relation(Permision=%s, Role=%s)...' % (name, role_name) flag = rel.save() if flag: print msg
python
def process_permission_roles(perm, v): """ v is roles """ if isinstance(v, (tuple, list)): roles = v else: roles = [v] for r in roles: if isinstance(r, (tuple, list)): role_name, role_props = r else: role_name, role_props = r, '' role = Role.get(Role.c.name == role_name) if not role: raise Exception, 'Role [%s] not found.' % r rel = Rel.get((Rel.c.role==role.id) & (Rel.c.permission==perm.id)) if not rel: rel = Rel(role=role, permission=perm, props=role_props) msg = 'Add Relation(Permision=%s, Role=%s)...' % (name, role_name) else: rel.update(props=role_props) msg = 'Update Relation(Permision=%s, Role=%s)...' % (name, role_name) flag = rel.save() if flag: print msg
[ "def", "process_permission_roles", "(", "perm", ",", "v", ")", ":", "if", "isinstance", "(", "v", ",", "(", "tuple", ",", "list", ")", ")", ":", "roles", "=", "v", "else", ":", "roles", "=", "[", "v", "]", "for", "r", "in", "roles", ":", "if", "isinstance", "(", "r", ",", "(", "tuple", ",", "list", ")", ")", ":", "role_name", ",", "role_props", "=", "r", "else", ":", "role_name", ",", "role_props", "=", "r", ",", "''", "role", "=", "Role", ".", "get", "(", "Role", ".", "c", ".", "name", "==", "role_name", ")", "if", "not", "role", ":", "raise", "Exception", ",", "'Role [%s] not found.'", "%", "r", "rel", "=", "Rel", ".", "get", "(", "(", "Rel", ".", "c", ".", "role", "==", "role", ".", "id", ")", "&", "(", "Rel", ".", "c", ".", "permission", "==", "perm", ".", "id", ")", ")", "if", "not", "rel", ":", "rel", "=", "Rel", "(", "role", "=", "role", ",", "permission", "=", "perm", ",", "props", "=", "role_props", ")", "msg", "=", "'Add Relation(Permision=%s, Role=%s)...'", "%", "(", "name", ",", "role_name", ")", "else", ":", "rel", ".", "update", "(", "props", "=", "role_props", ")", "msg", "=", "'Update Relation(Permision=%s, Role=%s)...'", "%", "(", "name", ",", "role_name", ")", "flag", "=", "rel", ".", "save", "(", ")", "if", "flag", ":", "print", "msg" ]
v is roles
[ "v", "is", "roles" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/rbac/dbinit.py#L32-L58
6,955
limodou/uliweb
uliweb/lib/werkzeug/contrib/jsrouting.py
generate_adapter
def generate_adapter(adapter, name='url_for', map_name='url_map'): """Generates the url building function for a map.""" values = { u'server_name': dumps(adapter.server_name), u'script_name': dumps(adapter.script_name), u'subdomain': dumps(adapter.subdomain), u'url_scheme': dumps(adapter.url_scheme), u'name': name, u'map_name': map_name } return u'''\ var %(name)s = %(map_name)s( %(server_name)s, %(script_name)s, %(subdomain)s, %(url_scheme)s );''' % values
python
def generate_adapter(adapter, name='url_for', map_name='url_map'): """Generates the url building function for a map.""" values = { u'server_name': dumps(adapter.server_name), u'script_name': dumps(adapter.script_name), u'subdomain': dumps(adapter.subdomain), u'url_scheme': dumps(adapter.url_scheme), u'name': name, u'map_name': map_name } return u'''\ var %(name)s = %(map_name)s( %(server_name)s, %(script_name)s, %(subdomain)s, %(url_scheme)s );''' % values
[ "def", "generate_adapter", "(", "adapter", ",", "name", "=", "'url_for'", ",", "map_name", "=", "'url_map'", ")", ":", "values", "=", "{", "u'server_name'", ":", "dumps", "(", "adapter", ".", "server_name", ")", ",", "u'script_name'", ":", "dumps", "(", "adapter", ".", "script_name", ")", ",", "u'subdomain'", ":", "dumps", "(", "adapter", ".", "subdomain", ")", ",", "u'url_scheme'", ":", "dumps", "(", "adapter", ".", "url_scheme", ")", ",", "u'name'", ":", "name", ",", "u'map_name'", ":", "map_name", "}", "return", "u'''\\\nvar %(name)s = %(map_name)s(\n %(server_name)s,\n %(script_name)s,\n %(subdomain)s,\n %(url_scheme)s\n);'''", "%", "values" ]
Generates the url building function for a map.
[ "Generates", "the", "url", "building", "function", "for", "a", "map", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/jsrouting.py#L217-L233
6,956
limodou/uliweb
uliweb/lib/werkzeug/contrib/jsrouting.py
js_to_url_function
def js_to_url_function(converter): """Get the JavaScript converter function from a rule.""" if hasattr(converter, 'js_to_url_function'): data = converter.js_to_url_function() else: for cls in getmro(type(converter)): if cls in js_to_url_functions: data = js_to_url_functions[cls](converter) break else: return 'encodeURIComponent' return '(function(value) { %s })' % data
python
def js_to_url_function(converter): """Get the JavaScript converter function from a rule.""" if hasattr(converter, 'js_to_url_function'): data = converter.js_to_url_function() else: for cls in getmro(type(converter)): if cls in js_to_url_functions: data = js_to_url_functions[cls](converter) break else: return 'encodeURIComponent' return '(function(value) { %s })' % data
[ "def", "js_to_url_function", "(", "converter", ")", ":", "if", "hasattr", "(", "converter", ",", "'js_to_url_function'", ")", ":", "data", "=", "converter", ".", "js_to_url_function", "(", ")", "else", ":", "for", "cls", "in", "getmro", "(", "type", "(", "converter", ")", ")", ":", "if", "cls", "in", "js_to_url_functions", ":", "data", "=", "js_to_url_functions", "[", "cls", "]", "(", "converter", ")", "break", "else", ":", "return", "'encodeURIComponent'", "return", "'(function(value) { %s })'", "%", "data" ]
Get the JavaScript converter function from a rule.
[ "Get", "the", "JavaScript", "converter", "function", "from", "a", "rule", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/jsrouting.py#L236-L247
6,957
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
_warn_if_string
def _warn_if_string(iterable): """Helper for the response objects to check if the iterable returned to the WSGI server is not a string. """ if isinstance(iterable, string_types): from warnings import warn warn(Warning('response iterable was set to a string. This appears ' 'to work but means that the server will send the ' 'data to the client char, by char. This is almost ' 'never intended behavior, use response.data to assign ' 'strings to the response object.'), stacklevel=2)
python
def _warn_if_string(iterable): """Helper for the response objects to check if the iterable returned to the WSGI server is not a string. """ if isinstance(iterable, string_types): from warnings import warn warn(Warning('response iterable was set to a string. This appears ' 'to work but means that the server will send the ' 'data to the client char, by char. This is almost ' 'never intended behavior, use response.data to assign ' 'strings to the response object.'), stacklevel=2)
[ "def", "_warn_if_string", "(", "iterable", ")", ":", "if", "isinstance", "(", "iterable", ",", "string_types", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "Warning", "(", "'response iterable was set to a string. This appears '", "'to work but means that the server will send the '", "'data to the client char, by char. This is almost '", "'never intended behavior, use response.data to assign '", "'strings to the response object.'", ")", ",", "stacklevel", "=", "2", ")" ]
Helper for the response objects to check if the iterable returned to the WSGI server is not a string.
[ "Helper", "for", "the", "response", "objects", "to", "check", "if", "the", "iterable", "returned", "to", "the", "WSGI", "server", "is", "not", "a", "string", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L60-L70
6,958
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseRequest._get_file_stream
def _get_file_stream(self, total_content_length, content_type, filename=None, content_length=None): """Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters. :param total_content_length: the total content length of all the data in the request combined. This value is guaranteed to be there. :param content_type: the mimetype of the uploaded file. :param filename: the filename of the uploaded file. May be `None`. :param content_length: the length of this file. This value is usually not provided because webbrowsers do not provide this value. """ return default_stream_factory(total_content_length, content_type, filename, content_length)
python
def _get_file_stream(self, total_content_length, content_type, filename=None, content_length=None): """Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters. :param total_content_length: the total content length of all the data in the request combined. This value is guaranteed to be there. :param content_type: the mimetype of the uploaded file. :param filename: the filename of the uploaded file. May be `None`. :param content_length: the length of this file. This value is usually not provided because webbrowsers do not provide this value. """ return default_stream_factory(total_content_length, content_type, filename, content_length)
[ "def", "_get_file_stream", "(", "self", ",", "total_content_length", ",", "content_type", ",", "filename", "=", "None", ",", "content_length", "=", "None", ")", ":", "return", "default_stream_factory", "(", "total_content_length", ",", "content_type", ",", "filename", ",", "content_length", ")" ]
Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters. :param total_content_length: the total content length of all the data in the request combined. This value is guaranteed to be there. :param content_type: the mimetype of the uploaded file. :param filename: the filename of the uploaded file. May be `None`. :param content_length: the length of this file. This value is usually not provided because webbrowsers do not provide this value.
[ "Called", "to", "get", "a", "stream", "for", "the", "file", "upload", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L288-L310
6,959
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseRequest.close
def close(self): """Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement with will automatically close it. .. versionadded:: 0.9 """ files = self.__dict__.get('files') for key, value in iter_multi_items(files or ()): value.close()
python
def close(self): """Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement with will automatically close it. .. versionadded:: 0.9 """ files = self.__dict__.get('files') for key, value in iter_multi_items(files or ()): value.close()
[ "def", "close", "(", "self", ")", ":", "files", "=", "self", ".", "__dict__", ".", "get", "(", "'files'", ")", "for", "key", ",", "value", "in", "iter_multi_items", "(", "files", "or", "(", ")", ")", ":", "value", ".", "close", "(", ")" ]
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement with will automatically close it. .. versionadded:: 0.9
[ "Closes", "associated", "resources", "of", "this", "request", "object", ".", "This", "closes", "all", "file", "handles", "explicitly", ".", "You", "can", "also", "use", "the", "request", "object", "in", "a", "with", "statement", "with", "will", "automatically", "close", "it", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L364-L373
6,960
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse.get_data
def get_data(self, as_text=False): """The string representation of the request body. Whenever you call this property the request iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting :attr:`implicit_sequence_conversion` to `False`. If `as_text` is set to `True` the return value will be a decoded unicode string. .. versionadded:: 0.9 """ self._ensure_sequence() rv = b''.join(self.iter_encoded()) if as_text: rv = rv.decode(self.charset) return rv
python
def get_data(self, as_text=False): """The string representation of the request body. Whenever you call this property the request iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting :attr:`implicit_sequence_conversion` to `False`. If `as_text` is set to `True` the return value will be a decoded unicode string. .. versionadded:: 0.9 """ self._ensure_sequence() rv = b''.join(self.iter_encoded()) if as_text: rv = rv.decode(self.charset) return rv
[ "def", "get_data", "(", "self", ",", "as_text", "=", "False", ")", ":", "self", ".", "_ensure_sequence", "(", ")", "rv", "=", "b''", ".", "join", "(", "self", ".", "iter_encoded", "(", ")", ")", "if", "as_text", ":", "rv", "=", "rv", ".", "decode", "(", "self", ".", "charset", ")", "return", "rv" ]
The string representation of the request body. Whenever you call this property the request iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting :attr:`implicit_sequence_conversion` to `False`. If `as_text` is set to `True` the return value will be a decoded unicode string. .. versionadded:: 0.9
[ "The", "string", "representation", "of", "the", "request", "body", ".", "Whenever", "you", "call", "this", "property", "the", "request", "iterable", "is", "encoded", "and", "flattened", ".", "This", "can", "lead", "to", "unwanted", "behavior", "if", "you", "stream", "big", "data", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L836-L853
6,961
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse._ensure_sequence
def _ensure_sequence(self, mutable=False): """This method can be called by methods that need a sequence. If `mutable` is true, it will also ensure that the response sequence is a standard Python list. .. versionadded:: 0.6 """ if self.is_sequence: # if we need a mutable object, we ensure it's a list. if mutable and not isinstance(self.response, list): self.response = list(self.response) return if self.direct_passthrough: raise RuntimeError('Attempted implicit sequence conversion ' 'but the response object is in direct ' 'passthrough mode.') if not self.implicit_sequence_conversion: raise RuntimeError('The response object required the iterable ' 'to be a sequence, but the implicit ' 'conversion was disabled. Call ' 'make_sequence() yourself.') self.make_sequence()
python
def _ensure_sequence(self, mutable=False): """This method can be called by methods that need a sequence. If `mutable` is true, it will also ensure that the response sequence is a standard Python list. .. versionadded:: 0.6 """ if self.is_sequence: # if we need a mutable object, we ensure it's a list. if mutable and not isinstance(self.response, list): self.response = list(self.response) return if self.direct_passthrough: raise RuntimeError('Attempted implicit sequence conversion ' 'but the response object is in direct ' 'passthrough mode.') if not self.implicit_sequence_conversion: raise RuntimeError('The response object required the iterable ' 'to be a sequence, but the implicit ' 'conversion was disabled. Call ' 'make_sequence() yourself.') self.make_sequence()
[ "def", "_ensure_sequence", "(", "self", ",", "mutable", "=", "False", ")", ":", "if", "self", ".", "is_sequence", ":", "# if we need a mutable object, we ensure it's a list.", "if", "mutable", "and", "not", "isinstance", "(", "self", ".", "response", ",", "list", ")", ":", "self", ".", "response", "=", "list", "(", "self", ".", "response", ")", "return", "if", "self", ".", "direct_passthrough", ":", "raise", "RuntimeError", "(", "'Attempted implicit sequence conversion '", "'but the response object is in direct '", "'passthrough mode.'", ")", "if", "not", "self", ".", "implicit_sequence_conversion", ":", "raise", "RuntimeError", "(", "'The response object required the iterable '", "'to be a sequence, but the implicit '", "'conversion was disabled. Call '", "'make_sequence() yourself.'", ")", "self", ".", "make_sequence", "(", ")" ]
This method can be called by methods that need a sequence. If `mutable` is true, it will also ensure that the response sequence is a standard Python list. .. versionadded:: 0.6
[ "This", "method", "can", "be", "called", "by", "methods", "that", "need", "a", "sequence", ".", "If", "mutable", "is", "true", "it", "will", "also", "ensure", "that", "the", "response", "sequence", "is", "a", "standard", "Python", "list", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L885-L906
6,962
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse.delete_cookie
def delete_cookie(self, key, path='/', domain=None): """Delete a cookie. Fails silently if key doesn't exist. :param key: the key (name) of the cookie to be deleted. :param path: if the cookie that should be deleted was limited to a path, the path has to be defined here. :param domain: if the cookie that should be deleted was limited to a domain, that domain has to be defined here. """ self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
python
def delete_cookie(self, key, path='/', domain=None): """Delete a cookie. Fails silently if key doesn't exist. :param key: the key (name) of the cookie to be deleted. :param path: if the cookie that should be deleted was limited to a path, the path has to be defined here. :param domain: if the cookie that should be deleted was limited to a domain, that domain has to be defined here. """ self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
[ "def", "delete_cookie", "(", "self", ",", "key", ",", "path", "=", "'/'", ",", "domain", "=", "None", ")", ":", "self", ".", "set_cookie", "(", "key", ",", "expires", "=", "0", ",", "max_age", "=", "0", ",", "path", "=", "path", ",", "domain", "=", "domain", ")" ]
Delete a cookie. Fails silently if key doesn't exist. :param key: the key (name) of the cookie to be deleted. :param path: if the cookie that should be deleted was limited to a path, the path has to be defined here. :param domain: if the cookie that should be deleted was limited to a domain, that domain has to be defined here.
[ "Delete", "a", "cookie", ".", "Fails", "silently", "if", "key", "doesn", "t", "exist", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L962-L971
6,963
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse.freeze
def freeze(self): """Call this method if you want to make your response object ready for being pickled. This buffers the generator if there is one. It will also set the `Content-Length` header to the length of the body. .. versionchanged:: 0.6 The `Content-Length` header is now set. """ # we explicitly set the length to a list of the *encoded* response # iterator. Even if the implicit sequence conversion is disabled. self.response = list(self.iter_encoded()) self.headers['Content-Length'] = str(sum(map(len, self.response)))
python
def freeze(self): """Call this method if you want to make your response object ready for being pickled. This buffers the generator if there is one. It will also set the `Content-Length` header to the length of the body. .. versionchanged:: 0.6 The `Content-Length` header is now set. """ # we explicitly set the length to a list of the *encoded* response # iterator. Even if the implicit sequence conversion is disabled. self.response = list(self.iter_encoded()) self.headers['Content-Length'] = str(sum(map(len, self.response)))
[ "def", "freeze", "(", "self", ")", ":", "# we explicitly set the length to a list of the *encoded* response", "# iterator. Even if the implicit sequence conversion is disabled.", "self", ".", "response", "=", "list", "(", "self", ".", "iter_encoded", "(", ")", ")", "self", ".", "headers", "[", "'Content-Length'", "]", "=", "str", "(", "sum", "(", "map", "(", "len", ",", "self", ".", "response", ")", ")", ")" ]
Call this method if you want to make your response object ready for being pickled. This buffers the generator if there is one. It will also set the `Content-Length` header to the length of the body. .. versionchanged:: 0.6 The `Content-Length` header is now set.
[ "Call", "this", "method", "if", "you", "want", "to", "make", "your", "response", "object", "ready", "for", "being", "pickled", ".", "This", "buffers", "the", "generator", "if", "there", "is", "one", ".", "It", "will", "also", "set", "the", "Content", "-", "Length", "header", "to", "the", "length", "of", "the", "body", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L1017-L1028
6,964
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse.get_app_iter
def get_app_iter(self, environ): """Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is `HEAD` or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. .. versionadded:: 0.6 :param environ: the WSGI environment of the request. :return: a response iterable. """ status = self.status_code if environ['REQUEST_METHOD'] == 'HEAD' or \ 100 <= status < 200 or status in (204, 304): iterable = () elif self.direct_passthrough: if __debug__: _warn_if_string(self.response) return self.response else: iterable = self.iter_encoded() return ClosingIterator(iterable, self.close)
python
def get_app_iter(self, environ): """Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is `HEAD` or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. .. versionadded:: 0.6 :param environ: the WSGI environment of the request. :return: a response iterable. """ status = self.status_code if environ['REQUEST_METHOD'] == 'HEAD' or \ 100 <= status < 200 or status in (204, 304): iterable = () elif self.direct_passthrough: if __debug__: _warn_if_string(self.response) return self.response else: iterable = self.iter_encoded() return ClosingIterator(iterable, self.close)
[ "def", "get_app_iter", "(", "self", ",", "environ", ")", ":", "status", "=", "self", ".", "status_code", "if", "environ", "[", "'REQUEST_METHOD'", "]", "==", "'HEAD'", "or", "100", "<=", "status", "<", "200", "or", "status", "in", "(", "204", ",", "304", ")", ":", "iterable", "=", "(", ")", "elif", "self", ".", "direct_passthrough", ":", "if", "__debug__", ":", "_warn_if_string", "(", "self", ".", "response", ")", "return", "self", ".", "response", "else", ":", "iterable", "=", "self", ".", "iter_encoded", "(", ")", "return", "ClosingIterator", "(", "iterable", ",", "self", ".", "close", ")" ]
Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is `HEAD` or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. .. versionadded:: 0.6 :param environ: the WSGI environment of the request. :return: a response iterable.
[ "Returns", "the", "application", "iterator", "for", "the", "given", "environ", ".", "Depending", "on", "the", "request", "method", "and", "the", "current", "status", "code", "the", "return", "value", "might", "be", "an", "empty", "response", "rather", "than", "the", "one", "from", "the", "response", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L1117-L1141
6,965
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
WWWAuthenticateMixin.www_authenticate
def www_authenticate(self): """The `WWW-Authenticate` header in a parsed form.""" def on_update(www_auth): if not www_auth and 'www-authenticate' in self.headers: del self.headers['www-authenticate'] elif www_auth: self.headers['WWW-Authenticate'] = www_auth.to_header() header = self.headers.get('www-authenticate') return parse_www_authenticate_header(header, on_update)
python
def www_authenticate(self): """The `WWW-Authenticate` header in a parsed form.""" def on_update(www_auth): if not www_auth and 'www-authenticate' in self.headers: del self.headers['www-authenticate'] elif www_auth: self.headers['WWW-Authenticate'] = www_auth.to_header() header = self.headers.get('www-authenticate') return parse_www_authenticate_header(header, on_update)
[ "def", "www_authenticate", "(", "self", ")", ":", "def", "on_update", "(", "www_auth", ")", ":", "if", "not", "www_auth", "and", "'www-authenticate'", "in", "self", ".", "headers", ":", "del", "self", ".", "headers", "[", "'www-authenticate'", "]", "elif", "www_auth", ":", "self", ".", "headers", "[", "'WWW-Authenticate'", "]", "=", "www_auth", ".", "to_header", "(", ")", "header", "=", "self", ".", "headers", ".", "get", "(", "'www-authenticate'", ")", "return", "parse_www_authenticate_header", "(", "header", ",", "on_update", ")" ]
The `WWW-Authenticate` header in a parsed form.
[ "The", "WWW", "-", "Authenticate", "header", "in", "a", "parsed", "form", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L1730-L1738
6,966
limodou/uliweb
uliweb/lib/werkzeug/routing.py
MapAdapter.make_alias_redirect_url
def make_alias_redirect_url(self, path, endpoint, values, method, query_args): """Internally called to make an alias redirect URL.""" url = self.build(endpoint, values, method, append_unknown=False, force_external=True) if query_args: url += '?' + self.encode_query_args(query_args) assert url != path, 'detected invalid alias setting. No canonical ' \ 'URL found' return url
python
def make_alias_redirect_url(self, path, endpoint, values, method, query_args): """Internally called to make an alias redirect URL.""" url = self.build(endpoint, values, method, append_unknown=False, force_external=True) if query_args: url += '?' + self.encode_query_args(query_args) assert url != path, 'detected invalid alias setting. No canonical ' \ 'URL found' return url
[ "def", "make_alias_redirect_url", "(", "self", ",", "path", ",", "endpoint", ",", "values", ",", "method", ",", "query_args", ")", ":", "url", "=", "self", ".", "build", "(", "endpoint", ",", "values", ",", "method", ",", "append_unknown", "=", "False", ",", "force_external", "=", "True", ")", "if", "query_args", ":", "url", "+=", "'?'", "+", "self", ".", "encode_query_args", "(", "query_args", ")", "assert", "url", "!=", "path", ",", "'detected invalid alias setting. No canonical '", "'URL found'", "return", "url" ]
Internally called to make an alias redirect URL.
[ "Internally", "called", "to", "make", "an", "alias", "redirect", "URL", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/routing.py#L1523-L1531
6,967
limodou/uliweb
uliweb/lib/werkzeug/templates.py
Template.from_file
def from_file(cls, file, charset='utf-8', errors='strict', unicode_mode=True): """Load a template from a file. .. versionchanged:: 0.5 The encoding parameter was renamed to charset. :param file: a filename or file object to load the template from. :param charset: the charset of the template to load. :param errors: the error behavior of the charset decoding. :param unicode_mode: set to `False` to disable unicode mode. :return: a template """ close = False f = file if isinstance(file, basestring): f = open(file, 'r') close = True try: data = _decode_unicode(f.read(), charset, errors) finally: if close: f.close() return cls(data, getattr(f, 'name', '<template>'), charset, errors, unicode_mode)
python
def from_file(cls, file, charset='utf-8', errors='strict', unicode_mode=True): """Load a template from a file. .. versionchanged:: 0.5 The encoding parameter was renamed to charset. :param file: a filename or file object to load the template from. :param charset: the charset of the template to load. :param errors: the error behavior of the charset decoding. :param unicode_mode: set to `False` to disable unicode mode. :return: a template """ close = False f = file if isinstance(file, basestring): f = open(file, 'r') close = True try: data = _decode_unicode(f.read(), charset, errors) finally: if close: f.close() return cls(data, getattr(f, 'name', '<template>'), charset, errors, unicode_mode)
[ "def", "from_file", "(", "cls", ",", "file", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'strict'", ",", "unicode_mode", "=", "True", ")", ":", "close", "=", "False", "f", "=", "file", "if", "isinstance", "(", "file", ",", "basestring", ")", ":", "f", "=", "open", "(", "file", ",", "'r'", ")", "close", "=", "True", "try", ":", "data", "=", "_decode_unicode", "(", "f", ".", "read", "(", ")", ",", "charset", ",", "errors", ")", "finally", ":", "if", "close", ":", "f", ".", "close", "(", ")", "return", "cls", "(", "data", ",", "getattr", "(", "f", ",", "'name'", ",", "'<template>'", ")", ",", "charset", ",", "errors", ",", "unicode_mode", ")" ]
Load a template from a file. .. versionchanged:: 0.5 The encoding parameter was renamed to charset. :param file: a filename or file object to load the template from. :param charset: the charset of the template to load. :param errors: the error behavior of the charset decoding. :param unicode_mode: set to `False` to disable unicode mode. :return: a template
[ "Load", "a", "template", "from", "a", "file", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/templates.py#L351-L375
6,968
limodou/uliweb
uliweb/lib/werkzeug/security.py
safe_str_cmp
def safe_str_cmp(a, b): """This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7 """ if _builtin_safe_str_cmp is not None: return _builtin_safe_str_cmp(a, b) if len(a) != len(b): return False rv = 0 if isinstance(a, bytes) and isinstance(b, bytes) and not PY2: for x, y in izip(a, b): rv |= x ^ y else: for x, y in izip(a, b): rv |= ord(x) ^ ord(y) return rv == 0
python
def safe_str_cmp(a, b): """This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7 """ if _builtin_safe_str_cmp is not None: return _builtin_safe_str_cmp(a, b) if len(a) != len(b): return False rv = 0 if isinstance(a, bytes) and isinstance(b, bytes) and not PY2: for x, y in izip(a, b): rv |= x ^ y else: for x, y in izip(a, b): rv |= ord(x) ^ ord(y) return rv == 0
[ "def", "safe_str_cmp", "(", "a", ",", "b", ")", ":", "if", "_builtin_safe_str_cmp", "is", "not", "None", ":", "return", "_builtin_safe_str_cmp", "(", "a", ",", "b", ")", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "return", "False", "rv", "=", "0", "if", "isinstance", "(", "a", ",", "bytes", ")", "and", "isinstance", "(", "b", ",", "bytes", ")", "and", "not", "PY2", ":", "for", "x", ",", "y", "in", "izip", "(", "a", ",", "b", ")", ":", "rv", "|=", "x", "^", "y", "else", ":", "for", "x", ",", "y", "in", "izip", "(", "a", ",", "b", ")", ":", "rv", "|=", "ord", "(", "x", ")", "^", "ord", "(", "y", ")", "return", "rv", "==", "0" ]
This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7
[ "This", "function", "compares", "strings", "in", "somewhat", "constant", "time", ".", "This", "requires", "that", "the", "length", "of", "at", "least", "one", "string", "is", "known", "in", "advance", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/security.py#L108-L127
6,969
limodou/uliweb
uliweb/lib/werkzeug/security.py
gen_salt
def gen_salt(length): """Generate a random string of SALT_CHARS with specified ``length``.""" if length <= 0: raise ValueError('requested salt of length <= 0') return ''.join(_sys_rng.choice(SALT_CHARS) for _ in range_type(length))
python
def gen_salt(length): """Generate a random string of SALT_CHARS with specified ``length``.""" if length <= 0: raise ValueError('requested salt of length <= 0') return ''.join(_sys_rng.choice(SALT_CHARS) for _ in range_type(length))
[ "def", "gen_salt", "(", "length", ")", ":", "if", "length", "<=", "0", ":", "raise", "ValueError", "(", "'requested salt of length <= 0'", ")", "return", "''", ".", "join", "(", "_sys_rng", ".", "choice", "(", "SALT_CHARS", ")", "for", "_", "in", "range_type", "(", "length", ")", ")" ]
Generate a random string of SALT_CHARS with specified ``length``.
[ "Generate", "a", "random", "string", "of", "SALT_CHARS", "with", "specified", "length", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/security.py#L130-L134
6,970
limodou/uliweb
uliweb/form/uliform.py
BaseField.html
def html(self, data='', py=True): """ Convert data to html value format. """ if py: value = self.to_html(data) else: value = data if self.static: return str('<span class="value">%s</span>' % safe_str(value)) else: if self.hidden: build = Hidden else: build = self.build self._get_http_attrs() return str(build(name=self.name, value=value, id=self.id, **self.html_attrs))
python
def html(self, data='', py=True): """ Convert data to html value format. """ if py: value = self.to_html(data) else: value = data if self.static: return str('<span class="value">%s</span>' % safe_str(value)) else: if self.hidden: build = Hidden else: build = self.build self._get_http_attrs() return str(build(name=self.name, value=value, id=self.id, **self.html_attrs))
[ "def", "html", "(", "self", ",", "data", "=", "''", ",", "py", "=", "True", ")", ":", "if", "py", ":", "value", "=", "self", ".", "to_html", "(", "data", ")", "else", ":", "value", "=", "data", "if", "self", ".", "static", ":", "return", "str", "(", "'<span class=\"value\">%s</span>'", "%", "safe_str", "(", "value", ")", ")", "else", ":", "if", "self", ".", "hidden", ":", "build", "=", "Hidden", "else", ":", "build", "=", "self", ".", "build", "self", ".", "_get_http_attrs", "(", ")", "return", "str", "(", "build", "(", "name", "=", "self", ".", "name", ",", "value", "=", "value", ",", "id", "=", "self", ".", "id", ",", "*", "*", "self", ".", "html_attrs", ")", ")" ]
Convert data to html value format.
[ "Convert", "data", "to", "html", "value", "format", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/form/uliform.py#L176-L193
6,971
limodou/uliweb
uliweb/form/uliform.py
BaseField.validate
def validate(self, data, all_data=None): """ if 'rule' in kwargs, then validate extra rules e.g.: rule= {'required':True, 'minlength':6} """ all_data = all_data or {} if hasattr(data, 'stream'): data.file = data.stream if hasattr(data, 'file'): if data.file: v = data.filename else: raise Exception, 'Unsupport type %s' % type(data) else: v = data # if v is None: msg = TEST_NOT_EMPTY()(v) if self.required: if msg: return False, msg else: if msg: return True, self.default try: if isinstance(data, list): v = [] for i in data: v.append(self.to_python(i)) data = v else: data = self.to_python(data) except: return False, unicode(ERR_CONVERT) % (data, self.__class__.__name__) for v in self.get_validators(): msg = v(data, all_data) if msg: return False, msg return True, data
python
def validate(self, data, all_data=None): """ if 'rule' in kwargs, then validate extra rules e.g.: rule= {'required':True, 'minlength':6} """ all_data = all_data or {} if hasattr(data, 'stream'): data.file = data.stream if hasattr(data, 'file'): if data.file: v = data.filename else: raise Exception, 'Unsupport type %s' % type(data) else: v = data # if v is None: msg = TEST_NOT_EMPTY()(v) if self.required: if msg: return False, msg else: if msg: return True, self.default try: if isinstance(data, list): v = [] for i in data: v.append(self.to_python(i)) data = v else: data = self.to_python(data) except: return False, unicode(ERR_CONVERT) % (data, self.__class__.__name__) for v in self.get_validators(): msg = v(data, all_data) if msg: return False, msg return True, data
[ "def", "validate", "(", "self", ",", "data", ",", "all_data", "=", "None", ")", ":", "all_data", "=", "all_data", "or", "{", "}", "if", "hasattr", "(", "data", ",", "'stream'", ")", ":", "data", ".", "file", "=", "data", ".", "stream", "if", "hasattr", "(", "data", ",", "'file'", ")", ":", "if", "data", ".", "file", ":", "v", "=", "data", ".", "filename", "else", ":", "raise", "Exception", ",", "'Unsupport type %s'", "%", "type", "(", "data", ")", "else", ":", "v", "=", "data", "# if v is None:", "msg", "=", "TEST_NOT_EMPTY", "(", ")", "(", "v", ")", "if", "self", ".", "required", ":", "if", "msg", ":", "return", "False", ",", "msg", "else", ":", "if", "msg", ":", "return", "True", ",", "self", ".", "default", "try", ":", "if", "isinstance", "(", "data", ",", "list", ")", ":", "v", "=", "[", "]", "for", "i", "in", "data", ":", "v", ".", "append", "(", "self", ".", "to_python", "(", "i", ")", ")", "data", "=", "v", "else", ":", "data", "=", "self", ".", "to_python", "(", "data", ")", "except", ":", "return", "False", ",", "unicode", "(", "ERR_CONVERT", ")", "%", "(", "data", ",", "self", ".", "__class__", ".", "__name__", ")", "for", "v", "in", "self", ".", "get_validators", "(", ")", ":", "msg", "=", "v", "(", "data", ",", "all_data", ")", "if", "msg", ":", "return", "False", ",", "msg", "return", "True", ",", "data" ]
if 'rule' in kwargs, then validate extra rules e.g.: rule= {'required':True, 'minlength':6}
[ "if", "rule", "in", "kwargs", "then", "validate", "extra", "rules" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/form/uliform.py#L277-L321
6,972
limodou/uliweb
uliweb/lib/werkzeug/datastructures.py
cache_property
def cache_property(key, empty, type): """Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass.""" return property(lambda x: x._get_cache_value(key, empty, type), lambda x, v: x._set_cache_value(key, v, type), lambda x: x._del_cache_value(key), 'accessor for %r' % key)
python
def cache_property(key, empty, type): """Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass.""" return property(lambda x: x._get_cache_value(key, empty, type), lambda x, v: x._set_cache_value(key, v, type), lambda x: x._del_cache_value(key), 'accessor for %r' % key)
[ "def", "cache_property", "(", "key", ",", "empty", ",", "type", ")", ":", "return", "property", "(", "lambda", "x", ":", "x", ".", "_get_cache_value", "(", "key", ",", "empty", ",", "type", ")", ",", "lambda", "x", ",", "v", ":", "x", ".", "_set_cache_value", "(", "key", ",", "v", ",", "type", ")", ",", "lambda", "x", ":", "x", ".", "_del_cache_value", "(", "key", ")", ",", "'accessor for %r'", "%", "key", ")" ]
Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass.
[ "Return", "a", "new", "property", "object", "for", "a", "cache", "header", ".", "Useful", "if", "you", "want", "to", "add", "support", "for", "a", "cache", "extension", "in", "a", "subclass", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/datastructures.py#L1731-L1737
6,973
limodou/uliweb
uliweb/lib/werkzeug/datastructures.py
ContentRange.set
def set(self, start, stop, length=None, units='bytes'): """Simple method to update the ranges.""" assert is_byte_range_valid(start, stop, length), \ 'Bad range provided' self._units = units self._start = start self._stop = stop self._length = length if self.on_update is not None: self.on_update(self)
python
def set(self, start, stop, length=None, units='bytes'): """Simple method to update the ranges.""" assert is_byte_range_valid(start, stop, length), \ 'Bad range provided' self._units = units self._start = start self._stop = stop self._length = length if self.on_update is not None: self.on_update(self)
[ "def", "set", "(", "self", ",", "start", ",", "stop", ",", "length", "=", "None", ",", "units", "=", "'bytes'", ")", ":", "assert", "is_byte_range_valid", "(", "start", ",", "stop", ",", "length", ")", ",", "'Bad range provided'", "self", ".", "_units", "=", "units", "self", ".", "_start", "=", "start", "self", ".", "_stop", "=", "stop", "self", ".", "_length", "=", "length", "if", "self", ".", "on_update", "is", "not", "None", ":", "self", ".", "on_update", "(", "self", ")" ]
Simple method to update the ranges.
[ "Simple", "method", "to", "update", "the", "ranges", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/datastructures.py#L2242-L2251
6,974
limodou/uliweb
uliweb/lib/werkzeug/datastructures.py
Authorization.qop
def qop(self): """Indicates what "quality of protection" the client has applied to the message for HTTP digest auth.""" def on_update(header_set): if not header_set and 'qop' in self: del self['qop'] elif header_set: self['qop'] = header_set.to_header() return parse_set_header(self.get('qop'), on_update)
python
def qop(self): """Indicates what "quality of protection" the client has applied to the message for HTTP digest auth.""" def on_update(header_set): if not header_set and 'qop' in self: del self['qop'] elif header_set: self['qop'] = header_set.to_header() return parse_set_header(self.get('qop'), on_update)
[ "def", "qop", "(", "self", ")", ":", "def", "on_update", "(", "header_set", ")", ":", "if", "not", "header_set", "and", "'qop'", "in", "self", ":", "del", "self", "[", "'qop'", "]", "elif", "header_set", ":", "self", "[", "'qop'", "]", "=", "header_set", ".", "to_header", "(", ")", "return", "parse_set_header", "(", "self", ".", "get", "(", "'qop'", ")", ",", "on_update", ")" ]
Indicates what "quality of protection" the client has applied to the message for HTTP digest auth.
[ "Indicates", "what", "quality", "of", "protection", "the", "client", "has", "applied", "to", "the", "message", "for", "HTTP", "digest", "auth", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/datastructures.py#L2336-L2344
6,975
limodou/uliweb
uliweb/lib/werkzeug/datastructures.py
WWWAuthenticate.set_basic
def set_basic(self, realm='authentication required'): """Clear the auth info and enable basic auth.""" dict.clear(self) dict.update(self, {'__auth_type__': 'basic', 'realm': realm}) if self.on_update: self.on_update(self)
python
def set_basic(self, realm='authentication required'): """Clear the auth info and enable basic auth.""" dict.clear(self) dict.update(self, {'__auth_type__': 'basic', 'realm': realm}) if self.on_update: self.on_update(self)
[ "def", "set_basic", "(", "self", ",", "realm", "=", "'authentication required'", ")", ":", "dict", ".", "clear", "(", "self", ")", "dict", ".", "update", "(", "self", ",", "{", "'__auth_type__'", ":", "'basic'", ",", "'realm'", ":", "realm", "}", ")", "if", "self", ".", "on_update", ":", "self", ".", "on_update", "(", "self", ")" ]
Clear the auth info and enable basic auth.
[ "Clear", "the", "auth", "info", "and", "enable", "basic", "auth", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/datastructures.py#L2359-L2364
6,976
limodou/uliweb
uliweb/orm/__init__.py
get_connection
def get_connection(connection='', engine_name=None, connection_type='long', **args): """ Creating an NamedEngine or just return existed engine instance if '://' include in connection parameter, it'll create new engine object otherwise return existed engine isntance """ engine_name = engine_name or __default_engine__ if '://' in connection: d = { 'connection_string':connection, 'connection_args':args, 'connection_type':connection_type, } return engine_manager.add(engine_name, d).engine else: connection = connection or __default_engine__ if connection in engine_manager: return engine_manager[connection].engine else: raise Error("Can't find engine %s" % connection)
python
def get_connection(connection='', engine_name=None, connection_type='long', **args): """ Creating an NamedEngine or just return existed engine instance if '://' include in connection parameter, it'll create new engine object otherwise return existed engine isntance """ engine_name = engine_name or __default_engine__ if '://' in connection: d = { 'connection_string':connection, 'connection_args':args, 'connection_type':connection_type, } return engine_manager.add(engine_name, d).engine else: connection = connection or __default_engine__ if connection in engine_manager: return engine_manager[connection].engine else: raise Error("Can't find engine %s" % connection)
[ "def", "get_connection", "(", "connection", "=", "''", ",", "engine_name", "=", "None", ",", "connection_type", "=", "'long'", ",", "*", "*", "args", ")", ":", "engine_name", "=", "engine_name", "or", "__default_engine__", "if", "'://'", "in", "connection", ":", "d", "=", "{", "'connection_string'", ":", "connection", ",", "'connection_args'", ":", "args", ",", "'connection_type'", ":", "connection_type", ",", "}", "return", "engine_manager", ".", "add", "(", "engine_name", ",", "d", ")", ".", "engine", "else", ":", "connection", "=", "connection", "or", "__default_engine__", "if", "connection", "in", "engine_manager", ":", "return", "engine_manager", "[", "connection", "]", ".", "engine", "else", ":", "raise", "Error", "(", "\"Can't find engine %s\"", "%", "connection", ")" ]
Creating an NamedEngine or just return existed engine instance if '://' include in connection parameter, it'll create new engine object otherwise return existed engine isntance
[ "Creating", "an", "NamedEngine", "or", "just", "return", "existed", "engine", "instance" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L453-L474
6,977
limodou/uliweb
uliweb/orm/__init__.py
get_metadata
def get_metadata(engine_name=None): """ get metadata according used for alembic It'll import all tables """ dispatch.get(None, 'load_models') engine = engine_manager[engine_name] for tablename, m in engine.models.items(): get_model(tablename, engine_name, signal=False) if hasattr(m, '__dynamic__') and getattr(m, '__dynamic__'): m.table.__mapping_only__ = True return engine.metadata
python
def get_metadata(engine_name=None): """ get metadata according used for alembic It'll import all tables """ dispatch.get(None, 'load_models') engine = engine_manager[engine_name] for tablename, m in engine.models.items(): get_model(tablename, engine_name, signal=False) if hasattr(m, '__dynamic__') and getattr(m, '__dynamic__'): m.table.__mapping_only__ = True return engine.metadata
[ "def", "get_metadata", "(", "engine_name", "=", "None", ")", ":", "dispatch", ".", "get", "(", "None", ",", "'load_models'", ")", "engine", "=", "engine_manager", "[", "engine_name", "]", "for", "tablename", ",", "m", "in", "engine", ".", "models", ".", "items", "(", ")", ":", "get_model", "(", "tablename", ",", "engine_name", ",", "signal", "=", "False", ")", "if", "hasattr", "(", "m", ",", "'__dynamic__'", ")", "and", "getattr", "(", "m", ",", "'__dynamic__'", ")", ":", "m", ".", "table", ".", "__mapping_only__", "=", "True", "return", "engine", ".", "metadata" ]
get metadata according used for alembic It'll import all tables
[ "get", "metadata", "according", "used", "for", "alembic", "It", "ll", "import", "all", "tables" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L476-L489
6,978
limodou/uliweb
uliweb/orm/__init__.py
get_session
def get_session(ec=None, create=True): """ ec - engine_name or connection """ ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): session = engine_manager[ec].session(create=True) elif isinstance(ec, Session): session = ec else: raise Error("Connection %r should be existed engine name or Session object" % ec) return session
python
def get_session(ec=None, create=True): """ ec - engine_name or connection """ ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): session = engine_manager[ec].session(create=True) elif isinstance(ec, Session): session = ec else: raise Error("Connection %r should be existed engine name or Session object" % ec) return session
[ "def", "get_session", "(", "ec", "=", "None", ",", "create", "=", "True", ")", ":", "ec", "=", "ec", "or", "__default_engine__", "if", "isinstance", "(", "ec", ",", "(", "str", ",", "unicode", ")", ")", ":", "session", "=", "engine_manager", "[", "ec", "]", ".", "session", "(", "create", "=", "True", ")", "elif", "isinstance", "(", "ec", ",", "Session", ")", ":", "session", "=", "ec", "else", ":", "raise", "Error", "(", "\"Connection %r should be existed engine name or Session object\"", "%", "ec", ")", "return", "session" ]
ec - engine_name or connection
[ "ec", "-", "engine_name", "or", "connection" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L491-L503
6,979
limodou/uliweb
uliweb/orm/__init__.py
rawsql
def rawsql(query, ec=None): """ ec could be engine name or engine instance """ if isinstance(query, Result): query = query.get_query() ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): engine = engine_manager[ec] dialect = engine.engine.dialect else: dialect = ec.dialect if isinstance(query, (str, unicode)): return query # comp = query.compile(dialect=dialect) compiler = query._compiler(dialect) class LiteralCompiler(compiler.__class__): def visit_bindparam( self, bindparam, within_columns_clause=False, literal_binds=False, **kwargs ): return super(LiteralCompiler, self).render_literal_bindparam( bindparam, within_columns_clause=within_columns_clause, literal_binds=literal_binds, **kwargs ) def render_literal_value(self, value, type_): """Render the value of a bind parameter as a quoted literal. This is used for statement sections that do not accept bind paramters on the target driver/database. This should be implemented by subclasses using the quoting services of the DBAPI. """ return repr_value(value) compiler = LiteralCompiler(dialect, query) return str(compiler.process(query)).replace('\n', '')
python
def rawsql(query, ec=None): """ ec could be engine name or engine instance """ if isinstance(query, Result): query = query.get_query() ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): engine = engine_manager[ec] dialect = engine.engine.dialect else: dialect = ec.dialect if isinstance(query, (str, unicode)): return query # comp = query.compile(dialect=dialect) compiler = query._compiler(dialect) class LiteralCompiler(compiler.__class__): def visit_bindparam( self, bindparam, within_columns_clause=False, literal_binds=False, **kwargs ): return super(LiteralCompiler, self).render_literal_bindparam( bindparam, within_columns_clause=within_columns_clause, literal_binds=literal_binds, **kwargs ) def render_literal_value(self, value, type_): """Render the value of a bind parameter as a quoted literal. This is used for statement sections that do not accept bind paramters on the target driver/database. This should be implemented by subclasses using the quoting services of the DBAPI. """ return repr_value(value) compiler = LiteralCompiler(dialect, query) return str(compiler.process(query)).replace('\n', '')
[ "def", "rawsql", "(", "query", ",", "ec", "=", "None", ")", ":", "if", "isinstance", "(", "query", ",", "Result", ")", ":", "query", "=", "query", ".", "get_query", "(", ")", "ec", "=", "ec", "or", "__default_engine__", "if", "isinstance", "(", "ec", ",", "(", "str", ",", "unicode", ")", ")", ":", "engine", "=", "engine_manager", "[", "ec", "]", "dialect", "=", "engine", ".", "engine", ".", "dialect", "else", ":", "dialect", "=", "ec", ".", "dialect", "if", "isinstance", "(", "query", ",", "(", "str", ",", "unicode", ")", ")", ":", "return", "query", "# comp = query.compile(dialect=dialect)", "compiler", "=", "query", ".", "_compiler", "(", "dialect", ")", "class", "LiteralCompiler", "(", "compiler", ".", "__class__", ")", ":", "def", "visit_bindparam", "(", "self", ",", "bindparam", ",", "within_columns_clause", "=", "False", ",", "literal_binds", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "LiteralCompiler", ",", "self", ")", ".", "render_literal_bindparam", "(", "bindparam", ",", "within_columns_clause", "=", "within_columns_clause", ",", "literal_binds", "=", "literal_binds", ",", "*", "*", "kwargs", ")", "def", "render_literal_value", "(", "self", ",", "value", ",", "type_", ")", ":", "\"\"\"Render the value of a bind parameter as a quoted literal.\n\n This is used for statement sections that do not accept bind paramters\n on the target driver/database.\n\n This should be implemented by subclasses using the quoting services\n of the DBAPI.\n\n \"\"\"", "return", "repr_value", "(", "value", ")", "compiler", "=", "LiteralCompiler", "(", "dialect", ",", "query", ")", "return", "str", "(", "compiler", ".", "process", "(", "query", ")", ")", ".", "replace", "(", "'\\n'", ",", "''", ")" ]
ec could be engine name or engine instance
[ "ec", "could", "be", "engine", "name", "or", "engine", "instance" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L555-L595
6,980
limodou/uliweb
uliweb/orm/__init__.py
get_engine_name
def get_engine_name(ec=None): """ Get the name of a engine or session """ ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): return ec elif isinstance(ec, Session): return ec.engine_name else: raise Error("Parameter ec should be an engine_name or Session object, but %r found" % ec)
python
def get_engine_name(ec=None): """ Get the name of a engine or session """ ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): return ec elif isinstance(ec, Session): return ec.engine_name else: raise Error("Parameter ec should be an engine_name or Session object, but %r found" % ec)
[ "def", "get_engine_name", "(", "ec", "=", "None", ")", ":", "ec", "=", "ec", "or", "__default_engine__", "if", "isinstance", "(", "ec", ",", "(", "str", ",", "unicode", ")", ")", ":", "return", "ec", "elif", "isinstance", "(", "ec", ",", "Session", ")", ":", "return", "ec", ".", "engine_name", "else", ":", "raise", "Error", "(", "\"Parameter ec should be an engine_name or Session object, but %r found\"", "%", "ec", ")" ]
Get the name of a engine or session
[ "Get", "the", "name", "of", "a", "engine", "or", "session" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L597-L607
6,981
limodou/uliweb
uliweb/orm/__init__.py
CommitAll
def CommitAll(close=None): """ Commit all transactions according Local.conn """ if close: warnings.simplefilter('default') warnings.warn("close parameter will not need at all.", DeprecationWarning) for k, v in engine_manager.items(): session = v.session(create=False) if session: session.commit()
python
def CommitAll(close=None): """ Commit all transactions according Local.conn """ if close: warnings.simplefilter('default') warnings.warn("close parameter will not need at all.", DeprecationWarning) for k, v in engine_manager.items(): session = v.session(create=False) if session: session.commit()
[ "def", "CommitAll", "(", "close", "=", "None", ")", ":", "if", "close", ":", "warnings", ".", "simplefilter", "(", "'default'", ")", "warnings", ".", "warn", "(", "\"close parameter will not need at all.\"", ",", "DeprecationWarning", ")", "for", "k", ",", "v", "in", "engine_manager", ".", "items", "(", ")", ":", "session", "=", "v", ".", "session", "(", "create", "=", "False", ")", "if", "session", ":", "session", ".", "commit", "(", ")" ]
Commit all transactions according Local.conn
[ "Commit", "all", "transactions", "according", "Local", ".", "conn" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L814-L825
6,982
limodou/uliweb
uliweb/orm/__init__.py
RollbackAll
def RollbackAll(close=None): """ Rollback all transactions, according Local.conn """ if close: warnings.simplefilter('default') warnings.warn("close parameter will not need at all.", DeprecationWarning) for k, v in engine_manager.items(): session = v.session(create=False) if session: session.rollback()
python
def RollbackAll(close=None): """ Rollback all transactions, according Local.conn """ if close: warnings.simplefilter('default') warnings.warn("close parameter will not need at all.", DeprecationWarning) for k, v in engine_manager.items(): session = v.session(create=False) if session: session.rollback()
[ "def", "RollbackAll", "(", "close", "=", "None", ")", ":", "if", "close", ":", "warnings", ".", "simplefilter", "(", "'default'", ")", "warnings", ".", "warn", "(", "\"close parameter will not need at all.\"", ",", "DeprecationWarning", ")", "for", "k", ",", "v", "in", "engine_manager", ".", "items", "(", ")", ":", "session", "=", "v", ".", "session", "(", "create", "=", "False", ")", "if", "session", ":", "session", ".", "rollback", "(", ")" ]
Rollback all transactions, according Local.conn
[ "Rollback", "all", "transactions", "according", "Local", ".", "conn" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L836-L847
6,983
limodou/uliweb
uliweb/orm/__init__.py
set_model
def set_model(model, tablename=None, created=None, appname=None, model_path=None): """ Register an model and tablename to a global variable. model could be a string format, i.e., 'uliweb.contrib.auth.models.User' :param appname: if no appname, then archive according to model item structure created model model_path appname For dynamic model you should pass model_path with '' value """ if isinstance(model, type) and issubclass(model, Model): #use alias first tablename = model._alias or model.tablename tablename = tablename.lower() #set global __models__ d = __models__.setdefault(tablename, {}) engines = d.get('config', {}).pop('engines', ['default']) if isinstance(engines, (str, unicode)): engines = [engines] d['engines'] = engines item = {} if created is not None: item['created'] = created else: item['created'] = None if isinstance(model, (str, unicode)): if model_path is None: model_path = model else: model_path = model_path if not appname: appname = model.rsplit('.', 2)[0] #for example 'uliweb.contrib.auth.models.User' model = None else: appname = model.__module__.rsplit('.', 1)[0] if model_path is None: model_path = model.__module__ + '.' + model.__name__ else: model_path = '' #for example 'uliweb.contrib.auth.models' model.__engines__ = engines item['model'] = model item['model_path'] = model_path item['appname'] = appname d['model_path'] = model_path d['appname'] = appname for name in engines: if not isinstance(name, (str, unicode)): raise BadValueError('Engine name should be string type, but %r found' % name) engine_manager[name].models[tablename] = item.copy()
python
def set_model(model, tablename=None, created=None, appname=None, model_path=None): """ Register an model and tablename to a global variable. model could be a string format, i.e., 'uliweb.contrib.auth.models.User' :param appname: if no appname, then archive according to model item structure created model model_path appname For dynamic model you should pass model_path with '' value """ if isinstance(model, type) and issubclass(model, Model): #use alias first tablename = model._alias or model.tablename tablename = tablename.lower() #set global __models__ d = __models__.setdefault(tablename, {}) engines = d.get('config', {}).pop('engines', ['default']) if isinstance(engines, (str, unicode)): engines = [engines] d['engines'] = engines item = {} if created is not None: item['created'] = created else: item['created'] = None if isinstance(model, (str, unicode)): if model_path is None: model_path = model else: model_path = model_path if not appname: appname = model.rsplit('.', 2)[0] #for example 'uliweb.contrib.auth.models.User' model = None else: appname = model.__module__.rsplit('.', 1)[0] if model_path is None: model_path = model.__module__ + '.' + model.__name__ else: model_path = '' #for example 'uliweb.contrib.auth.models' model.__engines__ = engines item['model'] = model item['model_path'] = model_path item['appname'] = appname d['model_path'] = model_path d['appname'] = appname for name in engines: if not isinstance(name, (str, unicode)): raise BadValueError('Engine name should be string type, but %r found' % name) engine_manager[name].models[tablename] = item.copy()
[ "def", "set_model", "(", "model", ",", "tablename", "=", "None", ",", "created", "=", "None", ",", "appname", "=", "None", ",", "model_path", "=", "None", ")", ":", "if", "isinstance", "(", "model", ",", "type", ")", "and", "issubclass", "(", "model", ",", "Model", ")", ":", "#use alias first", "tablename", "=", "model", ".", "_alias", "or", "model", ".", "tablename", "tablename", "=", "tablename", ".", "lower", "(", ")", "#set global __models__", "d", "=", "__models__", ".", "setdefault", "(", "tablename", ",", "{", "}", ")", "engines", "=", "d", ".", "get", "(", "'config'", ",", "{", "}", ")", ".", "pop", "(", "'engines'", ",", "[", "'default'", "]", ")", "if", "isinstance", "(", "engines", ",", "(", "str", ",", "unicode", ")", ")", ":", "engines", "=", "[", "engines", "]", "d", "[", "'engines'", "]", "=", "engines", "item", "=", "{", "}", "if", "created", "is", "not", "None", ":", "item", "[", "'created'", "]", "=", "created", "else", ":", "item", "[", "'created'", "]", "=", "None", "if", "isinstance", "(", "model", ",", "(", "str", ",", "unicode", ")", ")", ":", "if", "model_path", "is", "None", ":", "model_path", "=", "model", "else", ":", "model_path", "=", "model_path", "if", "not", "appname", ":", "appname", "=", "model", ".", "rsplit", "(", "'.'", ",", "2", ")", "[", "0", "]", "#for example 'uliweb.contrib.auth.models.User'", "model", "=", "None", "else", ":", "appname", "=", "model", ".", "__module__", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "if", "model_path", "is", "None", ":", "model_path", "=", "model", ".", "__module__", "+", "'.'", "+", "model", ".", "__name__", "else", ":", "model_path", "=", "''", "#for example 'uliweb.contrib.auth.models'", "model", ".", "__engines__", "=", "engines", "item", "[", "'model'", "]", "=", "model", "item", "[", "'model_path'", "]", "=", "model_path", "item", "[", "'appname'", "]", "=", "appname", "d", "[", "'model_path'", "]", "=", "model_path", "d", "[", "'appname'", "]", "=", "appname", "for", "name", "in", "engines", ":", "if", "not", "isinstance", "(", "name", ",", "(", "str", ",", "unicode", ")", ")", ":", "raise", "BadValueError", "(", "'Engine name should be string type, but %r found'", "%", "name", ")", "engine_manager", "[", "name", "]", ".", "models", "[", "tablename", "]", "=", "item", ".", "copy", "(", ")" ]
Register an model and tablename to a global variable. model could be a string format, i.e., 'uliweb.contrib.auth.models.User' :param appname: if no appname, then archive according to model item structure created model model_path appname For dynamic model you should pass model_path with '' value
[ "Register", "an", "model", "and", "tablename", "to", "a", "global", "variable", ".", "model", "could", "be", "a", "string", "format", "i", ".", "e", ".", "uliweb", ".", "contrib", ".", "auth", ".", "models", ".", "User" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L855-L914
6,984
limodou/uliweb
uliweb/orm/__init__.py
create_model
def create_model(modelname, fields, indexes=None, basemodel=None, **props): """ Create model dynamically :param fields: Just format like [ {'name':name, 'type':type, ...}, ... ] type should be a string, eg. 'str', 'int', etc kwargs will be passed to Property.__init__() according field type, it'll be a dict :param props: Model attributes, such as '__mapping_only__', '__replace__' :param indexes: Multiple fields index, single index can be set directly using `index=True` to a field, the value format should be: [ {'name':name, 'fields':[...], ...}, ] e.g. [ {'name':'audit_idx', 'fields':['table_id', 'obj_id']} ] for kwargs can be ommited. :param basemodel: Will be the new Model base class, so new Model can inherited parent methods, it can be a string or a real class object """ assert not props or isinstance(props, dict) assert not indexes or isinstance(indexes, list) props = SortedDict(props or {}) props['__dynamic__'] = True props['__config__'] = False for p in fields: kwargs = p.copy() name = kwargs.pop('name') _type = kwargs.pop('type') #if the key is start with '_', then remove it for k in kwargs.keys(): if k.startswith('_'): kwargs.pop(k, None) field_type = get_field_type(_type) prop = field_type(**kwargs) props[name] = prop if basemodel: model = import_attr(basemodel) # model.clear_relation() else: model = Model # try: # old = get_model(modelname, signal=False) # old.clear_relation() # except ModelNotFound as e: # pass cls = type(str(modelname.title()), (model,), props) tablename = props.get('__tablename__', modelname) set_model(cls, tablename, appname=__name__, model_path='') get_model(modelname, signal=False, reload=True) indexes = indexes or [] for x in indexes: kwargs = x.copy() name = kwargs.pop('name') fields = kwargs.pop('fields') #if the key is start with '_', then remove it for k in kwargs.keys(): if k.startswith('_'): kwargs.pop(k, None) if not isinstance(fields, (list, tuple)): raise ValueError("Index value format is not right, the value is %r" % indexes) props = [] for y in fields: props.append(cls.c[y]) Index(name, *props, **kwargs) return cls
python
def create_model(modelname, fields, indexes=None, basemodel=None, **props): """ Create model dynamically :param fields: Just format like [ {'name':name, 'type':type, ...}, ... ] type should be a string, eg. 'str', 'int', etc kwargs will be passed to Property.__init__() according field type, it'll be a dict :param props: Model attributes, such as '__mapping_only__', '__replace__' :param indexes: Multiple fields index, single index can be set directly using `index=True` to a field, the value format should be: [ {'name':name, 'fields':[...], ...}, ] e.g. [ {'name':'audit_idx', 'fields':['table_id', 'obj_id']} ] for kwargs can be ommited. :param basemodel: Will be the new Model base class, so new Model can inherited parent methods, it can be a string or a real class object """ assert not props or isinstance(props, dict) assert not indexes or isinstance(indexes, list) props = SortedDict(props or {}) props['__dynamic__'] = True props['__config__'] = False for p in fields: kwargs = p.copy() name = kwargs.pop('name') _type = kwargs.pop('type') #if the key is start with '_', then remove it for k in kwargs.keys(): if k.startswith('_'): kwargs.pop(k, None) field_type = get_field_type(_type) prop = field_type(**kwargs) props[name] = prop if basemodel: model = import_attr(basemodel) # model.clear_relation() else: model = Model # try: # old = get_model(modelname, signal=False) # old.clear_relation() # except ModelNotFound as e: # pass cls = type(str(modelname.title()), (model,), props) tablename = props.get('__tablename__', modelname) set_model(cls, tablename, appname=__name__, model_path='') get_model(modelname, signal=False, reload=True) indexes = indexes or [] for x in indexes: kwargs = x.copy() name = kwargs.pop('name') fields = kwargs.pop('fields') #if the key is start with '_', then remove it for k in kwargs.keys(): if k.startswith('_'): kwargs.pop(k, None) if not isinstance(fields, (list, tuple)): raise ValueError("Index value format is not right, the value is %r" % indexes) props = [] for y in fields: props.append(cls.c[y]) Index(name, *props, **kwargs) return cls
[ "def", "create_model", "(", "modelname", ",", "fields", ",", "indexes", "=", "None", ",", "basemodel", "=", "None", ",", "*", "*", "props", ")", ":", "assert", "not", "props", "or", "isinstance", "(", "props", ",", "dict", ")", "assert", "not", "indexes", "or", "isinstance", "(", "indexes", ",", "list", ")", "props", "=", "SortedDict", "(", "props", "or", "{", "}", ")", "props", "[", "'__dynamic__'", "]", "=", "True", "props", "[", "'__config__'", "]", "=", "False", "for", "p", "in", "fields", ":", "kwargs", "=", "p", ".", "copy", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "_type", "=", "kwargs", ".", "pop", "(", "'type'", ")", "#if the key is start with '_', then remove it", "for", "k", "in", "kwargs", ".", "keys", "(", ")", ":", "if", "k", ".", "startswith", "(", "'_'", ")", ":", "kwargs", ".", "pop", "(", "k", ",", "None", ")", "field_type", "=", "get_field_type", "(", "_type", ")", "prop", "=", "field_type", "(", "*", "*", "kwargs", ")", "props", "[", "name", "]", "=", "prop", "if", "basemodel", ":", "model", "=", "import_attr", "(", "basemodel", ")", "# model.clear_relation()", "else", ":", "model", "=", "Model", "# try:", "# old = get_model(modelname, signal=False)", "# old.clear_relation()", "# except ModelNotFound as e:", "# pass", "cls", "=", "type", "(", "str", "(", "modelname", ".", "title", "(", ")", ")", ",", "(", "model", ",", ")", ",", "props", ")", "tablename", "=", "props", ".", "get", "(", "'__tablename__'", ",", "modelname", ")", "set_model", "(", "cls", ",", "tablename", ",", "appname", "=", "__name__", ",", "model_path", "=", "''", ")", "get_model", "(", "modelname", ",", "signal", "=", "False", ",", "reload", "=", "True", ")", "indexes", "=", "indexes", "or", "[", "]", "for", "x", "in", "indexes", ":", "kwargs", "=", "x", ".", "copy", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "fields", "=", "kwargs", ".", "pop", "(", "'fields'", ")", "#if the key is start with '_', then remove it", "for", "k", "in", "kwargs", ".", "keys", "(", ")", ":", "if", "k", ".", "startswith", "(", "'_'", ")", ":", "kwargs", ".", "pop", "(", "k", ",", "None", ")", "if", "not", "isinstance", "(", "fields", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"Index value format is not right, the value is %r\"", "%", "indexes", ")", "props", "=", "[", "]", "for", "y", "in", "fields", ":", "props", ".", "append", "(", "cls", ".", "c", "[", "y", "]", ")", "Index", "(", "name", ",", "*", "props", ",", "*", "*", "kwargs", ")", "return", "cls" ]
Create model dynamically :param fields: Just format like [ {'name':name, 'type':type, ...}, ... ] type should be a string, eg. 'str', 'int', etc kwargs will be passed to Property.__init__() according field type, it'll be a dict :param props: Model attributes, such as '__mapping_only__', '__replace__' :param indexes: Multiple fields index, single index can be set directly using `index=True` to a field, the value format should be: [ {'name':name, 'fields':[...], ...}, ] e.g. [ {'name':'audit_idx', 'fields':['table_id', 'obj_id']} ] for kwargs can be ommited. :param basemodel: Will be the new Model base class, so new Model can inherited parent methods, it can be a string or a real class object
[ "Create", "model", "dynamically" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L934-L1020
6,985
limodou/uliweb
uliweb/orm/__init__.py
reflect_table_model
def reflect_table_model(table, mapping=None, without_id=False, engine_name='default'): """ Write table to Model class """ table = reflect_table(table, engine_name) mapping = mapping or {} meta = reflect_table_data(table) code = ['class {}(Model):'.format(table.name.title())] code.append(''' """ Description: """ __tablename__ = '{}\''''.format(table.name)) if sa_version >= '1.2' and table.comment: code.append(' __verbose_name__ = {}\n'.format(dumps(table.comment, bool_int=False))) #process id if 'id' not in meta['columns'] and without_id: code.append(' __without_id__ = True\n') # if _primary_key: # code.append(' _primary_field = {}'.format(_primary_key)) #output columns text for k, v in meta['columns'].items(): kw = v[1].items() x_v = mapping.get(v[0]) kwargs = ', '.join([v[0]] + ['{0}={1}'.format(x, dumps(y, bool_int=False)) for x, y in kw]) if x_v: type_class = ' ,type_class={}'.format(x_v) else: type_class = '' txt = " "*4 + "{0} = Field({1}{2})".format(k, kwargs, type_class) code.append(txt) #output index text if meta['indexes']: code.append(""" @classmethod def OnInit(cls):""") for index in meta['indexes']: buf = [] buf.append(index['name']) for c in index['columns']: buf.append('cls.c.{}'.format(c)) if index['unique']: buf.append('unique=True') code.append(' '*8 + 'Index({})'.format(', '.join(buf))) return '\n'.join(code)
python
def reflect_table_model(table, mapping=None, without_id=False, engine_name='default'): """ Write table to Model class """ table = reflect_table(table, engine_name) mapping = mapping or {} meta = reflect_table_data(table) code = ['class {}(Model):'.format(table.name.title())] code.append(''' """ Description: """ __tablename__ = '{}\''''.format(table.name)) if sa_version >= '1.2' and table.comment: code.append(' __verbose_name__ = {}\n'.format(dumps(table.comment, bool_int=False))) #process id if 'id' not in meta['columns'] and without_id: code.append(' __without_id__ = True\n') # if _primary_key: # code.append(' _primary_field = {}'.format(_primary_key)) #output columns text for k, v in meta['columns'].items(): kw = v[1].items() x_v = mapping.get(v[0]) kwargs = ', '.join([v[0]] + ['{0}={1}'.format(x, dumps(y, bool_int=False)) for x, y in kw]) if x_v: type_class = ' ,type_class={}'.format(x_v) else: type_class = '' txt = " "*4 + "{0} = Field({1}{2})".format(k, kwargs, type_class) code.append(txt) #output index text if meta['indexes']: code.append(""" @classmethod def OnInit(cls):""") for index in meta['indexes']: buf = [] buf.append(index['name']) for c in index['columns']: buf.append('cls.c.{}'.format(c)) if index['unique']: buf.append('unique=True') code.append(' '*8 + 'Index({})'.format(', '.join(buf))) return '\n'.join(code)
[ "def", "reflect_table_model", "(", "table", ",", "mapping", "=", "None", ",", "without_id", "=", "False", ",", "engine_name", "=", "'default'", ")", ":", "table", "=", "reflect_table", "(", "table", ",", "engine_name", ")", "mapping", "=", "mapping", "or", "{", "}", "meta", "=", "reflect_table_data", "(", "table", ")", "code", "=", "[", "'class {}(Model):'", ".", "format", "(", "table", ".", "name", ".", "title", "(", ")", ")", "]", "code", ".", "append", "(", "''' \"\"\"\n Description:\n \"\"\"\n\n __tablename__ = '{}\\''''", ".", "format", "(", "table", ".", "name", ")", ")", "if", "sa_version", ">=", "'1.2'", "and", "table", ".", "comment", ":", "code", ".", "append", "(", "' __verbose_name__ = {}\\n'", ".", "format", "(", "dumps", "(", "table", ".", "comment", ",", "bool_int", "=", "False", ")", ")", ")", "#process id", "if", "'id'", "not", "in", "meta", "[", "'columns'", "]", "and", "without_id", ":", "code", ".", "append", "(", "' __without_id__ = True\\n'", ")", "# if _primary_key:", "# code.append(' _primary_field = {}'.format(_primary_key))", "#output columns text", "for", "k", ",", "v", "in", "meta", "[", "'columns'", "]", ".", "items", "(", ")", ":", "kw", "=", "v", "[", "1", "]", ".", "items", "(", ")", "x_v", "=", "mapping", ".", "get", "(", "v", "[", "0", "]", ")", "kwargs", "=", "', '", ".", "join", "(", "[", "v", "[", "0", "]", "]", "+", "[", "'{0}={1}'", ".", "format", "(", "x", ",", "dumps", "(", "y", ",", "bool_int", "=", "False", ")", ")", "for", "x", ",", "y", "in", "kw", "]", ")", "if", "x_v", ":", "type_class", "=", "' ,type_class={}'", ".", "format", "(", "x_v", ")", "else", ":", "type_class", "=", "''", "txt", "=", "\" \"", "*", "4", "+", "\"{0} = Field({1}{2})\"", ".", "format", "(", "k", ",", "kwargs", ",", "type_class", ")", "code", ".", "append", "(", "txt", ")", "#output index text", "if", "meta", "[", "'indexes'", "]", ":", "code", ".", "append", "(", "\"\"\"\n @classmethod\n def OnInit(cls):\"\"\"", ")", "for", "index", "in", "meta", "[", "'indexes'", "]", ":", "buf", "=", "[", "]", "buf", ".", "append", "(", "index", "[", "'name'", "]", ")", "for", "c", "in", "index", "[", "'columns'", "]", ":", "buf", ".", "append", "(", "'cls.c.{}'", ".", "format", "(", "c", ")", ")", "if", "index", "[", "'unique'", "]", ":", "buf", ".", "append", "(", "'unique=True'", ")", "code", ".", "append", "(", "' '", "*", "8", "+", "'Index({})'", ".", "format", "(", "', '", ".", "join", "(", "buf", ")", ")", ")", "return", "'\\n'", ".", "join", "(", "code", ")" ]
Write table to Model class
[ "Write", "table", "to", "Model", "class" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L1372-L1422
6,986
limodou/uliweb
uliweb/orm/__init__.py
SelfReferenceProperty
def SelfReferenceProperty(label=None, collection_name=None, **attrs): """Create a self reference. """ if 'reference_class' in attrs: raise ConfigurationError( 'Do not provide reference_class to self-reference.') return ReferenceProperty(_SELF_REFERENCE, label, collection_name, **attrs)
python
def SelfReferenceProperty(label=None, collection_name=None, **attrs): """Create a self reference. """ if 'reference_class' in attrs: raise ConfigurationError( 'Do not provide reference_class to self-reference.') return ReferenceProperty(_SELF_REFERENCE, label, collection_name, **attrs)
[ "def", "SelfReferenceProperty", "(", "label", "=", "None", ",", "collection_name", "=", "None", ",", "*", "*", "attrs", ")", ":", "if", "'reference_class'", "in", "attrs", ":", "raise", "ConfigurationError", "(", "'Do not provide reference_class to self-reference.'", ")", "return", "ReferenceProperty", "(", "_SELF_REFERENCE", ",", "label", ",", "collection_name", ",", "*", "*", "attrs", ")" ]
Create a self reference.
[ "Create", "a", "self", "reference", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3595-L3601
6,987
limodou/uliweb
uliweb/orm/__init__.py
NamedEngine.session
def session(self, create=True): """ Used to created default session """ if hasattr(self.local, 'session'): return self.local.session else: if create: s = Session(self.name) self.local.session = s return s
python
def session(self, create=True): """ Used to created default session """ if hasattr(self.local, 'session'): return self.local.session else: if create: s = Session(self.name) self.local.session = s return s
[ "def", "session", "(", "self", ",", "create", "=", "True", ")", ":", "if", "hasattr", "(", "self", ".", "local", ",", "'session'", ")", ":", "return", "self", ".", "local", ".", "session", "else", ":", "if", "create", ":", "s", "=", "Session", "(", "self", ".", "name", ")", "self", ".", "local", ".", "session", "=", "s", "return", "s" ]
Used to created default session
[ "Used", "to", "created", "default", "session" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L263-L273
6,988
limodou/uliweb
uliweb/orm/__init__.py
Property.get_parameters
def get_parameters(self): """ Get common attributes and it'll used for Model.relationship clone process """ d = {} for k in ['label', 'verbose_name', 'required', 'hint', 'placeholder', 'choices', 'default', 'validators', 'max_length']: d[k] = getattr(self, k) return d
python
def get_parameters(self): """ Get common attributes and it'll used for Model.relationship clone process """ d = {} for k in ['label', 'verbose_name', 'required', 'hint', 'placeholder', 'choices', 'default', 'validators', 'max_length']: d[k] = getattr(self, k) return d
[ "def", "get_parameters", "(", "self", ")", ":", "d", "=", "{", "}", "for", "k", "in", "[", "'label'", ",", "'verbose_name'", ",", "'required'", ",", "'hint'", ",", "'placeholder'", ",", "'choices'", ",", "'default'", ",", "'validators'", ",", "'max_length'", "]", ":", "d", "[", "k", "]", "=", "getattr", "(", "self", ",", "k", ")", "return", "d" ]
Get common attributes and it'll used for Model.relationship clone process
[ "Get", "common", "attributes", "and", "it", "ll", "used", "for", "Model", ".", "relationship", "clone", "process" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L1628-L1636
6,989
limodou/uliweb
uliweb/orm/__init__.py
ReferenceProperty.validate
def validate(self, value): """Validate reference. Returns: A valid value. Raises: BadValueError for the following reasons: - Value is not saved. - Object not of correct model type for reference. """ if value == '': if self.kwargs.get('nullable', __nullable__): value = None else: value = 0 if not isinstance(value, Model): return super(ReferenceProperty, self).validate(value) if not value.is_saved(): raise BadValueError( '%s instance must be saved before it can be stored as a ' 'reference' % self.reference_class.__class__.__name__) if not isinstance(value, self.reference_class): raise KindError('Property %s must be an instance of %s' % (self.name, self.reference_class.__class__.__name__)) return value
python
def validate(self, value): """Validate reference. Returns: A valid value. Raises: BadValueError for the following reasons: - Value is not saved. - Object not of correct model type for reference. """ if value == '': if self.kwargs.get('nullable', __nullable__): value = None else: value = 0 if not isinstance(value, Model): return super(ReferenceProperty, self).validate(value) if not value.is_saved(): raise BadValueError( '%s instance must be saved before it can be stored as a ' 'reference' % self.reference_class.__class__.__name__) if not isinstance(value, self.reference_class): raise KindError('Property %s must be an instance of %s' % (self.name, self.reference_class.__class__.__name__)) return value
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "value", "==", "''", ":", "if", "self", ".", "kwargs", ".", "get", "(", "'nullable'", ",", "__nullable__", ")", ":", "value", "=", "None", "else", ":", "value", "=", "0", "if", "not", "isinstance", "(", "value", ",", "Model", ")", ":", "return", "super", "(", "ReferenceProperty", ",", "self", ")", ".", "validate", "(", "value", ")", "if", "not", "value", ".", "is_saved", "(", ")", ":", "raise", "BadValueError", "(", "'%s instance must be saved before it can be stored as a '", "'reference'", "%", "self", ".", "reference_class", ".", "__class__", ".", "__name__", ")", "if", "not", "isinstance", "(", "value", ",", "self", ".", "reference_class", ")", ":", "raise", "KindError", "(", "'Property %s must be an instance of %s'", "%", "(", "self", ".", "name", ",", "self", ".", "reference_class", ".", "__class__", ".", "__name__", ")", ")", "return", "value" ]
Validate reference. Returns: A valid value. Raises: BadValueError for the following reasons: - Value is not saved. - Object not of correct model type for reference.
[ "Validate", "reference", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2394-L2422
6,990
limodou/uliweb
uliweb/orm/__init__.py
Result.get_fields
def get_fields(self): """ get property instance according self.columns """ columns = self.columns model = self.model fields = [] for col in columns: if isinstance(col, (str, unicode)): v = col.split('.') if len(v) > 1: field = get_model(v[0], engine_name=self.model.get_engine_name(), signal=False).properties(v[1]) else: field = model.properties[col] elif isinstance(col, Column): field = get_model(col.table.name, engine_name=self.model.get_engine_name(), signal=False).properties[col.name] else: field = col fields.append(field) return fields
python
def get_fields(self): """ get property instance according self.columns """ columns = self.columns model = self.model fields = [] for col in columns: if isinstance(col, (str, unicode)): v = col.split('.') if len(v) > 1: field = get_model(v[0], engine_name=self.model.get_engine_name(), signal=False).properties(v[1]) else: field = model.properties[col] elif isinstance(col, Column): field = get_model(col.table.name, engine_name=self.model.get_engine_name(), signal=False).properties[col.name] else: field = col fields.append(field) return fields
[ "def", "get_fields", "(", "self", ")", ":", "columns", "=", "self", ".", "columns", "model", "=", "self", ".", "model", "fields", "=", "[", "]", "for", "col", "in", "columns", ":", "if", "isinstance", "(", "col", ",", "(", "str", ",", "unicode", ")", ")", ":", "v", "=", "col", ".", "split", "(", "'.'", ")", "if", "len", "(", "v", ")", ">", "1", ":", "field", "=", "get_model", "(", "v", "[", "0", "]", ",", "engine_name", "=", "self", ".", "model", ".", "get_engine_name", "(", ")", ",", "signal", "=", "False", ")", ".", "properties", "(", "v", "[", "1", "]", ")", "else", ":", "field", "=", "model", ".", "properties", "[", "col", "]", "elif", "isinstance", "(", "col", ",", "Column", ")", ":", "field", "=", "get_model", "(", "col", ".", "table", ".", "name", ",", "engine_name", "=", "self", ".", "model", ".", "get_engine_name", "(", ")", ",", "signal", "=", "False", ")", ".", "properties", "[", "col", ".", "name", "]", "else", ":", "field", "=", "col", "fields", ".", "append", "(", "field", ")", "return", "fields" ]
get property instance according self.columns
[ "get", "property", "instance", "according", "self", ".", "columns" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2596-L2619
6,991
limodou/uliweb
uliweb/orm/__init__.py
Result.count
def count(self): """ If result is True, then the count will process result set , if result if False, then only use condition to count """ if self._group_by or self._join or self.distinct_field: return self.do_(self.get_query().limit(None).order_by(None).offset(None).alias().count()).scalar() else: return self.do_(self.get_query().with_only_columns([func.count()]).limit(None).order_by(None).offset(None)).scalar()
python
def count(self): """ If result is True, then the count will process result set , if result if False, then only use condition to count """ if self._group_by or self._join or self.distinct_field: return self.do_(self.get_query().limit(None).order_by(None).offset(None).alias().count()).scalar() else: return self.do_(self.get_query().with_only_columns([func.count()]).limit(None).order_by(None).offset(None)).scalar()
[ "def", "count", "(", "self", ")", ":", "if", "self", ".", "_group_by", "or", "self", ".", "_join", "or", "self", ".", "distinct_field", ":", "return", "self", ".", "do_", "(", "self", ".", "get_query", "(", ")", ".", "limit", "(", "None", ")", ".", "order_by", "(", "None", ")", ".", "offset", "(", "None", ")", ".", "alias", "(", ")", ".", "count", "(", ")", ")", ".", "scalar", "(", ")", "else", ":", "return", "self", ".", "do_", "(", "self", ".", "get_query", "(", ")", ".", "with_only_columns", "(", "[", "func", ".", "count", "(", ")", "]", ")", ".", "limit", "(", "None", ")", ".", "order_by", "(", "None", ")", ".", "offset", "(", "None", ")", ")", ".", "scalar", "(", ")" ]
If result is True, then the count will process result set , if result if False, then only use condition to count
[ "If", "result", "is", "True", "then", "the", "count", "will", "process", "result", "set", "if", "result", "if", "False", "then", "only", "use", "condition", "to", "count" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2661-L2669
6,992
limodou/uliweb
uliweb/orm/__init__.py
Result.update
def update(self, **kwargs): """ Execute update table set field = field+1 like statement """ if self.condition is not None: self.result = self.do_(self.model.table.update().where(self.condition).values(**kwargs)) else: self.result = self.do_(self.model.table.update().values(**kwargs)) return self.result
python
def update(self, **kwargs): """ Execute update table set field = field+1 like statement """ if self.condition is not None: self.result = self.do_(self.model.table.update().where(self.condition).values(**kwargs)) else: self.result = self.do_(self.model.table.update().values(**kwargs)) return self.result
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "condition", "is", "not", "None", ":", "self", ".", "result", "=", "self", ".", "do_", "(", "self", ".", "model", ".", "table", ".", "update", "(", ")", ".", "where", "(", "self", ".", "condition", ")", ".", "values", "(", "*", "*", "kwargs", ")", ")", "else", ":", "self", ".", "result", "=", "self", ".", "do_", "(", "self", ".", "model", ".", "table", ".", "update", "(", ")", ".", "values", "(", "*", "*", "kwargs", ")", ")", "return", "self", ".", "result" ]
Execute update table set field = field+1 like statement
[ "Execute", "update", "table", "set", "field", "=", "field", "+", "1", "like", "statement" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2754-L2762
6,993
limodou/uliweb
uliweb/orm/__init__.py
Result.save_file
def save_file(self, filename, encoding='utf8', headers=None, convertors=None, display=True, **kwargs): """ save result to a csv file. display = True will convert value according choices value """ global save_file convertors = convertors or {} headers = headers or [] fields = self.get_fields() _header = [] for i, column in enumerate(fields): if column.name not in convertors: if display: def f(value, data): return column.get_display_value(value) convertors[column.name] = f flag = False for j in headers: if not isinstance(j, dict): raise ValueError("Header should be a list of dict, but {} type found".format(type(j))) if j['name'] == column.name: _header.append(j) flag = True break if not flag: d = {'name':column.name} if display: d['title'] = column.verbose_name or column.name else: d['title'] = column.name _header.append(d) return save_file(self.run(), filename, encoding=encoding, headers=_header, convertors=convertors, **kwargs)
python
def save_file(self, filename, encoding='utf8', headers=None, convertors=None, display=True, **kwargs): """ save result to a csv file. display = True will convert value according choices value """ global save_file convertors = convertors or {} headers = headers or [] fields = self.get_fields() _header = [] for i, column in enumerate(fields): if column.name not in convertors: if display: def f(value, data): return column.get_display_value(value) convertors[column.name] = f flag = False for j in headers: if not isinstance(j, dict): raise ValueError("Header should be a list of dict, but {} type found".format(type(j))) if j['name'] == column.name: _header.append(j) flag = True break if not flag: d = {'name':column.name} if display: d['title'] = column.verbose_name or column.name else: d['title'] = column.name _header.append(d) return save_file(self.run(), filename, encoding=encoding, headers=_header, convertors=convertors, **kwargs)
[ "def", "save_file", "(", "self", ",", "filename", ",", "encoding", "=", "'utf8'", ",", "headers", "=", "None", ",", "convertors", "=", "None", ",", "display", "=", "True", ",", "*", "*", "kwargs", ")", ":", "global", "save_file", "convertors", "=", "convertors", "or", "{", "}", "headers", "=", "headers", "or", "[", "]", "fields", "=", "self", ".", "get_fields", "(", ")", "_header", "=", "[", "]", "for", "i", ",", "column", "in", "enumerate", "(", "fields", ")", ":", "if", "column", ".", "name", "not", "in", "convertors", ":", "if", "display", ":", "def", "f", "(", "value", ",", "data", ")", ":", "return", "column", ".", "get_display_value", "(", "value", ")", "convertors", "[", "column", ".", "name", "]", "=", "f", "flag", "=", "False", "for", "j", "in", "headers", ":", "if", "not", "isinstance", "(", "j", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"Header should be a list of dict, but {} type found\"", ".", "format", "(", "type", "(", "j", ")", ")", ")", "if", "j", "[", "'name'", "]", "==", "column", ".", "name", ":", "_header", ".", "append", "(", "j", ")", "flag", "=", "True", "break", "if", "not", "flag", ":", "d", "=", "{", "'name'", ":", "column", ".", "name", "}", "if", "display", ":", "d", "[", "'title'", "]", "=", "column", ".", "verbose_name", "or", "column", ".", "name", "else", ":", "d", "[", "'title'", "]", "=", "column", ".", "name", "_header", ".", "append", "(", "d", ")", "return", "save_file", "(", "self", ".", "run", "(", ")", ",", "filename", ",", "encoding", "=", "encoding", ",", "headers", "=", "_header", ",", "convertors", "=", "convertors", ",", "*", "*", "kwargs", ")" ]
save result to a csv file. display = True will convert value according choices value
[ "save", "result", "to", "a", "csv", "file", ".", "display", "=", "True", "will", "convert", "value", "according", "choices", "value" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2777-L2814
6,994
limodou/uliweb
uliweb/orm/__init__.py
ManyResult.all
def all(self, cache=False): """ can use cache to return objects """ if cache: return [get_object(self.modelb, obj_id, cache=True, use_local=True) for obj_id in self.keys(True)] else: return self
python
def all(self, cache=False): """ can use cache to return objects """ if cache: return [get_object(self.modelb, obj_id, cache=True, use_local=True) for obj_id in self.keys(True)] else: return self
[ "def", "all", "(", "self", ",", "cache", "=", "False", ")", ":", "if", "cache", ":", "return", "[", "get_object", "(", "self", ".", "modelb", ",", "obj_id", ",", "cache", "=", "True", ",", "use_local", "=", "True", ")", "for", "obj_id", "in", "self", ".", "keys", "(", "True", ")", "]", "else", ":", "return", "self" ]
can use cache to return objects
[ "can", "use", "cache", "to", "return", "objects" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3010-L3017
6,995
limodou/uliweb
uliweb/orm/__init__.py
ManyResult.update
def update(self, *objs): """ Update the third relationship table, but not the ModelA or ModelB """ keys = self.keys() new_keys = get_objs_columns(objs, self.realfieldb) modified = False for v in new_keys: if v in keys: #the id has been existed, so don't insert new record keys.remove(v) else: d = {self.fielda:self.valuea, self.fieldb:v} if self.before_save: self.before_save(d) if self.through_model: obj = self.through_model(**d) obj.save() else: self.do_(self.table.insert().values(**d)) modified = True if keys: #if there are still keys, so delete them self.clear(*keys) modified = True #cache [] to _STORED_attr_name setattr(self.instance, self.store_key, new_keys) return modified
python
def update(self, *objs): """ Update the third relationship table, but not the ModelA or ModelB """ keys = self.keys() new_keys = get_objs_columns(objs, self.realfieldb) modified = False for v in new_keys: if v in keys: #the id has been existed, so don't insert new record keys.remove(v) else: d = {self.fielda:self.valuea, self.fieldb:v} if self.before_save: self.before_save(d) if self.through_model: obj = self.through_model(**d) obj.save() else: self.do_(self.table.insert().values(**d)) modified = True if keys: #if there are still keys, so delete them self.clear(*keys) modified = True #cache [] to _STORED_attr_name setattr(self.instance, self.store_key, new_keys) return modified
[ "def", "update", "(", "self", ",", "*", "objs", ")", ":", "keys", "=", "self", ".", "keys", "(", ")", "new_keys", "=", "get_objs_columns", "(", "objs", ",", "self", ".", "realfieldb", ")", "modified", "=", "False", "for", "v", "in", "new_keys", ":", "if", "v", "in", "keys", ":", "#the id has been existed, so don't insert new record", "keys", ".", "remove", "(", "v", ")", "else", ":", "d", "=", "{", "self", ".", "fielda", ":", "self", ".", "valuea", ",", "self", ".", "fieldb", ":", "v", "}", "if", "self", ".", "before_save", ":", "self", ".", "before_save", "(", "d", ")", "if", "self", ".", "through_model", ":", "obj", "=", "self", ".", "through_model", "(", "*", "*", "d", ")", "obj", ".", "save", "(", ")", "else", ":", "self", ".", "do_", "(", "self", ".", "table", ".", "insert", "(", ")", ".", "values", "(", "*", "*", "d", ")", ")", "modified", "=", "True", "if", "keys", ":", "#if there are still keys, so delete them", "self", ".", "clear", "(", "*", "keys", ")", "modified", "=", "True", "#cache [] to _STORED_attr_name", "setattr", "(", "self", ".", "instance", ",", "self", ".", "store_key", ",", "new_keys", ")", "return", "modified" ]
Update the third relationship table, but not the ModelA or ModelB
[ "Update", "the", "third", "relationship", "table", "but", "not", "the", "ModelA", "or", "ModelB" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3099-L3128
6,996
limodou/uliweb
uliweb/orm/__init__.py
ManyResult.with_relation
def with_relation(self, relation_name=None): """ if relation is not None, when fetch manytomany result, also fetch relation record and saved them to manytomany object, and named them as relation. If relation_name is not given, then default value is 'relation' """ if not relation_name: relation_name = 'relation' if hasattr(self.modelb, relation_name): raise Error("The attribute name %s has already existed in Model %s!" % (relation_name, self.modelb.__name__)) if not self.through_model: raise Error("Only with through style in ManyToMany supports with_relation function of Model %s!" % self.modelb.__name__) self.with_relation_name = relation_name return self
python
def with_relation(self, relation_name=None): """ if relation is not None, when fetch manytomany result, also fetch relation record and saved them to manytomany object, and named them as relation. If relation_name is not given, then default value is 'relation' """ if not relation_name: relation_name = 'relation' if hasattr(self.modelb, relation_name): raise Error("The attribute name %s has already existed in Model %s!" % (relation_name, self.modelb.__name__)) if not self.through_model: raise Error("Only with through style in ManyToMany supports with_relation function of Model %s!" % self.modelb.__name__) self.with_relation_name = relation_name return self
[ "def", "with_relation", "(", "self", ",", "relation_name", "=", "None", ")", ":", "if", "not", "relation_name", ":", "relation_name", "=", "'relation'", "if", "hasattr", "(", "self", ".", "modelb", ",", "relation_name", ")", ":", "raise", "Error", "(", "\"The attribute name %s has already existed in Model %s!\"", "%", "(", "relation_name", ",", "self", ".", "modelb", ".", "__name__", ")", ")", "if", "not", "self", ".", "through_model", ":", "raise", "Error", "(", "\"Only with through style in ManyToMany supports with_relation function of Model %s!\"", "%", "self", ".", "modelb", ".", "__name__", ")", "self", ".", "with_relation_name", "=", "relation_name", "return", "self" ]
if relation is not None, when fetch manytomany result, also fetch relation record and saved them to manytomany object, and named them as relation. If relation_name is not given, then default value is 'relation'
[ "if", "relation", "is", "not", "None", "when", "fetch", "manytomany", "result", "also", "fetch", "relation", "record", "and", "saved", "them", "to", "manytomany", "object", "and", "named", "them", "as", "relation", ".", "If", "relation_name", "is", "not", "given", "then", "default", "value", "is", "relation" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3192-L3207
6,997
limodou/uliweb
uliweb/orm/__init__.py
ManyToMany.in_
def in_(self, *objs): """ Create a condition """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) sub_query = select([self.table.c[self.fielda]], (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & (self.table.c[self.fieldb].in_(keys))) condition = self.model_class.c[self.reversed_fieldname].in_(sub_query) return condition
python
def in_(self, *objs): """ Create a condition """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) sub_query = select([self.table.c[self.fielda]], (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & (self.table.c[self.fieldb].in_(keys))) condition = self.model_class.c[self.reversed_fieldname].in_(sub_query) return condition
[ "def", "in_", "(", "self", ",", "*", "objs", ")", ":", "if", "not", "objs", ":", "return", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "!=", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "else", ":", "keys", "=", "get_objs_columns", "(", "objs", ",", "self", ".", "reference_fieldname", ")", "sub_query", "=", "select", "(", "[", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "]", ",", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fieldb", "]", "==", "self", ".", "reference_class", ".", "c", "[", "self", ".", "reference_fieldname", "]", ")", "&", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fieldb", "]", ".", "in_", "(", "keys", ")", ")", ")", "condition", "=", "self", ".", "model_class", ".", "c", "[", "self", ".", "reversed_fieldname", "]", ".", "in_", "(", "sub_query", ")", "return", "condition" ]
Create a condition
[ "Create", "a", "condition" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3529-L3539
6,998
limodou/uliweb
uliweb/orm/__init__.py
ManyToMany.join_in
def join_in(self, *objs): """ Create a join condition, connect A and C """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) return (self.table.c[self.fielda] == self.model_class.c[self.reversed_fieldname]) & (self.table.c[self.fieldb].in_(keys))
python
def join_in(self, *objs): """ Create a join condition, connect A and C """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) return (self.table.c[self.fielda] == self.model_class.c[self.reversed_fieldname]) & (self.table.c[self.fieldb].in_(keys))
[ "def", "join_in", "(", "self", ",", "*", "objs", ")", ":", "if", "not", "objs", ":", "return", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "!=", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "else", ":", "keys", "=", "get_objs_columns", "(", "objs", ",", "self", ".", "reference_fieldname", ")", "return", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "==", "self", ".", "model_class", ".", "c", "[", "self", ".", "reversed_fieldname", "]", ")", "&", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fieldb", "]", ".", "in_", "(", "keys", ")", ")" ]
Create a join condition, connect A and C
[ "Create", "a", "join", "condition", "connect", "A", "and", "C" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3541-L3549
6,999
limodou/uliweb
uliweb/orm/__init__.py
ManyToMany.join_right_in
def join_right_in(self, *objs): """ Create a join condition, connect B and C """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) return (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & (self.table.c[self.fielda].in_(keys))
python
def join_right_in(self, *objs): """ Create a join condition, connect B and C """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) return (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & (self.table.c[self.fielda].in_(keys))
[ "def", "join_right_in", "(", "self", ",", "*", "objs", ")", ":", "if", "not", "objs", ":", "return", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "!=", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "else", ":", "keys", "=", "get_objs_columns", "(", "objs", ",", "self", ".", "reference_fieldname", ")", "return", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fieldb", "]", "==", "self", ".", "reference_class", ".", "c", "[", "self", ".", "reference_fieldname", "]", ")", "&", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", ".", "in_", "(", "keys", ")", ")" ]
Create a join condition, connect B and C
[ "Create", "a", "join", "condition", "connect", "B", "and", "C" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3551-L3559