text:
Sample Applications
===================

The sample applications illustrate how to [use the toolkit](UsingToolkit.html) in Streams applications. They are defined in the Streams namespace 'samples', and use the [operators and types](OperatorsAndTypes.html) in the namespace 'com.ibm.streamsx.opencv'.

All of the sample applications are compiled when the toolkit is [installed](InstallingToolkit.html). The sample applications can also be built individually within Streams Studio, or with the 'sc' command, like this:

        cd .../streams.opencv/com.ibm.streamsx.opencv
        make sample-application-name
        ./output/sample-application-name/bin/standalone -t 3

Below are descriptions of each sample application, including which operators it uses.

addtext.spl
-----------

Reads a stream of images from a video file. Prints width, height, and frame count on the image. The resulting video is displayed in a X11 window.

toolkit operators used:

- `AddText`
- `CaptureFromFile`
- `X11Viewer`

blank2.spl
----------

Creates a stream of blank images with a specific height, width, fps, and color. The stream stats are printed on the image. The resulting video is output to a HTTPViewer on a specific port.

toolkit operators used:

- `Blank`
- `HTTPViewer`
- `Stats`

blank.spl
---------

Creates a stream of blank images with a specific height, width, fps, and color. The stream stats are printed on the image. The resulting video is output to a MJPEGStreamer on a specific port.

toolkit operators used:

- `Blank`
- `MJPEGStreamer`
- `Stats`

box.spl
-------

Periodically polls for an image from a url. A box is added to the retrieved images. The resulting video is displayed in a X11 window.

toolkit operators used:

- `CaptureFromURL`
- `MakeBox`
- `X11Viewer`

cam\_proxy.spl
--------------

Captures video from a local webcam. The resulting video is output through a proxy connection.

(See src\_proxy demo for the receiving proxy demo)

toolkit operators used:

- `CaptureFromCAM`
- `DisplayProxy`

cam.spl
-------

Captures video from a local webcam. The resulting video is displayed in a X11 window.

toolkit operators used:

- `CaptureFromCAM`
- `X11Viewer`

codebook.spl
------------

Reads a stream of images from a video file. The images are smoothed before background/foreground detection is done. For the first 1s, the background is "learned", then only the foreground connected objects will be displayed in a X11 window.

The image from the CodeBook operator is a binary matrix of pixels of whether a foreground object is present(255) or not(0). This needed to be converted to a color image before the binary image was "ANDed" with the original image. This results in the foreground color image showing through and the background remaining black(0).

toolkit operators used:

- `Apply2`
- `CaptureFromFile`
- `CodeBook`
- `ConnectedComponents`
- `CvtColor`
- `Smooth`
- `X11Viewer`

common.spl
----------

This is not a sample application, although it does have the .spl file extension.

This file is used to define all of the common tuple types, so the tuple definitions did not have to be included at the top of each sample application.

toolkit operators used: none

contours\_on\_file.spl
----------------------

Reads a stream of images from a video file. The images are converted to grey and smoothed before thresholding is done. All pixels with value 75 or less are changed to zero(black). Then white contours are drawn on the image.

In order to display the new image next to the original, they first have to have the same number of color channels. So the new image is converted to color first. The result is displayed in a X11 window and saved to an output file at the same frame rate as the input file.

toolkit operators used:

- `CaptureFromFile`
- `Collage`
- `CvtColor`
- `DrawContours`
- `SaveToFile`
- `Smooth`
- `Threshold`
- `X11Viewer`

contours\_on\_jpg.spl
---------------------

Creates a stream of images from a single jpg file. The images are converted to grey and smoothed before thresholding is done. All pixels with value 150 or less are changed to zero(black). Then white contours are drawn on the image. The result is displayed in a X11 window. Then the stats tuples/s, bytes/s, and number of seconds are written to a log.

toolkit operators used:

- `BitBucket`
- `Blank`
- `CvtColor`
- `DrawContours`
- `Smooth`
- `Threshold`
- `X11Viewer`

copy.spl
--------

Reads a stream of images from a video file. The images are then saved to an output video file with same rate as the input file. The video is also displayed in a X11 window.

toolkit operators used:

- `CaptureFromFile`
- `SaveToFile`
- `X11Viewer`

crawler.spl
-----------

Scans two directories, one for all files and another only for files matching a specific REGEX pattern. The file names are output to files.

For some operators (i.e. ReadImage), this could be used as an input specification mechanism (see imgcrawler demo.)

toolkit operators used: none

demo1b.spl
----------

Reads a stream of images from a video file. The resulting video is output to a MJPEGStreamer on a specific port.

toolkit operators used:

- `CaptureFromFile`
- `MJPEGStreamer`

demo1.spl
---------

Captures video from a local webcam. The resulting video is displayed in a X11 window.

toolkit operators used:

- `CaptureFromCAM`
- `X11Viewer`

demo2b.spl
----------

Reads a stream of images from a video file. Images are converted to grey scale and output to a MJPEGStreamer on a specific port.

Grey scale images are then passed through erode and dilate functions before outputing to a second MJPEGStreamer on a different port.

The original video is smoothed and outputted to a third MJPEGStreamer on a different port.

Using the original grey scale images, high and low thresholds are applied. The low value indicates pixels with a value less than are converted to black(0). The high value indicates pixels with larger values are converted to max(255) and less/equal are converted to black (0). Trackbars are used to allow the user to adjust the threshold values for the high and low thresholds. The two thresholded images are "ORed" together resulting in all "max" pixels being kept from the high threshold image and then all remaining pixels being kept from the low threshold image. The resulting video is output to a fourth MJPEGStreamer on a different port.

Using the eroded/dilated grey scale images, the same high and low thresholds as above are applied. The resulting video is output to a fifth MJPEGStreamer on a different port.

toolkit operators used:

- `Apply2`
- `CaptureFromFile`
- `CvtColor`
- `Dilate`
- `Erode`
- `MJPEGStreamer`
- `Smooth`
- `Threshold`
- `TrackBar`

demo2.spl
---------

Captures video from a local webcam. Images are converted to grey scale and displayed in a X11 window.

Grey scale images are then passed through erode and dilate functions before displaying in a second X11 window.

The original video is smoothed and displayed in a third X11 window.

Using the original grey scale images, high and low thresholds are applied. The low value indicates pixels with a value less than are converted to black(0). The high value indicates pixels with larger values are converted to max(255) and less/equal are converted to black (0). Trackbars are used to allow the user to adjust the threshold values for the high and low thresholds. The two thresholded images are "ORed" together resulting in all "max" pixels being kept from the high threshold image and then all remaining pixels being kept from the low threshold image. The resulting video is displayed in a fourth X11 window.

Using the eroded/dilated grey scale images, the same high and low thresholds as above are applied. The resulting video is displayed in a fifth X11 window.

toolkit operators used:

- `Apply2`
- `CaptureFromCAM`
- `CvtColor`
- `Dilate`
- `Erode`
- `Smooth`
- `Threshold`
- `TrackBar`
- `X11Viewer`

demo3b2.spl
-----------

Captures video from a input file. Images are converted to grey scale. High and low thresholds are applied. The low value indicates pixels with a value less than are converted to black(0). The high value indicates pixels with larger values are converted to max(255) and less/equal are converted to black(0). Trackbars are used to allow the user to adjust the threshold values for the high and low thresholds. The two thresholded images are "ORed" together resulting in all "max" pixels being kept from the high threshold image and then all remaining pixels being kept from the low threshold image. The resulting video is output to a MJPEGStreamer on a specific port. Then contours are drawn in white on a black image and output to a second MJPEGStreamer on a different port.

For comparison the original grey images are smoothed first prior to thresholding and drawing contours. The resulting contour images are output to a third MJPEGStreamer on a different port.

toolkit operators used:

- `Apply2`
- `CaptureFromFile`
- `CvtColor`
- `DrawContours`
- `MJPEGStreamer`
- `Smooth`
- `Threshold`
- `TrackBar`

demo3b.spl
----------

Captures video from a input file. Images are converted to grey scale. High and low thresholds are applied. The low value indicates pixels with a value less than are converted to black(0). The high value indicates pixels with larger values are converted to max(255) and less/equal are converted to black(0). Trackbars are used to allow the user to adjust the threshold values for the high and low thresholds. The two thresholded images are "ORed" together resulting in all "max" pixels being kept from the high threshold image and then all remaining pixels being kept from the low threshold image. The resulting video is output to a MJPEGStreamer on a specific port. Then contours are drawn in white on a black image and output to a second MJPEGStreamer on a different port.

For comparison the original grey images are smoothed first prior to thresholding and drawing contours. The resulting contour images are output to a third MJPEGStreamer on a different port.

In order to display the new contour image next to the original, the two must have the same number of color channels. So the new image is converted to color first. The result is output to a forth MJPEGStreamer on a different port and saved to an output file at 15 frames/s.

toolkit operators used:

- `Apply2`
- `CaptureFromFile`
- `Collage`
- `CvtColor`
- `DrawContours`
- `MJPEGStreamer`
- `SaveToFile`
- `Smooth`
- `Threshold`
- `TrackBar`

demo3.spl
---------

Captures video from a local web cam. Images are converted to grey scale. High and low thresholds are applied. The low value indicates pixels with a value less than are converted to black(0). The high value indicates pixels with larger values are converted to max(255) and less/equal are converted to black(0). Trackbars are used to allow the user to adjust the threshold values for the high and low thresholds. The two thresholded images are "ORed" together resulting in all "max" pixels being kept from the high threshold image and then all remaining pixels being kept from the low threshold image. The resulting video is displayed in a X11 window. Then contours are drawn in white on a black image and displayed in a second X11 window.

For comparison the original grey images are smoothed first prior to thresholding and drawing contours. The resulting contour images are displayed in a third X11 window.

toolkit operators used:

- `Apply2`
- `CaptureFromCAM`
- `CvtColor`
- `DrawContours`
- `Smooth`
- `Threshold`
- `TrackBar`
- `X11Viewer`

demo4b.spl
----------

Reads a stream of images from a video file. The images are smoothed before background/foreground detection is done. For the first 1s, the background is "learned", then only the foreground connected objects will be output to a MJPEGStreamer on a specific port.

The image from the CodeBook operator is a binary matrix of pixels of whether a foreground object is present(255) or not(0). This needed to be converted to a color image before the binary image was "ANDed" with the original image. This results in the foreground color image showing through and the background remaining black(0).

toolkit operators used:

- `Apply2`
- `CaptureFromFile`
- `CodeBook`
- `ConnectedComponents`
- `CvtColor`
- `MJPEGStreamer`
- `Smooth`

demo4.spl
---------

Captures video through a proxy connection. The images are smoothed before background/foreground detection is done. For the first 1s, the background is "learned", then only the foreground connected objects will be displayed in a X11 window.

The image from the CodeBook operator is a binary matrix of pixels of whether a foreground object is present(255) or not(0). This needed to be converted to a color image before the binary image was "ANDed" with the original image. This results in the foreground color image showing through and the background remaining black(0).

toolkit operators used:

- `Apply2`
- `CodeBook`
- `ConnectedComponents`
- `CvtColor`
- `Smooth`
- `SourceProxy`
- `X11Viewer`

demo5b.spl
----------

Reads a stream of images from a video file. The images are passed through face detection model. Then circles are drawn around the detected faces. The result is outputted to a MJPEGStreamer on a specific port.

toolkit operators used:

- `CaptureFromFile`
- `DrawCircles`
- `FaceDetection`
- `MJPEGStreamer`

demo5.spl
---------

