text:
use url::Url;
use method::Method;
use method::Method::Options;
use status;
use status::Status::{BadRequest, RequestUriTooLong, HttpVersionNotSupported};
use std::io::{Stream, IoResult};
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::TcpStream;
use std::fmt;
use rfc2616::{CR, LF, SP};
use headers;
use buffer::BufferedStream;
use common::read_http_version;

use headers::HeaderLineErr;
use headers::HeaderLineErr::{EndOfFile, EndOfHeaders, MalformedHeaderSyntax,
                             MalformedHeaderValue};

use self::RequestUri::{Star, AbsoluteUri, AbsolutePath, Authority};

// /// Line/header can't be more than 4KB long (note that with the compacting of LWS the actual source
// /// data could be longer than 4KB)
// const MAX_LINE_LEN: usize = 0x1000;

const MAX_REQUEST_URI_LEN: usize = 1024;
pub const MAX_METHOD_LEN: usize = 64;

pub struct RequestBuffer<'a, S: 'a> {
    /// The socket connection to read from
    pub stream: &'a mut BufferedStream<S>,
}

impl<'a, S: Stream> RequestBuffer<'a, S> {
    pub fn new(stream: &'a mut BufferedStream<S>) -> RequestBuffer<'a, S> {
        RequestBuffer {
            stream: stream,
        }
    }

    pub fn read_request_line(&mut self) -> Result<(Method, RequestUri, (usize, usize)),
                                                  status::Status> {
        let method = match self.read_method() {
            Ok(m) => m,
            // TODO: this is a very common case, if a connection is kept open but then closed or
            // timed out. We should handle that case specially if we can improve perf—check if the
            // peer is still there and just drop the request if it is not
            Err(_) => return Err(BadRequest),
        };

        // Finished reading the method, including consuming a single SP.
        // Before we read the Request-URI, we should consume *SP (it's invalid,
        // but the spec recommends supporting it anyway).
        let mut next_byte;
        loop {
            match self.stream.read_byte() {
                Ok(_b@SP) => continue,
                Ok(b) => {
                    next_byte = b;
                    break;
                },
                _ => return Err(BadRequest),
            };
        }

        // Good, we're now into the Request-URI. Bear in mind that as well as
        // ending in SP, it can for HTTP/0.9 end in CR LF or LF.
        let mut raw_request_uri = String::new();
        loop {
            if next_byte == CR {
                // For CR, we must have an LF immediately afterwards.
                if self.stream.read_byte() != Ok(LF) {
                    return Err(BadRequest);
                } else {
                    // Simplify it by just dealing with the LF possibility
                    next_byte = LF;
                    break;
                }
            } else if next_byte == SP || next_byte == LF {
                break;
            }

            if raw_request_uri.len() == MAX_REQUEST_URI_LEN {
                return Err(RequestUriTooLong)
            }
            raw_request_uri.push(next_byte as char);

            next_byte = match self.stream.read_byte() {
                Ok(b) => b,
                _ => return Err(BadRequest),
            }
        }

        // Now parse it into a RequestUri.
        let request_uri = match RequestUri::from_string(raw_request_uri) {
            Some(r) => r,
            None => return Err(BadRequest),
        };

        // At this point, we need to consider what came immediately after the
        // Request-URI. If it was a SP, then we expect (again after allowing for
        // possible *SP, though illegal) to get an HTTP-Version. If it was CR LF
        // or LF, we consider it to be HTTP/0.9.
        if next_byte == LF {
            // Good, we got CR LF or LF; HTTP/0.9 it is.
            return Ok((method, request_uri, (0, 9)));
        }

        // By this point, next_byte can only be SP. Now we want an HTTP-Version.

        let mut read_b = 0;

        // FIXME: we still have one inconsistency here: this isn't trimming *SP.
        match read_http_version(self.stream, &mut |b| { read_b = b; b == CR || b == LF }) {
            Ok(vv) => {
                if read_b == LF || self.stream.read_byte() == Ok(LF) {
                    Ok((method, request_uri, vv))  // LF or CR LF: valid
                } else {
                    Err(BadRequest)  // CR but no LF: not valid
                }
            },
            Err(_) => Err(BadRequest),  // invalid: ... not valid ;-)
        }
    }

    #[inline]
    fn read_method(&mut self) -> IoResult<Method> {
        mod dummy { include!(concat!(env!("OUT_DIR"), "/read_method.rs")); }

        dummy::dummy::read_method(self.stream)
    }

    /// Read a header (name, value) pair.
    ///
    /// This is not necessarily just a line ending with CRLF; there are much fancier rules at work.
    /// Where appropriate (TODO, it's everywhere at present) linear whitespace is collapsed into a
    /// single space.
    ///
    /// # Error values
    ///
    /// - `EndOfHeaders`: I have no more headers to give; go forth and conquer on the body!
    /// - `EndOfFile`: socket was closed unexpectedly; probable best behavour is to drop the request
    /// - `MalformedHeaderValue`: header's value is invalid; normally, ignore it.
    /// - `MalformedHeaderSyntax`: bad request; you could drop it or try returning 400 Bad Request
    pub fn read_header<T: headers::HeaderEnum>(&mut self) -> Result<T, HeaderLineErr> {
        match headers::header_enum_from_stream(&mut *self.stream) {
        //match headers::HeaderEnum::from_stream(self.stream) {
            (Err(m), None) => Err(m),
            (Err(m), Some(b)) => {
                self.stream.poke_byte(b);
                Err(m)
            },
            (Ok(header), Some(b)) => {
                self.stream.poke_byte(b);
                Ok(header)
            }
            (Ok(header), None) => {
                // This should have read an extra byte, on account of the CR LF SP possibility
                error!("header with no next byte, did reading go wrong?");
                Ok(header)
            }
        }
    }
}

impl<'a, S: Stream> Reader for RequestBuffer<'a, S> {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        self.stream.read(buf)
    }
}

#[test]
fn test_request_uri_from_string() {
    assert_eq!(RequestUri::from_string("*".to_string()), Some(RequestUri::Star));
    assert_eq!(RequestUri::from_string("/abc".to_string()), Some(RequestUri::AbsolutePath("/abc".to_string())));
    let url = "http://example.com/abc";
    match RequestUri::from_string(url.to_string()) {
	Some(RequestUri::AbsoluteUri(url)) => {
	    assert_eq!(url.domain(), Some("example.com"));
	    assert_eq!(url.path(), Some(&["abc".to_string()][]));
	},
	_ => panic!("Parse failed for {}", url),
    };
    assert_eq!(RequestUri::from_string("".to_string()), None);
    assert_eq!(RequestUri::from_string(" ".to_string()), Some(Authority(" ".to_string())));
    Url::parse("").unwrap_err();    // Url::parse() should return error for empty string
}

#[test]
fn test_read_request_line() {
    use method::Method::{Get, Options, Connect, ExtensionMethod};
    use buffer::BufferedStream;
    use memstream::MemReaderFakeStream;

    macro_rules! tt {
        ($value:expr => $expected:expr) => {{
            let expected = $expected;
            let mut stream = BufferedStream::new(
                MemReaderFakeStream::new($value.bytes().collect::<Vec<_>>()));
            assert_eq!(RequestBuffer::new(&mut stream).read_request_line(), expected);
        }}
    }

    tt!("GET / HTTP/1.1\n" => Ok((Get, AbsolutePath(String::from_str("/")), (1, 1))));
    tt!("GET / HTTP/1.1\r\n" => Ok((Get, AbsolutePath(String::from_str("/")), (1, 1))));
    tt!("OPTIONS /foo/bar HTTP/1.1\r\n" => Ok((Options, AbsolutePath(String::from_str("/foo/bar")), (1, 1))));
    tt!("OPTIONS * HTTP/1.1\r\n" => Ok((Options, Star, (1, 1))));
    tt!("CONNECT example.com HTTP/1.1\r\n" => Ok((Connect,
                                                Authority(String::from_str("example.com")),
                                                (1, 1))));
    tt!("FOO /\r\n" => Ok((ExtensionMethod(String::from_str("FOO")), AbsolutePath(String::from_str("/")), (0, 9))));
    tt!("FOO /\n" => Ok((ExtensionMethod(String::from_str("FOO")), AbsolutePath(String::from_str("/")), (0, 9))));
    tt!("get    http://example.com/ HTTP/42.17\r\n"
            => Ok((ExtensionMethod(String::from_str("get")),
                    AbsoluteUri(Url::parse("http://example.com/").unwrap()),
                    (42, 17))));

    // Now for some failing cases.

    // method name is not a token
    tt!("GE,T / HTTP/1.1\r\n" => Err(BadRequest));

    // Request-URI is missing ("HTTP/1.1" isn't a valid Request-URI; I confirmed this by tracing the
    // rule through RFC 2396: the "/" prevents it from being a reg_name authority, and it doesn't
    // satisfy any of the other possibilities for Request-URI either)
    tt!("GET  HTTP/1.1\r\n" => Err(BadRequest));

    // Invalid HTTP-Version
    tt!("GET / HTTX/1.1\r\n" => Err(BadRequest));
}

/// An HTTP request sent to the server.
pub struct Request {
    /// The originating IP address of the request.
    pub remote_addr: Option<SocketAddr>,

    /// The host name and IP address that the request was sent to; this must always be specified for
    /// HTTP/1.1 requests (or the request will be rejected), but for HTTP/1.0 requests the Host
    /// header was not defined, and so this field will probably be None in such cases.
    //host: Option<Host>,  // Now in headers.host

    /// The headers sent with the request.
    pub headers: headers::request::HeaderCollection,

    /// The body of the request; empty for such methods as GET.
    pub body: Vec<u8>,

    /// The HTTP method for the request.
    pub method: Method,

