repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
hovren/crisp
crisp/camera.py
AtanCameraModel.invert
def invert(self, points): """Invert the distortion Parameters ------------------ points : ndarray Input image points Returns ----------------- ndarray Undistorted points """ X = points if not points.ndim == 1 else points.r...
python
def invert(self, points): """Invert the distortion Parameters ------------------ points : ndarray Input image points Returns ----------------- ndarray Undistorted points """ X = points if not points.ndim == 1 else points.r...
[ "def", "invert", "(", "self", ",", "points", ")", ":", "X", "=", "points", "if", "not", "points", ".", "ndim", "==", "1", "else", "points", ".", "reshape", "(", "(", "points", ".", "size", ",", "1", ")", ")", "wx", ",", "wy", "=", "self", ".", ...
Invert the distortion Parameters ------------------ points : ndarray Input image points Returns ----------------- ndarray Undistorted points
[ "Invert", "the", "distortion" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L160-L187
hovren/crisp
crisp/camera.py
AtanCameraModel.project
def project(self, points): """Project 3D points to image coordinates. This projects 3D points expressed in the camera coordinate system to image points. Parameters -------------------- points : (3, N) ndarray 3D points Returns -------------------- ...
python
def project(self, points): """Project 3D points to image coordinates. This projects 3D points expressed in the camera coordinate system to image points. Parameters -------------------- points : (3, N) ndarray 3D points Returns -------------------- ...
[ "def", "project", "(", "self", ",", "points", ")", ":", "K", "=", "self", ".", "camera_matrix", "XU", "=", "points", "XU", "=", "XU", "/", "np", ".", "tile", "(", "XU", "[", "2", "]", ",", "(", "3", ",", "1", ")", ")", "X", "=", "self", "."...
Project 3D points to image coordinates. This projects 3D points expressed in the camera coordinate system to image points. Parameters -------------------- points : (3, N) ndarray 3D points Returns -------------------- image_points : (2, N) ndarray ...
[ "Project", "3D", "points", "to", "image", "coordinates", "." ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L219-L239
hovren/crisp
crisp/camera.py
AtanCameraModel.unproject
def unproject(self, image_points): """Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray ...
python
def unproject(self, image_points): """Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray ...
[ "def", "unproject", "(", "self", ",", "image_points", ")", ":", "Ki", "=", "self", ".", "inv_camera_matrix", "X", "=", "np", ".", "dot", "(", "Ki", ",", "to_homogeneous", "(", "image_points", ")", ")", "X", "=", "X", "/", "X", "[", "2", "]", "XU", ...
Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray Image points Returns ---...
[ "Find", "(", "up", "to", "scale", ")", "3D", "coordinate", "of", "an", "image", "point" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L241-L261
hovren/crisp
crisp/camera.py
OpenCVCameraModel.project
def project(self, points): """Project 3D points to image coordinates. This projects 3D points expressed in the camera coordinate system to image points. Parameters -------------------- points : (3, N) ndarray 3D points Returns -------------------- ...
python
def project(self, points): """Project 3D points to image coordinates. This projects 3D points expressed in the camera coordinate system to image points. Parameters -------------------- points : (3, N) ndarray 3D points Returns -------------------- ...
[ "def", "project", "(", "self", ",", "points", ")", ":", "rvec", "=", "tvec", "=", "np", ".", "zeros", "(", "3", ")", "image_points", ",", "jac", "=", "cv2", ".", "projectPoints", "(", "points", ".", "T", ".", "reshape", "(", "-", "1", ",", "1", ...
Project 3D points to image coordinates. This projects 3D points expressed in the camera coordinate system to image points. Parameters -------------------- points : (3, N) ndarray 3D points Returns -------------------- image_points : (2, N) ndarray ...
[ "Project", "3D", "points", "to", "image", "coordinates", "." ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L292-L309
hovren/crisp
crisp/camera.py
OpenCVCameraModel.unproject
def unproject(self, image_points): """Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray ...
python
def unproject(self, image_points): """Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray ...
[ "def", "unproject", "(", "self", ",", "image_points", ")", ":", "undist_image_points", "=", "cv2", ".", "undistortPoints", "(", "image_points", ".", "T", ".", "reshape", "(", "1", ",", "-", "1", ",", "2", ")", ",", "self", ".", "camera_matrix", ",", "s...
Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray Image points Returns ---...
[ "Find", "(", "up", "to", "scale", ")", "3D", "coordinate", "of", "an", "image", "point" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L311-L329
hovren/crisp
crisp/camera.py
Kinect.timestamps_from_file_list
def timestamps_from_file_list(file_list): "Take list of Kinect filenames (without path) and extracts timestamps while accounting for timestamp overflow (returns linear timestamps)." timestamps = np.array([Kinect.timestamp_from_filename(fname) for fname in file_list]) # Handle overflow d...
python
def timestamps_from_file_list(file_list): "Take list of Kinect filenames (without path) and extracts timestamps while accounting for timestamp overflow (returns linear timestamps)." timestamps = np.array([Kinect.timestamp_from_filename(fname) for fname in file_list]) # Handle overflow d...
[ "def", "timestamps_from_file_list", "(", "file_list", ")", ":", "timestamps", "=", "np", ".", "array", "(", "[", "Kinect", ".", "timestamp_from_filename", "(", "fname", ")", "for", "fname", "in", "file_list", "]", ")", "# Handle overflow", "diff", "=", "np", ...
Take list of Kinect filenames (without path) and extracts timestamps while accounting for timestamp overflow (returns linear timestamps).
[ "Take", "list", "of", "Kinect", "filenames", "(", "without", "path", ")", "and", "extracts", "timestamps", "while", "accounting", "for", "timestamp", "overflow", "(", "returns", "linear", "timestamps", ")", "." ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L472-L483
hovren/crisp
crisp/camera.py
Kinect.purge_bad_timestamp_files
def purge_bad_timestamp_files(file_list): "Given a list of image files, find bad frames, remove them and modify file_list" MAX_INITIAL_BAD_FRAMES = 15 bad_ts = Kinect.detect_bad_timestamps(Kinect.timestamps_from_file_list(file_list)) # Trivial case if not bad_ts: ...
python
def purge_bad_timestamp_files(file_list): "Given a list of image files, find bad frames, remove them and modify file_list" MAX_INITIAL_BAD_FRAMES = 15 bad_ts = Kinect.detect_bad_timestamps(Kinect.timestamps_from_file_list(file_list)) # Trivial case if not bad_ts: ...
[ "def", "purge_bad_timestamp_files", "(", "file_list", ")", ":", "MAX_INITIAL_BAD_FRAMES", "=", "15", "bad_ts", "=", "Kinect", ".", "detect_bad_timestamps", "(", "Kinect", ".", "timestamps_from_file_list", "(", "file_list", ")", ")", "# Trivial case", "if", "not", "b...
Given a list of image files, find bad frames, remove them and modify file_list
[ "Given", "a", "list", "of", "image", "files", "find", "bad", "frames", "remove", "them", "and", "modify", "file_list" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L498-L519
hovren/crisp
crisp/camera.py
Kinect.depth_file_for_nir_file
def depth_file_for_nir_file(video_filename, depth_file_list): """Returns the corresponding depth filename given a NIR filename""" (root, filename) = os.path.split(video_filename) needle_ts = int(filename.split('-')[2].split('.')[0]) haystack_ts_list = np.array(Kinect.timestamps_from_file...
python
def depth_file_for_nir_file(video_filename, depth_file_list): """Returns the corresponding depth filename given a NIR filename""" (root, filename) = os.path.split(video_filename) needle_ts = int(filename.split('-')[2].split('.')[0]) haystack_ts_list = np.array(Kinect.timestamps_from_file...
[ "def", "depth_file_for_nir_file", "(", "video_filename", ",", "depth_file_list", ")", ":", "(", "root", ",", "filename", ")", "=", "os", ".", "path", ".", "split", "(", "video_filename", ")", "needle_ts", "=", "int", "(", "filename", ".", "split", "(", "'-...
Returns the corresponding depth filename given a NIR filename
[ "Returns", "the", "corresponding", "depth", "filename", "given", "a", "NIR", "filename" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L522-L529
hovren/crisp
crisp/camera.py
Kinect.depth_file_for_rgb_file
def depth_file_for_rgb_file(rgb_filename, rgb_file_list, depth_file_list): """Returns the *closest* depth file from an RGB filename""" (root, filename) = os.path.split(rgb_filename) rgb_timestamps = np.array(Kinect.timestamps_from_file_list(rgb_file_list)) depth_timestamps = np.array(Kin...
python
def depth_file_for_rgb_file(rgb_filename, rgb_file_list, depth_file_list): """Returns the *closest* depth file from an RGB filename""" (root, filename) = os.path.split(rgb_filename) rgb_timestamps = np.array(Kinect.timestamps_from_file_list(rgb_file_list)) depth_timestamps = np.array(Kin...
[ "def", "depth_file_for_rgb_file", "(", "rgb_filename", ",", "rgb_file_list", ",", "depth_file_list", ")", ":", "(", "root", ",", "filename", ")", "=", "os", ".", "path", ".", "split", "(", "rgb_filename", ")", "rgb_timestamps", "=", "np", ".", "array", "(", ...
Returns the *closest* depth file from an RGB filename
[ "Returns", "the", "*", "closest", "*", "depth", "file", "from", "an", "RGB", "filename" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L532-L540
hovren/crisp
crisp/camera.py
Kinect.find_nir_file_with_missing_depth
def find_nir_file_with_missing_depth(video_file_list, depth_file_list): "Remove all files without its own counterpart. Returns new lists of files" new_video_list = [] new_depth_list = [] for fname in video_file_list: try: depth_file = Kinect.depth_file_for_nir...
python
def find_nir_file_with_missing_depth(video_file_list, depth_file_list): "Remove all files without its own counterpart. Returns new lists of files" new_video_list = [] new_depth_list = [] for fname in video_file_list: try: depth_file = Kinect.depth_file_for_nir...
[ "def", "find_nir_file_with_missing_depth", "(", "video_file_list", ",", "depth_file_list", ")", ":", "new_video_list", "=", "[", "]", "new_depth_list", "=", "[", "]", "for", "fname", "in", "video_file_list", ":", "try", ":", "depth_file", "=", "Kinect", ".", "de...
Remove all files without its own counterpart. Returns new lists of files
[ "Remove", "all", "files", "without", "its", "own", "counterpart", ".", "Returns", "new", "lists", "of", "files" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L543-L559
hovren/crisp
crisp/camera.py
Kinect.disparity_image_to_distance
def disparity_image_to_distance(self, dval_img): "Convert image of Kinect disparity values to distance (linear method)" dist_img = dval_img / 2048.0 dist_img = 1 / (self.opars[0]*dist_img + self.opars[1]) return dist_img
python
def disparity_image_to_distance(self, dval_img): "Convert image of Kinect disparity values to distance (linear method)" dist_img = dval_img / 2048.0 dist_img = 1 / (self.opars[0]*dist_img + self.opars[1]) return dist_img
[ "def", "disparity_image_to_distance", "(", "self", ",", "dval_img", ")", ":", "dist_img", "=", "dval_img", "/", "2048.0", "dist_img", "=", "1", "/", "(", "self", ".", "opars", "[", "0", "]", "*", "dist_img", "+", "self", ".", "opars", "[", "1", "]", ...
Convert image of Kinect disparity values to distance (linear method)
[ "Convert", "image", "of", "Kinect", "disparity", "values", "to", "distance", "(", "linear", "method", ")" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L561-L565
hovren/crisp
crisp/videoslice.py
fill_sampling
def fill_sampling(slice_list, N): """Given a list of slices, draw N samples such that each slice contributes as much as possible Parameters -------------------------- slice_list : list of Slice List of slices N : int Number of samples to draw """ A = [len(s.inliers) for s in...
python
def fill_sampling(slice_list, N): """Given a list of slices, draw N samples such that each slice contributes as much as possible Parameters -------------------------- slice_list : list of Slice List of slices N : int Number of samples to draw """ A = [len(s.inliers) for s in...
[ "def", "fill_sampling", "(", "slice_list", ",", "N", ")", ":", "A", "=", "[", "len", "(", "s", ".", "inliers", ")", "for", "s", "in", "slice_list", "]", "N_max", "=", "np", ".", "sum", "(", "A", ")", "if", "N", ">", "N_max", ":", "raise", "Valu...
Given a list of slices, draw N samples such that each slice contributes as much as possible Parameters -------------------------- slice_list : list of Slice List of slices N : int Number of samples to draw
[ "Given", "a", "list", "of", "slices", "draw", "N", "samples", "such", "that", "each", "slice", "contributes", "as", "much", "as", "possible" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/videoslice.py#L117-L162
hovren/crisp
crisp/videoslice.py
Slice.estimate_rotation
def estimate_rotation(self, camera, ransac_threshold=7.0): """Estimate the rotation between first and last frame It uses RANSAC where the error metric is the reprojection error of the points from the last frame to the first frame. Parameters ----------------- camera : C...
python
def estimate_rotation(self, camera, ransac_threshold=7.0): """Estimate the rotation between first and last frame It uses RANSAC where the error metric is the reprojection error of the points from the last frame to the first frame. Parameters ----------------- camera : C...
[ "def", "estimate_rotation", "(", "self", ",", "camera", ",", "ransac_threshold", "=", "7.0", ")", ":", "if", "self", ".", "axis", "is", "None", ":", "x", "=", "self", ".", "points", "[", ":", ",", "0", ",", ":", "]", ".", "T", "y", "=", "self", ...
Estimate the rotation between first and last frame It uses RANSAC where the error metric is the reprojection error of the points from the last frame to the first frame. Parameters ----------------- camera : CameraModel Camera model ransac_threshold : float ...
[ "Estimate", "the", "rotation", "between", "first", "and", "last", "frame" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/videoslice.py#L31-L61
hovren/crisp
crisp/videoslice.py
Slice.from_stream_randomly
def from_stream_randomly(video_stream, step_bounds=(5, 15), length_bounds=(2, 15), max_start=None, min_distance=10, min_slice_points=10): """Create slices from a video stream using random sampling Parameters ----------------- video_stream : VideoStream A video stream ...
python
def from_stream_randomly(video_stream, step_bounds=(5, 15), length_bounds=(2, 15), max_start=None, min_distance=10, min_slice_points=10): """Create slices from a video stream using random sampling Parameters ----------------- video_stream : VideoStream A video stream ...
[ "def", "from_stream_randomly", "(", "video_stream", ",", "step_bounds", "=", "(", "5", ",", "15", ")", ",", "length_bounds", "=", "(", "2", ",", "15", ")", ",", "max_start", "=", "None", ",", "min_distance", "=", "10", ",", "min_slice_points", "=", "10",...
Create slices from a video stream using random sampling Parameters ----------------- video_stream : VideoStream A video stream step_bounds : tuple Range bounds (inclusive) of possible step lengths length_bounds : tuple Range bounds (inclusive)...
[ "Create", "slices", "from", "a", "video", "stream", "using", "random", "sampling" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/videoslice.py#L64-L115
hovren/crisp
crisp/rotations.py
procrustes
def procrustes(X, Y, remove_mean=False): """Orthogonal procrustes problem solver The procrustes problem finds the best rotation R, and translation t where X = R*Y + t The number of points in X and Y must be at least 2. For the minimal case of two points, a third point is temporari...
python
def procrustes(X, Y, remove_mean=False): """Orthogonal procrustes problem solver The procrustes problem finds the best rotation R, and translation t where X = R*Y + t The number of points in X and Y must be at least 2. For the minimal case of two points, a third point is temporari...
[ "def", "procrustes", "(", "X", ",", "Y", ",", "remove_mean", "=", "False", ")", ":", "assert", "X", ".", "shape", "==", "Y", ".", "shape", "assert", "X", ".", "shape", "[", "0", "]", ">", "1", "# Minimal case, create third point using cross product", "if",...
Orthogonal procrustes problem solver The procrustes problem finds the best rotation R, and translation t where X = R*Y + t The number of points in X and Y must be at least 2. For the minimal case of two points, a third point is temporarily created and used for the estimation. ...
[ "Orthogonal", "procrustes", "problem", "solver", "The", "procrustes", "problem", "finds", "the", "best", "rotation", "R", "and", "translation", "t", "where", "X", "=", "R", "*", "Y", "+", "t", "The", "number", "of", "points", "in", "X", "and", "Y", "must...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/rotations.py#L21-L84
hovren/crisp
crisp/rotations.py
rotation_matrix_to_axis_angle
def rotation_matrix_to_axis_angle(R): """Convert a 3D rotation matrix to a 3D axis angle representation Parameters --------------- R : (3,3) array Rotation matrix Returns ---------------- v : (3,) array (Unit-) rotation angle theta : float Angle of r...
python
def rotation_matrix_to_axis_angle(R): """Convert a 3D rotation matrix to a 3D axis angle representation Parameters --------------- R : (3,3) array Rotation matrix Returns ---------------- v : (3,) array (Unit-) rotation angle theta : float Angle of r...
[ "def", "rotation_matrix_to_axis_angle", "(", "R", ")", ":", "assert", "R", ".", "shape", "==", "(", "3", ",", "3", ")", "assert_almost_equal", "(", "np", ".", "linalg", ".", "det", "(", "R", ")", ",", "1.0", ",", "err_msg", "=", "\"Not a rotation matrix:...
Convert a 3D rotation matrix to a 3D axis angle representation Parameters --------------- R : (3,3) array Rotation matrix Returns ---------------- v : (3,) array (Unit-) rotation angle theta : float Angle of rotations, in radians Note ------...
[ "Convert", "a", "3D", "rotation", "matrix", "to", "a", "3D", "axis", "angle", "representation", "Parameters", "---------------", "R", ":", "(", "3", "3", ")", "array", "Rotation", "matrix", "Returns", "----------------", "v", ":", "(", "3", ")", "array", "...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/rotations.py#L88-L120
hovren/crisp
crisp/rotations.py
axis_angle_to_rotation_matrix
def axis_angle_to_rotation_matrix(v, theta): """Convert rotation from axis-angle to rotation matrix Parameters --------------- v : (3,) ndarray Rotation axis (normalized) theta : float Rotation angle (radians) Returns ---------------- R : (3,3) ndarray ...
python
def axis_angle_to_rotation_matrix(v, theta): """Convert rotation from axis-angle to rotation matrix Parameters --------------- v : (3,) ndarray Rotation axis (normalized) theta : float Rotation angle (radians) Returns ---------------- R : (3,3) ndarray ...
[ "def", "axis_angle_to_rotation_matrix", "(", "v", ",", "theta", ")", ":", "if", "np", ".", "abs", "(", "theta", ")", "<", "np", ".", "spacing", "(", "1", ")", ":", "return", "np", ".", "eye", "(", "3", ")", "else", ":", "v", "=", "v", ".", "res...
Convert rotation from axis-angle to rotation matrix Parameters --------------- v : (3,) ndarray Rotation axis (normalized) theta : float Rotation angle (radians) Returns ---------------- R : (3,3) ndarray Rotation matrix
[ "Convert", "rotation", "from", "axis", "-", "angle", "to", "rotation", "matrix", "Parameters", "---------------", "v", ":", "(", "3", ")", "ndarray", "Rotation", "axis", "(", "normalized", ")", "theta", ":", "float", "Rotation", "angle", "(", "radians", ")" ...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/rotations.py#L124-L149
hovren/crisp
crisp/rotations.py
quat_to_rotation_matrix
def quat_to_rotation_matrix(q): """Convert unit quaternion to rotation matrix Parameters ------------- q : (4,) ndarray Unit quaternion, scalar as first element Returns ---------------- R : (3,3) ndarray Rotation matrix """ q = q.flatten() asser...
python
def quat_to_rotation_matrix(q): """Convert unit quaternion to rotation matrix Parameters ------------- q : (4,) ndarray Unit quaternion, scalar as first element Returns ---------------- R : (3,3) ndarray Rotation matrix """ q = q.flatten() asser...
[ "def", "quat_to_rotation_matrix", "(", "q", ")", ":", "q", "=", "q", ".", "flatten", "(", ")", "assert", "q", ".", "size", "==", "4", "assert_almost_equal", "(", "np", ".", "linalg", ".", "norm", "(", "q", ")", ",", "1.0", ",", "err_msg", "=", "\"N...
Convert unit quaternion to rotation matrix Parameters ------------- q : (4,) ndarray Unit quaternion, scalar as first element Returns ---------------- R : (3,3) ndarray Rotation matrix
[ "Convert", "unit", "quaternion", "to", "rotation", "matrix", "Parameters", "-------------", "q", ":", "(", "4", ")", "ndarray", "Unit", "quaternion", "scalar", "as", "first", "element" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/rotations.py#L153-L177
hovren/crisp
crisp/rotations.py
integrate_gyro_quaternion
def integrate_gyro_quaternion(gyro_ts, gyro_data): """Integrate angular velocities to rotations Parameters --------------- gyro_ts : ndarray Timestamps gyro_data : (3, N) ndarray Angular velocity measurements Returns --------------- rotations : (4, N) nd...
python
def integrate_gyro_quaternion(gyro_ts, gyro_data): """Integrate angular velocities to rotations Parameters --------------- gyro_ts : ndarray Timestamps gyro_data : (3, N) ndarray Angular velocity measurements Returns --------------- rotations : (4, N) nd...
[ "def", "integrate_gyro_quaternion", "(", "gyro_ts", ",", "gyro_data", ")", ":", "#NB: Quaternion q = [a, n1, n2, n3], scalar first", "q_list", "=", "np", ".", "zeros", "(", "(", "gyro_ts", ".", "shape", "[", "0", "]", ",", "4", ")", ")", "# Nx4 quaternion list", ...
Integrate angular velocities to rotations Parameters --------------- gyro_ts : ndarray Timestamps gyro_data : (3, N) ndarray Angular velocity measurements Returns --------------- rotations : (4, N) ndarray Rotation sequence as unit quaternions (f...
[ "Integrate", "angular", "velocities", "to", "rotations", "Parameters", "---------------", "gyro_ts", ":", "ndarray", "Timestamps", "gyro_data", ":", "(", "3", "N", ")", "ndarray", "Angular", "velocity", "measurements", "Returns", "---------------", "rotations", ":", ...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/rotations.py#L181-L216
hovren/crisp
crisp/rotations.py
slerp
def slerp(q1, q2, u): """SLERP: Spherical linear interpolation between two unit quaternions. Parameters ------------ q1 : (4, ) ndarray Unit quaternion (first element scalar) q2 : (4, ) ndarray Unit quaternion (first element scalar) u : float Interpolatio...
python
def slerp(q1, q2, u): """SLERP: Spherical linear interpolation between two unit quaternions. Parameters ------------ q1 : (4, ) ndarray Unit quaternion (first element scalar) q2 : (4, ) ndarray Unit quaternion (first element scalar) u : float Interpolatio...
[ "def", "slerp", "(", "q1", ",", "q2", ",", "u", ")", ":", "q1", "=", "q1", ".", "flatten", "(", ")", "q2", "=", "q2", ".", "flatten", "(", ")", "assert", "q1", ".", "shape", "==", "q2", ".", "shape", "assert", "q1", ".", "size", "==", "4", ...
SLERP: Spherical linear interpolation between two unit quaternions. Parameters ------------ q1 : (4, ) ndarray Unit quaternion (first element scalar) q2 : (4, ) ndarray Unit quaternion (first element scalar) u : float Interpolation factor in range [0,1] where...
[ "SLERP", ":", "Spherical", "linear", "interpolation", "between", "two", "unit", "quaternions", ".", "Parameters", "------------", "q1", ":", "(", "4", ")", "ndarray", "Unit", "quaternion", "(", "first", "element", "scalar", ")", "q2", ":", "(", "4", ")", "...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/rotations.py#L220-L266
hovren/crisp
crisp/rotations.py
estimate_rotation_procrustes_ransac
def estimate_rotation_procrustes_ransac(x, y, camera, threshold, inlier_ratio=0.75, do_translation=False): """Calculate rotation between two sets of image coordinates using ransac. Inlier criteria is the reprojection error of y into image 1. Parameters ------------------------- x : array 2xN i...
python
def estimate_rotation_procrustes_ransac(x, y, camera, threshold, inlier_ratio=0.75, do_translation=False): """Calculate rotation between two sets of image coordinates using ransac. Inlier criteria is the reprojection error of y into image 1. Parameters ------------------------- x : array 2xN i...
[ "def", "estimate_rotation_procrustes_ransac", "(", "x", ",", "y", ",", "camera", ",", "threshold", ",", "inlier_ratio", "=", "0.75", ",", "do_translation", "=", "False", ")", ":", "assert", "x", ".", "shape", "==", "y", ".", "shape", "assert", "x", ".", ...
Calculate rotation between two sets of image coordinates using ransac. Inlier criteria is the reprojection error of y into image 1. Parameters ------------------------- x : array 2xN image coordinates in image 1 y : array 2xN image coordinates in image 2 camera : Camera model threshold...
[ "Calculate", "rotation", "between", "two", "sets", "of", "image", "coordinates", "using", "ransac", ".", "Inlier", "criteria", "is", "the", "reprojection", "error", "of", "y", "into", "image", "1", "." ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/rotations.py#L270-L325
hovren/crisp
crisp/ransac.py
RANSAC
def RANSAC(model_func, eval_func, data, num_points, num_iter, threshold, recalculate=False): """Apply RANSAC. This RANSAC implementation will choose the best model based on the number of points in the consensus set. At evaluation time the model is created using num_points points. Then it will be recalculated u...
python
def RANSAC(model_func, eval_func, data, num_points, num_iter, threshold, recalculate=False): """Apply RANSAC. This RANSAC implementation will choose the best model based on the number of points in the consensus set. At evaluation time the model is created using num_points points. Then it will be recalculated u...
[ "def", "RANSAC", "(", "model_func", ",", "eval_func", ",", "data", ",", "num_points", ",", "num_iter", ",", "threshold", ",", "recalculate", "=", "False", ")", ":", "M", "=", "None", "max_consensus", "=", "0", "all_idx", "=", "list", "(", "range", "(", ...
Apply RANSAC. This RANSAC implementation will choose the best model based on the number of points in the consensus set. At evaluation time the model is created using num_points points. Then it will be recalculated using the points in the consensus set. Parameters ------------ model_func: Takes a data ...
[ "Apply", "RANSAC", "." ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/ransac.py#L5-L41
hovren/crisp
crisp/tracking.py
track_points
def track_points(img1, img2, initial_points=None, gftt_params={}): """Track points between two images Parameters ----------------- img1 : (M, N) ndarray First image img2 : (M, N) ndarray Second image initial_points : ndarray Initial points. If empty, init...
python
def track_points(img1, img2, initial_points=None, gftt_params={}): """Track points between two images Parameters ----------------- img1 : (M, N) ndarray First image img2 : (M, N) ndarray Second image initial_points : ndarray Initial points. If empty, init...
[ "def", "track_points", "(", "img1", ",", "img2", ",", "initial_points", "=", "None", ",", "gftt_params", "=", "{", "}", ")", ":", "params", "=", "GFTT_DEFAULTS", "if", "gftt_params", ":", "params", ".", "update", "(", "gftt_params", ")", "if", "initial_poi...
Track points between two images Parameters ----------------- img1 : (M, N) ndarray First image img2 : (M, N) ndarray Second image initial_points : ndarray Initial points. If empty, initial points will be calculated from img1 using goodFeaturesToTr...
[ "Track", "points", "between", "two", "images", "Parameters", "-----------------", "img1", ":", "(", "M", "N", ")", "ndarray", "First", "image", "img2", ":", "(", "M", "N", ")", "ndarray", "Second", "image", "initial_points", ":", "ndarray", "Initial", "point...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/tracking.py#L32-L67
hovren/crisp
crisp/tracking.py
optical_flow_magnitude
def optical_flow_magnitude(image_sequence, max_diff=60, gftt_options={}): """Return optical flow magnitude for the given image sequence The flow magnitude is the mean value of the total (sparse) optical flow between two images. Crude outlier detection using the max_diff parameter is used. ...
python
def optical_flow_magnitude(image_sequence, max_diff=60, gftt_options={}): """Return optical flow magnitude for the given image sequence The flow magnitude is the mean value of the total (sparse) optical flow between two images. Crude outlier detection using the max_diff parameter is used. ...
[ "def", "optical_flow_magnitude", "(", "image_sequence", ",", "max_diff", "=", "60", ",", "gftt_options", "=", "{", "}", ")", ":", "flow", "=", "[", "]", "prev_img", "=", "None", "for", "img", "in", "image_sequence", ":", "if", "img", ".", "ndim", "==", ...
Return optical flow magnitude for the given image sequence The flow magnitude is the mean value of the total (sparse) optical flow between two images. Crude outlier detection using the max_diff parameter is used. Parameters ---------------- image_sequence : sequence Sequenc...
[ "Return", "optical", "flow", "magnitude", "for", "the", "given", "image", "sequence", "The", "flow", "magnitude", "is", "the", "mean", "value", "of", "the", "total", "(", "sparse", ")", "optical", "flow", "between", "two", "images", ".", "Crude", "outlier", ...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/tracking.py#L71-L110
hovren/crisp
crisp/tracking.py
track
def track(image_list, initial_points, remove_bad=True): """Track points in image list Parameters ---------------- image_list : list List of images to track in initial_points : ndarray Initial points to use (in first image in image_list) remove_bad : bool ...
python
def track(image_list, initial_points, remove_bad=True): """Track points in image list Parameters ---------------- image_list : list List of images to track in initial_points : ndarray Initial points to use (in first image in image_list) remove_bad : bool ...
[ "def", "track", "(", "image_list", ",", "initial_points", ",", "remove_bad", "=", "True", ")", ":", "# Precreate track array", "tracks", "=", "np", ".", "zeros", "(", "(", "initial_points", ".", "shape", "[", "0", "]", ",", "len", "(", "image_list", ")", ...
Track points in image list Parameters ---------------- image_list : list List of images to track in initial_points : ndarray Initial points to use (in first image in image_list) remove_bad : bool If True, then the resulting list of tracks will only contain su...
[ "Track", "points", "in", "image", "list", "Parameters", "----------------", "image_list", ":", "list", "List", "of", "images", "to", "track", "in", "initial_points", ":", "ndarray", "Initial", "points", "to", "use", "(", "in", "first", "image", "in", "image_li...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/tracking.py#L114-L159
hovren/crisp
crisp/tracking.py
track_retrack
def track_retrack(image_list, initial_points, max_retrack_distance=0.5, keep_bad=False): """Track-retracks points in image list Using track-retrack can help in only getting point tracks of high quality. The point is tracked forward, and then backwards in the image sequence. Points that end...
python
def track_retrack(image_list, initial_points, max_retrack_distance=0.5, keep_bad=False): """Track-retracks points in image list Using track-retrack can help in only getting point tracks of high quality. The point is tracked forward, and then backwards in the image sequence. Points that end...
[ "def", "track_retrack", "(", "image_list", ",", "initial_points", ",", "max_retrack_distance", "=", "0.5", ",", "keep_bad", "=", "False", ")", ":", "(", "forward_track", ",", "forward_status", ")", "=", "track", "(", "image_list", ",", "initial_points", ",", "...
Track-retracks points in image list Using track-retrack can help in only getting point tracks of high quality. The point is tracked forward, and then backwards in the image sequence. Points that end up further than max_retrack_distance from its starting point are marked as bad. Pa...
[ "Track", "-", "retracks", "points", "in", "image", "list", "Using", "track", "-", "retrack", "can", "help", "in", "only", "getting", "point", "tracks", "of", "high", "quality", ".", "The", "point", "is", "tracked", "forward", "and", "then", "backwards", "i...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/tracking.py#L163-L215
hovren/crisp
crisp/imu.py
IMU.from_mat_file
def from_mat_file(cls, matfilename): """Load gyro data from .mat file The MAT file should contain the following two arrays gyro : (3, N) float ndarray The angular velocity measurements. timestamps : (N, ) float ndarray Timestamps of the m...
python
def from_mat_file(cls, matfilename): """Load gyro data from .mat file The MAT file should contain the following two arrays gyro : (3, N) float ndarray The angular velocity measurements. timestamps : (N, ) float ndarray Timestamps of the m...
[ "def", "from_mat_file", "(", "cls", ",", "matfilename", ")", ":", "M", "=", "scipy", ".", "io", ".", "loadmat", "(", "matfilename", ")", "instance", "=", "cls", "(", ")", "instance", ".", "gyro_data", "=", "M", "[", "'gyro'", "]", "instance", ".", "t...
Load gyro data from .mat file The MAT file should contain the following two arrays gyro : (3, N) float ndarray The angular velocity measurements. timestamps : (N, ) float ndarray Timestamps of the measurements. Parameters...
[ "Load", "gyro", "data", "from", ".", "mat", "file", "The", "MAT", "file", "should", "contain", "the", "following", "two", "arrays", "gyro", ":", "(", "3", "N", ")", "float", "ndarray", "The", "angular", "velocity", "measurements", ".", "timestamps", ":", ...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/imu.py#L39-L62
hovren/crisp
crisp/imu.py
IMU.rate
def rate(self): """Get the sample rate in Hz. Returns --------- rate : float The sample rate, in Hz, calculated from the timestamps """ N = len(self.timestamps) t = self.timestamps[-1] - self.timestamps[0] rate = 1.0 * N / ...
python
def rate(self): """Get the sample rate in Hz. Returns --------- rate : float The sample rate, in Hz, calculated from the timestamps """ N = len(self.timestamps) t = self.timestamps[-1] - self.timestamps[0] rate = 1.0 * N / ...
[ "def", "rate", "(", "self", ")", ":", "N", "=", "len", "(", "self", ".", "timestamps", ")", "t", "=", "self", ".", "timestamps", "[", "-", "1", "]", "-", "self", ".", "timestamps", "[", "0", "]", "rate", "=", "1.0", "*", "N", "/", "t", "retur...
Get the sample rate in Hz. Returns --------- rate : float The sample rate, in Hz, calculated from the timestamps
[ "Get", "the", "sample", "rate", "in", "Hz", ".", "Returns", "---------", "rate", ":", "float", "The", "sample", "rate", "in", "Hz", "calculated", "from", "the", "timestamps" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/imu.py#L66-L77
hovren/crisp
crisp/imu.py
IMU.zero_level_calibrate
def zero_level_calibrate(self, duration, t0=0.0): """Performs zero-level calibration from the chosen time interval. This changes the previously lodaded data in-place. Parameters -------------------- duration : float Number of timeunits to use for...
python
def zero_level_calibrate(self, duration, t0=0.0): """Performs zero-level calibration from the chosen time interval. This changes the previously lodaded data in-place. Parameters -------------------- duration : float Number of timeunits to use for...
[ "def", "zero_level_calibrate", "(", "self", ",", "duration", ",", "t0", "=", "0.0", ")", ":", "t1", "=", "t0", "+", "duration", "indices", "=", "np", ".", "flatnonzero", "(", "(", "self", ".", "timestamps", ">=", "t0", ")", "&", "(", "self", ".", "...
Performs zero-level calibration from the chosen time interval. This changes the previously lodaded data in-place. Parameters -------------------- duration : float Number of timeunits to use for calibration t0 : float Starting tim...
[ "Performs", "zero", "-", "level", "calibration", "from", "the", "chosen", "time", "interval", ".", "This", "changes", "the", "previously", "lodaded", "data", "in", "-", "place", ".", "Parameters", "--------------------", "duration", ":", "float", "Number", "of",...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/imu.py#L79-L102
hovren/crisp
crisp/imu.py
IMU.integrate
def integrate(self, pose_correction=np.eye(3), uniform=True): """Integrate angular velocity measurements to rotations. Parameters ------------- pose_correction : (3,3) ndarray, optional Rotation matrix that describes the relative pose between the IMU and something else (...
python
def integrate(self, pose_correction=np.eye(3), uniform=True): """Integrate angular velocity measurements to rotations. Parameters ------------- pose_correction : (3,3) ndarray, optional Rotation matrix that describes the relative pose between the IMU and something else (...
[ "def", "integrate", "(", "self", ",", "pose_correction", "=", "np", ".", "eye", "(", "3", ")", ",", "uniform", "=", "True", ")", ":", "if", "uniform", ":", "dt", "=", "float", "(", "self", ".", "timestamps", "[", "1", "]", "-", "self", ".", "time...
Integrate angular velocity measurements to rotations. Parameters ------------- pose_correction : (3,3) ndarray, optional Rotation matrix that describes the relative pose between the IMU and something else (e.g. camera). uniform : bool If True (default), a...
[ "Integrate", "angular", "velocity", "measurements", "to", "rotations", "." ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/imu.py#L119-L157
hovren/crisp
crisp/imu.py
IMU.rotation_at_time
def rotation_at_time(t, timestamps, rotation_sequence): """Get the gyro rotation at time t using SLERP. Parameters ----------- t : float The query timestamp. timestamps : array_like float List of all timestamps rotation_sequence : ...
python
def rotation_at_time(t, timestamps, rotation_sequence): """Get the gyro rotation at time t using SLERP. Parameters ----------- t : float The query timestamp. timestamps : array_like float List of all timestamps rotation_sequence : ...
[ "def", "rotation_at_time", "(", "t", ",", "timestamps", ",", "rotation_sequence", ")", ":", "idx", "=", "np", ".", "flatnonzero", "(", "timestamps", ">=", "(", "t", "-", "0.0001", ")", ")", "[", "0", "]", "t0", "=", "timestamps", "[", "idx", "-", "1"...
Get the gyro rotation at time t using SLERP. Parameters ----------- t : float The query timestamp. timestamps : array_like float List of all timestamps rotation_sequence : (4, N) ndarray Rotation sequence as unit quaternion...
[ "Get", "the", "gyro", "rotation", "at", "time", "t", "using", "SLERP", ".", "Parameters", "-----------", "t", ":", "float", "The", "query", "timestamp", ".", "timestamps", ":", "array_like", "float", "List", "of", "all", "timestamps", "rotation_sequence", ":",...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/imu.py#L160-L185
hovren/crisp
crisp/stream.py
GyroStream.from_csv
def from_csv(cls, filename): """Create gyro stream from CSV data Load data from a CSV file. The data must be formatted with three values per line: (x, y, z) where x, y, z is the measured angular velocity (in radians) of the specified axis. Parameters -------------------...
python
def from_csv(cls, filename): """Create gyro stream from CSV data Load data from a CSV file. The data must be formatted with three values per line: (x, y, z) where x, y, z is the measured angular velocity (in radians) of the specified axis. Parameters -------------------...
[ "def", "from_csv", "(", "cls", ",", "filename", ")", ":", "instance", "=", "cls", "(", ")", "instance", ".", "data", "=", "np", ".", "loadtxt", "(", "filename", ",", "delimiter", "=", "','", ")", "return", "instance" ]
Create gyro stream from CSV data Load data from a CSV file. The data must be formatted with three values per line: (x, y, z) where x, y, z is the measured angular velocity (in radians) of the specified axis. Parameters ------------------- filename : str Path...
[ "Create", "gyro", "stream", "from", "CSV", "data" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/stream.py#L36-L55
hovren/crisp
crisp/stream.py
GyroStream.from_data
def from_data(cls, data): """Create gyroscope stream from data array Parameters ------------------- data : (N, 3) ndarray Data array of angular velocities (rad/s) Returns ------------------- GyroStream Stream object """ if...
python
def from_data(cls, data): """Create gyroscope stream from data array Parameters ------------------- data : (N, 3) ndarray Data array of angular velocities (rad/s) Returns ------------------- GyroStream Stream object """ if...
[ "def", "from_data", "(", "cls", ",", "data", ")", ":", "if", "not", "data", ".", "shape", "[", "1", "]", "==", "3", ":", "raise", "ValueError", "(", "\"Gyroscope data must have shape (N, 3)\"", ")", "instance", "=", "cls", "(", ")", "instance", ".", "dat...
Create gyroscope stream from data array Parameters ------------------- data : (N, 3) ndarray Data array of angular velocities (rad/s) Returns ------------------- GyroStream Stream object
[ "Create", "gyroscope", "stream", "from", "data", "array" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/stream.py#L58-L76
hovren/crisp
crisp/stream.py
GyroStream.integrate
def integrate(self, dt): """Integrate gyro measurements to orientation using a uniform sample rate. Parameters ------------------- dt : float Sample distance in seconds Returns ---------------- orientation : (4, N) ndarray Gyrosco...
python
def integrate(self, dt): """Integrate gyro measurements to orientation using a uniform sample rate. Parameters ------------------- dt : float Sample distance in seconds Returns ---------------- orientation : (4, N) ndarray Gyrosco...
[ "def", "integrate", "(", "self", ",", "dt", ")", ":", "if", "not", "dt", "==", "self", ".", "__last_dt", ":", "self", ".", "__last_q", "=", "fastintegrate", ".", "integrate_gyro_quaternion_uniform", "(", "self", ".", "data", ",", "dt", ")", "self", ".", ...
Integrate gyro measurements to orientation using a uniform sample rate. Parameters ------------------- dt : float Sample distance in seconds Returns ---------------- orientation : (4, N) ndarray Gyroscope orientation in quaternion form (s...
[ "Integrate", "gyro", "measurements", "to", "orientation", "using", "a", "uniform", "sample", "rate", "." ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/stream.py#L83-L99
hovren/crisp
crisp/znccpyr.py
gaussian_kernel
def gaussian_kernel(gstd): """Generate odd sized truncated Gaussian The generated filter kernel has a cutoff at $3\sigma$ and is normalized to sum to 1 Parameters ------------- gstd : float Standard deviation of filter Returns ------------- g : ndarray Arra...
python
def gaussian_kernel(gstd): """Generate odd sized truncated Gaussian The generated filter kernel has a cutoff at $3\sigma$ and is normalized to sum to 1 Parameters ------------- gstd : float Standard deviation of filter Returns ------------- g : ndarray Arra...
[ "def", "gaussian_kernel", "(", "gstd", ")", ":", "Nc", "=", "np", ".", "ceil", "(", "gstd", "*", "3", ")", "*", "2", "+", "1", "x", "=", "np", ".", "linspace", "(", "-", "(", "Nc", "-", "1", ")", "/", "2", ",", "(", "Nc", "-", "1", ")", ...
Generate odd sized truncated Gaussian The generated filter kernel has a cutoff at $3\sigma$ and is normalized to sum to 1 Parameters ------------- gstd : float Standard deviation of filter Returns ------------- g : ndarray Array with kernel coefficients
[ "Generate", "odd", "sized", "truncated", "Gaussian" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/znccpyr.py#L18-L39
hovren/crisp
crisp/znccpyr.py
subsample
def subsample(time_series, downsample_factor): """Subsample with Gaussian prefilter The prefilter will have the filter size $\sigma_g=.5*ssfactor$ Parameters -------------- time_series : ndarray Input signal downsample_factor : float Downsampling factor Retu...
python
def subsample(time_series, downsample_factor): """Subsample with Gaussian prefilter The prefilter will have the filter size $\sigma_g=.5*ssfactor$ Parameters -------------- time_series : ndarray Input signal downsample_factor : float Downsampling factor Retu...
[ "def", "subsample", "(", "time_series", ",", "downsample_factor", ")", ":", "Ns", "=", "np", ".", "int", "(", "np", ".", "floor", "(", "np", ".", "size", "(", "time_series", ")", "/", "downsample_factor", ")", ")", "g", "=", "gaussian_kernel", "(", "0....
Subsample with Gaussian prefilter The prefilter will have the filter size $\sigma_g=.5*ssfactor$ Parameters -------------- time_series : ndarray Input signal downsample_factor : float Downsampling factor Returns -------------- ts_out : ndarray ...
[ "Subsample", "with", "Gaussian", "prefilter" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/znccpyr.py#L41-L71
hovren/crisp
crisp/znccpyr.py
upsample
def upsample(time_series, scaling_factor): """Upsample using linear interpolation The function uses replication of the value at edges Parameters -------------- time_series : ndarray Input signal scaling_factor : float The factor to upsample with Returns ---...
python
def upsample(time_series, scaling_factor): """Upsample using linear interpolation The function uses replication of the value at edges Parameters -------------- time_series : ndarray Input signal scaling_factor : float The factor to upsample with Returns ---...
[ "def", "upsample", "(", "time_series", ",", "scaling_factor", ")", ":", "Ns0", "=", "np", ".", "size", "(", "time_series", ")", "Ns", "=", "np", ".", "int", "(", "np", ".", "floor", "(", "np", ".", "size", "(", "time_series", ")", "*", "scaling_facto...
Upsample using linear interpolation The function uses replication of the value at edges Parameters -------------- time_series : ndarray Input signal scaling_factor : float The factor to upsample with Returns -------------- ts_out : ndarray The ...
[ "Upsample", "using", "linear", "interpolation" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/znccpyr.py#L73-L103
hovren/crisp
crisp/znccpyr.py
zncc
def zncc(ts1,ts2): """Zero mean normalised cross-correlation (ZNCC) This function does ZNCC of two signals, ts1 and ts2 Normalisation by very small values is avoided by doing max(nmin,nvalue) Parameters -------------- ts1 : ndarray Input signal 1 to be aligned with ts2 : nd...
python
def zncc(ts1,ts2): """Zero mean normalised cross-correlation (ZNCC) This function does ZNCC of two signals, ts1 and ts2 Normalisation by very small values is avoided by doing max(nmin,nvalue) Parameters -------------- ts1 : ndarray Input signal 1 to be aligned with ts2 : nd...
[ "def", "zncc", "(", "ts1", ",", "ts2", ")", ":", "# Output is the same size as ts1", "Ns1", "=", "np", ".", "size", "(", "ts1", ")", "Ns2", "=", "np", ".", "size", "(", "ts2", ")", "ts_out", "=", "np", ".", "zeros", "(", "(", "Ns1", ",", "1", ")"...
Zero mean normalised cross-correlation (ZNCC) This function does ZNCC of two signals, ts1 and ts2 Normalisation by very small values is avoided by doing max(nmin,nvalue) Parameters -------------- ts1 : ndarray Input signal 1 to be aligned with ts2 : ndarray Input si...
[ "Zero", "mean", "normalised", "cross", "-", "correlation", "(", "ZNCC", ")" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/znccpyr.py#L123-L180
hovren/crisp
crisp/znccpyr.py
find_shift_pyr
def find_shift_pyr(ts1,ts2,nlevels): """ Find shift that best aligns two time series The shift that aligns the timeseries ts1 with ts2. This is sought using zero mean normalized cross correlation (ZNCC) in a coarse to fine search with an octave pyramid on nlevels levels. Parameters -----------...
python
def find_shift_pyr(ts1,ts2,nlevels): """ Find shift that best aligns two time series The shift that aligns the timeseries ts1 with ts2. This is sought using zero mean normalized cross correlation (ZNCC) in a coarse to fine search with an octave pyramid on nlevels levels. Parameters -----------...
[ "def", "find_shift_pyr", "(", "ts1", ",", "ts2", ",", "nlevels", ")", ":", "pyr1", "=", "create_pyramid", "(", "ts1", ",", "nlevels", ")", "pyr2", "=", "create_pyramid", "(", "ts2", ",", "nlevels", ")", "logger", ".", "debug", "(", "\"pyramid size = %d\"",...
Find shift that best aligns two time series The shift that aligns the timeseries ts1 with ts2. This is sought using zero mean normalized cross correlation (ZNCC) in a coarse to fine search with an octave pyramid on nlevels levels. Parameters ---------------- ts1 : list_like The first t...
[ "Find", "shift", "that", "best", "aligns", "two", "time", "series" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/znccpyr.py#L245-L278
hovren/crisp
crisp/l3g4200d.py
load_L3G_arduino
def load_L3G_arduino(filename, remove_begin_spurious=False, return_parser=False): "Load gyro data collected by the arduino version of the L3G logging platform, and return the data (in rad/s), a time vector, and the sample rate (seconds)" file_data = open(filename, 'rb').read() parser = L3GArduinoParser() ...
python
def load_L3G_arduino(filename, remove_begin_spurious=False, return_parser=False): "Load gyro data collected by the arduino version of the L3G logging platform, and return the data (in rad/s), a time vector, and the sample rate (seconds)" file_data = open(filename, 'rb').read() parser = L3GArduinoParser() ...
[ "def", "load_L3G_arduino", "(", "filename", ",", "remove_begin_spurious", "=", "False", ",", "return_parser", "=", "False", ")", ":", "file_data", "=", "open", "(", "filename", ",", "'rb'", ")", ".", "read", "(", ")", "parser", "=", "L3GArduinoParser", "(", ...
Load gyro data collected by the arduino version of the L3G logging platform, and return the data (in rad/s), a time vector, and the sample rate (seconds)
[ "Load", "gyro", "data", "collected", "by", "the", "arduino", "version", "of", "the", "L3G", "logging", "platform", "and", "return", "the", "data", "(", "in", "rad", "/", "s", ")", "a", "time", "vector", "and", "the", "sample", "rate", "(", "seconds", "...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/l3g4200d.py#L105-L134
hovren/crisp
examples/gopro_dataset_example.py
to_rot_matrix
def to_rot_matrix(r): "Convert combined axis angle vector to rotation matrix" theta = np.linalg.norm(r) v = r/theta R = crisp.rotations.axis_angle_to_rotation_matrix(v, theta) return R
python
def to_rot_matrix(r): "Convert combined axis angle vector to rotation matrix" theta = np.linalg.norm(r) v = r/theta R = crisp.rotations.axis_angle_to_rotation_matrix(v, theta) return R
[ "def", "to_rot_matrix", "(", "r", ")", ":", "theta", "=", "np", ".", "linalg", ".", "norm", "(", "r", ")", "v", "=", "r", "/", "theta", "R", "=", "crisp", ".", "rotations", ".", "axis_angle_to_rotation_matrix", "(", "v", ",", "theta", ")", "return", ...
Convert combined axis angle vector to rotation matrix
[ "Convert", "combined", "axis", "angle", "vector", "to", "rotation", "matrix" ]
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/examples/gopro_dataset_example.py#L42-L47
hovren/crisp
crisp/pose.py
estimate_pose
def estimate_pose(image_sequences, imu_sequences, K): """Estimate sync between IMU and camera based on gyro readings and optical flow. The user should first create at least two sequences of corresponding image and gyroscope data. From each sequence we calculate the rotation axis (one from images, ...
python
def estimate_pose(image_sequences, imu_sequences, K): """Estimate sync between IMU and camera based on gyro readings and optical flow. The user should first create at least two sequences of corresponding image and gyroscope data. From each sequence we calculate the rotation axis (one from images, ...
[ "def", "estimate_pose", "(", "image_sequences", ",", "imu_sequences", ",", "K", ")", ":", "assert", "len", "(", "image_sequences", ")", "==", "len", "(", "imu_sequences", ")", "assert", "len", "(", "image_sequences", ")", ">=", "2", "# Note: list(image_sequence)...
Estimate sync between IMU and camera based on gyro readings and optical flow. The user should first create at least two sequences of corresponding image and gyroscope data. From each sequence we calculate the rotation axis (one from images, one from IMU/gyro). The final set of len(image_sequences)...
[ "Estimate", "sync", "between", "IMU", "and", "camera", "based", "on", "gyro", "readings", "and", "optical", "flow", ".", "The", "user", "should", "first", "create", "at", "least", "two", "sequences", "of", "corresponding", "image", "and", "gyroscope", "data", ...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/pose.py#L24-L106
hovren/crisp
crisp/pose.py
pick_manual
def pick_manual(image_sequence, imu_gyro, num_sequences=2): """Select N matching sequences and return data indices. Parameters --------------- image_sequence : list_like A list, or generator, of image data imu_gyro : (3, N) ndarray Gyroscope data (angular velocities) ...
python
def pick_manual(image_sequence, imu_gyro, num_sequences=2): """Select N matching sequences and return data indices. Parameters --------------- image_sequence : list_like A list, or generator, of image data imu_gyro : (3, N) ndarray Gyroscope data (angular velocities) ...
[ "def", "pick_manual", "(", "image_sequence", ",", "imu_gyro", ",", "num_sequences", "=", "2", ")", ":", "assert", "num_sequences", ">=", "2", "# Create optical flow for user to select parts in", "logger", ".", "info", "(", "\"Calculating optical flow\"", ")", "flow", ...
Select N matching sequences and return data indices. Parameters --------------- image_sequence : list_like A list, or generator, of image data imu_gyro : (3, N) ndarray Gyroscope data (angular velocities) num_sequences : int The number of matching sequences t...
[ "Select", "N", "matching", "sequences", "and", "return", "data", "indices", ".", "Parameters", "---------------", "image_sequence", ":", "list_like", "A", "list", "or", "generator", "of", "image", "data", "imu_gyro", ":", "(", "3", "N", ")", "ndarray", "Gyrosc...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/pose.py#L110-L138
hovren/crisp
crisp/pose.py
principal_rotation_axis
def principal_rotation_axis(gyro_data): """Get the principal rotation axis of angular velocity measurements. Parameters ------------- gyro_data : (3, N) ndarray Angular velocity measurements Returns ------------- v : (3,1) ndarray The principal ro...
python
def principal_rotation_axis(gyro_data): """Get the principal rotation axis of angular velocity measurements. Parameters ------------- gyro_data : (3, N) ndarray Angular velocity measurements Returns ------------- v : (3,1) ndarray The principal ro...
[ "def", "principal_rotation_axis", "(", "gyro_data", ")", ":", "N", "=", "np", ".", "zeros", "(", "(", "3", ",", "3", ")", ")", "for", "x", "in", "gyro_data", ".", "T", ":", "# Transpose because samples are stored as columns", "y", "=", "x", ".", "reshape",...
Get the principal rotation axis of angular velocity measurements. Parameters ------------- gyro_data : (3, N) ndarray Angular velocity measurements Returns ------------- v : (3,1) ndarray The principal rotation axis for the chosen sequence
[ "Get", "the", "principal", "rotation", "axis", "of", "angular", "velocity", "measurements", ".", "Parameters", "-------------", "gyro_data", ":", "(", "3", "N", ")", "ndarray", "Angular", "velocity", "measurements", "Returns", "-------------", "v", ":", "(", "3"...
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/pose.py#L142-L171
codejamninja/sphinx-markdown-builder
sphinx_markdown_builder/markdown_writer.py
MarkdownTranslator.visit_image
def visit_image(self, node): """ Image directive """ uri = node.attributes['uri'] doc_folder = os.path.dirname(self.builder.current_docname) if uri.startswith(doc_folder): # drop docname prefix uri = uri[len(doc_folder):] if uri.startsw...
python
def visit_image(self, node): """ Image directive """ uri = node.attributes['uri'] doc_folder = os.path.dirname(self.builder.current_docname) if uri.startswith(doc_folder): # drop docname prefix uri = uri[len(doc_folder):] if uri.startsw...
[ "def", "visit_image", "(", "self", ",", "node", ")", ":", "uri", "=", "node", ".", "attributes", "[", "'uri'", "]", "doc_folder", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "builder", ".", "current_docname", ")", "if", "uri", ".", "sta...
Image directive
[ "Image", "directive" ]
train
https://github.com/codejamninja/sphinx-markdown-builder/blob/a28f48df937d4b0e158ba453e5e1c66824299196/sphinx_markdown_builder/markdown_writer.py#L203-L214
codejamninja/sphinx-markdown-builder
sphinx_markdown_builder/doctree2md.py
add_pref_suff
def add_pref_suff(pref_suff_map): """ Decorator adds visit, depart methods for prefix/suffix pairs """ def dec(cls): # Need _make_method to ensure new variable picked up for each iteration # of the loop. The defined method picks up this new variable in its # scope. for key, ...
python
def add_pref_suff(pref_suff_map): """ Decorator adds visit, depart methods for prefix/suffix pairs """ def dec(cls): # Need _make_method to ensure new variable picked up for each iteration # of the loop. The defined method picks up this new variable in its # scope. for key, ...
[ "def", "add_pref_suff", "(", "pref_suff_map", ")", ":", "def", "dec", "(", "cls", ")", ":", "# Need _make_method to ensure new variable picked up for each iteration", "# of the loop. The defined method picks up this new variable in its", "# scope.", "for", "key", ",", "(", "pr...
Decorator adds visit, depart methods for prefix/suffix pairs
[ "Decorator", "adds", "visit", "depart", "methods", "for", "prefix", "/", "suffix", "pairs" ]
train
https://github.com/codejamninja/sphinx-markdown-builder/blob/a28f48df937d4b0e158ba453e5e1c66824299196/sphinx_markdown_builder/doctree2md.py#L241-L253
codejamninja/sphinx-markdown-builder
sphinx_markdown_builder/doctree2md.py
add_pass_thru
def add_pass_thru(pass_thrus): """ Decorator adds explicit pass-through visit and depart methods """ def meth(self, node): pass def dec(cls): for element_name in pass_thrus: for meth_prefix in ('visit_', 'depart_'): meth_name = meth_prefix + element_name ...
python
def add_pass_thru(pass_thrus): """ Decorator adds explicit pass-through visit and depart methods """ def meth(self, node): pass def dec(cls): for element_name in pass_thrus: for meth_prefix in ('visit_', 'depart_'): meth_name = meth_prefix + element_name ...
[ "def", "add_pass_thru", "(", "pass_thrus", ")", ":", "def", "meth", "(", "self", ",", "node", ")", ":", "pass", "def", "dec", "(", "cls", ")", ":", "for", "element_name", "in", "pass_thrus", ":", "for", "meth_prefix", "in", "(", "'visit_'", ",", "'depa...
Decorator adds explicit pass-through visit and depart methods
[ "Decorator", "adds", "explicit", "pass", "-", "through", "visit", "and", "depart", "methods" ]
train
https://github.com/codejamninja/sphinx-markdown-builder/blob/a28f48df937d4b0e158ba453e5e1c66824299196/sphinx_markdown_builder/doctree2md.py#L256-L272
codejamninja/sphinx-markdown-builder
sphinx_markdown_builder/doctree2md.py
IndentLevel.write
def write(self): """ Add ``self.contents`` with current ``prefix`` and ``first_prefix`` Add processed ``self.contents`` to ``self.base``. The first line has ``first_prefix`` prepended, further lines have ``prefix`` prepended. Empty (all whitespace) lines get written as bare carriage r...
python
def write(self): """ Add ``self.contents`` with current ``prefix`` and ``first_prefix`` Add processed ``self.contents`` to ``self.base``. The first line has ``first_prefix`` prepended, further lines have ``prefix`` prepended. Empty (all whitespace) lines get written as bare carriage r...
[ "def", "write", "(", "self", ")", ":", "string", "=", "''", ".", "join", "(", "self", ".", "content", ")", "lines", "=", "string", ".", "splitlines", "(", "True", ")", "if", "len", "(", "lines", ")", "==", "0", ":", "return", "texts", "=", "[", ...
Add ``self.contents`` with current ``prefix`` and ``first_prefix`` Add processed ``self.contents`` to ``self.base``. The first line has ``first_prefix`` prepended, further lines have ``prefix`` prepended. Empty (all whitespace) lines get written as bare carriage returns, to avoid ugly...
[ "Add", "self", ".", "contents", "with", "current", "prefix", "and", "first_prefix" ]
train
https://github.com/codejamninja/sphinx-markdown-builder/blob/a28f48df937d4b0e158ba453e5e1c66824299196/sphinx_markdown_builder/doctree2md.py#L206-L225
sbuss/bitmerchant
bitmerchant/wallet/bip32.py
Wallet.identifier
def identifier(self): """Get the identifier for this node. Extended keys can be identified by the Hash160 (RIPEMD160 after SHA256) of the public key's `key`. This corresponds exactly to the data used in traditional Bitcoin addresses. It is not advised to represent this data in b...
python
def identifier(self): """Get the identifier for this node. Extended keys can be identified by the Hash160 (RIPEMD160 after SHA256) of the public key's `key`. This corresponds exactly to the data used in traditional Bitcoin addresses. It is not advised to represent this data in b...
[ "def", "identifier", "(", "self", ")", ":", "key", "=", "self", ".", "get_public_key_hex", "(", ")", "return", "ensure_bytes", "(", "hexlify", "(", "hash160", "(", "unhexlify", "(", "ensure_bytes", "(", "key", ")", ")", ")", ")", ")" ]
Get the identifier for this node. Extended keys can be identified by the Hash160 (RIPEMD160 after SHA256) of the public key's `key`. This corresponds exactly to the data used in traditional Bitcoin addresses. It is not advised to represent this data in base58 format though, as it may be...
[ "Get", "the", "identifier", "for", "this", "node", "." ]
train
https://github.com/sbuss/bitmerchant/blob/901de06489805c396a922f955eeef2da04734e3e/bitmerchant/wallet/bip32.py#L153-L164
sbuss/bitmerchant
bitmerchant/wallet/bip32.py
Wallet.get_child
def get_child(self, child_number, is_prime=None, as_private=True): """Derive a child key. :param child_number: The number of the child key to compute :type child_number: int :param is_prime: If True, the child is calculated via private derivation. If False, then public deriv...
python
def get_child(self, child_number, is_prime=None, as_private=True): """Derive a child key. :param child_number: The number of the child key to compute :type child_number: int :param is_prime: If True, the child is calculated via private derivation. If False, then public deriv...
[ "def", "get_child", "(", "self", ",", "child_number", ",", "is_prime", "=", "None", ",", "as_private", "=", "True", ")", ":", "boundary", "=", "0x80000000", "# Note: If this boundary check gets removed, then children above", "# the boundary should use private (prime) derivati...
Derive a child key. :param child_number: The number of the child key to compute :type child_number: int :param is_prime: If True, the child is calculated via private derivation. If False, then public derivation is used. If None, then it is figured out from the value of c...
[ "Derive", "a", "child", "key", "." ]
train
https://github.com/sbuss/bitmerchant/blob/901de06489805c396a922f955eeef2da04734e3e/bitmerchant/wallet/bip32.py#L247-L363
sbuss/bitmerchant
bitmerchant/wallet/bip32.py
Wallet.crack_private_key
def crack_private_key(self, child_private_key): """Crack the parent private key given a child private key. BIP32 has a vulnerability/feature that allows you to recover the master private key if you're given a master public key and any of its publicly-derived child private keys. This is ...
python
def crack_private_key(self, child_private_key): """Crack the parent private key given a child private key. BIP32 has a vulnerability/feature that allows you to recover the master private key if you're given a master public key and any of its publicly-derived child private keys. This is ...
[ "def", "crack_private_key", "(", "self", ",", "child_private_key", ")", ":", "if", "self", ".", "private_key", ":", "raise", "AssertionError", "(", "\"You already know the private key\"", ")", "if", "child_private_key", ".", "parent_fingerprint", "!=", "self", ".", ...
Crack the parent private key given a child private key. BIP32 has a vulnerability/feature that allows you to recover the master private key if you're given a master public key and any of its publicly-derived child private keys. This is a pretty serious security vulnerability that looks ...
[ "Crack", "the", "parent", "private", "key", "given", "a", "child", "private", "key", "." ]
train
https://github.com/sbuss/bitmerchant/blob/901de06489805c396a922f955eeef2da04734e3e/bitmerchant/wallet/bip32.py#L375-L424
sbuss/bitmerchant
bitmerchant/wallet/bip32.py
Wallet.export_to_wif
def export_to_wif(self): """Export a key to WIF. See https://en.bitcoin.it/wiki/Wallet_import_format for a full description. """ # Add the network byte, creating the "extended key" extended_key_hex = self.private_key.get_extended_key() # BIP32 wallets have a trai...
python
def export_to_wif(self): """Export a key to WIF. See https://en.bitcoin.it/wiki/Wallet_import_format for a full description. """ # Add the network byte, creating the "extended key" extended_key_hex = self.private_key.get_extended_key() # BIP32 wallets have a trai...
[ "def", "export_to_wif", "(", "self", ")", ":", "# Add the network byte, creating the \"extended key\"", "extended_key_hex", "=", "self", ".", "private_key", ".", "get_extended_key", "(", ")", "# BIP32 wallets have a trailing \\01 byte", "extended_key_bytes", "=", "unhexlify", ...
Export a key to WIF. See https://en.bitcoin.it/wiki/Wallet_import_format for a full description.
[ "Export", "a", "key", "to", "WIF", "." ]
train
https://github.com/sbuss/bitmerchant/blob/901de06489805c396a922f955eeef2da04734e3e/bitmerchant/wallet/bip32.py#L426-L437
CloverHealth/pytest-pgsql
deploy.py
_pypi_push
def _pypi_push(dist): """Push created package to PyPI. Requires the following defined environment variables: - TWINE_USERNAME: The PyPI username to upload this package under - TWINE_PASSWORD: The password to the user's account Args: dist (str): The distribution to push....
python
def _pypi_push(dist): """Push created package to PyPI. Requires the following defined environment variables: - TWINE_USERNAME: The PyPI username to upload this package under - TWINE_PASSWORD: The password to the user's account Args: dist (str): The distribution to push....
[ "def", "_pypi_push", "(", "dist", ")", ":", "# Register all distributions and wheels with PyPI. We have to list the dist", "# directory and register each file individually because `twine` doesn't", "# handle globs.", "for", "filename", "in", "os", ".", "listdir", "(", "dist", ")", ...
Push created package to PyPI. Requires the following defined environment variables: - TWINE_USERNAME: The PyPI username to upload this package under - TWINE_PASSWORD: The password to the user's account Args: dist (str): The distribution to push. Must be a valid directory; s...
[ "Push", "created", "package", "to", "PyPI", "." ]
train
https://github.com/CloverHealth/pytest-pgsql/blob/a863ed4b652053e315dfa039d978b56f03664c07/deploy.py#L19-L40
CloverHealth/pytest-pgsql
deploy.py
deploy
def deploy(target): """Deploys the package and documentation. Proceeds in the following steps: 1. Ensures proper environment variables are set and checks that we are on Circle CI 2. Tags the repository with the new version 3. Creates a standard distribution and a wheel 4. Updates version.py to...
python
def deploy(target): """Deploys the package and documentation. Proceeds in the following steps: 1. Ensures proper environment variables are set and checks that we are on Circle CI 2. Tags the repository with the new version 3. Creates a standard distribution and a wheel 4. Updates version.py to...
[ "def", "deploy", "(", "target", ")", ":", "# Ensure proper environment", "if", "not", "os", ".", "getenv", "(", "CIRCLECI_ENV_VAR", ")", ":", "# pragma: no cover", "raise", "EnvironmentError", "(", "'Must be on CircleCI to run this script'", ")", "current_branch", "=", ...
Deploys the package and documentation. Proceeds in the following steps: 1. Ensures proper environment variables are set and checks that we are on Circle CI 2. Tags the repository with the new version 3. Creates a standard distribution and a wheel 4. Updates version.py to have the proper version ...
[ "Deploys", "the", "package", "and", "documentation", "." ]
train
https://github.com/CloverHealth/pytest-pgsql/blob/a863ed4b652053e315dfa039d978b56f03664c07/deploy.py#L43-L124
pyvisa/pyvisa-sim
pyvisa-sim/parser.py
_get_triplet
def _get_triplet(dd): """Return a triplet from a dialogue dictionary. :param dd: Dialogue dictionary. :type dd: Dict[str, str] :return: (query, response, error response) :rtype: (str, str | NoResponse, str | NoResponse) """ return _s(dd['q']), _s(dd.get('r', NoResponse)), _s(dd.get('e', NoR...
python
def _get_triplet(dd): """Return a triplet from a dialogue dictionary. :param dd: Dialogue dictionary. :type dd: Dict[str, str] :return: (query, response, error response) :rtype: (str, str | NoResponse, str | NoResponse) """ return _s(dd['q']), _s(dd.get('r', NoResponse)), _s(dd.get('e', NoR...
[ "def", "_get_triplet", "(", "dd", ")", ":", "return", "_s", "(", "dd", "[", "'q'", "]", ")", ",", "_s", "(", "dd", ".", "get", "(", "'r'", ",", "NoResponse", ")", ")", ",", "_s", "(", "dd", ".", "get", "(", "'e'", ",", "NoResponse", ")", ")" ...
Return a triplet from a dialogue dictionary. :param dd: Dialogue dictionary. :type dd: Dict[str, str] :return: (query, response, error response) :rtype: (str, str | NoResponse, str | NoResponse)
[ "Return", "a", "triplet", "from", "a", "dialogue", "dictionary", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L71-L79
pyvisa/pyvisa-sim
pyvisa-sim/parser.py
_load
def _load(content_or_fp): """YAML Parse a file or str and check version. """ try: data = yaml.load(content_or_fp, Loader=yaml.loader.BaseLoader) except Exception as e: raise type(e)('Malformed yaml file:\n%r' % format_exc()) try: ver = data['spec'] except: raise ...
python
def _load(content_or_fp): """YAML Parse a file or str and check version. """ try: data = yaml.load(content_or_fp, Loader=yaml.loader.BaseLoader) except Exception as e: raise type(e)('Malformed yaml file:\n%r' % format_exc()) try: ver = data['spec'] except: raise ...
[ "def", "_load", "(", "content_or_fp", ")", ":", "try", ":", "data", "=", "yaml", ".", "load", "(", "content_or_fp", ",", "Loader", "=", "yaml", ".", "loader", ".", "BaseLoader", ")", "except", "Exception", "as", "e", ":", "raise", "type", "(", "e", "...
YAML Parse a file or str and check version.
[ "YAML", "Parse", "a", "file", "or", "str", "and", "check", "version", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L82-L106
pyvisa/pyvisa-sim
pyvisa-sim/parser.py
parse_resource
def parse_resource(name): """Parse a resource file """ with closing(pkg_resources.resource_stream(__name__, name)) as fp: rbytes = fp.read() return _load(StringIO(rbytes.decode('utf-8')))
python
def parse_resource(name): """Parse a resource file """ with closing(pkg_resources.resource_stream(__name__, name)) as fp: rbytes = fp.read() return _load(StringIO(rbytes.decode('utf-8')))
[ "def", "parse_resource", "(", "name", ")", ":", "with", "closing", "(", "pkg_resources", ".", "resource_stream", "(", "__name__", ",", "name", ")", ")", "as", "fp", ":", "rbytes", "=", "fp", ".", "read", "(", ")", "return", "_load", "(", "StringIO", "(...
Parse a resource file
[ "Parse", "a", "resource", "file" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L109-L115
pyvisa/pyvisa-sim
pyvisa-sim/parser.py
update_component
def update_component(name, comp, component_dict): """Get a component from a component dict. """ for dia in component_dict.get('dialogues', ()): try: comp.add_dialogue(*_get_pair(dia)) except Exception as e: msg = 'In device %s, malformed dialogue %s\n%r' ...
python
def update_component(name, comp, component_dict): """Get a component from a component dict. """ for dia in component_dict.get('dialogues', ()): try: comp.add_dialogue(*_get_pair(dia)) except Exception as e: msg = 'In device %s, malformed dialogue %s\n%r' ...
[ "def", "update_component", "(", "name", ",", "comp", ",", "component_dict", ")", ":", "for", "dia", "in", "component_dict", ".", "get", "(", "'dialogues'", ",", "(", ")", ")", ":", "try", ":", "comp", ".", "add_dialogue", "(", "*", "_get_pair", "(", "d...
Get a component from a component dict.
[ "Get", "a", "component", "from", "a", "component", "dict", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L126-L147
pyvisa/pyvisa-sim
pyvisa-sim/parser.py
get_bases
def get_bases(definition_dict, loader): """Collect dependencies. """ bases = definition_dict.get('bases', ()) if bases: bases = (loader.get_comp_dict(required_version=SPEC_VERSION_TUPLE[0], **b) for b in bases) return SimpleChainmap...
python
def get_bases(definition_dict, loader): """Collect dependencies. """ bases = definition_dict.get('bases', ()) if bases: bases = (loader.get_comp_dict(required_version=SPEC_VERSION_TUPLE[0], **b) for b in bases) return SimpleChainmap...
[ "def", "get_bases", "(", "definition_dict", ",", "loader", ")", ":", "bases", "=", "definition_dict", ".", "get", "(", "'bases'", ",", "(", ")", ")", "if", "bases", ":", "bases", "=", "(", "loader", ".", "get_comp_dict", "(", "required_version", "=", "SP...
Collect dependencies.
[ "Collect", "dependencies", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L150-L161
pyvisa/pyvisa-sim
pyvisa-sim/parser.py
get_channel
def get_channel(device, ch_name, channel_dict, loader, resource_dict): """Get a channels from a channels dictionary. :param name: name of the device :param device_dict: device dictionary :rtype: Device """ channel_dict = get_bases(channel_dict, loader) r_ids = resource_dict.get('channel_id...
python
def get_channel(device, ch_name, channel_dict, loader, resource_dict): """Get a channels from a channels dictionary. :param name: name of the device :param device_dict: device dictionary :rtype: Device """ channel_dict = get_bases(channel_dict, loader) r_ids = resource_dict.get('channel_id...
[ "def", "get_channel", "(", "device", ",", "ch_name", ",", "channel_dict", ",", "loader", ",", "resource_dict", ")", ":", "channel_dict", "=", "get_bases", "(", "channel_dict", ",", "loader", ")", "r_ids", "=", "resource_dict", ".", "get", "(", "'channel_ids'",...
Get a channels from a channels dictionary. :param name: name of the device :param device_dict: device dictionary :rtype: Device
[ "Get", "a", "channels", "from", "a", "channels", "dictionary", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L164-L181
pyvisa/pyvisa-sim
pyvisa-sim/parser.py
get_device
def get_device(name, device_dict, loader, resource_dict): """Get a device from a device dictionary. :param name: name of the device :param device_dict: device dictionary :rtype: Device """ device = Device(name, device_dict.get('delimiter', ';').encode('utf-8')) device_dict = get_bases(devi...
python
def get_device(name, device_dict, loader, resource_dict): """Get a device from a device dictionary. :param name: name of the device :param device_dict: device dictionary :rtype: Device """ device = Device(name, device_dict.get('delimiter', ';').encode('utf-8')) device_dict = get_bases(devi...
[ "def", "get_device", "(", "name", ",", "device_dict", ",", "loader", ",", "resource_dict", ")", ":", "device", "=", "Device", "(", "name", ",", "device_dict", ".", "get", "(", "'delimiter'", ",", "';'", ")", ".", "encode", "(", "'utf-8'", ")", ")", "de...
Get a device from a device dictionary. :param name: name of the device :param device_dict: device dictionary :rtype: Device
[ "Get", "a", "device", "from", "a", "device", "dictionary", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L184-L207
pyvisa/pyvisa-sim
pyvisa-sim/parser.py
get_devices
def get_devices(filename, bundled): """Get a Devices object from a file. :param filename: full path of the file to parse or name of the resource. :param is_resource: boolean indicating if it is a resource. :rtype: Devices """ loader = Loader(filename, bundled) data = loader.data devi...
python
def get_devices(filename, bundled): """Get a Devices object from a file. :param filename: full path of the file to parse or name of the resource. :param is_resource: boolean indicating if it is a resource. :rtype: Devices """ loader = Loader(filename, bundled) data = loader.data devi...
[ "def", "get_devices", "(", "filename", ",", "bundled", ")", ":", "loader", "=", "Loader", "(", "filename", ",", "bundled", ")", "data", "=", "loader", ".", "data", "devices", "=", "Devices", "(", ")", "# Iterate through the resources and generate each individual d...
Get a Devices object from a file. :param filename: full path of the file to parse or name of the resource. :param is_resource: boolean indicating if it is a resource. :rtype: Devices
[ "Get", "a", "Devices", "object", "from", "a", "file", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/parser.py#L270-L298
pyvisa/pyvisa-sim
pyvisa-sim/channels.py
ChannelProperty.init_value
def init_value(self, string_value): """Create an empty defaultdict holding the default value. """ value = self.validate_value(string_value) self._value = defaultdict(lambda: value)
python
def init_value(self, string_value): """Create an empty defaultdict holding the default value. """ value = self.validate_value(string_value) self._value = defaultdict(lambda: value)
[ "def", "init_value", "(", "self", ",", "string_value", ")", ":", "value", "=", "self", ".", "validate_value", "(", "string_value", ")", "self", ".", "_value", "=", "defaultdict", "(", "lambda", ":", "value", ")" ]
Create an empty defaultdict holding the default value.
[ "Create", "an", "empty", "defaultdict", "holding", "the", "default", "value", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/channels.py#L30-L35
pyvisa/pyvisa-sim
pyvisa-sim/channels.py
ChannelProperty.set_value
def set_value(self, string_value): """Set the current value for a channel. """ value = self.validate_value(string_value) self._value[self._channel._selected] = value
python
def set_value(self, string_value): """Set the current value for a channel. """ value = self.validate_value(string_value) self._value[self._channel._selected] = value
[ "def", "set_value", "(", "self", ",", "string_value", ")", ":", "value", "=", "self", ".", "validate_value", "(", "string_value", ")", "self", ".", "_value", "[", "self", ".", "_channel", ".", "_selected", "]", "=", "value" ]
Set the current value for a channel.
[ "Set", "the", "current", "value", "for", "a", "channel", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/channels.py#L43-L48
pyvisa/pyvisa-sim
pyvisa-sim/channels.py
Channels.add_dialogue
def add_dialogue(self, query, response): """Add dialogue to channel. :param query: query string :param response: response string """ self._dialogues['__default__'][to_bytes(query)] = to_bytes(response)
python
def add_dialogue(self, query, response): """Add dialogue to channel. :param query: query string :param response: response string """ self._dialogues['__default__'][to_bytes(query)] = to_bytes(response)
[ "def", "add_dialogue", "(", "self", ",", "query", ",", "response", ")", ":", "self", ".", "_dialogues", "[", "'__default__'", "]", "[", "to_bytes", "(", "query", ")", "]", "=", "to_bytes", "(", "response", ")" ]
Add dialogue to channel. :param query: query string :param response: response string
[ "Add", "dialogue", "to", "channel", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/channels.py#L93-L99
pyvisa/pyvisa-sim
pyvisa-sim/channels.py
Channels.add_property
def add_property(self, name, default_value, getter_pair, setter_triplet, specs): """Add property to channel :param name: property name :param default_value: default value as string :param getter_pair: (query, response) :param setter_triplet: (query, response...
python
def add_property(self, name, default_value, getter_pair, setter_triplet, specs): """Add property to channel :param name: property name :param default_value: default value as string :param getter_pair: (query, response) :param setter_triplet: (query, response...
[ "def", "add_property", "(", "self", ",", "name", ",", "default_value", ",", "getter_pair", ",", "setter_triplet", ",", "specs", ")", ":", "self", ".", "_properties", "[", "name", "]", "=", "ChannelProperty", "(", "self", ",", "name", ",", "default_value", ...
Add property to channel :param name: property name :param default_value: default value as string :param getter_pair: (query, response) :param setter_triplet: (query, response, error) :param specs: specification of the Property
[ "Add", "property", "to", "channel" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/channels.py#L101-L123
pyvisa/pyvisa-sim
pyvisa-sim/channels.py
Channels.match
def match(self, query): """Try to find a match for a query in the channel commands. """ if not self.can_select: ch_id = self._device._properties['selected_channel'].get_value() if ch_id in self._ids: self._selected = ch_id else: ...
python
def match(self, query): """Try to find a match for a query in the channel commands. """ if not self.can_select: ch_id = self._device._properties['selected_channel'].get_value() if ch_id in self._ids: self._selected = ch_id else: ...
[ "def", "match", "(", "self", ",", "query", ")", ":", "if", "not", "self", ".", "can_select", ":", "ch_id", "=", "self", ".", "_device", ".", "_properties", "[", "'selected_channel'", "]", ".", "get_value", "(", ")", "if", "ch_id", "in", "self", ".", ...
Try to find a match for a query in the channel commands.
[ "Try", "to", "find", "a", "match", "for", "a", "query", "in", "the", "channel", "commands", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/channels.py#L125-L160
pyvisa/pyvisa-sim
pyvisa-sim/channels.py
Channels._match_setters
def _match_setters(self, query): """Try to find a match """ q = query.decode('utf-8') for name, parser, response, error_response in self._setters: try: parsed = parser(q) logger.debug('Found response in setter of %s' % name) except ...
python
def _match_setters(self, query): """Try to find a match """ q = query.decode('utf-8') for name, parser, response, error_response in self._setters: try: parsed = parser(q) logger.debug('Found response in setter of %s' % name) except ...
[ "def", "_match_setters", "(", "self", ",", "query", ")", ":", "q", "=", "query", ".", "decode", "(", "'utf-8'", ")", "for", "name", ",", "parser", ",", "response", ",", "error_response", "in", "self", ".", "_setters", ":", "try", ":", "parsed", "=", ...
Try to find a match
[ "Try", "to", "find", "a", "match" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/channels.py#L162-L185
pyvisa/pyvisa-sim
pyvisa-sim/highlevel.py
SimVisaLibrary.get_debug_info
def get_debug_info(): """Return a list of lines with backend info. """ from . import __version__ from .parser import SPEC_VERSION d = OrderedDict() d['Version'] = '%s' % __version__ d['Spec version'] = SPEC_VERSION return d
python
def get_debug_info(): """Return a list of lines with backend info. """ from . import __version__ from .parser import SPEC_VERSION d = OrderedDict() d['Version'] = '%s' % __version__ d['Spec version'] = SPEC_VERSION return d
[ "def", "get_debug_info", "(", ")", ":", "from", ".", "import", "__version__", "from", ".", "parser", "import", "SPEC_VERSION", "d", "=", "OrderedDict", "(", ")", "d", "[", "'Version'", "]", "=", "'%s'", "%", "__version__", "d", "[", "'Spec version'", "]", ...
Return a list of lines with backend info.
[ "Return", "a", "list", "of", "lines", "with", "backend", "info", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/highlevel.py#L44-L53
pyvisa/pyvisa-sim
pyvisa-sim/highlevel.py
SimVisaLibrary.open
def open(self, session, resource_name, access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE): """Opens a session to the specified resource. Corresponds to viOpen function of the VISA library. :param session: Resource Manager session ...
python
def open(self, session, resource_name, access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE): """Opens a session to the specified resource. Corresponds to viOpen function of the VISA library. :param session: Resource Manager session ...
[ "def", "open", "(", "self", ",", "session", ",", "resource_name", ",", "access_mode", "=", "constants", ".", "AccessModes", ".", "no_lock", ",", "open_timeout", "=", "constants", ".", "VI_TMO_IMMEDIATE", ")", ":", "try", ":", "open_timeout", "=", "int", "(",...
Opens a session to the specified resource. Corresponds to viOpen function of the VISA library. :param session: Resource Manager session (should always be a session returned from open_default_resource_manager()). :param resource_name: Unique symbo...
[ "Opens", "a", "session", "to", "the", "specified", "resource", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/highlevel.py#L87-L124
pyvisa/pyvisa-sim
pyvisa-sim/highlevel.py
SimVisaLibrary.close
def close(self, session): """Closes the specified session, event, or find list. Corresponds to viClose function of the VISA library. :param session: Unique logical identifier to a session, event, or find list. :return: return value of the library call. :rtype: :class:`pyvisa.co...
python
def close(self, session): """Closes the specified session, event, or find list. Corresponds to viClose function of the VISA library. :param session: Unique logical identifier to a session, event, or find list. :return: return value of the library call. :rtype: :class:`pyvisa.co...
[ "def", "close", "(", "self", ",", "session", ")", ":", "try", ":", "del", "self", ".", "sessions", "[", "session", "]", "return", "constants", ".", "StatusCode", ".", "success", "except", "KeyError", ":", "return", "constants", ".", "StatusCode", ".", "e...
Closes the specified session, event, or find list. Corresponds to viClose function of the VISA library. :param session: Unique logical identifier to a session, event, or find list. :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode`
[ "Closes", "the", "specified", "session", "event", "or", "find", "list", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/highlevel.py#L126-L139
pyvisa/pyvisa-sim
pyvisa-sim/highlevel.py
SimVisaLibrary.list_resources
def list_resources(self, session, query='?*::INSTR'): """Returns a tuple of all connected devices matching query. :param query: regular expression used to match devices. """ # For each session type, ask for the list of connected resources and merge them into a single list. res...
python
def list_resources(self, session, query='?*::INSTR'): """Returns a tuple of all connected devices matching query. :param query: regular expression used to match devices. """ # For each session type, ask for the list of connected resources and merge them into a single list. res...
[ "def", "list_resources", "(", "self", ",", "session", ",", "query", "=", "'?*::INSTR'", ")", ":", "# For each session type, ask for the list of connected resources and merge them into a single list.", "resources", "=", "self", ".", "devices", ".", "list_resources", "(", ")"...
Returns a tuple of all connected devices matching query. :param query: regular expression used to match devices.
[ "Returns", "a", "tuple", "of", "all", "connected", "devices", "matching", "query", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/highlevel.py#L151-L166
pyvisa/pyvisa-sim
pyvisa-sim/highlevel.py
SimVisaLibrary.read
def read(self, session, count): """Reads data from device or interface synchronously. Corresponds to viRead function of the VISA library. :param session: Unique logical identifier to a session. :param count: Number of bytes to be read. :return: data read, return value of the li...
python
def read(self, session, count): """Reads data from device or interface synchronously. Corresponds to viRead function of the VISA library. :param session: Unique logical identifier to a session. :param count: Number of bytes to be read. :return: data read, return value of the li...
[ "def", "read", "(", "self", ",", "session", ",", "count", ")", ":", "try", ":", "sess", "=", "self", ".", "sessions", "[", "session", "]", "except", "KeyError", ":", "return", "b''", ",", "constants", ".", "StatusCode", ".", "error_invalid_object", "try"...
Reads data from device or interface synchronously. Corresponds to viRead function of the VISA library. :param session: Unique logical identifier to a session. :param count: Number of bytes to be read. :return: data read, return value of the library call. :rtype: bytes, :class:`...
[ "Reads", "data", "from", "device", "or", "interface", "synchronously", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/highlevel.py#L168-L190
pyvisa/pyvisa-sim
pyvisa-sim/highlevel.py
SimVisaLibrary.write
def write(self, session, data): """Writes data to device or interface synchronously. Corresponds to viWrite function of the VISA library. :param session: Unique logical identifier to a session. :param data: data to be written. :type data: str :return: Number of bytes ac...
python
def write(self, session, data): """Writes data to device or interface synchronously. Corresponds to viWrite function of the VISA library. :param session: Unique logical identifier to a session. :param data: data to be written. :type data: str :return: Number of bytes ac...
[ "def", "write", "(", "self", ",", "session", ",", "data", ")", ":", "try", ":", "sess", "=", "self", ".", "sessions", "[", "session", "]", "except", "KeyError", ":", "return", "constants", ".", "StatusCode", ".", "error_invalid_object", "try", ":", "retu...
Writes data to device or interface synchronously. Corresponds to viWrite function of the VISA library. :param session: Unique logical identifier to a session. :param data: data to be written. :type data: str :return: Number of bytes actually transferred, return value of the lib...
[ "Writes", "data", "to", "device", "or", "interface", "synchronously", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/highlevel.py#L192-L212
pyvisa/pyvisa-sim
pyvisa-sim/sessions.py
Session.get_session_class
def get_session_class(cls, interface_type, resource_class): """Return the session class for a given interface type and resource class. :type interface_type: constants.InterfaceType :type resource_class: str :return: Session """ try: return cls._session_classe...
python
def get_session_class(cls, interface_type, resource_class): """Return the session class for a given interface type and resource class. :type interface_type: constants.InterfaceType :type resource_class: str :return: Session """ try: return cls._session_classe...
[ "def", "get_session_class", "(", "cls", ",", "interface_type", ",", "resource_class", ")", ":", "try", ":", "return", "cls", ".", "_session_classes", "[", "(", "interface_type", ",", "resource_class", ")", "]", "except", "KeyError", ":", "raise", "ValueError", ...
Return the session class for a given interface type and resource class. :type interface_type: constants.InterfaceType :type resource_class: str :return: Session
[ "Return", "the", "session", "class", "for", "a", "given", "interface", "type", "and", "resource", "class", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/sessions.py#L42-L52
pyvisa/pyvisa-sim
pyvisa-sim/sessions.py
Session.register
def register(cls, interface_type, resource_class): """Register a session class for a given interface type and resource class. :type interface_type: constants.InterfaceType :type resource_class: str """ def _internal(python_class): if (interface_type, resource_class) ...
python
def register(cls, interface_type, resource_class): """Register a session class for a given interface type and resource class. :type interface_type: constants.InterfaceType :type resource_class: str """ def _internal(python_class): if (interface_type, resource_class) ...
[ "def", "register", "(", "cls", ",", "interface_type", ",", "resource_class", ")", ":", "def", "_internal", "(", "python_class", ")", ":", "if", "(", "interface_type", ",", "resource_class", ")", "in", "cls", ".", "_session_classes", ":", "logger", ".", "warn...
Register a session class for a given interface type and resource class. :type interface_type: constants.InterfaceType :type resource_class: str
[ "Register", "a", "session", "class", "for", "a", "given", "interface", "type", "and", "resource", "class", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/sessions.py#L55-L69
pyvisa/pyvisa-sim
pyvisa-sim/sessions.py
Session.get_attribute
def get_attribute(self, attribute): """Get an attribute from the session. :param attribute: :return: attribute value, status code :rtype: object, constants.StatusCode """ # Check that the attribute exists. try: attr = attributes.AttributesByID[attrib...
python
def get_attribute(self, attribute): """Get an attribute from the session. :param attribute: :return: attribute value, status code :rtype: object, constants.StatusCode """ # Check that the attribute exists. try: attr = attributes.AttributesByID[attrib...
[ "def", "get_attribute", "(", "self", ",", "attribute", ")", ":", "# Check that the attribute exists.", "try", ":", "attr", "=", "attributes", ".", "AttributesByID", "[", "attribute", "]", "except", "KeyError", ":", "return", "0", ",", "constants", ".", "StatusCo...
Get an attribute from the session. :param attribute: :return: attribute value, status code :rtype: object, constants.StatusCode
[ "Get", "an", "attribute", "from", "the", "session", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/sessions.py#L90-L113
pyvisa/pyvisa-sim
pyvisa-sim/sessions.py
Session.set_attribute
def set_attribute(self, attribute, attribute_state): """Get an attribute from the session. :param attribute: :return: attribute value, status code :rtype: object, constants.StatusCode """ # Check that the attribute exists. try: attr = attributes.Attr...
python
def set_attribute(self, attribute, attribute_state): """Get an attribute from the session. :param attribute: :return: attribute value, status code :rtype: object, constants.StatusCode """ # Check that the attribute exists. try: attr = attributes.Attr...
[ "def", "set_attribute", "(", "self", ",", "attribute", ",", "attribute_state", ")", ":", "# Check that the attribute exists.", "try", ":", "attr", "=", "attributes", ".", "AttributesByID", "[", "attribute", "]", "except", "KeyError", ":", "return", "constants", "....
Get an attribute from the session. :param attribute: :return: attribute value, status code :rtype: object, constants.StatusCode
[ "Get", "an", "attribute", "from", "the", "session", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/sessions.py#L115-L142
pyvisa/pyvisa-sim
pyvisa-sim/component.py
to_bytes
def to_bytes(val): """Takes a text message and return a tuple """ if val is NoResponse: return val val = val.replace('\\r', '\r').replace('\\n', '\n') return val.encode()
python
def to_bytes(val): """Takes a text message and return a tuple """ if val is NoResponse: return val val = val.replace('\\r', '\r').replace('\\n', '\n') return val.encode()
[ "def", "to_bytes", "(", "val", ")", ":", "if", "val", "is", "NoResponse", ":", "return", "val", "val", "=", "val", ".", "replace", "(", "'\\\\r'", ",", "'\\r'", ")", ".", "replace", "(", "'\\\\n'", ",", "'\\n'", ")", "return", "val", ".", "encode", ...
Takes a text message and return a tuple
[ "Takes", "a", "text", "message", "and", "return", "a", "tuple" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/component.py#L16-L22
pyvisa/pyvisa-sim
pyvisa-sim/component.py
Property.validate_value
def validate_value(self, string_value): """Validate that a value match the Property specs. """ specs = self.specs if 'type' in specs: value = specs['type'](string_value) else: value = string_value if 'min' in specs and value < specs['min']: ...
python
def validate_value(self, string_value): """Validate that a value match the Property specs. """ specs = self.specs if 'type' in specs: value = specs['type'](string_value) else: value = string_value if 'min' in specs and value < specs['min']: ...
[ "def", "validate_value", "(", "self", ",", "string_value", ")", ":", "specs", "=", "self", ".", "specs", "if", "'type'", "in", "specs", ":", "value", "=", "specs", "[", "'type'", "]", "(", "string_value", ")", "else", ":", "value", "=", "string_value", ...
Validate that a value match the Property specs.
[ "Validate", "that", "a", "value", "match", "the", "Property", "specs", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/component.py#L77-L92
pyvisa/pyvisa-sim
pyvisa-sim/component.py
Component._match_dialog
def _match_dialog(self, query, dialogues=None): """Tries to match in dialogues :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ if dialogues is None: dialogues = self._dialogues ...
python
def _match_dialog(self, query, dialogues=None): """Tries to match in dialogues :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ if dialogues is None: dialogues = self._dialogues ...
[ "def", "_match_dialog", "(", "self", ",", "query", ",", "dialogues", "=", "None", ")", ":", "if", "dialogues", "is", "None", ":", "dialogues", "=", "self", ".", "_dialogues", "# Try to match in the queries", "if", "query", "in", "dialogues", ":", "response", ...
Tries to match in dialogues :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None
[ "Tries", "to", "match", "in", "dialogues" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/component.py#L158-L174
pyvisa/pyvisa-sim
pyvisa-sim/component.py
Component._match_getters
def _match_getters(self, query, getters=None): """Tries to match in getters :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ if getters is None: getters = self._getters i...
python
def _match_getters(self, query, getters=None): """Tries to match in getters :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ if getters is None: getters = self._getters i...
[ "def", "_match_getters", "(", "self", ",", "query", ",", "getters", "=", "None", ")", ":", "if", "getters", "is", "None", ":", "getters", "=", "self", ".", "_getters", "if", "query", "in", "getters", ":", "name", ",", "response", "=", "getters", "[", ...
Tries to match in getters :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None
[ "Tries", "to", "match", "in", "getters" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/component.py#L176-L191
pyvisa/pyvisa-sim
pyvisa-sim/component.py
Component._match_setters
def _match_setters(self, query): """Tries to match in setters :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ q = query.decode('utf-8') for name, parser, response, error_response in ...
python
def _match_setters(self, query): """Tries to match in setters :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ q = query.decode('utf-8') for name, parser, response, error_response in ...
[ "def", "_match_setters", "(", "self", ",", "query", ")", ":", "q", "=", "query", ".", "decode", "(", "'utf-8'", ")", "for", "name", ",", "parser", ",", "response", ",", "error_response", "in", "self", ".", "_setters", ":", "try", ":", "value", "=", "...
Tries to match in setters :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None
[ "Tries", "to", "match", "in", "setters" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/component.py#L193-L217
pyvisa/pyvisa-sim
pyvisa-sim/devices.py
Device.add_error_handler
def add_error_handler(self, error_input): """Add error handler to the device """ if isinstance(error_input, dict): error_response = error_input.get('response', {}) cerr = error_response.get('command_error', NoResponse) qerr = error_response.get('query_error',...
python
def add_error_handler(self, error_input): """Add error handler to the device """ if isinstance(error_input, dict): error_response = error_input.get('response', {}) cerr = error_response.get('command_error', NoResponse) qerr = error_response.get('query_error',...
[ "def", "add_error_handler", "(", "self", ",", "error_input", ")", ":", "if", "isinstance", "(", "error_input", ",", "dict", ")", ":", "error_response", "=", "error_input", ".", "get", "(", "'response'", ",", "{", "}", ")", "cerr", "=", "error_response", "....
Add error handler to the device
[ "Add", "error", "handler", "to", "the", "device" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L156-L189
pyvisa/pyvisa-sim
pyvisa-sim/devices.py
Device.add_eom
def add_eom(self, type_class, query_termination, response_termination): """Add default end of message for a given interface type and resource class. :param type_class: interface type and resource class as strings joined by space :param query_termination: end of message used in queries. ...
python
def add_eom(self, type_class, query_termination, response_termination): """Add default end of message for a given interface type and resource class. :param type_class: interface type and resource class as strings joined by space :param query_termination: end of message used in queries. ...
[ "def", "add_eom", "(", "self", ",", "type_class", ",", "query_termination", ",", "response_termination", ")", ":", "interface_type", ",", "resource_class", "=", "type_class", ".", "split", "(", "' '", ")", "interface_type", "=", "getattr", "(", "constants", ".",...
Add default end of message for a given interface type and resource class. :param type_class: interface type and resource class as strings joined by space :param query_termination: end of message used in queries. :param response_termination: end of message used in responses.
[ "Add", "default", "end", "of", "message", "for", "a", "given", "interface", "type", "and", "resource", "class", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L200-L212
pyvisa/pyvisa-sim
pyvisa-sim/devices.py
Device.write
def write(self, data): """Write data into the device input buffer. :param data: single element byte :type data: bytes """ logger.debug('Writing into device input buffer: %r' % data) if not isinstance(data, bytes): raise TypeError('data must be an instance of ...
python
def write(self, data): """Write data into the device input buffer. :param data: single element byte :type data: bytes """ logger.debug('Writing into device input buffer: %r' % data) if not isinstance(data, bytes): raise TypeError('data must be an instance of ...
[ "def", "write", "(", "self", ",", "data", ")", ":", "logger", ".", "debug", "(", "'Writing into device input buffer: %r'", "%", "data", ")", "if", "not", "isinstance", "(", "data", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'data must be an instance o...
Write data into the device input buffer. :param data: single element byte :type data: bytes
[ "Write", "data", "into", "the", "device", "input", "buffer", "." ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L214-L250
pyvisa/pyvisa-sim
pyvisa-sim/devices.py
Device.read
def read(self): """Return a single byte from the output buffer """ if self._output_buffer: b, self._output_buffer = (self._output_buffer[0:1], self._output_buffer[1:]) return b return b''
python
def read(self): """Return a single byte from the output buffer """ if self._output_buffer: b, self._output_buffer = (self._output_buffer[0:1], self._output_buffer[1:]) return b return b''
[ "def", "read", "(", "self", ")", ":", "if", "self", ".", "_output_buffer", ":", "b", ",", "self", ".", "_output_buffer", "=", "(", "self", ".", "_output_buffer", "[", "0", ":", "1", "]", ",", "self", ".", "_output_buffer", "[", "1", ":", "]", ")", ...
Return a single byte from the output buffer
[ "Return", "a", "single", "byte", "from", "the", "output", "buffer" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L252-L260
pyvisa/pyvisa-sim
pyvisa-sim/devices.py
Device._match
def _match(self, query): """Tries to match in dialogues, getters and setters and subcomponents :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ response = self._match_dialog(query) if...
python
def _match(self, query): """Tries to match in dialogues, getters and setters and subcomponents :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ response = self._match_dialog(query) if...
[ "def", "_match", "(", "self", ",", "query", ")", ":", "response", "=", "self", ".", "_match_dialog", "(", "query", ")", "if", "response", "is", "not", "None", ":", "return", "response", "response", "=", "self", ".", "_match_getters", "(", "query", ")", ...
Tries to match in dialogues, getters and setters and subcomponents :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None
[ "Tries", "to", "match", "in", "dialogues", "getters", "and", "setters", "and", "subcomponents" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L262-L296
pyvisa/pyvisa-sim
pyvisa-sim/devices.py
Device._match_registers
def _match_registers(self, query): """Tries to match in status registers :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ if query in self._status_registers: register = self._stat...
python
def _match_registers(self, query): """Tries to match in status registers :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ if query in self._status_registers: register = self._stat...
[ "def", "_match_registers", "(", "self", ",", "query", ")", ":", "if", "query", "in", "self", ".", "_status_registers", ":", "register", "=", "self", ".", "_status_registers", "[", "query", "]", "response", "=", "register", ".", "value", "logger", ".", "deb...
Tries to match in status registers :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None
[ "Tries", "to", "match", "in", "status", "registers" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L298-L313
pyvisa/pyvisa-sim
pyvisa-sim/devices.py
Device._match_errors_queues
def _match_errors_queues(self, query): """Tries to match in error queues :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ if query in self._error_queues: queue = self._error_queue...
python
def _match_errors_queues(self, query): """Tries to match in error queues :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None """ if query in self._error_queues: queue = self._error_queue...
[ "def", "_match_errors_queues", "(", "self", ",", "query", ")", ":", "if", "query", "in", "self", ".", "_error_queues", ":", "queue", "=", "self", ".", "_error_queues", "[", "query", "]", "response", "=", "queue", ".", "value", "logger", ".", "debug", "("...
Tries to match in error queues :param query: message tuple :type query: Tuple[bytes] :return: response if found or None :rtype: Tuple[bytes] | None
[ "Tries", "to", "match", "in", "error", "queues" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L315-L329
pyvisa/pyvisa-sim
pyvisa-sim/devices.py
Devices.add_device
def add_device(self, resource_name, device): """Bind device to resource name """ if device.resource_name is not None: msg = 'The device %r is already assigned to %s' raise ValueError(msg % (device, device.resource_name)) device.resource_name = resource_name ...
python
def add_device(self, resource_name, device): """Bind device to resource name """ if device.resource_name is not None: msg = 'The device %r is already assigned to %s' raise ValueError(msg % (device, device.resource_name)) device.resource_name = resource_name ...
[ "def", "add_device", "(", "self", ",", "resource_name", ",", "device", ")", ":", "if", "device", ".", "resource_name", "is", "not", "None", ":", "msg", "=", "'The device %r is already assigned to %s'", "raise", "ValueError", "(", "msg", "%", "(", "device", ","...
Bind device to resource name
[ "Bind", "device", "to", "resource", "name" ]
train
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L343-L353
percipient/django-querysetsequence
queryset_sequence/pagination.py
SequenceCursorPagination.get_ordering
def get_ordering(self, *args, **kwargs): """Take whatever the expected ordering is and then first order by QuerySet.""" result = super(SequenceCursorPagination, self).get_ordering(*args, **kwargs) # Because paginate_queryset sets self.ordering after reading it...we # need to only modify...
python
def get_ordering(self, *args, **kwargs): """Take whatever the expected ordering is and then first order by QuerySet.""" result = super(SequenceCursorPagination, self).get_ordering(*args, **kwargs) # Because paginate_queryset sets self.ordering after reading it...we # need to only modify...
[ "def", "get_ordering", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "SequenceCursorPagination", ",", "self", ")", ".", "get_ordering", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Because paginate_q...
Take whatever the expected ordering is and then first order by QuerySet.
[ "Take", "whatever", "the", "expected", "ordering", "is", "and", "then", "first", "order", "by", "QuerySet", "." ]
train
https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/pagination.py#L155-L165
percipient/django-querysetsequence
queryset_sequence/pagination.py
SequenceCursorPagination._get_position_from_instance
def _get_position_from_instance(self, instance, ordering): """ The position will be a tuple of values: The QuerySet number inside of the QuerySetSequence. Whatever the normal value taken from the ordering property gives. """ # Get the QuerySet number of the curr...
python
def _get_position_from_instance(self, instance, ordering): """ The position will be a tuple of values: The QuerySet number inside of the QuerySetSequence. Whatever the normal value taken from the ordering property gives. """ # Get the QuerySet number of the curr...
[ "def", "_get_position_from_instance", "(", "self", ",", "instance", ",", "ordering", ")", ":", "# Get the QuerySet number of the current instance.", "qs_order", "=", "getattr", "(", "instance", ",", "'#'", ")", "# Strip the '#' and call the standard _get_position_from_instance....
The position will be a tuple of values: The QuerySet number inside of the QuerySetSequence. Whatever the normal value taken from the ordering property gives.
[ "The", "position", "will", "be", "a", "tuple", "of", "values", ":" ]
train
https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/pagination.py#L167-L182
percipient/django-querysetsequence
queryset_sequence/pagination.py
SequenceCursorPagination.decode_cursor
def decode_cursor(self, request): """ Given a request with a cursor, return a `Cursor` instance. Differs from the standard CursorPagination to handle a tuple in the position field. """ # Determine if we have a cursor, and if so then decode it. encoded = request.q...
python
def decode_cursor(self, request): """ Given a request with a cursor, return a `Cursor` instance. Differs from the standard CursorPagination to handle a tuple in the position field. """ # Determine if we have a cursor, and if so then decode it. encoded = request.q...
[ "def", "decode_cursor", "(", "self", ",", "request", ")", ":", "# Determine if we have a cursor, and if so then decode it.", "encoded", "=", "request", ".", "query_params", ".", "get", "(", "self", ".", "cursor_query_param", ")", "if", "encoded", "is", "None", ":", ...
Given a request with a cursor, return a `Cursor` instance. Differs from the standard CursorPagination to handle a tuple in the position field.
[ "Given", "a", "request", "with", "a", "cursor", "return", "a", "Cursor", "instance", "." ]
train
https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/pagination.py#L184-L211
percipient/django-querysetsequence
queryset_sequence/__init__.py
multiply_iterables
def multiply_iterables(it1, it2): """ Element-wise iterables multiplications. """ assert len(it1) == len(it2),\ "Can not element-wise multiply iterables of different length." return list(map(mul, it1, it2))
python
def multiply_iterables(it1, it2): """ Element-wise iterables multiplications. """ assert len(it1) == len(it2),\ "Can not element-wise multiply iterables of different length." return list(map(mul, it1, it2))
[ "def", "multiply_iterables", "(", "it1", ",", "it2", ")", ":", "assert", "len", "(", "it1", ")", "==", "len", "(", "it2", ")", ",", "\"Can not element-wise multiply iterables of different length.\"", "return", "list", "(", "map", "(", "mul", ",", "it1", ",", ...
Element-wise iterables multiplications.
[ "Element", "-", "wise", "iterables", "multiplications", "." ]
train
https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/__init__.py#L29-L35
percipient/django-querysetsequence
queryset_sequence/__init__.py
ComparatorMixin._cmp
def _cmp(cls, value1, value2): """ Comparison method that takes into account Django's special rules when ordering by a field that is a model: 1. Try following the default ordering on the related model. 2. Order by the model's primary key, if there is no Meta.ordering. ...
python
def _cmp(cls, value1, value2): """ Comparison method that takes into account Django's special rules when ordering by a field that is a model: 1. Try following the default ordering on the related model. 2. Order by the model's primary key, if there is no Meta.ordering. ...
[ "def", "_cmp", "(", "cls", ",", "value1", ",", "value2", ")", ":", "if", "isinstance", "(", "value1", ",", "Model", ")", "and", "isinstance", "(", "value2", ",", "Model", ")", ":", "field_names", "=", "value1", ".", "_meta", ".", "ordering", "# Assert ...
Comparison method that takes into account Django's special rules when ordering by a field that is a model: 1. Try following the default ordering on the related model. 2. Order by the model's primary key, if there is no Meta.ordering.
[ "Comparison", "method", "that", "takes", "into", "account", "Django", "s", "special", "rules", "when", "ordering", "by", "a", "field", "that", "is", "a", "model", ":" ]
train
https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/__init__.py#L52-L80
percipient/django-querysetsequence
queryset_sequence/__init__.py
ComparatorMixin._generate_comparator
def _generate_comparator(cls, field_names): """ Construct a comparator function based on the field names. The comparator returns the first non-zero comparison value. Inputs: field_names (iterable of strings): The field names to sort on. Returns: A compar...
python
def _generate_comparator(cls, field_names): """ Construct a comparator function based on the field names. The comparator returns the first non-zero comparison value. Inputs: field_names (iterable of strings): The field names to sort on. Returns: A compar...
[ "def", "_generate_comparator", "(", "cls", ",", "field_names", ")", ":", "# Ensure that field names is a list and not a tuple.", "field_names", "=", "list", "(", "field_names", ")", "# For fields that start with a '-', reverse the ordering of the", "# comparison.", "reverses", "=...
Construct a comparator function based on the field names. The comparator returns the first non-zero comparison value. Inputs: field_names (iterable of strings): The field names to sort on. Returns: A comparator function.
[ "Construct", "a", "comparator", "function", "based", "on", "the", "field", "names", ".", "The", "comparator", "returns", "the", "first", "non", "-", "zero", "comparison", "value", "." ]
train
https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/__init__.py#L83-L127
percipient/django-querysetsequence
queryset_sequence/__init__.py
QuerySequenceIterable._ordered_iterator
def _ordered_iterator(self): """ Interleave the values of each QuerySet in order to handle the requested ordering. Also adds the '#' property to each returned item. """ # A list of tuples, each with: # * The iterable # * The QuerySet number # * The n...
python
def _ordered_iterator(self): """ Interleave the values of each QuerySet in order to handle the requested ordering. Also adds the '#' property to each returned item. """ # A list of tuples, each with: # * The iterable # * The QuerySet number # * The n...
[ "def", "_ordered_iterator", "(", "self", ")", ":", "# A list of tuples, each with:", "# * The iterable", "# * The QuerySet number", "# * The next value", "#", "# (Remember that each QuerySet is already sorted.)", "iterables", "=", "[", "]", "for", "i", ",", "qs", "in", ...
Interleave the values of each QuerySet in order to handle the requested ordering. Also adds the '#' property to each returned item.
[ "Interleave", "the", "values", "of", "each", "QuerySet", "in", "order", "to", "handle", "the", "requested", "ordering", ".", "Also", "adds", "the", "#", "property", "to", "each", "returned", "item", "." ]
train
https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/__init__.py#L140-L209
percipient/django-querysetsequence
queryset_sequence/__init__.py
QuerySequenceIterable._unordered_iterator
def _unordered_iterator(self): """ Return the value of each QuerySet, but also add the '#' property to each return item. """ for i, qs in zip(self._queryset_idxs, self._querysets): for item in qs: setattr(item, '#', i) yield item
python
def _unordered_iterator(self): """ Return the value of each QuerySet, but also add the '#' property to each return item. """ for i, qs in zip(self._queryset_idxs, self._querysets): for item in qs: setattr(item, '#', i) yield item
[ "def", "_unordered_iterator", "(", "self", ")", ":", "for", "i", ",", "qs", "in", "zip", "(", "self", ".", "_queryset_idxs", ",", "self", ".", "_querysets", ")", ":", "for", "item", "in", "qs", ":", "setattr", "(", "item", ",", "'#'", ",", "i", ")"...
Return the value of each QuerySet, but also add the '#' property to each return item.
[ "Return", "the", "value", "of", "each", "QuerySet", "but", "also", "add", "the", "#", "property", "to", "each", "return", "item", "." ]
train
https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/__init__.py#L211-L219
percipient/django-querysetsequence
queryset_sequence/__init__.py
QuerySetSequence._filter_or_exclude_querysets
def _filter_or_exclude_querysets(self, negate, **kwargs): """ Similar to QuerySet._filter_or_exclude, but run over the QuerySets in the QuerySetSequence instead of over each QuerySet's fields. """ # Ensure negate is a boolean. negate = bool(negate) for kwarg, val...
python
def _filter_or_exclude_querysets(self, negate, **kwargs): """ Similar to QuerySet._filter_or_exclude, but run over the QuerySets in the QuerySetSequence instead of over each QuerySet's fields. """ # Ensure negate is a boolean. negate = bool(negate) for kwarg, val...
[ "def", "_filter_or_exclude_querysets", "(", "self", ",", "negate", ",", "*", "*", "kwargs", ")", ":", "# Ensure negate is a boolean.", "negate", "=", "bool", "(", "negate", ")", "for", "kwarg", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "pa...
Similar to QuerySet._filter_or_exclude, but run over the QuerySets in the QuerySetSequence instead of over each QuerySet's fields.
[ "Similar", "to", "QuerySet", ".", "_filter_or_exclude", "but", "run", "over", "the", "QuerySets", "in", "the", "QuerySetSequence", "instead", "of", "over", "each", "QuerySet", "s", "fields", "." ]
train
https://github.com/percipient/django-querysetsequence/blob/7bf324b08af6268821d235c18482847d7bf75eaa/queryset_sequence/__init__.py#L445-L527