Captures video through a proxy connection. The images are passed through face detection model. Then circles are drawn around the detected faces. The result is displayed in a X11 window.

toolkit operators used:

- `DrawCircles`
- `FaceDetection`
- `SourceProxy`
- `X11Viewer`

demo6b.spl
----------

Reads a stream of images from a video file. The motion between consecutive images is detected and motion vectors are drawn on the image. The stream stats are printed on the image before outputing to a MJPEGStreamer on a specific port.

toolkit operators used:

- `CaptureFromFile`
- `MJPEGStreamer`
- `MotionDetection`
- `Stats`

demo6.spl
---------

Captures video from a local webcam. The motion between consecutive images is detected and motion vectors are drawn on the image. The stream stats are printed on the image before displaying in a X11 window.

toolkit operators used:

- `CaptureFromCAM`
- `MotionDetection`
- `Stats`
- `X11Viewer`

demo7b.spl
----------

Reads a stream of images from a video file. The motion between consecutive images is detected and motion vectors are drawn on the image. The stream stats are printed on the image before outputing to a MJPEGStreamer on a specific port.

The parameters for the motion detection algorithm are input by the user via trackbars.

toolkit operators used:

- `CaptureFromFile`
- `MJPEGStreamer`
- `MotionDetection`
- `Stats`
- `TrackBar`

demo7.spl
---------

Captures video from a local webcam. The motion between consecutive images is detected and motion vectors are drawn on the image. The stream stats are printed on the image before displaying in a X11 window.

The parameters for the motion detection algorithm are input by the user via trackbars.

toolkit operators used:

- `CaptureFromCAM`
- `MotionDetection`
- `Stats`
- `TrackBar`
- `X11Viewer`

draw\_contours\_on\_cam.spl
---------------------------

Captures video from a local webcam. The images are converted to grey and smoothed before thresholding is done. All pixels with value greater than 128 are changed to zero(black). Contours are detected and drawn in white on a black image. When this contour image is "ORed" with the black/white webcam image the result is white contour lines on top of the black/white webcam image. Images are displayed in a X11 window.

toolkit operators used:

- `Apply2`
- `CaptureFromCAM`
- `CvtColor`
- `DrawContours`
- `Smooth`
- `Threshold`
- `X11Viewer`

draw\_contours\_on\_url.spl
---------------------------

Periodically polls for an image from a url. The images are converted to grey and smoothed before thresholding is done. All pixels with value greater than 128 are changed to zero(black). Contours are detected and drawn in white on a black image. When this contour image is "ORed" with the black/white webcam image the result is white contour lines on top of the black/white webcam image. Images are displayed in a X11 window.

toolkit operators used:

- `Apply2`
- `CaptureFromURL`
- `CvtColor`
- `DrawContours`
- `Smooth`
- `Threshold`
- `X11Viewer`

equalizehist.spl
----------------

Captures video from a local webcam. The average luminosity of all the pixels in the image is computed and printed on the image. Then image frames are tagged with a unique ascending id value.

For (potential) parallel processing the input image stream is passed through a ThreadedSplit operator. Images will be sent to one of three operators (two equalize the image histograms and the third performs no operation). The three streams are then merged using a Custom operator.

At this point the images are not necessarily in order, so the image stream is passed through a Sequencer to guarantee image order. The average luminosity of the new images is computed again.

The original image stream is displayed next to the new images in a X11 window.

toolkit operators used:

- `Average`
- `CaptureFromCAM`
- `Collage`
- `EqualizeHist`
- `Nop`
- `Sequencer`
- `Tagger`
- `X11Viewer`

facedetect.spl
--------------

Captures video from a local webcam. The images are passed through face detection model, and rectangles are drawn around the detected faces. The result is displayed in a X11 window, and a sampling of the faces detected are written to files in JPEG format.

toolkit operators used:

- `CaptureFromCAM`
- `CropBoxes`
- `DrawRectangles`
- `FaceDetection`
- `SaveImage`
- `X11Viewer`

faces\_edges\_cam.spl
---------------------

Captures video from a camera attached to the machine, passes the images through a face detection model and an edge detector on separate threads, and displays the results side-by-side in an X11 window.

toolkit operators used:

- `CaptureFromCAM`
- `Collage`
- `CvtColor`
- `DrawRectangles`
- `FaceDetection`
- `Resize`
- `Sobel`
- `Threshold`
- `TrackBar`
- `X11Viewer`

faces\_edges\_file.spl
----------------------

Reads a stream of images from a video file, passes the images through a face detection model and an edge detector on separate threads, and streams a side-by-side video to an external viewer on TCP port 9001.

toolkit operators used:

- `CaptureFromFile`
- `Collage`
- `CvtColor`
- `DrawRectangles`
- `FaceDetection`
- `MJPEGStreamer`
- `Resize`
- `Sobel`
- `Threshold`

file\_proxy.spl
---------------

Reads a stream of images from a video file. The resulting video is output through a proxy connection. Then video is captured through a proxy connection. The resulting video is displayed in a X11 window.

(See cam\_proxy and src\_proxy demos for a similar split version of this proxy demo)

toolkit operators used:

- `CaptureFromFile`
- `DisplayProxy`
- `SourceProxy`
- `X11Viewer`

file.spl
--------

Reads a stream of images from a video file. Images are timestamped with a time relative to the start of the stream. The resulting video is displayed in a X11 window.

toolkit operators used:

- `CaptureFromFile`
- `TimeStamp`
- `X11Viewer`

fun.spl
-------

Captures video from a local web cam. Images are converted to grey scale and smoothed. A low threshold is applied. The low value indicates pixels with a value less than are converted to black(0). A Trackbar is used to allow the user to adjust the threshold value. Then contours are drawn in white on a black image followed by dilating the contours to make the lines thicker.

The dilated contour image is converted to a 3 channel image and then "ORed" with a smoothed version of the original web cam image. This keeps all of the color from the original image while outlining the contours in thick white lines. The stream stats are printed on the image before displaying in a X11 window.

toolkit operators used:

- `Apply2`
- `CaptureFromCAM`
- `CvtColor`
- `Dilate`
- `DrawContours`
- `Smooth`
- `Stats`
- `Threshold`
- `TrackBar`
- `X11Viewer`

imgcrawler.spl
--------------

Creates a stream of blank images with a specific height, width, and color at 1 frame/s. Scans a directory, one for all image files (matching a specific REGEX pattern.) The file names are input to the ReadImage operator which creates a tuple for each image. Images are combined with the blank image with 50 is added to the image and the result is displayed in a X11 window.

toolkit operators used:

- `AddText`
- `Blank`
- `CombineImg`
- `ReadImage`
- `X11Viewer`

log.spl
-------

Demonstrates the DoLog operator functionality. Web cam images are passed through the DoLog operator both regular and inverted. The results are displayed next to the original image in a X11 window.

toolkit operators used:

- `CaptureFromCAM`
- `Collage`
- `DoLog`
- `X11Viewer`

mix\_cam\_snow.spl
------------------

Captures video from a local webcam. Images are converted to grey. The snow operator creates a stream of random snow images the same dimensions as the web cam images. The grey web cam images and the snow images are "ORed" together, effectively creating a snowy cam image displayed in a X11 window.

toolkit operators used:

- `Apply2`
- `CaptureFromCAM`
- `CvtColor`
- `Snow`
- `X11Viewer`

modec.spl
---------

Captures video from a local webcam. The motion between consecutive images is detected and motion vectors are drawn on the image. The stream stats are printed on the image before displaying in a X11 window.

toolkit operators used:

- `CaptureFromCAM`
- `MotionDetection`
- `Stats`
- `X11Viewer`

multiple\_cameras.spl
---------------------

Captures video from one or more cameras attached to the machine, passes the images through a face detection model, adds text labels to the images, and displays the results side-by-side in an X11 window.

toolkit operators used:

- `AddText`
- `CaptureFromCAM`
- `Collage`
- `DrawRectangles`
- `FaceDetection`
- `X11Viewer`

onc1.spl
--------

Reads a stream of images from a video file as fast as possible. Images have a black box drawn on them hiding some feature of the input video (e.g. timestamp or logo), then any resulting empty frames are discarded.

The frames are then paced to the same rate as the input video and output to a MJPEGStreamer on a specific port.

toolkit operators used:

- `CaptureFromFile`
- `FramePacer`
- `MakeBox`
- `MJPEGStreamer`
- `SkipEmpty`

onc2.spl
--------

Captures video from a input file. Images are converted to grey scale. High and low thresholds are applied. The low value indicates pixels with a value less than are converted to black(0). The high value indicates pixels with larger values are converted to max(255) and less/equal are converted to black(0). Trackbars are used to allow the user to adjust the threshold values for the high and low thresholds. The two thresholded images are "ORed" together resulting in all "max" pixels being kept from the high threshold image and then all remaining pixels being kept from the low threshold image. Connected components are detected in the resulting image, components are white(255) and non-component pixels are black(0).

The thresholded video is displayed in a X11 window and the connect component video is displayed in a second X11 window.

toolkit operators used:

- `Apply2`
- `CaptureFromFile`
- `ConnectedComponents`
- `CvtColor`
- `Threshold`
- `TrackBar`
- `X11Viewer`

onc3.spl
--------

Captures video from a local webcam. Any empty frames are skipped prior to flipping the image vertically and displaying in a X11 window.

Also the flipped images are smoothed before background/foreground detection is done. For the first 5s, the background is "learned", then the foreground connected objects are detected. Components are displayed white(255) and non-component pixels are displayed black(0) in a second X11 window.

toolkit operators used:

- `CaptureFromCAM`
- `CodeBook`
- `ConnectedComponents`
- `Flip`
- `SkipEmpty`
- `Smooth`
- `X11Viewer`

onc4.spl
--------

Captures video from a local webcam. Any empty frames are skipped prior to pacing the input image stream to the same as an input file. The images are converted to grey before thresholding is done. All pixels with value greater than are changed to zero(black). A trackbar is used to allow the user to adjust the threshold value.

Connect components are detected in the threshold image and contours are detected and drawn in white on a black image. The threshold images and contour images are output to separate MJPEGStreamers.

toolkit operators used:

- `CaptureFromCAM`
- `ConnectedComponents`
- `CvtColor`
- `DrawContours`
- `FramePacer`
- `MJPEGStreamer`
- `SkipEmpty`
- `Threshold`
- `TrackBar`

onc5.spl
--------

Captures video from a local webcam. The images are converted to grey before the Canny operator is used to detect image contours. Trackbars are used to allow the user to adjust the threshold values to the Canny operator. Any empty frames (no contours) are skipped prior to displaying the results in a X11 window.

Also the images from the Canny operator are converted to 3 channel images in order to display next to the original input video. This image collage is saved to an output file at the same rate as an input video.

toolkit operators used:

- `Canny`
- `CaptureFromCAM`
- `Collage`
- `CvtColor`
- `SaveToFile`
- `SkipEmpty`
- `TrackBar`
- `X11Viewer`

onc\_f.spl
----------

Remove empty frames from a video file. Captures video from a input file. Any empty frames are skipped prior to saving to an output file.

toolkit operators used:

- `CaptureFromFile`
- `SaveToFile`
- `SkipEmpty`

proxy2.spl
----------

Captures video from a local webcam. The resulting video is output through a proxy connection. Then video is captured through a proxy connection. The resulting video is displayed in a X11 window.

(See cam\_proxy and src\_proxy demos for a similar split version of this proxy demo)

toolkit operators used:

- `CaptureFromCAM`
- `DisplayProxy`
- `SourceProxy`
- `X11Viewer`