    /// The URI that was requested, as found in the Request-URI of the Request-Line.
    /// You will almost never need to use this; you should prefer the `url` field instead.
    pub request_uri: RequestUri,

    /// Whether to close the TCP connection when the request has been served.
    /// The alternative is keeping the connection open and waiting for another request.
    pub close_connection: bool,

    /// The HTTP version number; typically `(1, 1)` or, less commonly, `(1, 0)`.
    pub version: (usize, usize)
}

/// The URI (Request-URI in RFC 2616) as specified in the Status-Line of an HTTP request
#[derive(PartialEq, Eq)]
pub enum RequestUri {
    /// 'The asterisk "*" means that the request does not apply to a particular resource, but to the
    /// server itself, and is only allowed when the method used does not necessarily apply to a
    /// resource. One example would be "OPTIONS * HTTP/1.1" '
    Star,

    /// 'The absoluteURI form is REQUIRED when the request is being made to a proxy. The proxy is
    /// requested to forward the request or service it from a valid cache, and return the response.
    /// Note that the proxy MAY forward the request on to another proxy or directly to the server
    /// specified by the absoluteURI. In order to avoid request loops, a proxy MUST be able to
    /// recognize all of its server names, including any aliases, local variations, and the numeric
    /// IP address. An example Request-Line would be:
    /// "GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1"'
    AbsoluteUri(Url),

    /// 'To allow for transition to absoluteURIs in all requests in future versions of HTTP, all
    /// HTTP/1.1 servers MUST accept the absoluteURI form in requests, even though HTTP/1.1 clients
    /// will only generate them in requests to proxies.'
    ///
    /// TODO: this shouldn't be a string; it should be further parsed. `extra::net::url` has some
    /// stuff which might help, but isn't public.
    AbsolutePath(String),

    /// 'The authority form is only used by the CONNECT method (CONNECT).'
    ///
    /// TODO: this shouldn't be a string; it should be further parsed. `extra::net::url` has some
    /// stuff which might help, but isn't public.
    Authority(String),
}

impl RequestUri {
    /// Interpret a RFC2616 Request-URI
    fn from_string(request_uri: String) -> Option<RequestUri> {
	if request_uri.is_empty() {
	    None
	} else if &request_uri[] == "*" {
            Some(Star)
        } else if request_uri.as_bytes()[0] as char == '/' {
            Some(AbsolutePath(request_uri))
        } else if request_uri.contains("/") {
            // An authority can't have a slash in it
            match Url::parse(&request_uri[]) {
                Ok(url) => Some(AbsoluteUri(url)),
                Err(_) => None,
            }
        } else {
            // TODO: parse authority with extra::net::url
            Some(Authority(request_uri))
        }
    }
}

impl fmt::Show for RequestUri {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Star => f.write_str("*"),
            AbsoluteUri(ref url) => url.fmt(f),
            AbsolutePath(ref s) => f.write_str(&s[]),
            Authority(ref s) => f.write_str(&s[]),
        }
    }
}

impl Request {

    /// Get a response from an open socket.
    pub fn load(stream: &mut BufferedStream<TcpStream>) -> (Request, Result<(), status::Status>) {
        let mut buffer = RequestBuffer::new(stream);

        // Start out with dummy values
        let mut request = Request {
            remote_addr: buffer.stream.wrapped.peer_name().ok(),
            headers: headers::request::HeaderCollection::new(),
            body: Vec::new(),
            method: Options,
            request_uri: Star,
            close_connection: true,
            version: (0, 0),
        };

        let (method, request_uri, version) = match buffer.read_request_line() {
            Ok(vals) => vals,
            Err(err) => return (request, Err(err)),
        };
        request.method = method;
        request.request_uri = request_uri;
        request.version = version;

        // request.close_connection is deliberately left set to true so that in case of a bad
        // request we can close the connection
        let close_connection = match version {
            (1, 0) => true,
            (1, 1) => false,
            _ => return (request, Err(HttpVersionNotSupported)),
        };

        loop {
            match buffer.read_header() {
                Err(EndOfFile) => panic!("client disconnected, nowhere to send response"),
                Err(EndOfHeaders) => break,
                Err(MalformedHeaderSyntax) => {
                    println!("BAD REQUEST: malformed header (TODO: is this right?)");
                    return (request, Err(BadRequest));
                },
                Err(MalformedHeaderValue) => {
                    println!("Bad header encountered. TODO: handle this better.");
                    // Now just ignore the header
                },
                Ok(header) => {
                    request.headers.insert(header);
                },
            }
        }

        // HTTP/1.0 doesn't have Host, but HTTP/1.1 requires it
        if request.version == (1, 1) && request.headers.host.is_none() {
            println!("BAD REQUEST: host is none for HTTP/1.1 request");
            return (request, Err(BadRequest));
        }

        request.close_connection = close_connection;
        match request.headers.connection {
            Some(ref h) => for v in h.iter() {
                match *v {
                    headers::connection::Connection::Close => {
                        request.close_connection = true;
                        break;
                    },
                    headers::connection::Connection::Token(ref s) if &s[] == "keep-alive" => {
                        request.close_connection = false;
                        // No break; let it be overridden by close should some weird person do that
                    },
                    headers::connection::Connection::Token(_) => (),
                }
            },
            None => (),
        }

        // Read body if its length is specified
        match request.headers.content_length {
            Some(length) => {
                match buffer.read_exact(length) {
                    Ok(body) => request.body = body,
                    Err(_) => return (request, Err(BadRequest))
                }
            },
            None => ()
        }

        (request, Ok(()))
    }
}

/* What follows is most of Go's net/http module's definition of Request.

pub struct Request {
    // GET, POST, etc.
    method: ~Method,

    // The URL requested, constructed from the request line and (if available)
    // the Host header.
    url: ~Url,

    // The HTTP protocol version used; typically (1, 1)
    protocol: (usize, usize),

    // Request headers, all nicely and correctly parsed.
    headers: ~Headers,

    // The message body.
    body: Reader,

    // ContentLength records the length of the associated content.
    // The value -1 indicates that the length is unknown.
    // Values >= 0 indicate that the given number of bytes may
    // be read from Body.
    // For outgoing requests, a value of 0 means unknown if Body is not nil.
    content_length: i64,

    // TransferEncoding lists the transfer encodings from outermost to
    // innermost. An empty list denotes the "identity" encoding.
    // TransferEncoding can usually be ignored; chunked encoding is
    // automatically added and removed as necessary when sending and
    // receiving requests.
    transfer_encoding: ~[~str],

    // Close indicates whether to close the connection after
    // replying to this request.
    close: bool,

    // The host on which the URL is sought.
    // Per RFC 2616, this is either the value of the Host: header
    // or the host name given in the URL itself.
    // It may be of the form "host:port".
    host: ~str,

    // Form contains the parsed form data, including both the URL
    // field's query parameters and the POST or PUT form data.
    // This field is only available after ParseForm is called.
    // The HTTP client ignores Form and uses Body instead.
    form: url.Values,

    // PostForm contains the parsed form data from POST or PUT
    // body parameters.
    // This field is only available after ParseForm is called.
    // The HTTP client ignores PostForm and uses Body instead.
    post_form: url.Values,

    // MultipartForm is the parsed multipart form, including file uploads.
    // This field is only available after ParseMultipartForm is called.
    // The HTTP client ignores MultipartForm and uses Body instead.
    multipart_form: *multipart.Form,

    // Trailer maps trailer keys to values.  Like for Header, if the
    // response has multiple trailer lines with the same key, they will be
    // concatenated, delimited by commas.
    // For server requests, Trailer is only populated after Body has been
    // closed or fully consumed.
    // Trailer support is only partially complete.
    trailer: ~Headers,

    // RemoteAddr allows HTTP servers and other software to record
    // the network address that sent the request, usually for
    // logging. This field is not filled in by ReadRequest and
    // has no defined format. The HTTP server in this package
    // sets RemoteAddr to an "IP:port" address before invoking a
    // handler.
    // This field is ignored by the HTTP client.
    remote_addr: string,

    // RequestURI is the unmodified Request-URI of the
    // Request-Line (RFC 2616, Section 5.1) as sent by the client
    // to a server. Usually the URL field should be used instead.
    // It is an error to set this field in an HTTP client request.
    request_uri: string,

    // TLS allows HTTP servers and other software to record
    // information about the TLS connection on which the request
    // was received. This field is not filled in by ReadRequest.
    // The HTTP server in this package sets the field for
    // TLS-enabled connections before invoking a handler;
    // otherwise it leaves the field nil.
    // This field is ignored by the HTTP client.
    tls: *tls.ConnectionState,
}*/