rank.spl
--------

Captures video from a local webcam.

Frames are adaptively skipped prior to performing minimum rank filtering. The stream stats are printed on the image before displaying in a X11 window.

Frames are adaptively skipped prior to performing median rank filtering. The stream stats are printed on the image before displaying in a X11 window.

Frames are adaptively skipped prior to performing maximum rank filtering. The stream stats are printed on the image before displaying in a X11 window.

toolkit operators used:

- `CaptureFromCAM`
- `RankFilter`
- `SkipFrame`
- `Stats`
- `X11Viewer`

record.spl
----------

Reads a stream of images from a video file. Images are flipped and timestamped with a time relative to the start of the stream.

The original and flipped/timestamp videos are displayed in separate X11 windows. Also the flipped/timestamp video is saved to an output file.

toolkit operators used:

- `CaptureFromFile`
- `Flip`
- `SaveToFile`
- `TimeStamp`
- `X11Viewer`

rotate.spl
----------

Rotates and crops an image stream from a webcam (assumes a 640x480 input image.) Captures video from a local webcam. Images are rotates 90 degrees around a specified point and scaled to 75 image is the same size as the input image and has black background where the rotated image is not. The black background is cropped out of the image. The original, rotated, and cropped images are displayed side-by-side in a X11 window.

toolkit operators used:

- `CaptureFromCAM`
- `Collage`
- `Crop`
- `Rotate`
- `X11Viewer`

snow.spl
--------

Random snow images are created at 10 frames/s. The frames are resized to 640x480 before smoothing and displaying in a X11 window.

toolkit operators used:

- `Resize`
- `Smooth`
- `Snow`
- `X11Viewer`

speed.spl
---------

A rough speed test. Creates a stream of 1000 blank images with a specific height, width, and color as fast as possible. The images are smoothed. Then the stats tuples/s, bytes/s, and number of seconds are written to a log.

toolkit operators used:

- `BitBucket`
- `Blank`
- `Smooth`

src\_proxy.spl
--------------

Captures video through a proxy connection. The resulting video is displayed in a X11 window.

(See cam\_proxy demo for the transmitting proxy demo)

toolkit operators used:

- `SourceProxy`
- `X11Viewer`

threshold.spl
-------------

Captures video from a input file. Images are converted to grey scale. High and low thresholds are applied. The low value indicates pixels with a value less than are converted to black(0). The high value indicates pixels with larger values are converted to max(255) and less/equal are converted to black(0). Trackbars are used to allow the user to adjust the threshold values for the high and low thresholds. The two thresholded images are "ORed" together resulting in all "max" pixels being kept from the high threshold image and then all remaining pixels being kept from the low threshold image. The resulting video is displayed in a X11 window.

toolkit operators used:

- `Apply2`
- `CaptureFromFile`
- `CvtColor`
- `Threshold`
- `TrackBar`
- `X11Viewer`

url.spl
-------

Periodically polls for an image from a url. Images are displayed in a X11 window.

toolkit operators used:

- `CaptureFromURL`
- `X11Viewer`

video\_stream.spl
-----------------

Reads a stream of images from a video file. Images are output to a MJPEGStreamer on a specific port and output to a HTTPViewer on a specific port.

toolkit operators used:

- `CaptureFromFile`
- `HTTPViewer`
- `MJPEGStreamer`

xcombine.spl
------------

Reads a stream of images from a video file. A second image is created by resizing the first to 130 with an offset and 30 second image does not overlap the first, the pixels are discarded. The result is displayed in a X11 window.

toolkit operators used:

- `CaptureFromFile`
- `CombineImg`
- `Resize`
- `X11Viewer`

----

© Copyright 2012, 2016, International Business Machines Corporation, All Rights Reserved


text:
My solution to [Bribe the Prisoners](https://code.google.com/codejam/contest/189252/dashboard#s=p2) problem
in Python 2.7.x

redpajama_set_name: RedPajamaGithub


text:
/** Common constants */
/** Theme */
/** Common basic theme colors */
/** Footer specific constants */
/** Nice light blue */
/** Macros */
.all {
  background: #f9f9f9;
  width: 100%;
  height: 100%;
}
/** Main content area */
.content {
  padding: 10px 10px 10px 20px;
}
.content h1 {
  margin: 0px;
  padding: 0px;
  line-height: auto !important;
  font-size: 25px;
}
.content h2 {
  margin: 0px;
  padding: 0px;
  line-height: auto !important;
  font-size: 20px;
}
.content h3 {
  margin: 0px;
  padding: 0px;
  line-height: auto !important;
  font-size: 18px;
  margin-top: 10px !important;
}
.tests .passed {
  margin: 10px 10px 10px 0px;
  background: #efe;
  border: 1px solid #0d0;
  border-radius: 4px;
  padding: 5px;
}
.tests .failed {
  margin: 10px 10px 10px 0px;
  background: #fee;
  border: 1px solid #d00;
  border-radius: 4px;
  padding: 5px;
}
.tests_running {
  margin: 10px 10px 10px 0px;
  padding: 5px;
  border: 1px solid #000;
  background: #fff;
}
.test_results {
  margin-right: 10px;
  font-size: 0.8em;
}
.test_results div {
  width: 300px;
}
.test_results div div {
  white-space: nowrap;
}
/** Search styles */
.search-keys {
  margin: 0px !important;
}
.search-keys li {
  list-style-type: none;
  padding: 1px 1px 1px 10px;
  margin-top: 2px;
  margin-left: 0px;
  background: #cfcfff;
  font-size: 0.7em;
  -webkit-border-radius: 3px !important;
  -moz-border-radius: 3px !important;
  -ms-border-radius: 3px !important;
  -o-border-radius: 3px !important;
  border-radius: 3px !important;
}
.search-results .search-count {
  padding: 10px 10px 10px 15px;
  background: #cfcfff;
  -webkit-border-radius: 3px !important;
  -moz-border-radius: 3px !important;
  -ms-border-radius: 3px !important;
  -o-border-radius: 3px !important;
  border-radius: 3px !important;
}
.search-results .search-result {
  margin-top: 4px;
  border: 1px solid #999;
  -webkit-border-radius: 3px !important;
  -moz-border-radius: 3px !important;
  -ms-border-radius: 3px !important;
  -o-border-radius: 3px !important;
  border-radius: 3px !important;
}
.search-results .search-result .search-item-header {
  background: #ffefef;
  padding: 3px 3px 3px 10px;
  font-weight: bold;
  font-size: 1.1em;
}
.search-results .search-result-items > table {
  width: 100%;
}
.search-results .search-result-items > table:nth-child(even) {
  background: #efefff;
}
.search-results .search-result-items > table:nth-child(odd) {
  background: #dfdfff;
}
.search-results .vert tr:nth-child(even) {
  background: #efefff;
}
.search-results .vert tr:nth-child(odd) {
  background: #dfdfff;
}
.search-results .vert tr td {
  padding: 3px 3px 3px 12px;
}
.search-results .search-result-item th {
  text-align: left;
  background: #dfdfff;
  padding: 6px 6px 6px 12px;
}
.search-results .search-result-item td {
  background: transparent;
  vertical-align: top;
  border: 1px solid #efefef;
}
.search-results .search-result-item td pre {
  font-size: 0.8em;
  background: none;
  padding: 0px;
  margin: 0px;
  border: 0px !important;
  height: 50px;
  overflow: scroll;
}
.search-results .search-result-item .key {
  width: 180px;
  padding-right: 10px;
  font-weight: bold;
  text-align: right;
}
/** Header styles */
/** Common header styles */
.header {
  float: right;
  position: absolute;
  right: 10px;
  top: 10px;
}
.header button {
  width: 165px;
  -webkit-border-radius: 5px !important;
  -moz-border-radius: 5px !important;
  -ms-border-radius: 5px !important;
  -o-border-radius: 5px !important;
  border-radius: 5px !important;
}
/** Footer styles */
.footer {
  background: #f9f9f9;
  width: 100%;
  position: fixed;
  bottom: 0px;
  left: 0px;
  text-align: center;
  padding: 10px 0px 0px;
}
.footer .alert {
  margin: 0px 10px 10px 10px;
  text-align: left;
}


text:
from unittest import TestCase

def setUpModule():  # noqa
    import c2cgeoportal
    c2cgeoportal.schema = 'main'
    c2cgeoportal.srid = 21781
    c2cgeoportal.caching.init_region({'backend': 'dogpile.cache.memory'})

class TestEntryView(TestCase):

    def setUp(self):  # noqa
        from pyramid import testing
        testing.setUp(
            settings={
                'default_locale_name': 'fr',
                'default_max_age': 1000,
            }
        )

    def test_decimal_json(self):
        from decimal import Decimal
        from pyramid.testing import DummyRequest
        from c2cgeoportal import DecimalJSON
        renderer = DecimalJSON()(None)
        request = DummyRequest()
        request.user = None
        system = {'request': request}

        self.assertEquals(
            renderer({'a': Decimal('3.3')}, system),
            '{"a": 3.3}'
        )
        self.assertEquals(request.response.content_type, 'application/json')

        request.params = {'callback': 'abc'}
        self.assertEquals(
            renderer({'a': Decimal('3.3')}, system),
            'abc({"a": 3.3});'
        )
        self.assertEquals(request.response.content_type, 'text/javascript')

        renderer = DecimalJSON(jsonp_param_name='cb')(None)
        request.params = {'cb': 'def'}
        self.assertEquals(
            renderer({'a': Decimal('3.3')}, system),
            'def({"a": 3.3});'
        )
        self.assertEquals(request.response.content_type, 'text/javascript')

    def test__get_child_layers_info_with_scalehint(self):
        import math
        from pyramid.testing import DummyRequest
        from c2cgeoportal.views.entry import Entry

        request = DummyRequest()
        request.user = None
        entry = Entry(request)

        class Layer(object):
            pass

        child_layer_1 = Layer()
        child_layer_1.name = 'layer_1'
        child_layer_1.scaleHint = {
            'min': 1 * math.sqrt(2),
            'max': 2 * math.sqrt(2)
        }
        child_layer_1.layers = []

        child_layer_2 = Layer()
        child_layer_2.name = 'layer_2'
        child_layer_2.scaleHint = {
            'min': 3 * math.sqrt(2),
            'max': 4 * math.sqrt(2)
        }
        child_layer_2.layers = []

        layer = Layer()
        layer.layers = [child_layer_1, child_layer_2]

        child_layers_info = entry._get_child_layers_info(layer)

        expected = [{
            'name': 'layer_1',
            'minResolutionHint': 1.0,
            'maxResolutionHint': 2.0
        }, {
            'name': 'layer_2',
            'minResolutionHint': 3.0,
            'maxResolutionHint': 4.0
        }]
        self.assertEqual(child_layers_info, expected)

    def test_login(self):
        from pyramid.testing import DummyRequest
        from c2cgeoportal.views.entry import Entry

        request = DummyRequest()
        request.user = None
        entry = Entry(request)

        request.path = '/for_test'
        expected = {
            'lang': 'fr',
            'came_from': '/for_test',
        }
        self.assertEqual(entry.loginform403(), expected)

        request.params = {
            'came_from': '/for_a_second_test',
        }
        entry = Entry(request)
        expected = {
            'lang': 'fr',
            'came_from': '/for_a_second_test',
        }
        self.assertEqual(entry.loginform(), expected)

        entry = Entry(request)
        request.params = {}
        expected = {
            'lang': 'fr',
            'came_from': '/',
        }
        self.assertEqual(entry.loginform(), expected)

    def test__get_child_layers_info_without_scalehint(self):
        from pyramid.testing import DummyRequest
        from c2cgeoportal.views.entry import Entry

        request = DummyRequest()
        request.user = None
        entry = Entry(request)

        class Layer(object):
            pass

        child_layer_1 = Layer()
        child_layer_1.name = 'layer_1'
        child_layer_1.scaleHint = None
        child_layer_1.layers = []

        child_layer_2 = Layer()
        child_layer_2.name = 'layer_2'
        child_layer_2.scaleHint = None
        child_layer_2.layers = []

        layer = Layer()
        layer.layers = [child_layer_1, child_layer_2]

        child_layers_info = entry._get_child_layers_info(layer)

        expected = [{
            'name': 'layer_1'
        }, {
            'name': 'layer_2',
        }]
        self.assertEqual(child_layers_info, expected)


text:
#pragma once
#include <kernel_headers/join.hpp>
#include <program.hpp>
#include <traits.hpp>
#include <string>
#include <mutex>
#include <map>
#include <dispatch.hpp>
#include <Param.hpp>
#include <debug_opencl.hpp>

using cl::Buffer;
using cl::Program;
using cl::Kernel;
using cl::make_kernel;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;

namespace opencl
{
    namespace kernel
    {
        // Kernel Launch Config Values
        static const int TX = 32;
        static const int TY = 8;
        static const int TILEX = 256;
        static const int TILEY = 32;

        template<typename To, typename Ti, int dim>
        void join(Param out, const Param in, const af::dim4 offset)
        {
            try {
                static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
                static std::map<int, Program*>   joinProgs;
                static std::map<int, Kernel *> joinKernels;

                int device = getActiveDeviceId();

                std::call_once( compileFlags[device], [device] () {
                    std::ostringstream options;
                    options << " -D To=" << dtype_traits<To>::getName()
                            << " -D Ti=" << dtype_traits<Ti>::getName()
                            << " -D dim=" << dim;

                    if (std::is_same<To, double>::value ||
                        std::is_same<To, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    } else if (std::is_same<Ti, double>::value ||
                               std::is_same<Ti, cdouble>::value) {
                        options << " -D USE_DOUBLE";
                    }

                    Program prog;
                    buildProgram(prog, join_cl, join_cl_len, options.str());
                    joinProgs[device] = new Program(prog);
                    joinKernels[device] = new Kernel(*joinProgs[device], "join_kernel");
                });

                auto joinOp = make_kernel<Buffer, const KParam, const Buffer, const KParam,
                              const int, const int, const int, const int,
                              const int, const int> (*joinKernels[device]);

                NDRange local(TX, TY, 1);

                int blocksPerMatX = divup(in.info.dims[0], TILEX);
                int blocksPerMatY = divup(in.info.dims[1], TILEY);
                NDRange global(local[0] * blocksPerMatX * in.info.dims[2],
                               local[1] * blocksPerMatY * in.info.dims[3],
                               1);

                joinOp(EnqueueArgs(getQueue(), global, local), *out.data, out.info, *in.data, in.info,
                        offset[0], offset[1], offset[2], offset[3], blocksPerMatX, blocksPerMatY);

                CL_DEBUG_FINISH(getQueue());
            } catch (cl::Error err) {
                CL_TO_AF_ERROR(err);
                throw;
            }
        }
    }
}


text:
@extends('master')
@section('navbar_menu')

TECHNOLOGY

@stop
@section('form_residencias')

 Nos preocupamos por ti en todos los sentidos

          En Sol & Luna Health Exclusive Resorts estamos a la vanguardia en la tecnologia, te ofrecemos los mejores servicios
          en tecnologia de punta para que tu estadia con nosotros sea una experiencia inolvidable.
          Te acercamos a tus seres queridos y amigos mediante el sistema de videollamada para que en cualquier momento puedas
          estar comunicarte con ellos y sentir que estan cerca de ti, tambien te acercamos con tu doctor, no importa si el esta
          del otro lado del mundo, con nuestra tecnologia sentiras que el esta contigo atendiendo tus necesidades y de esta manera
          tu salud estara en buenas manos.
          Contamos con camaras de seguridad las 24 horas y personal totalmente capacitado para cuidar  de ti en cualquier momento.

 Te acercamos a las personas que mas quieres.

          Una de nuestras tecnologias que implentamos en Sol & Luna Health Exclusive Resorts, es la impementacion
          de videolladas a traves de SKYPE.

    Con este sistema usted podra comunicarte "cara a cara" con sus seres queridos y asi estar en contacto con ellos,
    Si usted quiere comunicarse con un huesped de Assisting Living o Memory Care, con SKYPE usted podra hacer una videollamada
    a la residencia o centro donde esta hospedado y nuestro personal directamente lo comunicara con la persona que usted desee,
    asi podra estar con comunicacion en cualquier hora del dia con ellos y estar al pendiente de lo que pase.

 Tu doctor a tu lado, siempre.

          Una de nuestras tecnologias que implentamos en Sol & Luna Health Exclusive Resorts, es la impementacion
          de videolladas a traves de SKYPE.

    Con este sistema usted podra comunicarte "cara a cara" con sus seres queridos y asi estar en contacto con ellos,
    Si usted quiere comunicarse con un huesped de Assisting Living o Memory Care, con SKYPE usted podra hacer una videollamada
    a la residencia o centro donde esta hospedado y nuestro personal directamente lo comunicara con la persona que usted desee,
    asi podra estar con comunicacion en cualquier hora del dia con ellos y estar al pendiente de lo que pase.

@stop

@section('piepagina')
@stop


text:
import Base from './base'
import Util from './util'

const CollapseInline = (($) => {

  /**
   * ------------------------------------------------------------------------
   * Constants
   * ------------------------------------------------------------------------
   */
  const NAME = 'collapseInline'
  const DATA_KEY = `bmd.${NAME}`
  const JQUERY_NAME = `bmd${NAME.charAt(0).toUpperCase() + NAME.slice(1)}`
  const JQUERY_NO_CONFLICT = $.fn[JQUERY_NAME]

  const Selector = {
    ANY_INPUT: 'input, select, textarea'
  }

  const ClassName = {
    IN: 'in',
    COLLAPSE: 'collapse',
    COLLAPSING: 'collapsing',
    COLLAPSED: 'collapsed',
    WIDTH: 'width'
  }
  const Default = {}

  /**
   * ------------------------------------------------------------------------
   * Class Definition
   * ------------------------------------------------------------------------
   */
  class CollapseInline extends Base {

    // $element is expected to be the trigger
    //  i.e. <button class="btn bmd-btn-icon" for="search" data-toggle="collapse" data-target="#search-field" aria-expanded="false" aria-controls="search-field">
    constructor($element, config) {
      super($element, $.extend(true, {}, Default, config))
      this.$bmdFormGroup = this.findMdbFormGroup(true)

      let collapseSelector = $element.data('target')
      this.$collapse = $(collapseSelector)

      Util.assert($element, this.$collapse.length === 0, `Cannot find collapse target for ${Util.describe($element)}`)
      Util.assert(this.$collapse, !this.$collapse.hasClass(ClassName.COLLAPSE), `${Util.describe(this.$collapse)} is expected to have the '${ClassName.COLLAPSE}' class.  It is being targeted by ${Util.describe($element)}`)

      // find the first input for focusing
      let $inputs = this.$bmdFormGroup.find(Selector.ANY_INPUT)
      if ($inputs.length > 0) {
        this.$input = $inputs.first()
      }

      // automatically add the marker class to collapse width instead of height - nice convenience because it is easily forgotten
      if (!this.$collapse.hasClass(ClassName.WIDTH)) {
        this.$collapse.addClass(ClassName.WIDTH)
      }

      if (this.$input) {
        // add a listener to set focus
        this.$collapse.on('shown.bs.collapse', () => {
          this.$input.focus()
        })

        // add a listener to collapse field
        this.$input.blur(() => {
          this.$collapse.collapse('hide')
        })
      }
    }

    dispose() {
      super.dispose(DATA_KEY)
      this.$bmdFormGroup = null
      this.$collapse = null
      this.$input = null
    }

    // ------------------------------------------------------------------------
    // private

    // ------------------------------------------------------------------------
    // static
    static _jQueryInterface(config) {
      return this.each(function () {
        let $element = $(this)
        let data = $element.data(DATA_KEY)

        if (!data) {
          data = new CollapseInline($element, config)
          $element.data(DATA_KEY, data)
        }
      })
    }
  }

  /**
   * ------------------------------------------------------------------------
   * jQuery
   * ------------------------------------------------------------------------
   */
  $.fn[JQUERY_NAME] = CollapseInline._jQueryInterface
  $.fn[JQUERY_NAME].Constructor = CollapseInline
  $.fn[JQUERY_NAME].noConflict = () => {
    $.fn[JQUERY_NAME] = JQUERY_NO_CONFLICT
    return CollapseInline._jQueryInterface
  }

  return CollapseInline

})(jQuery)

export default CollapseInline


text:
import unittest

from pagarme.resources import Payment

class PaymentTest(unittest.TestCase):

    @unittest.skip('')
    def test_all(self):
        payables = Payment.all()
        self.assertGreater(len(payables), 0)


text: Site for fastonosql


text:
"""
- LICENCE

The MIT License (MIT)

Copyright (c) 2016 Eleftherios Anagnostopoulos for Ericsson AB (EU FP7 CityPulse Project)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

- DESCRIPTION OF DOCUMENTS

-- MongoDB Database Documents:

address_document: {
    '_id', 'name', 'node_id', 'point': {'longitude', 'latitude'}
}
bus_line_document: {
    '_id', 'bus_line_id', 'bus_stops': [{'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}}]
}
bus_stop_document: {
    '_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}
}
bus_stop_waypoints_document: {
    '_id', 'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'ending_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'waypoints': [[edge_object_id]]
}
bus_vehicle_document: {
    '_id', 'bus_vehicle_id', 'maximum_capacity',
    'routes': [{'starting_datetime', 'ending_datetime', 'timetable_id'}]
}
detailed_bus_stop_waypoints_document: {
    '_id', 'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'ending_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'waypoints': [[edge_document]]
}
edge_document: {
    '_id', 'starting_node': {'osm_id', 'point': {'longitude', 'latitude'}},
    'ending_node': {'osm_id', 'point': {'longitude', 'latitude'}},
    'max_speed', 'road_type', 'way_id', 'traffic_density'
}
node_document: {
    '_id', 'osm_id', 'tags', 'point': {'longitude', 'latitude'}
}
point_document: {
    '_id', 'osm_id', 'point': {'longitude', 'latitude'}
}
timetable_document: {
    '_id', 'timetable_id', 'bus_line_id', 'bus_vehicle_id',
    'timetable_entries': [{
        'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
        'ending_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
        'departure_datetime', 'arrival_datetime', 'number_of_onboarding_passengers',
        'number_of_deboarding_passengers', 'number_of_current_passengers',
        'route': {
            'total_distance', 'total_time', 'node_osm_ids', 'points', 'edges',
            'distances_from_starting_node', 'times_from_starting_node',
            'distances_from_previous_node', 'times_from_previous_node'
        }
    }],
    'travel_requests': [{
        '_id', 'client_id', 'bus_line_id',
        'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
        'ending_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
        'departure_datetime', 'arrival_datetime',
        'starting_timetable_entry_index', 'ending_timetable_entry_index'
    }]
}
traffic_event_document: {
    '_id', 'event_id', 'event_type', 'event_level', 'point': {'longitude', 'latitude'}, 'datetime'
}
travel_request_document: {
    '_id', 'client_id', 'bus_line_id',
    'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'ending_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'departure_datetime', 'arrival_datetime',
    'starting_timetable_entry_index', 'ending_timetable_entry_index'
}
way_document: {
    '_id', 'osm_id', 'tags', 'references'
}

-- Route Generator Responses:

get_route_between_two_bus_stops: {
    'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'ending_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'route': {
        'total_distance', 'total_time', 'node_osm_ids', 'points', 'edges',
        'distances_from_starting_node', 'times_from_starting_node',
        'distances_from_previous_node', 'times_from_previous_node'
    }
}
get_route_between_multiple_bus_stops: [{
    'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'ending_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'route': {
        'total_distance', 'total_time', 'node_osm_ids', 'points', 'edges',
        'distances_from_starting_node', 'times_from_starting_node',
        'distances_from_previous_node', 'times_from_previous_node'
    }
}]
get_waypoints_between_two_bus_stops: {
    'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'ending_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'waypoints': [[{
        '_id', 'starting_node': {'osm_id', 'point': {'longitude', 'latitude'}},
        'ending_node': {'osm_id', 'point': {'longitude', 'latitude'}},
        'max_speed', 'road_type', 'way_id', 'traffic_density'
    }]]
}
get_waypoints_between_multiple_bus_stops: [{
    'starting_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'ending_bus_stop': {'_id', 'osm_id', 'name', 'point': {'longitude', 'latitude'}},
    'waypoints': [[{
        '_id', 'starting_node': {'osm_id', 'point': {'longitude', 'latitude'}},
        'ending_node': {'osm_id', 'point': {'longitude', 'latitude'}},
        'max_speed', 'road_type', 'way_id', 'traffic_density'
    }]]
}]
"""
from src.geospatial_data.point import center

__author__ = 'Eleftherios Anagnostopoulos'
__email__ = 'eanagnostopoulos@hotmail.com'
__credits__ = [
    'Azadeh Bararsani (Senior Researcher at Ericsson AB) - email: azadeh.bararsani@ericsson.com'
    'Aneta Vulgarakis Feljan (Senior Researcher at Ericsson AB) - email: aneta.vulgarakis@ericsson.com'
]

class Address(object):
    """
    An address object is used to store street address. A address has a street
    name, points of street, and possibly numbers (usually marking a
    house or entrance).

    A building can be associated to several numbers, e.g 10A, 10B, and 10C. If
    the exact location of the entrance is unknown, all numbers can have a
    coordinate of the building.
    """

    def __init__(self, name, node_id, point):
        """
        :param name: The name of the address
        :type name: string
        :type node_id: integer
        :type point: Point
        """
        self.name = name
        self.nodes = [(node_id, point)]

    def add_node(self, node_id, point):
        """
        Add a node to the nodes list.

        :type node_id: integer
        :type point: Point
        """
        if (node_id, point) not in self.nodes:
            self.nodes.append((node_id, point))

    def nodes_to_string(self):
        result = '['

        for node_id, point in self.nodes:
            result += '(node_id:' + str(node_id) + ', point: ' + point.coordinates_to_string() + ')'

        result += ']'
        return result

    def get_center(self):
        return center([point for _, point in self.nodes])


text:
package slackbot

import (
	"fmt"
	"log"
	"math/rand"
	"strconv"
	"strings"
	"time"

	"github.com/Apollo-Community/slackbot/src/cleverbot"

	"github.com/arbovm/levenshtein"
	"github.com/nlopes/slack"
)

type Instance struct {
	Users    map[string]slack.User // TODO: not thread safe
	Channels map[string]slack.Channel
	Groups   map[string]slack.Group
	Latency  time.Duration
	Debug    bool
	BotId    string

	slack        *slack.Client
	rtm          *slack.RTM
	running      bool
	scores       map[string]map[string]int
	polls        map[string]int
	mutes        map[string]time.Time
	forum_topics []*ForumTopic
	goon         []*Quote
	apollo       []*Quote
	talking      bool
	cleverbot    *cleverbot.Session
}

func NewInstance(token string, debug bool, botid string) *Instance {
	s := slack.New(token)
	s.SetDebug(debug)

	i := &Instance{
		Users:    make(map[string]slack.User),
		Channels: make(map[string]slack.Channel),
		Groups:   make(map[string]slack.Group),
		Debug:    debug,
		BotId:    botid,
		slack:    s,
		running:  true,
		scores:   make(map[string]map[string]int),
		polls:    make(map[string]int),
		mutes:    make(map[string]time.Time),
		talking:  false,
	}

	var e error
	i.goon, e = load_quotes(GOON_QUOTES_FILE)
	if e != nil {
		fmt.Println("Warning: couldn't load goon quotes:", e)
	}
	i.apollo, e = load_quotes(APOLLO_QUOTES_FILE)
	if e != nil {
		fmt.Println("Warning: couldn't load apollo quotes:", e)
	}

	i.cleverbot, e = cleverbot.New()
	if e != nil {
		fmt.Println("Warning: couldn't initialize the cleverbot:", e)
	}

	// avoid using the same seed all the time (it defaults to 1)
	rand.Seed(time.Now().Unix())

	return i
}

func (i *Instance) Run() {
	rtm := i.slack.NewRTM()
	i.rtm = rtm
	go rtm.ManageConnection()

	for i.running {
		select {
		case msg := <-rtm.IncomingEvents:
			switch ev := msg.Data.(type) {
			case *slack.ConnectedEvent:
				i.slack.SetUserPresence("auto")
				for _, u := range ev.Info.Users {
					i.Users[u.ID] = u
				}
				for _, c := range ev.Info.Channels {
					i.Channels[c.ID] = c
				}
				for _, g := range ev.Info.Groups {
					i.Groups[g.ID] = g
				}
				go i.announce_latest_forum_topics()

			case *slack.MessageEvent:
				i.HandleMsg(ev)

			case *slack.LatencyReport:
				i.Latency = ev.Value

			case *slack.RTMError:
				fmt.Printf("Error: %s\n", ev.Error())

			case *slack.InvalidAuthEvent:
				panic("Invalid credentials")
			}
		}
	}
}

func (i *Instance) ChannelMsg(channel, msg string) {
	t := i.mutes[channel]
	if time.Now().Before(t) {
		return
	}
	m := i.rtm.NewOutgoingMessage(msg, channel)
	i.rtm.SendMessage(m)
}

func (i *Instance) UserMsg(user, msg string) error {
	_, _, cid, e := i.slack.OpenIMChannel(user)
	if e != nil {
		return e
	}
	i.ChannelMsg(cid, msg)
	return nil
}

func (i *Instance) AddScore(amount int, score_type, user string) {
	tmp, ok := i.scores[score_type]
	if ok != true {
		tmp = make(map[string]int)
	}
	tmp[user] += amount
	i.scores[score_type] = tmp
	fmt.Println(i.scores)
}

func (i *Instance) GetScore(score_type, user string) int {
	return i.scores[score_type][user]
}

func (i *Instance) StartVote(channel string) {
	i.polls[channel] = 0
}

func (i *Instance) StopVote(channel string) int {
	val := i.polls[channel]
	delete(i.polls, channel)
	return val

}

func (i *Instance) Vote(val int, channel string) {
	i.polls[channel] += val
}

func (i *Instance) Mute(channel string, dur time.Duration) {
	i.mutes[channel] = time.Now().Add(dur)
}

type Message struct {
	User      string
	Channel   string
	Timestamp time.Time
	Message   string
}

func (i *Instance) HandleMsg(msg *slack.MessageEvent) {
	if msg.User == i.BotId {
		// Sometimes we get a message from ourselves..
		return
	}

	sec, e := strconv.ParseInt(strings.Split(msg.Timestamp, ".")[0], 10, 64)
	if e != nil {
	}
	nsec, e := strconv.ParseInt(strings.Split(msg.Timestamp, ".")[1], 10, 64)
	if e != nil {
	}

	m := &Message{
		User:      msg.User,
		Channel:   msg.Channel,
		Timestamp: time.Unix(sec, nsec),
		Message:   msg.Text,
	}

	mention := fmt.Sprintf("<@%s>", i.BotId)
	if strings.HasPrefix(m.Message, mention) {
		m.Message = strings.TrimPrefix(m.Message, mention)
		m.Message = strings.TrimSpace(strings.TrimPrefix(m.Message, ":"))
		i.parse_msg(m)
	}
}

func (i *Instance) parse_msg(m *Message) {
	e := i.parse_cmd(m)
	if e != nil {
		i.UserMsg(m.User, e.Error())
	}
}

func (i *Instance) parse_cmd(m *Message) error {
	tokens := strings.Fields(m.Message)
	if len(tokens) < 1 {
		return nil
	}
	cmd := strings.ToLower(tokens[0])

	var bestscore float64
	var bestcmd *Command
	for _, c := range COMMANDS {
		score := calcScore(cmd, c.Name)
		if bestcmd == nil || score > bestscore {
			bestscore = score
			bestcmd = c
		}
	}
	if bestscore >= 0.75 { // 50% match is good enough!
		return bestcmd.Func(i, m, tokens[1:])
	}

	if m.Channel == TALK_CHANNEL && i.talking {
		resp, e := i.cleverbot.Ask(m.Message)
		if e != nil {
			fmt.Println("cleverbot error:", e)
			return nil
		}
		i.ChannelMsg(TALK_CHANNEL, resp)
		return nil
	}

	log.Printf("%v: %v\n", i.Users[m.User].Name, m.Message)
	return fmt.Errorf("Did you mean `%s`?", bestcmd.Name)
}

func calcScore(a, b string) float64 {
	score := levenshtein.Distance(a, b)
	lena := len(a)
	lenb := len(b)
	var bigger float64
	if lena > lenb {
		bigger = float64(lena)
	} else {
		bigger = float64(lenb)
	}
	return (bigger - float64(score)) / bigger
}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.cmd.function;

import java.util.*;

import ghidra.program.model.address.*;
import ghidra.program.model.block.CodeBlock;
import ghidra.program.model.lang.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.pcode.*;
import ghidra.program.model.scalar.Scalar;
import ghidra.program.model.symbol.FlowType;
import ghidra.program.model.symbol.Reference;
import ghidra.program.model.util.*;
import ghidra.program.util.*;
import ghidra.program.util.SymbolicPropogator.Value;
import ghidra.util.Msg;
import ghidra.util.exception.*;
import ghidra.util.task.TaskMonitor;

/**
 * CallDepthChangeInfo.java
 *
 * Date: Feb 6, 2003
 *
 */
/**
 *
 * Given a function in a program or the start of a function, record information
 * about the change to a stack pointer from a subroutine call. The routine
 * getCallChange() can be called with the address of a call instruction. If the
 * stack could be tracked, the call instruction will return the change in the
 * stack pointer that would result from a call to the function.
 *
 * The computation is based on a set of equations that are generated and solved.
 * Each equation represents the stack change for a given basic flow block or
 * call instruction within the function.
 *
 *
 */

public class CallDepthChangeInfo {

	Program program;

	ArrayList<CodeBlock> codeBlocks = new ArrayList<CodeBlock>();

	ArrayList<Address> callLocs = new ArrayList<Address>();

	IntPropertyMap changeMap;

	IntPropertyMap depthMap;

	private HashMap<Address, Integer> overrideMap = new HashMap<Address, Integer>();

	private VarnodeTranslator trans;

	private Register stackReg = null;
	private Register frameReg = null;

	SymbolicPropogator symEval = null;

	private int stackPurge = Function.UNKNOWN_STACK_DEPTH_CHANGE;

	//private static final int INVALID_DEPTH_CHANGE = 16777216; // 2^24

	private static final String STACK_DEPTH_CHANGE_NAME = "StackDepthChange";

	/**
	 * Construct a new CallDepthChangeInfo object.
	 * @param func function to examine
	 */
	public CallDepthChangeInfo(Function func) {
		this.program = func.getProgram();
		frameReg = program.getCompilerSpec().getStackPointer();
		try {
			initialize(func, func.getBody(), frameReg, TaskMonitor.DUMMY);
		}
		catch (CancelledException e) {
			throw new RuntimeException("Unexpected Exception", e);
		}
	}

	/**
	 * Construct a new CallDepthChangeInfo object.
	 * @param func
	 *            function to examine
	 * @param monitor
	 *            monitor used to cancel the operation
	 *
	 * @throws CancelledException
	 *             if the operation was canceled
	 */
	public CallDepthChangeInfo(Function func, TaskMonitor monitor) throws CancelledException {
		this(func, func.getBody(), null, monitor);
	}

	/**
	 * Construct a new CallDepthChangeInfo object.
	 * @param function function to examine
	 * @param restrictSet set of addresses to restrict flow flowing to.
	 * @param frameReg register that is to have it's depth(value) change tracked
	 * @param monitor monitor used to cancel the operation
	 *
	 * @throws CancelledException
	 *             if the operation was canceled
	 */
	public CallDepthChangeInfo(Function function, AddressSetView restrictSet, Register frameReg,
			TaskMonitor monitor) throws CancelledException {
		this.program = function.getProgram();
		if (frameReg == null) {
			frameReg = program.getCompilerSpec().getStackPointer();
		}
		initialize(function, restrictSet, frameReg, monitor);
	}

	/**
	 * Construct a new CallDepthChangeInfo object.
	 *
	 * @param program  program containing the function to examime
	 * @param addr     address within the function to examine
	 * @param restrictSet set of addresses to restrict flow flowing to.
	 * @param frameReg register that is to have it's depth(value) change tracked
	 * @param monitor  monitor used to cancel the operation
	 * @throws CancelledException
	 *             if the operation was canceled
	 */
	public CallDepthChangeInfo(Program program, Address addr, AddressSetView restrictSet,
			Register frameReg, TaskMonitor monitor) throws CancelledException {
		Function func = program.getFunctionManager().getFunctionContaining(addr);
		Register stackReg = program.getCompilerSpec().getStackPointer();
		initialize(func, restrictSet, stackReg, monitor);
	}

	/**
	 * initialize codeblocks and call locations.
	 *
	 * @param addressSetView
	 * @param monitor
	 * @throws CancelledException
	 */
	private void initialize(Function func, AddressSetView restrictSet, Register reg,
			TaskMonitor monitor) throws CancelledException {
		changeMap = new DefaultIntPropertyMap("change");
		depthMap = new DefaultIntPropertyMap("depth");
		trans = new VarnodeTranslator(program);

		symEval = new SymbolicPropogator(program);
		symEval.setParamRefCheck(false);
		symEval.setReturnRefCheck(false);
		symEval.setStoredRefCheck(false);

		// initialize stack pointer
		frameReg = reg;

		followFlows(func, restrictSet, monitor);

	}

	public int getCallChange(Address addr) {
		int i = Function.UNKNOWN_STACK_DEPTH_CHANGE;
		try {
			i = changeMap.getInt(addr);
		}
		catch (NoValueException exc) {
		}

		return i;
	}

	void setDepth(Instruction instr, int depth) {
		depthMap.add(instr.getMinAddress(), depth);
	}

	void setDepth(Address addr, int depth) {
		depthMap.add(addr, depth);
	}

	public int getDepth(Address addr) {
		int depth = Function.UNKNOWN_STACK_DEPTH_CHANGE;
		try {
			depth = depthMap.getInt(addr);
		}
		catch (NoValueException exc) {
		}
		return depth;
	}

	/**
	 * Inspect the instruction and return how it affects the stack depth. If the
	 * depth cannot be determined, then return that the stack depth change is
	 * unknown.
	 *
	 * @param instr
	 *            instruction to analyze
	 *
	 * @return int change to stack depth if it can be determined,
	 *         Function.UNKNOWN_STACK_DEPTH_CHANGE otherwise.
	 */
	public int getInstructionStackDepthChange(Instruction instr) {
		return getInstructionStackDepthChange(instr, null, 0);
	}

	/**
	 * Inspect the instruction and return how it affects the stack depth. If the
	 * depth cannot be determined, then return that the stack depth change is
	 * unknown.
	 *
	 * @param instr instruction to analyze
	 *
	 * @return int change to stack depth if it can be determined,
	 *         Function.UNKNOWN_STACK_DEPTH_CHANGE otherwise.
	 */
	int getInstructionStackDepthChange(Instruction instr, ProcessorContext procContext,
			int currentStackDepth) {
		// see if there is an override at this address
		Integer override = overrideMap.get(instr.getMinAddress());
		if (override != null) {
			return override.intValue();
		}

		int depthChange = 0;

		if (!trans.supportsPcode()) {
			return Function.UNKNOWN_STACK_DEPTH_CHANGE;
		}

		int possibleDepthChange = 0;

		// TODO: This is hack, a call instruction can modify the stack while
		//       in progress, it matters what happens upon return...
		//       what we care about here is what is the result after execution on the
		// stack pointer
		FlowType flowType = instr.getFlowType();
		if (flowType.isCall()) {
			//			depthChange = getCallPurge(instr);
			//			if (depthChange == Function.UNKNOWN_STACK_DEPTH_CHANGE)
			//				return 0;
			//			return depthChange;
			return 0;
		}

		PcodeOp[] pcode = instr.getPcode();
		Varnode outVarNode = null;
		for (PcodeOp op : pcode) {
			Varnode input0 = op.getInput(0);
			Varnode input1 = op.getInput(1);
			Varnode output = op.getOutput();
			switch (op.getOpcode()) {
				case PcodeOp.INT_ADD:
					if (isStackPointer(input0)) {
						possibleDepthChange = (int) input1.getOffset();
						outVarNode = output;
					}
					else if (input0.equals(outVarNode)) {
						possibleDepthChange += (int) input1.getOffset();
						outVarNode = output;
					}
					else if (isStackPointer(input1)) {
						possibleDepthChange = (int) input0.getOffset();
						outVarNode = output;
					}
					else if (input1.equals(outVarNode)) {
						possibleDepthChange += (int) input0.getOffset();
						outVarNode = output;
					}
					break;
				case PcodeOp.INT_SUB:
					if (isStackPointer(input0)) {
						possibleDepthChange = (int) -input1.getOffset();
						outVarNode = output;
					}
					else if (input0.equals(outVarNode)) {
						possibleDepthChange += (int) -input1.getOffset();
						outVarNode = output;
					}
					else if (isStackPointer(input1)) {
						possibleDepthChange = (int) -input0.getOffset();
						outVarNode = output;
					}
					else if (input1.equals(outVarNode)) {
						possibleDepthChange += (int) -input0.getOffset();
						outVarNode = output;
					}
					break;
				case PcodeOp.INT_AND: // Assume this is a stack alignment and do the and
					if (isStackPointer(input0)) {
						if (currentStackDepth != Function.UNKNOWN_STACK_DEPTH_CHANGE) {
							possibleDepthChange =
								(int) (currentStackDepth & input1.getOffset()) - currentStackDepth;
						}
						outVarNode = output;
					}
					else if (input0.equals(outVarNode)) {
						possibleDepthChange = 0;
						outVarNode = output;
					}
					else if (isStackPointer(input1)) {
						if (currentStackDepth != Function.UNKNOWN_STACK_DEPTH_CHANGE) {
							possibleDepthChange =
								(int) (currentStackDepth & input0.getOffset()) - currentStackDepth;
						}
						outVarNode = output;
					}
					else if (input1.equals(outVarNode)) {
						possibleDepthChange = 0;
						outVarNode = output;
					}
					break;
			}

			if (!isStackPointer(output)) {
				//				possibleDepthChange = 0;
				continue;
			}

			switch (op.getOpcode()) {
				case PcodeOp.INT_ADD:
				case PcodeOp.INT_SUB:
				case PcodeOp.INT_AND:
					depthChange += possibleDepthChange;
					break;
				case PcodeOp.STORE:
					break;
				case PcodeOp.INT_OR:
					// if the op is an OR, then this could be a copy
					Varnode orInput1 = op.getInput(0);
					Varnode orInput2 = op.getInput(1);
					if (!orInput1.equals(orInput2)) {
						break;
					}
					Msg.debug(this, "INT_OR" + instr.getMinAddress());
				case PcodeOp.COPY:
					Varnode input = op.getInput(0);
					// if we know the processor context, find the value
					if (procContext != null && input.isRegister()) {
						Register reg = null;
						reg = trans.getRegister(input);
						if (procContext.hasValue(reg)) {
							long value = procContext.getValue(reg, true).longValue();
							depthChange = (int) (value - currentStackDepth);
							currentStackDepth += depthChange;
							continue;
						}
					}
					if (!input.equals(outVarNode)) {
						return Function.UNKNOWN_STACK_DEPTH_CHANGE;
					}
					depthChange = possibleDepthChange;
					break;
				default:
					return Function.UNKNOWN_STACK_DEPTH_CHANGE;
			}
		}

		// TODO: Modify return by normal stack shift....
		if (flowType.isTerminal()) {
			depthChange -= program.getCompilerSpec().getDefaultCallingConvention().getStackshift();
		}

		// if the current stack depth is still bad, don't return a depth change.
		if (currentStackDepth == Function.UNKNOWN_STACK_DEPTH_CHANGE ||
			currentStackDepth == Function.INVALID_STACK_DEPTH_CHANGE) {
			return Function.UNKNOWN_STACK_DEPTH_CHANGE;
		}
		return depthChange;
	}

	boolean isStackPointer(Varnode output) {
		if (output == null) {
			return false;
		}

		Register reg = null;
		reg = trans.getRegister(output);

		// is this register the stack pointer
		if (reg == stackReg) {
			return true;
		}

		return false;
	}

	/**
	 * Gets the stack depth change value that has been set at the indicated address.
	 *
	 * @param program the program to be checked
	 * @param address the program address
	 * @return the stack depth change value or null if value has not been set
	 */
	public static Integer getStackDepthChange(Program program, Address address) {
		PropertyMapManager pmm = program.getUsrPropertyManager();
		IntPropertyMap ipm = pmm.getIntPropertyMap(STACK_DEPTH_CHANGE_NAME);
		if (ipm == null || !ipm.hasProperty(address)) {
			return null;
		}

		try {
			return ipm.getInt(address);
		}
		catch (NoValueException e) {
			throw new AssertException("Already checked that it has a property");
		}
	}

	/**
	 * Sets a new value for the stack depth change at the indicated address.
	 *
	 * @param program the program where the value will be set
	 * @param address the program address
	 * @param stackDepthChange the new stack depth change value
	 *
	 * @throws DuplicateNameException if the property name for stack depth changes conflicted
	 * with another property tha has the same name.
	 */
	public static void setStackDepthChange(Program program, Address address, int stackDepthChange)
			throws DuplicateNameException {

		PropertyMapManager pmm = program.getUsrPropertyManager();
		IntPropertyMap ipm = pmm.getIntPropertyMap(STACK_DEPTH_CHANGE_NAME);
		if (ipm == null) {
			ipm = pmm.createIntPropertyMap(STACK_DEPTH_CHANGE_NAME);
		}
		ipm.add(address, stackDepthChange);
	}

	/**
	 * Removes the value for the stack depth change at the indicated address.
	 *
	 * @param program the program where the value will be removed
	 * @param address the program address
	 *
	 * @return true if a stack depth change existed at the indicated at the address and it was removed.
	 */
	public static boolean removeStackDepthChange(Program program, Address address) {

		PropertyMapManager pmm = program.getUsrPropertyManager();
		IntPropertyMap ipm = pmm.getIntPropertyMap(STACK_DEPTH_CHANGE_NAME);
		if (ipm != null) {
			return ipm.remove(address);
		}
		return false;
	}

	/**
	 * Gets an iterator indicating all the addresses that have a stack depth change value specified
	 * within a program's indicated address set.
	 *
	 * @param program the program to be checked
	 * @param addressSet the set of addresses to check for a stack depth change value
	 * @return the address iterator indicating where stack depth change values have been set
	 */
	public static AddressIterator getStackDepthChanges(Program program, AddressSetView addressSet) {
		PropertyMapManager pmm = program.getUsrPropertyManager();
		IntPropertyMap ipm = pmm.getIntPropertyMap(STACK_DEPTH_CHANGE_NAME);
		if (ipm == null) {
			return new EmptyAddressIterator();
		}
		return ipm.getPropertyIterator(addressSet);
	}

	/**
	 * Follow the flows of the subroutine, accumulating information about the
	 * stack pointer and any other register the stack pointer is assigned to.
	 *
	 * @param func
	 *            function to analyze
	 * @param monitor
	 *            monitor to provide feedback and cancel
	 * @throws CancelledException if monitor canceled
	 */
	private void followFlows(Function func, AddressSetView restrictSet, TaskMonitor monitor)
			throws CancelledException {
		if (frameReg == null) {
			return;
		}

		// check if this is thunk function
		if (func.isThunk()) {
			return;
		}

		// if extrapop is has an unknown purge, check for a purge on return instructions
		int purge = (short) program.getCompilerSpec().getDefaultCallingConvention().getExtrapop();
		final boolean possiblePurge = purge == -1 || purge > 3200 || purge < -3200;

		// follow all flows building up context
		// use context to fill out addresses on certain instructions
		final ContextEvaluator eval = new ContextEvaluatorAdapter() {

			@Override
			public boolean evaluateContextBefore(VarnodeContext context, Instruction instr) {
				Varnode stackRegVarnode = context.getRegisterVarnode(frameReg);
				Varnode stackValue = null;
				try {
					stackValue = context.getValue(stackRegVarnode, true, this);

					if (stackValue != null && context.isSymbol(stackValue) && context.isStackSymbolicSpace(stackValue)) {
						int stackPointerDepth = (int) stackValue.getOffset();
						setDepth(instr, stackPointerDepth);
					}
				}
				catch (NotFoundException e) {
					// ignore
				}

				return false;
			}

			@Override
			public boolean evaluateContext(VarnodeContext context, Instruction instr) {
				FlowType ftype = instr.getFlowType();
				if (possiblePurge && ftype.isTerminal()) {
					String mnemonicStr = instr.getMnemonicString().toLowerCase();
					if ("ret".equals(mnemonicStr) || "retf".equals(mnemonicStr)) {
						// x86 has a scalar operand to purge value from the stack
						int tempPurge = 0;
						Scalar scalar = instr.getScalar(0);
						if (scalar != null) {
							tempPurge = (int) scalar.getSignedValue();
							stackPurge = tempPurge;
						}
						else {
							stackPurge = 0;
						}
					}
				}

				return false;
			}

			@Override
			public boolean evaluateSymbolicReference(VarnodeContext context, Instruction instr,
					Address address) {
				if (instr.getFlowType().isTerminal()) {
					return false;
				}
				checkForStackOffset(context, instr, address, -1);
				return false;
			}

			private void checkForStackOffset(VarnodeContext context, Instruction instr,
					Address address, int opIndex) {
				String spaceName = address.getAddressSpace().getName();
				if (spaceName.startsWith("track_") || context.isStackSpaceName(spaceName)) {
					// TODO: what to do on a Symbolic reference
				}
			}
		};

		// set the stack pointer to be tracked
		stackReg = program.getLanguage().getDefaultCompilerSpec().getStackPointer();
		if (stackReg == null) {
			return;
		}

		symEval.setRegister(func.getEntryPoint(), stackReg);

		setDepth(func.getEntryPoint(), 0);

		symEval.flowConstants(func.getEntryPoint(), restrictSet, eval, true, monitor);

		return;
	}

	public int getStackPurge() {
		return stackPurge;
	}

	public int getStackOffset(Instruction cu, int opIndex) {
		int offset = 0;
		int offsetReg = 0;
		Register offReg = null;
		Scalar s = null;
		Object obj[] = cu.getOpObjects(opIndex);
		for (int i = 0; obj != null && i < obj.length; i++) {
			if (obj[i] instanceof Scalar) {
				Scalar newsc = (Scalar) obj[i];
				if (s != null) {
					return Function.INVALID_STACK_DEPTH_CHANGE;
				}
				// choose the biggest value....
				if (Math.abs(offset) < newsc.getUnsignedValue()) {
					offset = (int) newsc.getSignedValue();
					s = newsc;
				}
			}

			// check if any register is the stack pointer
			// if it is, need to compute stack depth offset for function
			//
			if (obj[i] instanceof Register) {
				Register reg = (Register) obj[i];
				int depth = getRegDepth(cu.getMinAddress(), reg);
				if (depth != Function.INVALID_STACK_DEPTH_CHANGE &&
					depth != Function.UNKNOWN_STACK_DEPTH_CHANGE) {
					offReg = reg;
					offsetReg = depth;
				}
			}
		}

		// must have a register that has the stack depth in it and a scalar
		if (offReg == null || s == null) {
			return Function.INVALID_STACK_DEPTH_CHANGE;
		}
		offset += offsetReg;

		return offset;
	}

	/**
	 * @param addr the address to get the stack pointer depth at.
	 * @return the stack pointer depth at the address.
	 */
	public int getSPDepth(Address addr) {
		return getRegDepth(addr, stackReg);
	}

	/**
	 * @param addr the address to get the register depth at.
	 * @param reg the register to get the depth of.
	 * @return the depth of the register at the address.
	 */
	public int getRegDepth(Address addr, Register reg) {
		// OK lets CHEAT...
		// Since single instructions will give the wrong value,
		// get the value as of the end of the last instruction that fell into this one!
		Instruction instr = this.program.getListing().getInstructionAt(addr);
		if (instr != null && instr.getLength() < 2) {
			Address fallAddr = instr.getFallFrom();
			if (fallAddr != null) {
				addr = fallAddr;
			}
			// just in case this instruction falling from is bigger than 1 byte
			instr = program.getListing().getInstructionAt(addr);
			addr = instr.getMaxAddress();
		}
		Value rValue = symEval.getRegisterValue(addr, reg);
		if (rValue == null) {
			return Function.INVALID_STACK_DEPTH_CHANGE;
		}
		Register relativeReg = rValue.getRelativeRegister();
		if (!reg.equals(stackReg)) {
			if (relativeReg == null || !relativeReg.equals(stackReg)) {
				return Function.INVALID_STACK_DEPTH_CHANGE;
			}
		}
		else if (relativeReg != null && !relativeReg.equals(stackReg)) {
			return Function.INVALID_STACK_DEPTH_CHANGE;
		}
		return (int) rValue.getValue();
	}

	/**
	 * @param addr the address of the register value to get the representation of.
	 * @param reg the register to get the representation of.
	 * @return the string representation of the register value.
	 */
	public String getRegValueRepresentation(Address addr, Register reg) {
		return symEval.getRegisterValueRepresentation(addr, reg);
	}
}


text:
package com.fruit.service.management.impl;

import com.fruit.base.BaseServiceImpl;
import com.fruit.dao.management.EnvironmentDao;
import com.fruit.entity.management.Environment;
import com.fruit.service.management.EnvironmentService;
import com.fruit.utils.ImageBean;
import com.fruit.utils.ParamTool;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by TanLiu on 2017/3/21.
 */
@Service
public class EnvironmentServiceImpl extends BaseServiceImpl<Environment> implements EnvironmentService {

    EnvironmentDao environmentDao;

    @Resource(name=EnvironmentDao.DAO_NAME)
    public void setEnvironmentDao(EnvironmentDao environmentDao) {
        super.setDaoSupport(environmentDao);
        this.environmentDao = environmentDao;
    }

    /**获取品种详细信息
     * @param id
     * @return
     */
    public String getEnvironmentDetail(int id){
        StringBuffer sql = new StringBuffer();
        sql.append("select t.id,t.soiltype,t.soilgrade,t.airquality,t.waterquality,t.pictures,DATE_FORMAT(t.createTime, '%Y-%m-%d %H:%i:%s') createTime from environment t where id=?");
        Map<String, Object> result = findUniqueToMap(sql.toString(),id);
        if(result!=null){
            Object picobject = result.get("pictures");
            if(picobject!=null){
                String pictures = picobject.toString();
                List<ImageBean> list = ImageBean.getImageList(pictures);
                result.put("pictures", list);
            }
        }
        String str = ParamTool.subContent(JSONArray.fromObject(result).toString());

        return str;
    }
}


text:
require("spec_helper.js");
require("../../public/javascripts/project.js");

Screw.Unit(function() {

  describe("Project", function() {
    after(function(){ teardownFixtures() });

    describe("getLinesOfCodeForForm", function(){
      it("returns an array that is the numeric values of all lines-of-code inputs in the given form", function(){
        fixture($('<form id="project"/>')
          .append($("
")
            .append('<input type="text" value="123" class="lines-of-code"/>')
            .append('<input type="text" value="321" class="lines-of-code"/>')));

        expect(Project.getLinesOfCodeForForm("#project")).to(equal, [123, 321]);
      });

      it("returns a zero for an input with a non-numeric value", function(){
        fixture($('<form id="project"/>')
          .append($("
")
            .append('<input type="text" value="abc" class="lines-of-code"/>')
            .append('<input type="text" value="321" class="lines-of-code"/>')));

        expect(Project.getLinesOfCodeForForm("#project")).to(equal, [0, 321]);
      });
    });

    describe("getTotalLinesOfCodeForForm", function(){
      it("sums the lines of code values for the given form", function(){
        var form = "form";
        mock(Project).should_receive("getLinesOfCodeForForm").with_arguments(form).at_least(1, "times").and_return([123, 321])
        expect(Project.getTotalLinesOfCodeForForm(form)).to(equal, 444);
      });
    });

    describe("calculateLinesOfCodePercentageForInput", function(){
      it("returns a percentage given an input and the total lines of code", function(){
        fixture($('<form id="project"/>').append('<input type="text" value="123" class="lines-of-code"/>'));
        expect(Project.calculateLinesOfCodePercentageForInput("#project input:first", 444)).to(equal, 0.28);
      });

      it("returns zero if the total lines of code given is zero", function(){
        expect(Project.calculateLinesOfCodePercentageForInput(null, 0)).to(equal, 0);
      });

      it("returns zero if the input has a non-numeric value", function(){
        fixture($('<form id="project"/>').append('<input type="text" value="abc" class="lines-of-code"/>'));
        expect(Project.calculateLinesOfCodePercentageForInput("#project input:first", 444)).to(equal, 0);
      });
    });

    describe("calculateAndDisplayLinesOfCodePercentagesForForm", function(){
      it("for each lines-of-code input plug the associated percentage into the view", function(){
        fixture($('<form id="project"/>')
          .append('<input type="text" value="123" class="lines-of-code"/>')
          .append('')
          .append('<input type="text" value="321" class="lines-of-code"/>')
          .append(''));

        Project.calculateAndDisplayLinesOfCodePercentagesForForm("#project");
        expect($("span.percentage:first").text()).to(equal, "28%");
        expect($("span.percentage:last").text()).to(equal, "72%");
      });
    });

    describe("getLanguagesForForm", function(){
      it("returns an array of the language names in the given form", function(){
        fixture($('<form id="project"/>')
          .append('<input type="text" value="Ruby" class="language-name"/>')
          .append('<input type="text" value="JavaScript" class="language-name"/>'));

        expect(Project.getLanguagesForForm("#project")).to(equal, ["Ruby", "JavaScript"]);
      });

      it("returns an empty array if there are no lanuages present", function(){
        fixture($('<form id="project"/>'));
        expect(Project.getLanguagesForForm("#project")).to(equal, []);
      });
    });

    describe("calculateRewriteTextForForm", function(){
      it("returns 'Yes' if the language list includes any language other than 'Scala'", function(){
        mock(Project).should_receive("getLanguagesForForm").with_arguments("#project").at_least(1, "time").and_return(["blub"]);
        expect(Project.calculateRewriteTextForForm("#project")).to(equal, "Yes");
      });

      it("returns 'No' if the language list only includes 'Scala'", function(){
        mock(Project).should_receive("getLanguagesForForm").with_arguments("#project").at_least(1, "time").and_return(["Scala"]);
        expect(Project.calculateRewriteTextForForm("#project")).to(equal, "No");
      });
    });

  });

});


text:
Before do
    ActionMailer::Base.delivery_method = :cache
end


text:
import org.scalatest.FunSpec
import org.mockito.Mockito._;

import com.xuaps.eTenancy.TenantBeanPersistController;
import com.xuaps.eTenancy.TenantManager;
import java.util.UUID;

import com.avaje.ebean.event.BeanPersistRequest;

class TenantBeanPersistControllerSpec extends FunSpec{
  val tenantManager = new TenantManagerImpl

  describe("TenantBeanPersistController") {
    describe("isRegisterFor") {
      it("should return if Class implements tenant property or not") {
       	val persistController = new TenantBeanPersistController(tenantManager);
			val withoutTenant = new WithoutTenant;
			val withTenant = new WithTenant;

			assertResult(false){persistController.isRegisterFor(classOf[WithoutTenant]);}
			assertResult(true){persistController.isRegisterFor(classOf[WithTenant]);}
      }
    }

	describe("preInsert"){
		it("should set tenant id value"){
			val persistController = new TenantBeanPersistController(tenantManager)
      	val beanPersistRequestMock = mock(classOf[BeanPersistRequest[WithTenant]])
			val bean = new WithTenant

 			when(beanPersistRequestMock.getBean()).thenReturn(bean);

			persistController.preInsert(beanPersistRequestMock);

			assert(tenantManager.getValue() == bean.tenantId);
		}
	}
  }
}


text:
package com.qualogy.qafe.mgwt.client.ui.renderer;

import com.google.gwt.user.client.ui.UIObject;
import com.qualogy.qafe.mgwt.client.activities.AbstractActivity;
import com.qualogy.qafe.mgwt.client.ui.component.QTextFieldSpinner;
import com.qualogy.qafe.mgwt.client.vo.ui.ComponentGVO;
import com.qualogy.qafe.mgwt.client.vo.ui.TextFieldGVO;

public class TextFieldSpinnerRenderer extends AnyTextFieldRenderer {

	public UIObject render(ComponentGVO component, String owner, String uuid, String parent, String context, AbstractActivity activity) {
		UIObject widget = null;
		if (component instanceof TextFieldGVO) {
			TextFieldGVO textFieldGVO = (TextFieldGVO)component;
			QTextFieldSpinner textField = new QTextFieldSpinner();
			widget = textField;
		}
		return widget;
	}

	@Override
	protected void init(ComponentGVO component, UIObject widget, String owner, String uuid, String parent, String context, AbstractActivity activity) {
		super.init(component, widget, owner, uuid, parent, context, activity);
		TextFieldGVO textFieldGVO = (TextFieldGVO)component;
		QTextFieldSpinner textField = (QTextFieldSpinner)widget;
		int minValue = TextFieldGVO.DEFAULT_MINIMUM;
		int maxValue = TextFieldGVO.DEFAULT_MAXIMUM;
		if (textFieldGVO.getMinValue() != null) {
			minValue = Integer.parseInt(textFieldGVO.getMinValue());
		}
		if (textFieldGVO.getMaxValue() != null) {
			maxValue = Integer.parseInt(textFieldGVO.getMaxValue());
		}
		textField.setMinValue(minValue);
		textField.setMaxValue(maxValue);
	}
}


text:
var connectionBuilder = require('../jira/connection_builder');
var prompt = require('prompt');
var newTicketSchema = require('../utils/new_ticket_schema');
var splitCommaList = require('../utils/split_comma_list');
var jiraLink = require('../jira/link');

module.exports = function(){

  function buildIssue(results) {
    var comps;
    var labels;
    var issue = {fields: {}};
    var f = issue.fields;
    f.project = {key: results.project};
    f.summary = results.summary;
    f.issuetype = {name: results.issuetype};
    f.assignee = {name: results.assignee};
    f.description = results.description;

    comps = splitCommaList(results.components, 'name');
    if (comps){
      f.components = comps
    }
    labels = splitCommaList(results.labels);
    if (labels) {
      f.labels = labels;
    }
    return issue;
  }

  connectionBuilder(function(connection){
    newTicketSchema(function(schema) {
      prompt.start();
      prompt.get(schema, function(err, results) {
        var issue = buildIssue(results);
        connection.addNewIssue(issue, function(err, issue) {
          if (err) {
            console.log(err);
            return;
          } else {
            console.log('');
            console.log(issue.key + ' - ' + jiraLink(issue.key));
            console.log('');
          }
        });
      });
    });

  });
}


text:
import simplejson as json

def test_environment(client):
    uri = '/v0/environment/'
    res = client.get(uri)
    assert res.status_code == 200
    response = json.loads(res.get_data())
    assert 'build' in response['data'] and \
        'version' in response['data']['build']


text:
'use strict';
// generated on 2015-06-17 using generator-gulp-bootstrap 0.0.4

var gulp = require('gulp');
var gutil = require('gulp-util');
var exec = require('child_process').exec;

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', function () {
    return gulp.src(['sass/main.scss', 'sass/shelf.scss', 'sass/alma.scss'])
        .pipe($.sass({errLogToConsole: true}))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('css'))
        .pipe($.size())
        .pipe($.notify("Compilation complete."));
});