text:
namespace Igneel.Rendering.Bindings
{
    public interface IViewProjectionMap
    {
        Matrix ViewProj { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace AbstractFactory
{
    public class AccessUser : IUser
    {
        public void Insert(User user)
        {
            Console.WriteLine("在Access中给User插入了一条记录");
        }

        public User GetUser(int id)
        {
            Console.WriteLine("在Access中根据Id得到了一条记录");
            return null;
        }
    }
}


text:
package utils;

/**
 * Created by xdien on 10/6/14.
 */
import android.graphics.Bitmap;
import android.graphics.Matrix;

/**
 * Various bitmap utilities
 *
 * @author alessandro
 *
 */
public class BitmapUtils {

    /**
     * Resize a bitmap
     *
     * @param input
     * @param destWidth
     * @param destHeight
     * @return
     * @throws OutOfMemoryError
     */
    public static Bitmap resizeBitmap( final Bitmap input, int destWidth, int destHeight ) throws OutOfMemoryError {
        return resizeBitmap( input, destWidth, destHeight, 0 );
    }

    /**
     * Resize a bitmap object to fit the passed width and height
     *
     * @param input
     *           The bitmap to be resized
     * @param destWidth
     *           Desired maximum width of the result bitmap
     * @param destHeight
     *           Desired maximum height of the result bitmap
     * @return A new resized bitmap
     * @throws OutOfMemoryError
     *            if the operation exceeds the available vm memory
     */
    public static Bitmap resizeBitmap( final Bitmap input, int destWidth, int destHeight, int rotation ) throws OutOfMemoryError {

        int dstWidth = destWidth;
        int dstHeight = destHeight;
        final int srcWidth = input.getWidth();
        final int srcHeight = input.getHeight();

        if ( rotation == 90 || rotation == 270 ) {
            dstWidth = destHeight;
            dstHeight = destWidth;
        }

        boolean needsResize = false;
        float p;
        if ( ( srcWidth > dstWidth ) || ( srcHeight > dstHeight ) ) {
            needsResize = true;
            if ( ( srcWidth > srcHeight ) && ( srcWidth > dstWidth ) ) {
                p = (float) dstWidth / (float) srcWidth;
                dstHeight = (int) ( srcHeight * p );
            } else {
                p = (float) dstHeight / (float) srcHeight;
                dstWidth = (int) ( srcWidth * p );
            }
        } else {
            dstWidth = srcWidth;
            dstHeight = srcHeight;
        }

        if ( needsResize || rotation != 0 ) {
            Bitmap output;

            if ( rotation == 0 ) {
                output = Bitmap.createScaledBitmap( input, dstWidth, dstHeight, true );
            } else {
                Matrix matrix = new Matrix();
                matrix.postScale( (float) dstWidth / srcWidth, (float) dstHeight / srcHeight );
                matrix.postRotate( rotation );
                output = Bitmap.createBitmap( input, 0, 0, srcWidth, srcHeight, matrix, true );
            }
            return output;
        } else
            return input;
    }

}


text:
CWD=`dirname $0`
CWD=`cd "$APP_DIR";pwd`

START=$(date +%s)
"${CWD}/bin/whiskey" -m 2 --independent-tests "${CWD}/example/test-long-running-1.js ${CWD}/example/test-long-running-2.js"
if [ $? -ne 0 ]; then
    echo "long-running tests should pass"
    exit 1
fi
END=$(date +%s)
DIFF=$(( $END - $START ))
if [ $DIFF -ge 7 ]; then
    echo "Total test execution time should be less than 6 seconds (assuming code hasn't been changed.)"
    exit 1
fi

"${CWD}/bin/whiskey" --independent-tests "${CWD}/example/test-long-running-1.js ${CWD}/example/test-long-running-2.js ${CWD}/example/test-failure.js"
if [ $? -ne 2 ]; then
    echo "2 tests should fail when running tests independently."
    exit 1
fi

"${CWD}/bin/whiskey" --tests "${CWD}/example/test-success.js"

if [ $? -ne 0 ]; then
    echo "tests should pass"
    exit 1
fi

"${CWD}/bin/whiskey" --tests "${CWD}/example/test-failure.js"

if [ $? -ne 2 ]; then
    echo "2 tests should fail"
    exit 1
fi

"${CWD}/bin/whiskey" --failfast --timeout 500 \
  --tests --concurrency 100 "${CWD}/example/test-failure.js ${CWD}/example/test-timeout.js"

if [ $? -ne 1 ]; then
    echo "1 test should fail"
    exit 1
fi

"${CWD}/bin/whiskey" --failfast --timeout 500 \
  --tests "${CWD}/example/test-timeout.js ${CWD}/example/test-failure.js ${CWD}/example/test-timeout.js"

if [ $? -ne 1 ]; then
    echo "1 test should fail"
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 1000 --tests "${CWD}/example/test-timeout.js"

if [ ! $? -eq 1 ]; then
    echo "test should time out"
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 1000 --tests "${CWD}/example/test-timeout-blocking.js"

if [ ! $? -eq 1 ]; then
    echo "test should time out"
    exit 1
fi

"${CWD}/bin/whiskey" --tests "${CWD}/example/test-setup-and-teardown.js"

if [ $? -ne 0 ]; then
    echo "test should pass"
    exit 1
fi

# Test file does not exist
"${CWD}/bin/whiskey" --tests "${CWD}/example/test-inexistent.js"

if [ $? -ne 1 ]; then
    echo "1 test should fail"
    exit 1
fi

"${CWD}/bin/whiskey" --tests "${CWD}/example/test-setup-fail.js"

if [ $? -ne 3 ]; then
    echo "3 tests should fail"
    exit 1
fi

# Test relative path
"${CWD}/bin/whiskey" --tests "example/test-success.js"

if [ $? -ne 0 ]; then
    echo "tests should pass."
    exit 1
fi

# Test multiple files
"${CWD}/bin/whiskey" --tests "${CWD}/example/test-success.js ${CWD}/example/test-failure.js"

if [ ! $? -gt 0 ]; then
    echo "2 tests should fail"
    exit 1
fi

# Test test init file
FOLDER_EXISTS=0
rm -rf ${CWD}/example/test-123456

"${CWD}/bin/whiskey" --test-init-file "${CWD}/example/init.js" --tests "${CWD}/example/test-success.js"

if [ -d ${CWD}/example/test-123456 ]; then
  FOLDER_EXISTS=1
fi

rm -rf ${CWD}/example/test-123456

if [ $? -ne 0 ] || [ ${FOLDER_EXISTS} -ne 1 ]; then
  echo ${FOLDER_EXISTS}
    echo "test should pass m"
    exit 1
fi

# test uncaught exceptions
"${CWD}/bin/whiskey" --tests "${CWD}/example/test-uncaught.js"

if [ $? -ne 5 ]; then
    echo "5 tests should fail"
    exit 1
fi

# Test chdir
"${CWD}/bin/whiskey" --tests "${CWD}/example/test-chdir.js"

if [ $? -ne 1 ]; then
    echo "1 test should fail"
    exit 1
fi

"${CWD}/bin/whiskey" --tests "${CWD}/example/test-chdir.js" --chdir "${CWD}/example/"

if [ $? -ne 0 ]; then
    echo "tests should pass y"
    exit 1
fi

# Test per test init function
"${CWD}/bin/whiskey" --test-init-file "${CWD}/example/init-test.js" --tests "${CWD}/example/test-init-function.js"

if [ $? -ne 0 ]; then
    echo "tests should pass x"
    exit 1
fi

# Test init function timeout (callback in init function is not called)
"${CWD}/bin/whiskey" --timeout 2000 --test-init-file "${CWD}/example/init-timeout.js" --tests "${CWD}/example/test-failure.js"

if [ $? -ne 1 ]; then
    echo "1 test should fail (callback in init function is not called)"
    exit 1
fi

# Test setUp function timeout (setUp function .finish() is not called)
"${CWD}/bin/whiskey" --timeout 1000 --tests "${CWD}/example/test-setup-timeout.js" --chdir "${CWD}/example/"

if [ $? -ne 1 ]; then
  echo "1 test should fail (setUp timeout)"
    exit 1
fi

# Test tearDown function timeout (tearDown function .finish() is not called)
"${CWD}/bin/whiskey" --timeout 2000 --tests "${CWD}/example/test-teardown-timeout.js" --chdir "${CWD}/example/"

if [ $? -ne 2 ]; then
    echo "1 test should fail (tearDown timeout)"
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 2000 --tests "${CWD}/example/test-custom-assert-functions.js"

if [ $? -ne 2 ]; then
    echo "2 tests should fail"
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 2000 \
 --tests "${CWD}/example/test-custom-assert-functions.js" \
 --custom-assert-module "${CWD}/example/custom-assert-functions.js"

if [ $? -ne 1 ]; then
    echo "1 test should fail"
    exit 1
fi

"${CWD}/example/test-stdout-and-stderr-is-captured-on-timeout.js"

if [ $? -ne 0 ]; then
    echo "test file stdout and stderr was not properly captured during test timeout"
    exit 1
fi

# Verify that when a test file timeout the tests which haven't time out are
# reported properly
"${CWD}/example/test-succeeded-tests-are-reported-on-timeout.js"

if [ $? -ne 0 ]; then
    echo "succeeded tests were not reported properly upon a test file timeout"
    exit 1
fi

# Verify that coverage works properly
if [ "$(which jscoverage)" ]; then
  "${CWD}/example/test-jscoverage.js"

  if [ $? -ne 0 ]; then
      echo "coverage does not work properly"
      exit 1
  fi
else
  echo 'jscoverage not installed, skipping coverage tests'
fi

# Make sure that the child which blocks after call .finish() is killed and
# timeout properly reported
"${CWD}/bin/whiskey" --timeout 1000 \
 --tests "${CWD}/example/test-timeout-after-finish.js"

if [ $? -ne 1 ]; then
    echo "1 test should timeout"
    exit 1
fi

# Scope leaks test (sequential and parallel mode)
"${CWD}/example/test-leaks.js"

if [ $? -ne 0 ]; then
    echo "scope leaks were not reported properly"
    exit 1
fi

# No test function is exported, it should quit immediately
"${CWD}/bin/whiskey" --timeout 1000 \
 --tests "${CWD}/example/test-no-test-functions.js"

if [ $? -ne 0 ]; then
    echo "test didn't exit with zero exit code"
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 1000 \
 --tests "${CWD}/example/test-skipped.js"

if [ $? -ne 0 ]; then
    echo "test didn't exit with zero exit code"
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 1000 \
 --tests "${CWD}/example/test-custom-assert-methods.js"

if [ $? -ne 0 ]; then
    echo "test didn't exit with zero exit code"
    exit 1
fi

# Test pattern name matching
"${CWD}/bin/whiskey" --timeout 1000 \
 --tests "example.test-failure.test_one_is_not*"

if [ $? -ne 1 ]; then
    echo "test didn't exit with 1 exit code"
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 1000 \
 --tests "${CWD}/example/test-getFilePathAndPattern.js"

if [ $? -ne 0 ]; then
    echo "test didn't exit with zero exit code"
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 1000 \
 --tests "${CWD}/example/test-spyon.js"

if [ $? -ne 0 ]; then
    echo "Test didn't exit with zero exit code."
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 1000 \
--tests "${CWD}/example/test-bdd.js"

if [ $? -ne 0 ]; then
    echo "BDD test didn't exit with zero exit code."
    exit 1
fi

"${CWD}/bin/whiskey" --timeout 1000 \
--tests "${CWD}/example/test-bdd-failures.js"

if [ $? -ne 4 ]; then
    echo "BDD failure test didn't fail as expected."
    exit 1
fi

echo ""
echo "* * * Whiskey test suite PASSED. * * *"
exit 0


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.client.editor.simple.components;

import com.google.appinventor.client.editor.simple.SimpleEditor;
import com.google.appinventor.client.widgets.Icon;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;

/**
 * Class for components without a visual representation, such as sensors.
 *
 *
To add a new non-visual component:
 *

 *
 Put the image for the component's icon in {@code
 *        appengine/src/com/google/appinventor/images/FILENAME}
 *        (substituting the actual filename).
 *
 In the class implementing the component (in the directory
 *        {@code components/src/com/google/appinventor/components/runtime/}),
 *        make sure the
 *        {@link com.google.appinventor.components.annotations.DesignerComponent} annotation
 *        includes the following key-value pairs:
 *

 *
 nonVisible = true
 *
 iconName = "images/FILENAME"
 *

 *
 For good performance in fetching image files:
 *

 *
 Add a {@link com.google.gwt.resources.client.ClientBundle.Source}
 *                 annotation and corresponding method to
 *                 {@code appengine/src/com/google/appinventor/client/Images.java}.
 *
 Add a mapping from the name of the icon to this new method to the method
 *                 {@code initBundledImages()} in {@code
 *                 appengine/src/com/google/appinventor/client/editor/simple/palette/SimpleComponentDescriptor.java}.
 *

 *

 *
 * @author sharon@google.com (Sharon Perl)
 */
public final class MockNonVisibleComponent extends MockComponent {

  private final Icon iconWidget;

  /**
   * Creates a new instance of a non-visible component whose icon is
   * loaded dynamically (not part of the icon image bundle)
   */
  public MockNonVisibleComponent(SimpleEditor editor, String type, Image iconImage) {
    super(editor, type, iconImage);
    iconWidget = new Icon(iconImage);

    initComponent(iconWidget);
  }

  @Override
  public final void initComponent(Widget widget) {
    super.initComponent(widget);
  }

  /**
   * {@inheritDoc}
   *
   * This is always {@code false} for subclasses of this class.
   */
  @Override
  public final boolean isVisibleComponent() {
    return false;
  }

  @Override
  public final int getPreferredHeight() {
    return 0;
  }

  @Override
  public final int getPreferredWidth() {
    return 0;
  }

  @Override
  protected final void onSelectedChange(boolean selected) {
    super.onSelectedChange(selected);
    if (selected) {
      iconWidget.select();
    } else {
      iconWidget.deselect();
    }
  }

  // PropertyChangeListener implementation

  @Override
  public void onPropertyChange(String propertyName, String newValue) {
    super.onPropertyChange(propertyName, newValue);

    // No visual changes after property changes (other than icon name).
    if (propertyName.equals(PROPERTY_NAME_NAME)) {
      iconWidget.setCaption(newValue);
    }
  }
}


text:
@import url(http://fonts.googleapis.com/css?family=Montserrat);

/*basic reset*/

* {
    margin: 0;
    padding: 0;
}

/*forcing the body to take 100% height*/

html,
body {
    min-height: 100%;
}

/*a nice BG*/

body {
    background: #544;
    /*fallback*/
    background: linear-gradient(#544, #565);
}

/*Thumbnail Background*/

.thumb {
    width: 400px;
    height: 300px;
    margin: 70px auto;
    perspective: 1000px;
}

.thumb a {
    display: block;
    width: 100%;
    height: 100%;
    /*double layered BG for lighting effect*/
    background: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url("./1.jpg");
    /*disabling the translucent black bg on the main image*/
    background-size: 0, cover;
    /*3d space for children*/
    transform-style: preserve-3d;
    transform: rotateY(-45deg);
    transition: all 0.5s;
    //animation: swing 5s infinite 0.5s ease;
}

.thumb:hover a {
    animation: 0;
    transition: all 0.5s;
    //transform: rotateY(-30deg) rotateY(30deg) rotateX(80deg);
    transform-origin: bottom;

}

.thumb a:active {
    background-image: url("./2.jpg");
}

/*bottom surface */

.thumb a:after {
    /*36px high element positioned at the bottom of the image*/
    content: '';
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 36px;
    /*inherit the main BG*/
    background: inherit;
    background-size: cover, cover;
    /*draw the BG bottom up*/
    background-position: bottom;
    /*rotate the surface 90deg on the bottom axis*/
    transform: rotateX(90deg);
    transform-origin: bottom;
}

/*label style*/

.thumb a span {
    color: white;
    text-transform: uppercase;
    position: absolute;
    font: bold 12px/36px Montserrat;
    text-align: center;
    /*the rotation is a bit less than the bottom surface to avoid flickering*/
    transform: rotateY(89.99deg);
    transform-origin: left;
    z-index: 1;
    display: inline-block;
    width: 36px;
    word-break: break-all;
    line-height: 20px;
    height: 300px;
    left: 100%;
    background: inherit;
    background-size: cover,cover;
    background-position: right;
}

/*shadow*/

.thumb a:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    box-shadow: 0 0 100px 50px rgba(0, 0, 0, 0.5);
    transition: all 0.5s;
    /*by default the shadow will be almost flat, very transparent, scaled down with a large blur*/
    opacity: 0.15;
    transform: rotateX(95deg) translateZ(-80px) scale(0.75);
    transform-origin: bottom;
}

.thumb:hover a:before {
    opacity: 1;
    /*blurred effect using box shadow as filter: blur is not supported in all browsers*/
    box-shadow: 0 0 25px 25px rgba(0, 0, 0, 0.5);
    /*pushing the shadow down and scaling it down to size*/
    transform: rotateX(0) translateZ(-60px) scale(0.85);
}

@keyframes swing {
    0% {
        transform: translateY(0) rotateY(-45deg);
    }
    50% {
        transform: translateY(50px) rotateY(-15deg);
    }
    0% {
        transform: translateY(0) rotateY(-45deg);
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM /builds/slave/rel-2.0-xr-osx64-bld/build/dom/interfaces/events/nsIDOMMouseScrollEvent.idl
 */

#ifndef __gen_nsIDOMMouseScrollEvent_h__
#define __gen_nsIDOMMouseScrollEvent_h__

#ifndef __gen_nsIDOMMouseEvent_h__
#include "nsIDOMMouseEvent.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif

/* starting interface:    nsIDOMMouseScrollEvent */
#define NS_IDOMMOUSESCROLLEVENT_IID_STR "ba8d1a7e-b475-4542-8d32-01e7ea7b8091"

#define NS_IDOMMOUSESCROLLEVENT_IID \
  {0xba8d1a7e, 0xb475, 0x4542, \
    { 0x8d, 0x32, 0x01, 0xe7, 0xea, 0x7b, 0x80, 0x91 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMMouseScrollEvent : public nsIDOMMouseEvent {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMMOUSESCROLLEVENT_IID)

  enum { HORIZONTAL_AXIS = 1 };

  enum { VERTICAL_AXIS = 2 };

  /* readonly attribute long axis; */
  NS_SCRIPTABLE NS_IMETHOD GetAxis(PRInt32 *aAxis) = 0;

  /* void initMouseScrollEvent (in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in nsIDOMAbstractView viewArg, in long detailArg, in long screenXArg, in long screenYArg, in long clientXArg, in long clientYArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in unsigned short buttonArg, in nsIDOMEventTarget relatedTargetArg, in long axis); */
  NS_SCRIPTABLE NS_IMETHOD InitMouseScrollEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRInt32 detailArg, PRInt32 screenXArg, PRInt32 screenYArg, PRInt32 clientXArg, PRInt32 clientYArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint16 buttonArg, nsIDOMEventTarget *relatedTargetArg, PRInt32 axis) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMMouseScrollEvent, NS_IDOMMOUSESCROLLEVENT_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMMOUSESCROLLEVENT \
  NS_SCRIPTABLE NS_IMETHOD GetAxis(PRInt32 *aAxis); \
  NS_SCRIPTABLE NS_IMETHOD InitMouseScrollEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRInt32 detailArg, PRInt32 screenXArg, PRInt32 screenYArg, PRInt32 clientXArg, PRInt32 clientYArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint16 buttonArg, nsIDOMEventTarget *relatedTargetArg, PRInt32 axis);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMMOUSESCROLLEVENT(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetAxis(PRInt32 *aAxis) { return _to GetAxis(aAxis); } \
  NS_SCRIPTABLE NS_IMETHOD InitMouseScrollEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRInt32 detailArg, PRInt32 screenXArg, PRInt32 screenYArg, PRInt32 clientXArg, PRInt32 clientYArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint16 buttonArg, nsIDOMEventTarget *relatedTargetArg, PRInt32 axis) { return _to InitMouseScrollEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg, screenXArg, screenYArg, clientXArg, clientYArg, ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg, buttonArg, relatedTargetArg, axis); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMMOUSESCROLLEVENT(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetAxis(PRInt32 *aAxis) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAxis(aAxis); } \
  NS_SCRIPTABLE NS_IMETHOD InitMouseScrollEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRInt32 detailArg, PRInt32 screenXArg, PRInt32 screenYArg, PRInt32 clientXArg, PRInt32 clientYArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint16 buttonArg, nsIDOMEventTarget *relatedTargetArg, PRInt32 axis) { return !_to ? NS_ERROR_NULL_POINTER : _to->InitMouseScrollEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg, screenXArg, screenYArg, clientXArg, clientYArg, ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg, buttonArg, relatedTargetArg, axis); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsDOMMouseScrollEvent : public nsIDOMMouseScrollEvent
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIDOMMOUSESCROLLEVENT

  nsDOMMouseScrollEvent();

private:
  ~nsDOMMouseScrollEvent();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMMouseScrollEvent, nsIDOMMouseScrollEvent)

nsDOMMouseScrollEvent::nsDOMMouseScrollEvent()
{
  /* member initializers and constructor code */
}

nsDOMMouseScrollEvent::~nsDOMMouseScrollEvent()
{
  /* destructor code */
}

/* readonly attribute long axis; */
NS_IMETHODIMP nsDOMMouseScrollEvent::GetAxis(PRInt32 *aAxis)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void initMouseScrollEvent (in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in nsIDOMAbstractView viewArg, in long detailArg, in long screenXArg, in long screenYArg, in long clientXArg, in long clientYArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in unsigned short buttonArg, in nsIDOMEventTarget relatedTargetArg, in long axis); */
NS_IMETHODIMP nsDOMMouseScrollEvent::InitMouseScrollEvent(const nsAString & typeArg, PRBool canBubbleArg, PRBool cancelableArg, nsIDOMAbstractView *viewArg, PRInt32 detailArg, PRInt32 screenXArg, PRInt32 screenYArg, PRInt32 clientXArg, PRInt32 clientYArg, PRBool ctrlKeyArg, PRBool altKeyArg, PRBool shiftKeyArg, PRBool metaKeyArg, PRUint16 buttonArg, nsIDOMEventTarget *relatedTargetArg, PRInt32 axis)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIDOMMouseScrollEvent_h__ */


text:
import { NodeDef, PureExpressionData, ViewData } from './types';
export declare function purePipeDef(argCount: number): NodeDef;
export declare function pureArrayDef(argCount: number): NodeDef;
export declare function pureObjectDef(propToIndex: {
    [p: string]: number;
}): NodeDef;
export declare function createPureExpression(view: ViewData, def: NodeDef): PureExpressionData;
export declare function checkAndUpdatePureExpressionInline(view: ViewData, def: NodeDef, v0: any, v1: any, v2: any, v3: any, v4: any, v5: any, v6: any, v7: any, v8: any, v9: any): boolean;
export declare function checkAndUpdatePureExpressionDynamic(view: ViewData, def: NodeDef, values: any[]): boolean;


text:
module Fastlane
  module Actions
    class LastGitCommitAction < Action
      def self.run(params)
        Actions.last_git_commit_dict
      end

      #####################################################
      # @!group Documentation
      #####################################################

      def self.description
        "Return last git commit hash, abbreviated commit hash, commit message and author"
      end

      def self.return_value
        "Returns the following dict: {commit_hash: \"commit hash\", abbreviated_commit_hash: \"abbreviated commit hash\" author: \"Author\", message: \"commit message\"}"
      end

      def self.author
        "ngutman"
      end

      def self.is_supported?(platform)
        true
      end
    end
  end
end


text:
/* Author: Ioan Sucan */

#include "ompl/base/goals/GoalState.h"
#include "ompl/base/SpaceInformation.h"

ompl::base::GoalState::~GoalState()
{
    if (state_)
        si_->freeState(state_);
}

double ompl::base::GoalState::distanceGoal(const State *st) const
{
    return si_->distance(st, state_);
}

void ompl::base::GoalState::print(std::ostream &out) const
{
    out << "Goal state, threshold = " << threshold_ << ", memory address = " << this << ", state = " << std::endl;
    si_->printState(state_, out);
}

void ompl::base::GoalState::sampleGoal(base::State *st) const
{
    si_->copyState(st, state_);
}

unsigned int ompl::base::GoalState::maxSampleCount() const
{
    return 1;
}

void ompl::base::GoalState::setState(const State *st)
{
    if (state_)
        si_->freeState(state_);
    state_ = si_->cloneState(st);
}

void ompl::base::GoalState::setState(const ScopedState<> &st)
{
    setState(st.get());
}

const ompl::base::State *ompl::base::GoalState::getState() const
{
    return state_;
}

ompl::base::State *ompl::base::GoalState::getState()
{
    return state_;
}


text: It's a [Cordova](https://cordova.apache.org/) app.


text:
namespace rsm {
class VersionTracker {
public:
  enum Type {
    Application,
    Library
  };

  class Entity {
  public:
    Entity(const char* aVersionString, const VersionTracker::Type aEntityType);

  private:
    friend class VersionTracker;
    const char* versionString;
    const VersionTracker::Type entityType;
  };

  ::std::string getAllVersions() const;
  static VersionTracker& getInstance();

private:
  void registerEntity(const Entity& entity);

private:
  friend class Entity;
  const Entity* application = nullptr;
  std::vector<const Entity*> libraries;
};
}

#define VERSION_TRACKER_UNIQUE_NAME_INTERNAL_JOIN( prefix, line) prefix ## line
#define VERSION_TRACKER_UNIQUE_NAME_INTERNAL( prefix, line) VERSION_TRACKER_UNIQUE_NAME_INTERNAL_JOIN( prefix, line)
#define VERSION_TRACKER_UNIQUE_NAME( prefix ) VERSION_TRACKER_UNIQUE_NAME_INTERNAL( prefix, __LINE__)

#define REGISTER_APPLICATION_VERSION(applicationName, version) \
  namespace { \
  const rsm::VersionTracker::Entity VERSION_TRACKER_UNIQUE_NAME( _VERSION_TRACKER_APP ) ( "Application: " applicationName " (Version: " version ")", rsm::VersionTracker::Application ); \
  }

#define REGISTER_LIBRARY_VERSION(libraryName, version) \
  namespace { \
  const rsm::VersionTracker::Entity VERSION_TRACKER_UNIQUE_NAME( _VERSION_TRACKER_LIB ) ( "Library: " libraryName " (Version: " version ")", rsm::VersionTracker::Library ); \
  }


text:
package AsposeCellsExamples.Tables;

import com.aspose.cells.Workbook;
import AsposeCellsExamples.Utils;

public class ConvertTableToRange {
	public static void main(String[] args) throws Exception {
		// The path to the documents directory.
		String dataDir = Utils.getSharedDataDir(ConvertTableToRange.class) + "Tables/";
		// Open an existing file that contains a table/list object in it
		Workbook wb = new Workbook(dataDir + "book1.xlsx");

		// Convert the first table/list object (from the first worksheet) to normal range
		wb.getWorksheets().get(0).getListObjects().get(0).convertToRange();

		// Save the file
		wb.save(dataDir + "ConvertTableToRange_out.xlsx");
	}
}


text:
<link rel="import" href="../forge-shared/polymer.html">

<link rel="import" href="../forge-shared/forge-shared.html">

<dom-module id="forge-status-card">

  <template>

    <paper-card class$="status-card status-[[status]]">

        <iron-icon class="role-icon" icon="[[icon]]"></iron-icon>

[[localize(role)]]

    </paper-card>

  </template>

</dom-module>


text:
<?php

namespace BingAds\CampaignManagement;

/**
 * This feature is currently in pilot and will be generally available soon.
 *
 * @link http://msdn.microsoft.com/en-us/library/dn913136(v=msads.90).aspx GetCampaignCriterionsByCampaignId Request Object
 *
 * @uses CampaignCriterionType
 * @used-by BingAdsCampaignManagementService::GetCampaignCriterionsByCampaignId
 */
final class GetCampaignCriterionsByCampaignIdRequest
{
    /**
     * The identifier of the campaign that contains the criterions to get.
     *
     * @var int
     */
    public $CampaignId;
    /**
     * The types of campaign criterion to get, for example ProductScope.
     *
     * @var CampaignCriterionType
     */
    public $CriterionType;
}


text:
/**
 * Created by jackytianer on 15/10/26.
 */
angular.module('ui.tx', [])
    .directive('dtp', ['$timeout', function ($timeout) {
        return {
            stricts: 'EA',
            require: '^ngModel',
            replace: 'false',
            templateUrl: 'components/datetimepicker/dateTimPickerTemplate.html',
            scope: {},
            link: function (scope, ele, attrs, modelCtrl) {
                var uDtpElement = ele[0].querySelector('.u-dtp-content');
                if(!uDtpElement) return;
                uDtpElement.addEventListener('scroll', function (e) {
                    if (this.scrollTop === 0) {
                        $timeout(function () {
                            scope.setPreviousMonth(3, scope.offsetMonth, scope.source.result);
                            this.scrollTop = scope.eleHeight * 3;
                        }.bind(this), 100)
                    }
                    if (this.clientHeight + this.scrollTop >= this.scrollHeight) {
                        $timeout(function () {
                            scope.setNextMonth(3, scope.offsetMonth, scope.source.result);
                            this.scrollTop = this.scrollHeight - scope.eleHeight * 3;
                        }.bind(this), 100)
                    }
                });
                scope.$watch('source.crtDate', function (newV, oldV) {
                    scope.crtTimestamp = new Date(newV).setHours(0, 0, 0, 0 );
                    if (newV) {
                        var date = new Date(newV);
                        date.setDate(1);
                        date.setHours(0, 0, 0, 0);
                        for (var i = 0; i < scope.source.result.length; i++) {
                            if (date.getTime() === scope.source.result[i].date.getTime()) {
                                uDtpElement.scrollTop = i * scope.eleHeight;
                            }
                        }
                    }

                });

            },
            controller: ['$scope', '$filter', 'dtpService', function ($scope, $filter, dtpService) {
                $scope.offsetMonth = {
                    start: 2,
                    end: 2
                }
                // 列表数据源
                $scope.source = {
                    today: new Date(new Date().setHours(0, 0, 0, 0)),
                    crtDate: $filter('date')(new Date(), 'yyyy-MM-dd'),
                    crtTime: new Date(),
                    result: dtpService.getInitResult($scope.offsetMonth)
                };

                $scope.setDate = function (day) {
                    $scope.source.crtDate = $filter('date')(day, 'yyyy-MM-dd');
                    $scope.crtTimestamp = day.getTime();
                }

                $scope.eleHeight = dtpService.HEIGHT;
                $scope.offsetMonth = dtpService.offsetMonth;
                $scope.setPreviousMonth = dtpService.setPreviousMonth.bind(dtpService);
                $scope.setNextMonth = dtpService.setNextMonth.bind(dtpService);
            }]
        }
    }])
    .service('dtpService', [function () {
        var MS_OF_DAY = 24 * 3600 * 1000;
        this.HEIGHT = 176;

        this.crtPosition = 2;
        this.source = {
            crtDate: new Date()
        }

        this.offsetMonth = {
            start: 2,
            end: 2
        }

        var getResultInSource = function (crtDate, start, end) {
            var result = [];
            for (var l = crtDate.getMonth(), i = l - start; i <= l + end; i++) {
                var dateObj = {
                    date: '',
                    days: []
                }
                var mfirst = new Date();
                mfirst.setFullYear(mfirst.getFullYear(), i, 1);
                mfirst.setHours(0, 0, 0, 0);
                dateObj.date = mfirst;
                var mfirstTime = +mfirst;
                var nfirst = new Date();
                nfirst.setFullYear(nfirst.getFullYear(), i + 1, 1);
                var nfirstTime = +nfirst;
                var lastTime = nfirstTime + ((7 - nfirst.getDay()) % 7 - 1) * MS_OF_DAY;
                var num = -mfirst.getDay();
                var tmpTime, tmp;
                do {
                    tmpTime = mfirstTime + (num++) * MS_OF_DAY;
                    tmp = new Date(tmpTime);
                    dateObj.days.push(tmp);
                } while (tmpTime < lastTime);
                result.push(dateObj);
            }
            return result;
        }

        this.getInitResult = function (obj) {
            //this.source.result = getResultInSource(this.source.crtDate, this.offsetMonth.start, this.offsetMonth.end);
            return getResultInSource(this.source.crtDate, obj.start, obj.end);
        };

        this.setPreviousMonth = function (offset, obj, objResult) {
            var offset = offset || 3;
            var result = getResultInSource(this.source.crtDate, obj.start + offset, -obj.start - 1);
            for (var i = result.length - 1; i >= 0; i--) {
                //this.source.result.unshift(result[i]);
                objResult.unshift(result[i]);
            }
            obj.start += offset;
            //this.offsetMonth.start += offset;
        };
        this.setNextMonth = function (offset, obj, objResult) {
            var offset = offset || 3;
            var result = getResultInSource(this.source.crtDate, -obj.end - 1, obj.end + offset);
            for (var i in  result) {
                //this.source.result.push(result[i]);
                objResult.push(result[i]);
            }
            obj.end += offset;
            //this.offsetMonth.end += offset;
        }
    }])


text:
Clone this repository
```bash
git clone https://github.com/h2non/thread.js && cd thread.js
```

Install the `http-server` package (`node.js` required)
```bash
npm install -g http-server
```

Start the server (from the repository root directory)
```
http-server
```

Finally, open it in a browser
```
http://localhost:8080/examples
```


text:
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/videodev2.h>

#include <linux/dma-mapping.h>

#include <video/omapdss.h>

#include "omap_voutlib.h"

MODULE_AUTHOR("Texas Instruments");
MODULE_DESCRIPTION("OMAP Video library");
MODULE_LICENSE("GPL");

/* Return the default overlay cropping rectangle in crop given the image
 * size in pix and the video display size in fbuf.  The default
 * cropping rectangle is the largest rectangle no larger than the capture size
 * that will fit on the display.  The default cropping rectangle is centered in
 * the image.  All dimensions and offsets are rounded down to even numbers.
 */
void omap_vout_default_crop(struct v4l2_pix_format *pix,
		  struct v4l2_framebuffer *fbuf, struct v4l2_rect *crop)
{
	crop->width = (pix->width < fbuf->fmt.width) ?
		pix->width : fbuf->fmt.width;
	crop->height = (pix->height < fbuf->fmt.height) ?
		pix->height : fbuf->fmt.height;
	crop->width &= ~1;
	crop->height &= ~1;
	crop->left = ((pix->width - crop->width) >> 1) & ~1;
	crop->top = ((pix->height - crop->height) >> 1) & ~1;
}
EXPORT_SYMBOL_GPL(omap_vout_default_crop);

/* Given a new render window in new_win, adjust the window to the
 * nearest supported configuration.  The adjusted window parameters are
 * returned in new_win.
 * Returns zero if successful, or -EINVAL if the requested window is
 * impossible and cannot reasonably be adjusted.
 */
int omap_vout_try_window(struct v4l2_framebuffer *fbuf,
			struct v4l2_window *new_win)
{
	struct v4l2_rect try_win;

	/* make a working copy of the new_win rectangle */
	try_win = new_win->w;

	/* adjust the preview window so it fits on the display by clipping any
	 * offscreen areas
	 */
	if (try_win.left < 0) {
		try_win.width += try_win.left;
		try_win.left = 0;
	}
	if (try_win.top < 0) {
		try_win.height += try_win.top;
		try_win.top = 0;
	}
	try_win.width = (try_win.width < fbuf->fmt.width) ?
		try_win.width : fbuf->fmt.width;
	try_win.height = (try_win.height < fbuf->fmt.height) ?
		try_win.height : fbuf->fmt.height;
	if (try_win.left + try_win.width > fbuf->fmt.width)
		try_win.width = fbuf->fmt.width - try_win.left;
	if (try_win.top + try_win.height > fbuf->fmt.height)
		try_win.height = fbuf->fmt.height - try_win.top;
	try_win.width &= ~1;
	try_win.height &= ~1;

	if (try_win.width <= 0 || try_win.height <= 0)
		return -EINVAL;

	/* We now have a valid preview window, so go with it */
	new_win->w = try_win;
	new_win->field = V4L2_FIELD_ANY;
	return 0;
}
EXPORT_SYMBOL_GPL(omap_vout_try_window);

/* Given a new render window in new_win, adjust the window to the
 * nearest supported configuration.  The image cropping window in crop
 * will also be adjusted if necessary.  Preference is given to keeping the
 * the window as close to the requested configuration as possible.  If
 * successful, new_win, vout->win, and crop are updated.
 * Returns zero if successful, or -EINVAL if the requested preview window is
 * impossible and cannot reasonably be adjusted.
 */
int omap_vout_new_window(struct v4l2_rect *crop,
		struct v4l2_window *win, struct v4l2_framebuffer *fbuf,
		struct v4l2_window *new_win)
{
	int err;

	err = omap_vout_try_window(fbuf, new_win);
	if (err)
		return err;

	/* update our preview window */
	win->w = new_win->w;
	win->field = new_win->field;
	win->chromakey = new_win->chromakey;

	/* Adjust the cropping window to allow for resizing limitation */
	if (omap_vout_dss_omap24xx()) {
		/* For 24xx limit is 8x to 1/2x scaling. */
		if ((crop->height/win->w.height) >= 2)
			crop->height = win->w.height * 2;

		if ((crop->width/win->w.width) >= 2)
			crop->width = win->w.width * 2;

		if (crop->width > 768) {
			/* The OMAP2420 vertical resizing line buffer is 768
			 * pixels wide. If the cropped image is wider than
			 * 768 pixels then it cannot be vertically resized.
			 */
			if (crop->height != win->w.height)
				crop->width = 768;
		}
	} else if (omap_vout_dss_omap34xx()) {
		/* For 34xx limit is 8x to 1/4x scaling. */
		if ((crop->height/win->w.height) >= 4)
			crop->height = win->w.height * 4;

		if ((crop->width/win->w.width) >= 4)
			crop->width = win->w.width * 4;
	}
	return 0;
}
EXPORT_SYMBOL_GPL(omap_vout_new_window);

/* Given a new cropping rectangle in new_crop, adjust the cropping rectangle to
 * the nearest supported configuration.  The image render window in win will
 * also be adjusted if necessary.  The preview window is adjusted such that the
 * horizontal and vertical rescaling ratios stay constant.  If the render
 * window would fall outside the display boundaries, the cropping rectangle
 * will also be adjusted to maintain the rescaling ratios.  If successful, crop
 * and win are updated.
 * Returns zero if successful, or -EINVAL if the requested cropping rectangle is
 * impossible and cannot reasonably be adjusted.
 */
int omap_vout_new_crop(struct v4l2_pix_format *pix,
	      struct v4l2_rect *crop, struct v4l2_window *win,
	      struct v4l2_framebuffer *fbuf, const struct v4l2_rect *new_crop)
{
	struct v4l2_rect try_crop;
	unsigned long vresize, hresize;

	/* make a working copy of the new_crop rectangle */
	try_crop = *new_crop;

	/* adjust the cropping rectangle so it fits in the image */
	if (try_crop.left < 0) {
		try_crop.width += try_crop.left;
		try_crop.left = 0;
	}
	if (try_crop.top < 0) {
		try_crop.height += try_crop.top;
		try_crop.top = 0;
	}
	try_crop.width = (try_crop.width < pix->width) ?
		try_crop.width : pix->width;
	try_crop.height = (try_crop.height < pix->height) ?
		try_crop.height : pix->height;
	if (try_crop.left + try_crop.width > pix->width)
		try_crop.width = pix->width - try_crop.left;
	if (try_crop.top + try_crop.height > pix->height)
		try_crop.height = pix->height - try_crop.top;

	try_crop.width &= ~1;
	try_crop.height &= ~1;

	if (try_crop.width <= 0 || try_crop.height <= 0)
		return -EINVAL;

	if (omap_vout_dss_omap24xx()) {
		if (try_crop.height != win->w.height) {
			/* If we're resizing vertically, we can't support a
			 * crop width wider than 768 pixels.
			 */
			if (try_crop.width > 768)
				try_crop.width = 768;
		}
	}
	/* vertical resizing */
	vresize = (1024 * try_crop.height) / win->w.height;
	if (omap_vout_dss_omap24xx() && (vresize > 2048))
		vresize = 2048;
	else if (omap_vout_dss_omap34xx() && (vresize > 4096))
		vresize = 4096;

	win->w.height = ((1024 * try_crop.height) / vresize) & ~1;
	if (win->w.height == 0)
		win->w.height = 2;
	if (win->w.height + win->w.top > fbuf->fmt.height) {
		/* We made the preview window extend below the bottom of the
		 * display, so clip it to the display boundary and resize the
		 * cropping height to maintain the vertical resizing ratio.
		 */
		win->w.height = (fbuf->fmt.height - win->w.top) & ~1;
		if (try_crop.height == 0)
			try_crop.height = 2;
	}
	/* horizontal resizing */
	hresize = (1024 * try_crop.width) / win->w.width;
	if (omap_vout_dss_omap24xx() && (hresize > 2048))
		hresize = 2048;
	else if (omap_vout_dss_omap34xx() && (hresize > 4096))
		hresize = 4096;

	win->w.width = ((1024 * try_crop.width) / hresize) & ~1;
	if (win->w.width == 0)
		win->w.width = 2;
	if (win->w.width + win->w.left > fbuf->fmt.width) {
		/* We made the preview window extend past the right side of the
		 * display, so clip it to the display boundary and resize the
		 * cropping width to maintain the horizontal resizing ratio.
		 */
		win->w.width = (fbuf->fmt.width - win->w.left) & ~1;
		if (try_crop.width == 0)
			try_crop.width = 2;
	}
	if (omap_vout_dss_omap24xx()) {
		if ((try_crop.height/win->w.height) >= 2)
			try_crop.height = win->w.height * 2;

		if ((try_crop.width/win->w.width) >= 2)
			try_crop.width = win->w.width * 2;

		if (try_crop.width > 768) {
			/* The OMAP2420 vertical resizing line buffer is
			 * 768 pixels wide.  If the cropped image is wider
			 * than 768 pixels then it cannot be vertically resized.
			 */
			if (try_crop.height != win->w.height)
				try_crop.width = 768;
		}
	} else if (omap_vout_dss_omap34xx()) {
		if ((try_crop.height/win->w.height) >= 4)
			try_crop.height = win->w.height * 4;

		if ((try_crop.width/win->w.width) >= 4)
			try_crop.width = win->w.width * 4;
	}
	/* update our cropping rectangle and we're done */
	*crop = try_crop;
	return 0;
}
EXPORT_SYMBOL_GPL(omap_vout_new_crop);

/* Given a new format in pix and fbuf,  crop and win
 * structures are initialized to default values. crop
 * is initialized to the largest window size that will fit on the display.  The
 * crop window is centered in the image. win is initialized to
 * the same size as crop and is centered on the display.
 * All sizes and offsets are constrained to be even numbers.
 */
void omap_vout_new_format(struct v4l2_pix_format *pix,
		struct v4l2_framebuffer *fbuf, struct v4l2_rect *crop,
		struct v4l2_window *win)
{
	/* crop defines the preview source window in the image capture
	 * buffer
	 */
	omap_vout_default_crop(pix, fbuf, crop);

	/* win defines the preview target window on the display */
	win->w.width = crop->width;
	win->w.height = crop->height;
	win->w.left = ((fbuf->fmt.width - win->w.width) >> 1) & ~1;
	win->w.top = ((fbuf->fmt.height - win->w.height) >> 1) & ~1;
}
EXPORT_SYMBOL_GPL(omap_vout_new_format);

/*
 * Allocate buffers
 */
unsigned long omap_vout_alloc_buffer(u32 buf_size, u32 *phys_addr)
{
	u32 order, size;
	unsigned long virt_addr, addr;

	size = PAGE_ALIGN(buf_size);
	order = get_order(size);
	virt_addr = __get_free_pages(GFP_KERNEL, order);
	addr = virt_addr;

	if (virt_addr) {
		while (size > 0) {
			SetPageReserved(virt_to_page(addr));
			addr += PAGE_SIZE;
			size -= PAGE_SIZE;
		}
	}
	*phys_addr = (u32) virt_to_phys((void *) virt_addr);
	return virt_addr;
}

/*
 * Free buffers
 */
void omap_vout_free_buffer(unsigned long virtaddr, u32 buf_size)
{
	u32 order, size;
	unsigned long addr = virtaddr;

	size = PAGE_ALIGN(buf_size);
	order = get_order(size);

	while (size > 0) {
		ClearPageReserved(virt_to_page(addr));
		addr += PAGE_SIZE;
		size -= PAGE_SIZE;
	}
	free_pages((unsigned long) virtaddr, order);
}

bool omap_vout_dss_omap24xx(void)
{
	return omapdss_get_version() == OMAPDSS_VER_OMAP24xx;
}

bool omap_vout_dss_omap34xx(void)
{
	switch (omapdss_get_version()) {
	case OMAPDSS_VER_OMAP34xx_ES1:
	case OMAPDSS_VER_OMAP34xx_ES3:
	case OMAPDSS_VER_OMAP3630:
	case OMAPDSS_VER_AM35xx:
		return true;
	default:
		return false;
	}
}


text:
class Statement {
public:
    virtual void print(std::ofstream *ofs, std::ofstream *ofl, std::string proc_name) = 0;

    virtual void print_full_signature(std::ofstream *ofs, std::ofstream *ofl, std::string proc_name) = 0;

    virtual void print_arguments(std::ofstream *ofs, std::ofstream *ofl) = 0;

    virtual void print_dependencies(std::ofstream *ofs, std::ofstream *ofl) = 0;

    virtual ~Statement() = 0;
};

#endif //PROJECT_STATEMENT_H


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2017 Citrus-CAF Project
  ~ 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.
  ~
  -->
<resources>

    <style name="DrawerArrowStyle" parent="@*com.android.contacts:style/Widget.AppCompat.DrawerArrowToggle">
        <item name="*com.android.contacts:spinBars">false</item>
        <item name="*com.android.contacts:color">@*android:color/holo_blue_bright</item>
        <item name="android:color">@*android:color/holo_blue_bright</item>
    </style>

    <style name="ConfirmAddDetailDialogTheme" parent="@android:style/Theme.Material.Dialog.MinWidth">
        <item name="android:windowCloseOnTouchOutside">true</item>
    </style>

    <style name="ContactEditorAccountsChangedActivityTheme" parent="@android:style/Theme.Material.Dialog.NoActionBar.MinWidth">
        <item name="android:windowCloseOnTouchOutside">true</item>
        <item name="android:textColorPrimary">@*com.android.contacts:color/primary_text_color</item>
        <item name="android:textColorSecondary">@*com.android.contacts:color/secondary_text_color</item>
        <item name="android:listViewStyle">@*com.android.contacts:style/ListViewStyle</item>
        <item name="android:colorAccent">@*com.android.contacts:color/contacts_accent_color</item>
    </style>

    <style name="BackgroundOnlyTheme" parent="@android:style/Theme.Material">
        <item name="android:windowBackground">@null</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowAnimationStyle">@null</item>
        <item name="android:windowNoTitle">true</item>
        <!-- Activities that use this theme are background activities without obvious displays.
            However, some also have dialogs. Therefore, it doesn't make sense to set this true.-->
        <item name="android:windowNoDisplay">false</item>
        <item name="android:windowIsFloating">true</item>
    </style>

    <style name="Theme.CallSubjectDialogTheme" parent="@android:style/Theme.Material.Dialog">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">match_parent</item>

        <!-- No backgrounds, titles or window float -->
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowFullscreen">false</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowDrawsSystemBarBackgrounds">false</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowElevation">0dp</item>
    </style>

    <style name="TextAppearanceMedium" parent="@*android:style/TextAppearance.Medium">
        <item name="android:textSize">16.0sp</item>
        <item name="android:textColor">#ffffffff</item>
    </style>
    <style name="TextAppearanceSmall" parent="@*android:style/TextAppearance.Small">
        <item name="android:textSize">14.0sp</item>
        <item name="android:textColor">#ffdddddd</item>
    </style>

    <style name="NoAccountViewButtonStyle" parent="@*com.android.contacts:style/Widget.AppCompat.Button.Borderless">
        <item name="android:textSize">14.0sp</item>
        <item name="android:textColor">@*com.android.contacts:color/contacts_accent_color</item>
        <item name="android:textAllCaps">true</item>
        <item name="android:fontFamily">sans-serif-medium</item>
    </style>
    <style name="AddContactsButtonStyle" parent="@*com.android.contacts:style/Widget.AppCompat.Button.Borderless">
        <item name="android:textSize">16.0sp</item>
        <item name="android:textColor">@*com.android.contacts:color/contacts_accent_color</item>
        <item name="android:textAllCaps">true</item>
        <item name="android:fontFamily">sans-serif-medium</item>
    </style>

    <style name="DrawerItemTextActiveStyle">
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@*com.android.contacts:color/contacts_accent_color</item>
    </style>

</resources>


text:
This repository contains Structure files for the
[parameter-framework](https://github.com/01org/parameter-framework). These are
either for documentation/example purposes or are real-life Structures that
support existing systems (e.g. audio codecs found on smartphones and tablets).

## Installing the examples

    cmake -DCMAKE_PREFIX_PATH=</your/installed/pfw/plugin/dir> -DCMAKE_INSTALL_PREFIX=</example/destination> .
    make install


text:
import styled from 'styled-components'
import { url } from 'redux-form-validators'
// import muiThemeable from 'material-ui/styles/muiThemeable'

const FullWidthSection = styled.div`
  overflow: hidden;
  clear: both;
  background: ${(props) => props.color};
  text-align: center;
  width: 100%;
  padding-bottom: 30px;
  padding-top: 30px;
`
// export default muiThemeable()(FullWidthSection)
export default FullWidthSection


text:
package com.krishagni.catissueplus.core.administrative.services.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.krishagni.catissueplus.core.administrative.domain.PermissibleValue;
import com.krishagni.catissueplus.core.administrative.domain.StorageContainer;
import com.krishagni.catissueplus.core.administrative.services.ContainerReport;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol;
import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.catissueplus.core.common.util.CsvWriter;
import com.krishagni.catissueplus.core.common.util.MessageUtil;
import com.krishagni.catissueplus.core.common.util.Utility;

public abstract class AbstractContainerReport implements ContainerReport  {

	protected DaoFactory daoFactory;

	public void setDaoFactory(DaoFactory daoFactory) {
		this.daoFactory = daoFactory;
	}

	protected void exportContainerSummary(StorageContainer container, CsvWriter writer) {
		writer.writeNext(new String[] { message(CONTAINER_DETAILS) });
		writer.writeNext(new String[] { message(CONTAINER_NAME), container.getName() });
		writer.writeNext(new String[] { message(CONTAINER_DISPLAY_NAME), container.getDisplayName() });
		writer.writeNext(new String[] { message(CONTAINER_HIERARCHY), container.getStringifiedAncestors() });

		writer.writeNext(new String[] { message(CONTAINER_RESTRICTIONS) });

		List<String> cps = new ArrayList<>();
		cps.add(message(CONTAINER_PROTOCOL));
		if (container.getCompAllowedCps().isEmpty()) {
			cps.add(message(ALL));
		} else {
			for (CollectionProtocol cp : container.getCompAllowedCps()) {
				cps.add(cp.getTitle());
			}
		}
		writer.writeNext(cps.toArray(new String[0]));

		List<String> types = new ArrayList<>();
		types.add(message(CONTAINER_SPECIMEN_TYPES));
		if (container.getCompAllowedSpecimenClasses().isEmpty() &&
			container.getCompAllowedSpecimenTypes().isEmpty()) {
			types.add(message(ALL));
		} else {
			for (PermissibleValue specimenClass : container.getCompAllowedSpecimenClasses()) {
				types.add(specimenClass.getValue());
			}

			for (PermissibleValue type : container.getCompAllowedSpecimenTypes()) {
				types.add(type.getValue());
			}
		}
		writer.writeNext(types.toArray(new String[0]));

		writer.writeNext(new String[] { message(EXPORTED_BY), AuthUtil.getCurrentUser().formattedName() });
		writer.writeNext(new String[] { message(EXPORTED_ON), Utility.getDateTimeString(Calendar.getInstance().getTime()) });
		writer.writeNext(new String[0]);
	}

	protected String message(String key, Object... params) {
		return MessageUtil.getInstance().getMessage(key, params);
	}

	// <zip>_<uuid>_<userId>_<name>
	protected String getZipFileId(StorageContainer container, String uuid) {
		return getFileId(container, "zip", uuid);
	}

	// <csv>_<uuid>_<userId>_<name>
	protected String getCsvFileId(StorageContainer container, String uuid) {
		return getFileId(container, "csv", uuid);
	}

	private String getFileId(StorageContainer container, String type, String uuid) {
		return String.join(
			"_",
			type,
			uuid,
			AuthUtil.getCurrentUser().getId().toString(),
			Utility.sanitizeFilename(container.getName()));
	}

	protected static final String CONTAINER_DETAILS        = "storage_container_details";

	protected static final String CONTAINER_NAME           = "storage_container_name";

	protected static final String CONTAINER_DISPLAY_NAME   = "storage_container_display_name";

	protected static final String CONTAINER_HIERARCHY      = "storage_container_hierarchy";

	protected static final String CONTAINER_RESTRICTIONS   = "storage_container_restrictions";

	protected static final String CONTAINER_PROTOCOL       = "storage_container_restricted_protocols";

	protected static final String CONTAINER_SPECIMEN_TYPES = "storage_container_specimen_types";

	protected static final String ALL                      = "common_all";

	protected static final String EXPORTED_BY              = "common_exported_by";

	protected static final String EXPORTED_ON              = "common_exported_on";

	protected static final String CONTAINER_TYPE           = "container_type";

	protected static final String STORES_SPMN              = "container_stores_specimen";

	protected static final String CELL_ROW                 = "container_position_row";

	protected static final String CELL_COL                 = "container_position_column";

	protected static final String CELL_POS                 = "container_position_position";

	protected static final String YES                      = "common_yes";

	protected static final String NO                       = "common_no";
}


text:
class FilterDateParamsValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    return if value.blank?

    begin
      DateTime.parse(value)
    rescue
      record.errors.add(attribute, "の値が不正です")
    end
  end
end


text:
import unittest, os
import yaga.handle_geodata
import time
import json

class HandlingGeoDataTestCase(unittest.TestCase):

	#def setUp(self):

	#def tearDown(self):

	# # Testing of isTimestampValid
	# def test_isTimestampValid_badInputFormat(self):
	# 	self.assertFalse(yaga.handle_geodata.isTimestampValid("otis"))

	# If the event occured at the current minute, we consider it
	def test_isTimestampValid_goodInput_same_minute(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()}})
		self.assertTrue(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured one minute ago, we don't consider it
	def test_isTimestampValid_goodInput_minute_before(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()-60}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured at the current minute, one hour ago, we don't consider it
	def test_isTimestampValid_goodInput_minute_hour_ago(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()-3600}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured at the current minute, a day ago, we don't consider it
	def test_isTimestampValid_goodInput_same_minute_day_ago(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()-3600*24}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured at the current minute, a month ago or more, we don't consider it
	def test_isTimestampValid_goodInput_same_minute_month_ago(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()-3600*24*31}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured at the current minute, a year ago, we don't consider it
	def test_isTimestampValid_goodInput_same_minute_year_ago(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()-3600*24*365}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured a minute ahead, we don't consider it
	def test_isTimestampValid_goodInput_minute_after(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()+60}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured at the current minute, a hour ahead, we don't consider it
	def test_isTimestampValid_goodInput_same_minute_hour_ahead(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()+3600}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured at the current minute, a day ahead, we don't consider it
	def test_isTimestampValid_goodInput_same_minute_day_ahead(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()+3600*24}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured at the current minute, a month ahead or more, we don't consider it
	def test_isTimestampValid_goodInput_same_minute_month_ahead(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()+3600*24*31}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# If the event occured at the current minute, a year ahead, we don't consider it
	def test_isTimestampValid_goodInput_same_minute_year_ahead(self):
		timestamp = json.dumps({'data': { "timestamp" : time.time()+3600*24*365}})
		self.assertFalse(yaga.handle_geodata.isTimestampValid(timestamp))

	# point located in zone 1 in both cases
	def test_zoneFinder_zone1(self):
		point = {'data': {'latitude': 45.836, 'longitude': 4.681}}
		point = json.dumps(point)

		self.assertEqual(yaga.handle_geodata.zoneFinder(point)["zones"] ,{'bigzone': 1, 'littlezone': 1})

	# point located in zone 1 in the big and zone 2 in the little
	def test_zoneFinder_zone1_zone2(self):
		point = {'data': {'latitude': 45.836, 'longitude': 4.686}}
		point = json.dumps(point)
		self.assertEqual(yaga.handle_geodata.zoneFinder(point)["zones"] ,{'bigzone': 1, 'littlezone': 2})

	# point located at the north ouest of the NO limit
	def test_regionFilter_out_no(self):
		point = {'data': {'latitude': 45.825, 'longitude': 4.675}}
		point = json.dumps(point)

		self.assertFalse(yaga.handle_geodata.regionFilter(point))

	# point located at the north east of the NE limit
	def test_regionFilter_out_ne(self):
		point = {'data': {'latitude': 45.825, 'longitude': 4.835}}
		point = json.dumps(point)

		self.assertFalse(yaga.handle_geodata.regionFilter(point))

	# point located at the south ouest of the SO limit
	def test_regionFilter_out_so(self):
		point = {'data': {'latitude': 45.841, 'longitude': 4.686}}
		point = json.dumps(point)

		self.assertFalse(yaga.handle_geodata.regionFilter(point))

	# point located at the south ouest of the SE limit
	def test_regionFilter_out_se(self):
		point = {'data': {'latitude': 45.725, 'longitude': 4.835}}
		point = json.dumps(point)

		self.assertFalse(yaga.handle_geodata.regionFilter(point))

if __name__=='__main__':
	unittest.main()


text:
package com.oshare.thirdparty.dao;

import com.oshare.thirdparty.entity.model.SysConfigModel;

/**
 * 系统配置信息
 *
 * @author mengzhg
 * @version 1.0
 * @since 2016/11/20 22:35
 */
public interface SysConfigDao {

	/**
	 * 获取最新的版本信息
	 *
	 * @return the app version
	 */
	public SysConfigModel getAppVersion();
}