gulp.task('clean', function () {
    return gulp.src(['css/main.css', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('build', ['styles']);

gulp.task('default', ['clean', 'build'], function () {
    gulp.start('watch');
});

gulp.task('watch', function () {
    // watch for changes
    gulp.watch('sass/**/*.scss', ['styles']);
});

gulp.task('push', function (cb) {
    exec('./deploy', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
})


text:
using System;
using System.Collections.Generic;

namespace Faithlife.Utility
{
	/// <summary>
	/// Implements IEqualityComparer interfaces with delegates.
	/// </summary>
	/// <typeparam name="T">Type of the object to compare.</typeparam>
	internal sealed class GenericEqualityComparer<T> : EqualityComparer<T>
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="GenericEqualityComparer<T>"/> class.
		/// </summary>
		/// <param name="equals">The equals delegate.</param>
		/// <param name="getHashCode">The hash code delegate.</param>
		/// <remarks>If getHashCode is null and GetHashCode is called, it will throw a NotImplementedException.</remarks>
		public GenericEqualityComparer(Func<T?, T?, bool> equals, Func<T, int>? getHashCode = null)
		{
			m_equals = equals ?? throw new ArgumentNullException(nameof(equals));
			m_getHashCode = getHashCode ?? (_ => throw new NotImplementedException());
		}

		/// <summary>
		/// When overridden in a derived class, determines whether two objects are equal.
		/// </summary>
		/// <param name="x">The first object to compare.</param>
		/// <param name="y">The second object to compare.</param>
		/// <returns>
		/// true if the specified objects are equal; otherwise, false.
		/// </returns>
		public override bool Equals(T? x, T? y) => m_equals(x, y);

		/// <summary>
		/// When overridden in a derived class, serves as a hash function for the specified object for hashing algorithms and data structures, such as a hash table.
		/// </summary>
		/// <param name="obj">The object for which to get a hash code.</param>
		/// <returns>A hash code for the specified object.</returns>
		/// <exception cref="ArgumentNullException">
		/// The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.
		/// </exception>
		public override int GetHashCode(T obj) => m_getHashCode(obj);

		private readonly Func<T?, T?, bool> m_equals;
		private readonly Func<T, int> m_getHashCode;
	}
}


text:
import { ApplicationAccessModel } from './application-access.model';

export interface UserAccessModel {
    globalAccess: { roles: string[] };
    applicationAccess: ApplicationAccessModel[];
}


text:
package org.pyjks;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;
import org.junit.Test;

public class MiscTest extends PyJksTestCase
{
	/**
	 * Encrypt some known data with PBEWithMD5AndTripleDES to verify correct decryption in python.
	 * In particular, exercise the edge case where the two salt halves are equal, because there's a bug in the JCE lurking there
	 * (see the python side for details)
	 */
	@Test
	public void generate_PBEWithMD5AndTripleDES_samples() throws Exception
	{
		byte[] output1 = encryptPBEWithMD5AndTripleDES("sample".getBytes(), "my_password", new byte[]{1,2,3,4,5,6,7,8}, 42);
		byte[] output2 = encryptPBEWithMD5AndTripleDES("sample".getBytes(), "my_password", new byte[]{1,2,3,4,1,2,3,4}, 42); // special case for SunJCE's PBEWithMD5AndTripleDES: identical salt halves
		byte[] output3 = encryptPBEWithMD5AndTripleDES("sample".getBytes(), "my_password", new byte[]{1,2,3,4,1,2,3,5}, 42); // control case for the previous one

		System.out.println(toPythonString(output1));
		System.out.println(toPythonString(output2));
		System.out.println(toPythonString(output3));
	}

	@Test
	public void generate_MUTF8_samples() throws Exception {
		// produce a bunch of sample Modified-UTF-8 strings
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x000000)))));
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x000001)))));
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x00007F)))));
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x000080)))));
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x0007FF)))));
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x000800)))));
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x00D7FF)))));
		// reserved UTF-16 surrogate code point range 0xD800 -- 0xDFFF
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x00E000)))));
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x00FFFF)))));
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x010000)))));
		System.out.println(toPythonString(mutf8_encode(new String(Character.toChars(0x10FFFF)))));
	}

	public byte[] mutf8_encode(String s) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);

		dos.writeUTF(s);
		dos.close();
		byte[] out = baos.toByteArray();
		// first two bytes are the length of the string, ignore those
		return Arrays.copyOfRange(out, 2, out.length);
	}

	public String mutf8_decode(byte[] input) throws IOException {
		// prefix the input byte array with its length (encoded in 2 bytes)
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		dos.writeShort(input.length);
		dos.write(input);
		dos.close();
		byte[] prefixed = baos.toByteArray();

		DataInputStream dis = new DataInputStream(new ByteArrayInputStream(prefixed));
		return dis.readUTF();
	}
}