text:
var doc = require('..'),
    fs = require('fs'),
    rimraf = require('rimraf'),
    exec = require('child_process').exec;

/**
 * convertToText
 */
exports.convertToText = {

    'Return text when given a Microsoft doc': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/doc.doc').
            then(function(text) {
                    test.equal(text, 'This is supposed to be a Microsoft Word doc. ' +
                                     'It was created with LibreOffice.\n');
                    test.done();
              }).
            catch(function(err) {
                    console.log('err');
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    /**
     * 2014-7-14
     * I discovered that antiword doesn't like hosted servers. By passing
     * an environment variable, the associated problem disappears.
     *
     * This test is useless, except that it will remind me what it takes
     * to get antiword working
     */
    'Return text when given a Microsoft doc with options': function(test) {
        test.expect(1);

        var environment = process.env;
        environment.ANTIWORDHOME = '/usr/share/antiword';
        var options = { env: environment };

        doc.convertToText('test/docs/doc.doc', options).
            then(function(text) {
                    test.equal(text, 'This is supposed to be a Microsoft Word doc. ' +
                                     'It was created with LibreOffice.\n');
                    test.done();
              }).
            catch(function(err) {
                    console.log('err');
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given a Microsoft doc with no file extension': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/doc').
            then(function(text) {
                    test.equal(text, 'This is supposed to be a Microsoft Word doc. ' +
                                     'It was created with LibreOffice.\n');
                    test.done();
              }).
            catch(function(err) {
                    console.log('err');
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Delete temp file containing converted Microsoft DOC text': function(test) {
        test.expect(2);
        var count = fs.readdirSync('/tmp').length;

        doc.convertToText('test/docs/doc.doc').
            then(function(text) {
                    test.equal(text, 'This is supposed to be a Microsoft Word doc. ' +
                                     'It was created with LibreOffice.\n');
                    test.equal(count, fs.readdirSync('/tmp').length);
                    test.done();
              }).
            catch(function(err) {
                    console.log('err');
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given a Microsoft docx': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/docx.docx').
            then(function(text) {
                    test.equal(text, '\rThis is supposed to be a Microsoft docx. ' +
                                     'It was created with Google Docs.\n');
                    test.done();
              }).
            catch(function(err) {
                    console.log('err');
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given a Microsoft docx with no file extension': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/docx').
            then(function(text) {
                    test.equal(text, '\rThis is supposed to be a Microsoft docx. ' +
                                     'It was created with Google Docs.\n');
                    test.done();
              }).
            catch(function(err) {
                    console.log('err');
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Delete temp file containing converted Microsoft DOCX text': function(test) {
        test.expect(2);
        var count = fs.readdirSync('/tmp').length;

        doc.convertToText('test/docs/docx.docx').
            then(function(text) {
                    test.equal(text, '\rThis is supposed to be a Microsoft docx. ' +
                                     'It was created with Google Docs.\n');
                    test.equal(count, fs.readdirSync('/tmp').length);
                    test.done();
              }).
            catch(function(err) {
                    console.log('err');
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given an OpenOffice ODT': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/odt.odt').
            then(function(text) {
                    test.equal(text, 'This is an OpenOffice odt document. ' +
                                     'It was created with LibreOffice.\n');
                    test.done();
              }).
            catch(function(err) {
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given an OpenOffice ODT with no extension': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/odt').
            then(function(text) {
                    test.equal(text, 'This is an OpenOffice odt document. ' +
                                     'It was created with LibreOffice.\n');
                    test.done();
              }).
            catch(function(err) {
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Delete temp file containing converted OpenOffice ODT text': function(test) {
        test.expect(2);
        var count = fs.readdirSync('/tmp').length;

        doc.convertToText('test/docs/odt.odt').
            then(function(text) {
                    test.equal(text, 'This is an OpenOffice odt document. ' +
                                     'It was created with LibreOffice.\n');
                    test.equal(count, fs.readdirSync('/tmp').length);
                    test.done();
              }).
            catch(function(err) {
                    console.log('err');
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given a Google Doc PDF': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/pdf.pdf').
            then(function(text) {
                    test.equal(text, 'This is a pdf. It was created with Google Docs.\n\n\f');
                    test.done();
              }).
            catch(function(err) {
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given a Google Doc PDF with no extension': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/pdf').
            then(function(text) {
                    test.equal(text, 'This is a pdf. It was created with Google Docs.\n\n\f');
                    test.done();
              }).
            catch(function(err) {
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given a LibreOffice rtf': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/rtf.rtf').
            then(function(text) {
                    test.equal(text, 'This is an rtf document. It was created with LibreOffice.\n');
                    test.done();
              }).
            catch(function(err) {
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given a LibreOffice rtf with no extension': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/rtf').
            then(function(text) {
                    test.equal(text, 'This is an rtf document. It was created with LibreOffice.\n');
                    test.done();
              }).
            catch(function(err) {
                    console.log(err);
                    test.ok(false, err);
                    test.done();
              });
    },

    'Delete temp file containing converted LibreOffice RTF text': function(test) {
        test.expect(2);
        var count = fs.readdirSync('/tmp').length;

        doc.convertToText('test/docs/rtf.rtf').
            then(function(text) {
                    test.equal(text, 'This is an rtf document. ' +
                                     'It was created with LibreOffice.\n');
                    test.equal(count, fs.readdirSync('/tmp').length);
                    test.done();
              }).
            catch(function(err) {
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given a txt document': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/txt.txt').
            then(function(text) {
                    test.equal(text, 'This is a txt document. It was created with VIM.\n');
                    test.done();
              }).
            catch(function(err) {
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return text when given a txt document with no extension': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/txt').
            then(function(text) {
                    test.equal(text, 'This is a txt document. It was created with VIM.\n');
                    test.done();
              }).
            catch(function(err) {
                    test.ok(false, err);
                    test.done();
              });
    },

    'Return error when given a DOC that thinks it\'s a PDF': function(test) {
        test.expect(1);
        doc.convertToText('test/docs/doc.pdf').
            then(function(text) {
                    test.ok(false, 'Shouldn\'t get here');
                    test.done();
              }).
            catch(function(err) {
                    console.log
                    test.equal(err, 'Syntax Warning: May not be a PDF file (continuing anyway)\n' +
                                    'Syntax Error: Couldn\'t find trailer dictionary\n' +
                                    'Syntax Error: Couldn\'t read xref table\n');
                    test.done();
              });
    },
};

/**
 * getExtension
 */
exports.getExtension = {

    'Return the text behind the last period in a string': function(test) {
        test.expect(1);
        doc.getExtension('/some/../weird.looking/path/somefile.xyz').
            then(function(extension) {
                test.equal(extension, 'xyz');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Return \'doc\' when given a DOC with no extensions': function(test) {
        test.expect(1);
        doc.getExtension('test/docs/doc').
            then(function(extension) {
                test.equal(extension, 'doc');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Return \'docx\' when given a DOCX with no extensions': function(test) {
        test.expect(1);
        doc.getExtension('test/docs/docx').
            then(function(extension) {
                test.equal(extension, 'docx');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Return \'odt\' when given an ODT with no extensions': function(test) {
        test.expect(1);
        doc.getExtension('test/docs/odt').
            then(function(extension) {
                test.equal(extension, 'odt');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Return \'pdf\' when given a PDF with no extensions': function(test) {
        test.expect(1);
        doc.getExtension('test/docs/pdf').
            then(function(extension) {
                test.equal(extension, 'pdf');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Return \'rtf\' when given an RTF with no extensions': function(test) {
        test.expect(1);
        doc.getExtension('test/docs/rtf').
            then(function(extension) {
                test.equal(extension, 'rtf');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },

    'Return \'txt\' when given a TXT with no extensions': function(test) {
        test.expect(1);
        doc.getExtension('test/docs/txt').
            then(function(extension) {
                test.equal(extension, 'txt');
                test.done();
              }).
            catch(function(err) {
                test.ok(false, err);
                test.done();
              });
    },
};

/**
 * convertToXml
 */
//exports.convertToXml = {
//
//    'Return XML when given a PDF': function(test) {
//        test.expect(1);
//        doc.convertToXml('test/docs/pdf.pdf').
//            then(function(text) {
//                test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="14" family="Times" color="#000000"/>\n' +
//                                 '<text top="110" left="108" width="347" height="19" font="0">' +
//                                 'This is a pdf. It was created with Google Docs.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                test.done();
//              }).
//            catch(function(err) {
//                console.log(err);
//                test.ok(false, err);
//                test.done();
//              });
//    },
//
//    'Return XML when given a DOC': function(test) {
//        test.expect(1);
//        doc.convertToXml('test/docs/doc.doc').
//            then(function(text) {
//                test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="16" family="Times" color="#000000"/>\n' +
//                                 '<text top="86" left="85" width="561" height="20" font="0">' +
//                                 'This is supposed to be a Microsoft Word doc. It was created with LibreOffice.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                test.done();
//              }).
//            catch(function(err) {
//                console.log(err);
//                test.ok(false, err);
//                test.done();
//              });
//    },
//
//    'Delete temp file containing XML-converted Microsoft DOC data': function(test) {
//        test.expect(2);
//        var count = fs.readdirSync('/tmp').length;
//
//        doc.convertToXml('test/docs/doc.doc').
//            then(function(text) {
//                 test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="16" family="Times" color="#000000"/>\n' +
//                                 '<text top="86" left="85" width="561" height="20" font="0">' +
//                                 'This is supposed to be a Microsoft Word doc. It was created with LibreOffice.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                    test.equal(count, fs.readdirSync('/tmp').length);
//                    test.done();
//              }).
//            catch(function(err) {
//                    console.log('err');
//                    console.log(err);
//                    test.ok(false, err);
//                    test.done();
//              });
//    },
//
//    'Return XML when given a DOCX': function(test) {
//        test.expect(1);
//        doc.convertToXml('test/docs/docx.docx').
//            then(function(text) {
//                test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="16" family="Times" color="#000000"/>\n' +
//                                 '<text top="109" left="108" width="536" height="20" font="0">' +
//                                 'This is supposed to be a Microsoft docx. It was created with Google Docs.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                test.done();
//              }).
//            catch(function(err) {
//                console.log(err);
//                test.ok(false, err);
//                test.done();
//              });
//    },
//
//    'Delete temp file containing XML-converted Microsoft DOCX data': function(test) {
//        test.expect(2);
//        var count = fs.readdirSync('/tmp').length;
//
//        doc.convertToXml('test/docs/docx.docx').
//            then(function(text) {
//                test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="16" family="Times" color="#000000"/>\n' +
//                                 '<text top="109" left="108" width="536" height="20" font="0">' +
//                                 'This is supposed to be a Microsoft docx. It was created with Google Docs.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                    test.equal(count, fs.readdirSync('/tmp').length);
//                    test.done();
//              }).
//            catch(function(err) {
//                    console.log('err');
//                    console.log(err);
//                    test.ok(false, err);
//                    test.done();
//              });
//    },
//
//    'Return XML when given an ODT': function(test) {
//        test.expect(1);
//        doc.convertToXml('test/docs/odt.odt').
//            then(function(text) {
//                test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="16" family="Times" color="#000000"/>\n' +
//                                 '<text top="86" left="85" width="501" height="20" font="0">' +
//                                 'This is an OpenOffice odt document. It was created with LibreOffice.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                test.done();
//              }).
//            catch(function(err) {
//                console.log(err);
//                test.ok(false, err);
//                test.done();
//              });
//    },
//
//    'Delete temp file containing XML-converted ODT data': function(test) {
//        test.expect(2);
//        var count = fs.readdirSync('/tmp').length;
//
//        doc.convertToXml('test/docs/odt.odt').
//            then(function(text) {
//                test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="16" family="Times" color="#000000"/>\n' +
//                                 '<text top="86" left="85" width="501" height="20" font="0">' +
//                                 'This is an OpenOffice odt document. It was created with LibreOffice.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                    test.equal(count, fs.readdirSync('/tmp').length);
//                    test.done();
//              }).
//            catch(function(err) {
//                    console.log('err');
//                    console.log(err);
//                    test.ok(false, err);
//                    test.done();
//              });
//    },
//
//    'Return XML when given an RTF': function(test) {
//        test.expect(1);
//        doc.convertToXml('test/docs/rtf.rtf').
//            then(function(text) {
//                test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="16" family="Times" color="#000000"/>\n' +
//                                 '<text top="86" left="85" width="406" height="20" font="0">' +
//                                 'This is an rtf document. It was created with LibreOffice.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                test.done();
//              }).
//            catch(function(err) {
//                console.log(err);
//                test.ok(false, err);
//                test.done();
//              });
//    },
//
//    'Delete temp file containing XML-converted RTF data': function(test) {
//        test.expect(2);
//        var count = fs.readdirSync('/tmp').length;
//
//        doc.convertToXml('test/docs/rtf.rtf').
//            then(function(text) {
//                test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="16" family="Times" color="#000000"/>\n' +
//                                 '<text top="86" left="85" width="406" height="20" font="0">' +
//                                 'This is an rtf document. It was created with LibreOffice.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                test.equal(count, fs.readdirSync('/tmp').length);
//                test.done();
//              }).
//            catch(function(err) {
//                console.log('err');
//                console.log(err);
//                test.ok(false, err);
//                test.done();
//              });
//    },
//
//    'Return XML when given a TXT': function(test) {
//        test.expect(1);
//        doc.convertToXml('test/docs/txt.txt').
//            then(function(text) {
//                test.equal(text, '<?xml version="1.0" encoding="UTF-8"?>\n' +
//                                 '<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">\n\n' +
//                                 '<pdf2xml producer="poppler" version="0.24.5">\n' +
//                                 '<page number="1" position="absolute" top="0" left="0" height="1188" width="918">\n' +
//                                    '\t<fontspec id="0" size="13" family="Times" color="#000000"/>\n' +
//                                 '<text top="85" left="85" width="433" height="17" font="0">' +
//                                 'This is a txt document. It was created with VIM.</text>\n' +
//                                 '</page>\n' +
//                                 '</pdf2xml>\n');
//                test.done();
//              }).
//            catch(function(err) {
//                console.log(err);
//                test.ok(false, err);
//                test.done();
//              });
//    },

//    'Start an unoconv listener if it\'s not already running': function(test) {
//        test.expect(3);
//        // Make sure unoconv is not running
//        var command = 'ps ax | grep unoconv | grep -v grep | awk \'{print $1}\'';
//        exec(command, function(err, stdout, stderr) {
//            var unoconvPid = stdout;
//
//            // Make sure soffice.bin is not running
////            var command = 'ps ax | grep soffice.bin | grep -v grep | awk \'{print $1}\'';
////            exec(command, function(err, stdout, stderr) {
//
//                //command = 'kill ' + unoconvPid + ' ' + stdout;
//                command = 'kill ' + unoconvPid;
//                exec(command, function(err, stdout, stderr) {
//
//                    command = 'ps ax | grep unoconv | grep -v grep | awk \'{print $1}\'';
//                    exec(command, function(err, stdout, stderr) {
//                        test.equal(stdout, '');
//
//                        doc.convertToXml('test/docs/txt.txt').
//                            then(function(text) {
//                                command = 'ps ax | grep unoconv | grep -v grep | awk \'{print $1}\'';
//                                exec(command, function(err, stdout, stderr) {
//                                    test.notEqual(stdout, '');
//                                    test.done();
//                                  });
//                              }).
//                            catch(function(err) {
//                                console.log(err);
//                                test.ok(false, err);
//                                test.done();
//                              });
//                      });
//            });
//          });
//    },
//};

/**
 * sanitizePath
 */
exports.sanitizePath = {

    'Returns the same string when there\'s nothing to escape': function(test) {
	test.expect(1);
	var sanitized = doc.sanitizePath('/path/to/some/file.txt');
	test.equal(sanitized, '/path/to/some/file.txt');
	test.done();
    },

    'Escape brackets': function(test) {
	test.expect(2);
	var sanitized = doc.sanitizePath('/path/to/some/file(1).txt');
	test.equal(sanitized, '/path/to/some/file\\(1\\).txt');
	sanitized = doc.sanitizePath('/path/to/some/file(1)(2).txt');
	test.equal(sanitized, '/path/to/some/file\\(1\\)\\(2\\).txt');
	test.done();
    },

    'Escape spaces': function(test) {
	test.expect(2);
	var sanitized = doc.sanitizePath('/path/to/some file.txt');
	test.equal(sanitized, '/path/to/some\\ file.txt');
	sanitized = doc.sanitizePath('/path to some file.txt');
	test.equal(sanitized, '/path\\ to\\ some\\ file.txt');
	test.done();
    },

    'Escape brackets and spaces': function(test) {
	test.expect(2);
	var sanitized = doc.sanitizePath('/path/to/some file(1).txt');
	test.equal(sanitized, '/path/to/some\\ file\\(1\\).txt');
	sanitized = doc.sanitizePath('/path to some file(1)(2).txt');
	test.equal(sanitized, '/path\\ to\\ some\\ file\\(1\\)\\(2\\).txt');
	test.done();
    },

    'Should not double sanitize': function(test) {
	test.expect(2);
	var sanitized = doc.sanitizePath('/path to some file(1)(2).txt');
	test.equal(sanitized, '/path\\ to\\ some\\ file\\(1\\)\\(2\\).txt');
	sanitized = doc.sanitizePath(sanitized);
	test.equal(sanitized, '/path\\ to\\ some\\ file\\(1\\)\\(2\\).txt');
	test.done();
    },
};

/**
 * startUnoconvListener
 */
//exports.startUnoconvListener = {
//
//    // Make sure there's no unoconv listener running
//    setUp: function(callback) {
//        var command = 'ps ax | grep unoconv | grep -v grep | awk \'{print $1}\'';
//        exec(command, function(err, stdout, stderr) {
//            command = 'kill ' + stdout;
//            exec(command, function(err, stdout, stderr) {
//                callback();
//              });
//          });
//    },
//
//    'Start an unoconv listener': function(test) {
//        test.expect(2);
//        var command = 'ps ax | grep unoconv | grep -v grep | awk \'{print $1}\'';
//        exec(command, function(err, stdout, stderr) {
//            test.equal(stdout, '');
//
//            doc.startUnoconvListener().
//                then(function() {
//                    test.ok(true);
//                    test.done();
//                  }).
//                catch(function(err) {
//                    console.log(err);
//                    test.ok(false);
//                    test.done();
//                  });
//          });
//    },
//};

/**
 * checkUnoconv
 */
//exports.checkUnoconv = {
//
//    // Make sure there's no unoconv listener or soffice.bin running
//    setUp: function(callback) {
//        var command = 'ps ax | grep unoconv | grep -v grep | awk \'{print $1}\'';
//        exec(command, function(err, stdout, stderr) {
//            var unoconvPid = stdout;
//
//            // Get LibreOffice PID
//            command = 'ps ax | grep soffice.bin | grep -v grep | awk \'{print $1}\''
//            exec(command, function(err, stdout, stderr) {
//
//                // Kill the processes
//                command = 'kill ' + unoconvPid + ' ' + stdout;
//                exec(command, function(err, stdout, stderr) {
//                    callback();
//                  });
//              });
//          });
//    },
//
//    'Start listener when necessary': function(test) {
//        test.expect(3);
//        // Verify that the listener is not running
//        var unoconvCommand = 'ps ax | grep unoconv | grep -v grep | awk \'{print $1}\'';
//        exec(unoconvCommand, function(err, stdout, stderr) {
//            test.equal(stdout, '');
//
//            // Verify that there is no soffice.bin running
//            var sofficeCommand = 'ps ax | grep soffice.bin | grep -v grep | awk \'{print $1}\'';
//            exec(sofficeCommand, function(err, stdout, stderr) {
//                test.equal(stdout, '');
//
//                doc.checkUnoconv().
//                    then(function() {
//                        exec(unoconvCommand, function(err, stdout, stderr) {
//                            test.notEqual(stdout, '');
//                            test.done();
//                          });
//                      }).
//                    catch(function(err) {
//                        console.log(err);
//                        test.ok(false);
//                        test.done();
//                      });
//              });
//          });
//    },
//
//    'Don\'t restart listener if it\'s already running': function(test) {
//        test.expect(2);
//        doc.startUnoconvListener().
//            then(function() {
//                // Get the unoconv PID
//                var command = 'ps ax | grep unoconv | grep -v grep | awk \'{print $1}\'';
//                exec(command, function(err, stdout, stderr) {
//                    var pid = stdout;
//                    test.notEqual(pid, '');
//
//                    doc.checkUnoconv().
//                        then(function() {
//                            // Ensure the PID is the same
//                            // (otherwise a new instance was created)
//                            exec(command, function(err, stdout, stderr) {
//                                test.equal(pid, stdout);
//                                test.done();
//                              });
//                          }).
//                        catch(function(err) {
//                            console.log(err);
//                            test.ok(false);
//                            test.done();
//                          });
//                  });
//              }).
//            catch(function(err) {
//                console.log(err);
//                test.ok(false);
//                test.done();
//              });
//    },
//};


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [CSS](./puppeteer.protocol.css.md) > [SetStyleTextsResponse](./puppeteer.protocol.css.setstyletextsresponse.md)

## Protocol.CSS.SetStyleTextsResponse interface

<b>Signature:</b>

```typescript
export interface SetStyleTextsResponse
```

## Properties

|  Property | Type | Description |
|  --- | --- | --- |
|  [styles](./puppeteer.protocol.css.setstyletextsresponse.styles.md) | [CSSStyle](./puppeteer.protocol.css.cssstyle.md)<!-- -->\[\] | The resulting styles after modification. |

redpajama_set_name: RedPajamaGithub


text:
class Book < ActiveRecord::Base
  enum status: { reservation: 0, now_on_sale: 1, end_of_print: 2 }
  scope :costly, -> { where('price > ?', 3000) }
  scope :written_about, ->(theme) { where('name like ?', "%#{theme}%") }

  belongs_to :publisher

  has_many :book_authors
  has_many :authors, through: :book_authors

  validates :name, presence: true
  validates :name, length: { maximum: 15 }
  validates :price, numericality: { greater_than_or_equal_to: 0 }
  validate do |book|
    if book.name.include?('exercise')
      book.errors[:name] << "I don't like exercise."
    end
  end
  before_validation :add_lovely_to_cat
  after_destroy if: :high_price? do |book|
    Rails.logger.warn "Book with high price is deleted: #{book.attributes.inspect}"
    Rails.logger.warn 'Please Check!!'
  end

  def add_lovely_to_cat
    self.name = name.gsub(/Cat/) do |matched|
      "lovely #{matched}"
    end
  end

  def high_price?
    price >= 5000
  end
end


text:
public class B {
    final static String
            LEFT_JUSTIFIED_PREFIX   =   "%r";
}


text:
@interface BTLaunchView()
@property (nonatomic,strong) AVPlayerLayer *playLayer;
@property (nonatomic,strong) AVPlayer *player;
@property (nonatomic,strong) UIView *logoView;
@property (nonatomic,strong) UIImageView *adImageView;
@property (nonatomic,strong) UIImageView *adhitImageView;
@property (nonatomic,strong) UIView *skipBackgroundView;
@property (nonatomic,strong) UIImageView *logoImageView;
@property (nonatomic,strong) UIImageView *logoTextView;
@property (nonatomic,strong) UIButton *skipButton;
@property (nonatomic,strong) UIImageView *skipImageView;
@property (nonatomic,strong) BTLaunchCountDownView *countDownView;
@property (nonatomic,strong) UIImageView *launchView;

@property (nonatomic,strong) NSTimer *timeoutTimer;
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId;

@end

static inline CGFloat BTAdjustValue(CGFloat x)
{
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    if (DeviceIsPad) {
        return x * (height * scale) / 1024.0f;
    }
    return x;
}

@implementation BTLaunchView

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (!self) return nil;
    [self initViews];
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (!self) return nil;
    [self initViews];
    return self;
}

- (void)initViews
{
    CGFloat bottomHeight = [self bottomHeight];
    CGFloat logoHeight = BTAdjustValue(65.0f);

    // 底部整个图片
    [self addSubview:self.adImageView];
    [self.adImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];

    // 播放视图
    [self.layer addSublayer:self.playLayer];
    self.playLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - (DeviceIsPad ? 0 : bottomHeight));

    // 下方的logo视图
    [self addSubview:self.logoView];
    [self.logoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(bottomHeight);
    }];

    [self.logoView addSubview:self.logoImageView];
    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.logoView);
        make.top.equalTo(self.logoView).offset((bottomHeight - logoHeight) / 2);
        make.size.mas_equalTo(CGSizeMake(BTAdjustValue(52.0f), BTAdjustValue(35.0f)));
    }];

    [self.logoView addSubview:self.logoTextView];
    [self.logoTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.logoView);
        make.top.equalTo(self.logoImageView.mas_bottom).offset(BTAdjustValue(10));
        make.size.mas_equalTo(CGSizeMake(BTAdjustValue(138.0f), BTAdjustValue(20.0f)));
    }];

    [self addSubview:self.skipBackgroundView];
    [self.skipBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self).offset(-BTAdjustValue(7.5f));
        make.size.mas_equalTo(CGSizeMake(BTAdjustValue(62.0f), BTAdjustValue(26.0f)));
        make.centerY.equalTo(self.logoView);
    }];

    [self.skipBackgroundView addSubview:self.skipImageView];
    [self.skipImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.skipBackgroundView).offset(-10);
        make.centerY.equalTo(self.skipBackgroundView);
        make.size.mas_equalTo(CGSizeMake(BTAdjustValue(8), BTAdjustValue(8)));
    }];

    [self.skipBackgroundView addSubview:self.skipButton];
    [self.skipButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.skipImageView.mas_left).offset(-5);
        make.centerY.equalTo(self.skipBackgroundView);
    }];

    [self.skipBackgroundView addSubview:self.countDownView];
    [self.countDownView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.skipButton.mas_left).offset(SCREEN_WIDTH > 375.0f ? -6 : 0);
        make.centerY.equalTo(self.skipButton);
        make.size.mas_equalTo(CGSizeMake(BTAdjustValue(10), BTAdjustValue(10)));
    }];

    // 广告标签
    [self addSubview:self.adhitImageView];
    [self.adhitImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(3);
        make.right.equalTo(self).offset(-3);
        make.size.mas_equalTo(CGSizeMake(BTAdjustValue(16),BTAdjustValue(9)));
    }];

    // 假的启动图图片
    [self addSubview:self.launchView];
    [self.launchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];

    // 用于假的启动图消失的倒计时
    self.timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(skipAction) userInfo:nil repeats:NO];

    // 保持进入后台后视频资源以及倒计时控件依旧在转
    __weak typeof(self) ws = self;
    UIApplication * app = [UIApplication sharedApplication];
    self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{
        __strong __typeof (ws) BTelf = ws;
        if (BTelf)
        {
            [app endBackgroundTask:BTelf.backgroundTaskId];
            BTelf.backgroundTaskId = UIBackgroundTaskInvalid;
        }
    }];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restoreAudioPlay) name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (CGFloat)bottomHeight
{
    if (!DeviceIsPad)
    {
        return BTAdjustValue(121.0f);
    }
    else
    {
        return BTAdjustValue(110.0f);
    }
}

- (void)restoreAudioPlay
{
    if ( _launchView.isHidden && _wrapper.type == BTLaunchWrapperTypeVideo)
    {
        [_player play];
    }
}

+ (NSString *)launchImageName
{
    CGSize viewSize = [UIApplication sharedApplication].delegate.window.bounds.size;
    NSString *viewOrientation = @"Portrait"; //横屏请设置成 @"Landscape"
    NSString *launchImage = nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for (NSDictionary* dict in imagesDict) {
        CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);

        if (CGSizeEqualToSize(imageSize, viewSize)
            && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]]) {
            launchImage = dict[@"UILaunchImageName"];
        }
    }
    return launchImage;
}

- (void)launchViewDisplay
{
    [UIView animateWithDuration:0.3f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.launchView.alpha = 0.0f;
                     } completion:^(BOOL finished) {
                         self.launchView.hidden = YES;
                     }];

    if (_timeoutTimer)
    {
        [_timeoutTimer invalidate]; _timeoutTimer = nil;
    }

    switch (_wrapper.type)
    {
        case BTLaunchWrapperTypeImage:
        {
            UIImage *image = [_wrapper convertToImage];
            if (image)
            {
                _adImageView.image = image;
            }
        }
            break;
        case BTLaunchWrapperTypeGIF:
        {
            NSArray *images = [_wrapper convertToGIFImages];
            if (images && images.count > 0)
            {
                _adImageView.animationDuration = _wrapper.duration;
                _adImageView.animationImages = images;
                _adImageView.animationRepeatCount = 1;
                [_adImageView startAnimating];
            }
        }
            break;
        case BTLaunchWrapperTypeVideo:
        {
            NSURL *videoUrl = [_wrapper localUrlPath];
            if (videoUrl)
            {
                _player = [AVPlayer playerWithURL:videoUrl];
                _playLayer.player = _player;
                [_player play];

                if (DeviceIsPad)
                {
                    _logoView.hidden = YES;
                    _skipImageView.image = [UIImage imageNamed:@"skip_white"];
                    _countDownView.fillColor = [UIColor whiteColor];
                    [_skipButton setTitleColor:[UIColor whiteColor] forState:0];
                    _skipBackgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3f];
                    _skipBackgroundView.layer.cornerRadius = BTAdjustValue(26.0f) / 2.0f;
                    _skipBackgroundView.clipsToBounds = YES;

                    [self.skipBackgroundView mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.right.bottom.equalTo(self).offset(-BTAdjustValue(7.5f));
                        make.size.mas_equalTo(CGSizeMake(BTAdjustValue(62.0f), BTAdjustValue(26.0f)));
                    }];
                }
            }
        }
            break;

        default:
            break;
    }

    [_countDownView start];
}

- (void)setWrapper:(BTLaunchWrapper *)wrapper
{
    _wrapper = wrapper;
    _countDownView.countDownTimeInterval = _wrapper.duration;
}

- (void)touchAction
{
    NSURL *openUrl = [NSURL URLWithString:self.wrapper.linkurl];
    if ([[UIApplication sharedApplication] canOpenURL:openUrl])
    {
        [[UIApplication sharedApplication] openURL:openUrl];
    }
}

- (void)skipAction
{
    [UIView animateWithDuration:0.3f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.alpha = 0.0f;
                     } completion:^(BOOL finished) {
                         [self.player pause];
                         [self removeFromSuperview];
                     }];
}

- (UIView *)logoView
{
    if (!_logoView)
    {
        _logoView = [[UIView alloc] init];
        _logoView.backgroundColor = [UIColor whiteColor];
    }
    return _logoView;
}

- (UIImageView *)adImageView
{
    if (!_adImageView)
    {
        _adImageView = [[UIImageView alloc] init];
        _adImageView.backgroundColor = [UIColor whiteColor];
        _adImageView.contentMode = UIViewContentModeScaleAspectFill;
        _adImageView.clipsToBounds = YES;
        _adImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchAction)];
        [_adImageView addGestureRecognizer:ges];
    }
    return _adImageView;
}

- (UIImageView *)adhitImageView
{
    if (!_adhitImageView)
    {
        _adhitImageView = [UIImageView new];
        _adhitImageView.image = [UIImage imageNamed:@"ad"];
    }
    return _adhitImageView;
}

- (UIImageView *)logoImageView
{
    if (!_logoImageView)
    {
        _logoImageView = [UIImageView new];
        _logoImageView.image = [UIImage imageNamed:@"launchlogo"];
        _logoImageView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _logoImageView;
}

- (UIImageView *)logoTextView
{
    if (!_logoTextView)
    {
        _logoTextView = [UIImageView new];
        _logoTextView.image = [UIImage imageNamed:@"logo_text"];
        _logoTextView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _logoTextView;
}

- (UIButton *)skipButton
{
    if (!_skipButton)
    {
        _skipButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_skipButton setTitle:@"跳过" forState:0];
        _skipButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_skipButton setTitleColor:[UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0f] forState:0];
        [_skipButton addTarget:self action:@selector(skipAction) forControlEvents:1<<6];
        [_skipButton.titleLabel setFont:[UIFont systemFontOfSize:BTAdjustValue(12)]];
    }
    return _skipButton;
}

- (UIImageView *)skipImageView
{
    if (!_skipImageView)
    {
        _skipImageView = [UIImageView new];
        _skipImageView.image = [UIImage imageNamed:@"skip"];
        _skipImageView.contentMode =  UIViewContentModeScaleAspectFit;
    }
    return _skipImageView;
}

- (BTLaunchCountDownView *)countDownView
{
    if (!_countDownView)
    {
        _countDownView = [[BTLaunchCountDownView alloc] initWithFrame:CGRectMake(0, 0, BTAdjustValue(10), BTAdjustValue(10))];
        __weak typeof(self) ws = self;
        BTCountDownCompleteBlock block = ^(){
            [ws skipAction];
        };
        _countDownView.completeBlock = block;
    }
    return _countDownView;
}

- (AVPlayerLayer *)playLayer
{
    if (!_playLayer)
    {
        _playLayer = [AVPlayerLayer layer];
        [_playLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    }
    return _playLayer;
}

- (UIImageView *)launchView
{
    if (!_launchView)
    {
        _launchView = [UIImageView new];
        _launchView.image = [UIImage imageNamed:[BTLaunchView launchImageName]];
        _launchView.backgroundColor = [UIColor whiteColor];
    }
    return _launchView;
}

- (UIView *)skipBackgroundView
{
    if (!_skipBackgroundView)
    {
        _skipBackgroundView = [UIView new];
    }
    return _skipBackgroundView;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


text:
layout: page
title: Livingston - Rangel Wedding
date: 2016-05-24
author: Harold Tyler
tags: weekly links, java
status: published
summary: Sed sagittis at velit eget ornare. Vivamus.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 06/17/2018
  endDate: 06/19/2018
  ctyhocn: WASAXHX
  groupCode: LRW
published: true
---
Fusce risus dolor, imperdiet vel felis id, laoreet feugiat purus. Mauris nec gravida neque. Nullam varius odio ut iaculis placerat. Integer nec pretium leo. Curabitur iaculis finibus est. Suspendisse et augue vitae elit tristique feugiat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum sed elementum enim. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean congue vitae dui at tristique. Sed accumsan purus et iaculis accumsan.

* Phasellus ultrices eros id justo tempus facilisis
* Nullam nec quam id erat fermentum volutpat vitae eget mauris.

In ultricies pretium urna eget interdum. Duis facilisis molestie facilisis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur rhoncus gravida leo. Duis ac mauris condimentum libero posuere convallis. Praesent in pellentesque arcu. Vivamus egestas lobortis diam, quis scelerisque purus elementum sed. Mauris interdum rutrum dapibus. Integer vel orci a tortor porttitor venenatis eu a dolor. Ut tincidunt odio et velit interdum, et vulputate nisi accumsan. Cras vulputate semper leo, vel porta nibh consequat non. Nulla tincidunt, ante ac porta tincidunt, dui urna auctor nulla, ut ultrices dui tellus et turpis. Ut dictum suscipit ante at porta. Nullam urna augue, pharetra sed felis eu, luctus iaculis sapien. Sed fermentum nisl ut arcu sagittis aliquet.
In in nulla id justo venenatis commodo. Fusce nec lorem tempor, iaculis nunc in, posuere ligula. Cras viverra felis ut ipsum ultrices viverra ac at mi. Phasellus ac velit tincidunt, lacinia lectus quis, pulvinar metus. Duis magna orci, ullamcorper id rutrum sed, euismod nec nunc. Fusce sed vulputate erat, a luctus nisl. Etiam vitae placerat orci. Duis semper dapibus mattis. Nulla facilisi.


text:
package org.pentaho.di.engine.api.reporting;

import org.pentaho.di.engine.api.ExecutionContext;
import org.pentaho.di.engine.api.model.Transformation;

import java.io.Serializable;

public class SubTransCreation implements Serializable {
  private static final long serialVersionUID = 6249199047103429616L;
  private ExecutionContext context;
  private Transformation transformation;

  public ExecutionContext getContext() {
    return context;
  }

  public void setContext( ExecutionContext context ) {
    this.context = context;
  }

  public Transformation getTransformation() {
    return transformation;
  }

  public void setTransformation( Transformation transformation ) {
    this.transformation = transformation;
  }
}


text:
<?php

namespace Joli\Jane\OpenApi\Operation;

use Doctrine\Common\Inflector\Inflector;

class OperationCollection extends \ArrayObject
{
    /**
     * @param Operation $operation
     *
     * @return self
     */
    public function addOperation(Operation $operation)
    {
        $id    = $operation->getMethod().$operation->getPath();
        $group = 'Default';

        if ($operation->getOperation()->getOperationId()) {
            $id = $operation->getOperation()->getOperationId();
        }

        if ($operation->getOperation()->getTags() !== null && count($operation->getOperation()->getTags()) > 0) {
            $group = $operation->getOperation()->getTags()[0];
        }

        $group = trim(preg_replace('/[^a-z0-9 ]+/iu', '', $group));
        $group = Inflector::classify($group);

        if (!isset($this[$group])) {
            $this[$group] = [];
        }

        $this[$group][$id] = $operation;

        return $this;
    }
}


text:
using Android.App;
using Android.Content.PM;
using Cirrious.MvvmCross.Droid.Views;

namespace FSoft.WordApp.Droid
{
    [Activity(
		Label = "WordApp"
		, MainLauncher = true
		, Icon = "@drawable/icon"
		, Theme = "@style/Theme.Splash"
		, NoHistory = true
		, ScreenOrientation = ScreenOrientation.Portrait)]
    public class SplashScreen : MvxSplashScreenActivity
    {
        public SplashScreen()
            : base(Resource.Layout.SplashScreen)
        {
        }
    }
}


text:
using System.Xml.Serialization;

namespace dbqf.Serialization.DTO.Criterion
{
    [XmlRoot("BetweenParameter")]
    public class BetweenParameterDTO : ParameterDTO
    {
        [XmlElement]
        public FieldPathDTO Path { get; set; }

        /// <summary>
        /// Gets or sets the high value of a BetweenParameter.
        /// </summary>
        [XmlElement]
        public object High { get; set; }
        public bool ShouldSerializeHigh() { return High != null; }

        /// <summary>
        /// Gets or sets the low value of a BetweenParameter.
        /// </summary>
        [XmlElement]
        public object Low { get; set; }
        public bool ShouldSerializeLow() { return Low != null; }
    }
}


text:
import scala.reflect.runtime.universe._
import scala.reflect.runtime.{universe => ru}
import scala.reflect.runtime.{currentMirror => cm}
import scala.tools.reflect.ToolBox

object Test extends App {
  def foo[T: TypeTag](ys: List[T]): Int => Int = {
    val fun = reify{(x: Int) => {
      x + ys.length
    }}

    val toolbox = cm.mkToolBox()
    val dyn = toolbox.eval(fun.tree)
    dyn.asInstanceOf[Int => Int]
  }

  var fun1 = foo(List(1, 2, 3))
  println(fun1(10))
  var fun2 = foo(List(1, 2, 3, 4))
  println(fun2(10))
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>9_canvas.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for:

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

$Audio

$Button

$Canvas

$Color

$Document

$Event

$Image

$Input

$Keys

$Label

$Rectangle

$SpriteSheet

$UI

$Vector2

$Window

Array

Time

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: 9_canvas.js

/**
An object to manage a HTML5 <Canvas> element
@class $Canvas
@constructor
@param elm {Object} The Canvas element on the page to reference
@param [widthPercent=null] {Float} The width scale factor of the Canvas (if null uses default width set in the Canvas tag)
@param [heightPercent=null] {Float} The height scale factor of the Canvas (if null uses default height set in the Canvas tag)
*/
var $Canvas = function(elm, widthPercent, heightPercent) {
	if (elm === "undefined")
		throw "The Canvas id passed was not valid";

	/**
	This is the actual Canvas element in the document
	@property elm
	@protected
	*/
	this.elm				= elm;
	/**
	The context which is required to get anything showing up
	@property context
	*/
	this.context			= this.elm.getContext("2d");

	if (widthPercent != null)
		this.elm.width = document.body.clientWidth * widthPercent;

	if (heightPercent != null)
		this.elm.height = document.body.clientHeight * heightPercent;

	this.elm.style.width	= this.elm.width + "px";
	this.elm.style.height	= this.elm.height + "px";

	/**
	The current scale of the canvas on the x and y; 1 is default
	@property scale
	*/
	this.scale = new $Vector2(1, 1);
	/**
	The current width of the canvas (this works well with scaling)
	@property width
	*/
	this.width = this.elm.width;
	/**
	The current height of the canvas (this works well with scaling)
	@property height
	*/
	this.height = this.elm.height;

	/**
	Fires at the beginning this objects <a href="$Canvas.html#method_Draw">Draw</a> function before the <a href="$Canvas.html#event_Draw">drawing</a> event fires
	@event updating
	@param {$Canvas} Canvas
	*/
	this.updating			= new $Event();

	/**
	Fires whenever this objects <a href="$Canvas.html#method_Draw">Draw</a> function is called
	@event drawing
	@param {$Canvas} Canvas
	*/
	this.drawing			= new $Event();

	/**
	Calls all of the events registered to <a href="$Canvas.html#event_drawing">drawing</a> event on this Canvas object
	@method Draw
	*/
	this.Draw = function() {
		this.updating.Fire();
		this.drawing.Fire([this]);
	};

	/**
	This will scale the canvas up without resizing the canvas. It only scales up everything that is being drawn (1, 1) is default (2, 2) would be 2x the size of default
	@method Scale
	@param {Int} x The scale for the x-axis
	@param {Int} y The scale for the y-axis
	*/
	this.Scale = function(x, y) {
		this.context.scale(x, y);

		this.width = this.width * (1 / x);
		this.height = this.height * (1 / y);

		this.scale.x = x;
		this.scale.y = y;
	};
};

var Canvas = null;
var requestId = 0;

/**
Registers the Canvas to be used for the main drawing
@method registerCanvas
@param {Object} elm The Canvas element to be used from the document
@param [widthPercent=null] {Float} The width scale factor of the Canvas (if null uses default width set in the Canvas tag)
@param [heightPercent=null] {Float} The height scale factor of the Canvas (if null uses default height set in the Canvas tag)
@return
*/
function registerCanvas(elm, widthPercent, heightPercent) {
	if (Canvas != null)
		throw "Canvas already registered";

	Canvas = new $Canvas(elm, widthPercent, heightPercent);
	Canvas.drawing.Register(UpdateRequestId);

	Start();
}

//----------------------------------
// The following is automatic to register the HTML5 animation callback from the browser
//----------------------------------
(function(){
	var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
		window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

	window.requestAnimationFrame = requestAnimationFrame;
})();

function UpdateRequestId(context) {
	requestId = window.requestAnimationFrame(DrawCanvas);
}

function DrawCanvas() {
	Canvas.context.clearRect(0, 0, Canvas.elm.width, Canvas.elm.height);
	Canvas.Draw();
}

function Start() {
	if (Canvas == null)
		throw "You must first register a Canvas with the \"registerCanvas\" function";

	requestId = window.requestAnimationFrame(DrawCanvas);
}

function Stop() {
	if (requestId)
		window.cancelAnimationFrame(requestId);

	requestId = 0;
}


text:
package tdl.s3.helpers;

import java.io.File;
import org.junit.Test;

import java.nio.file.Path;
import java.nio.file.Paths;
import static net.trajano.commons.testing.UtilityClassTestUtil.assertUtilityClassWellDefined;

import static org.junit.Assert.*;

public class FileHelperTest {

    @Test
    public void shouldSatisfyContractForUtilityClass() throws Exception {
        assertUtilityClassWellDefined(FileHelper.class);
    }

    @Test
    public void getLockFilePath_returnsCorrect() throws Exception {
        Path path = Paths.get("src", "test", "resources", "test_lock", "file1.txt");
        Path lockFilePath = FileHelper.getLockFilePath(path.toFile());

        Path expectedLockFilePath = Paths.get("src", "test", "resources", "test_lock", "file1.txt.lock").toAbsolutePath();
        assertEquals(lockFilePath, expectedLockFilePath);
    }

    @Test
    public void lockFileExists_returnsTrue() throws Exception {
        Path path = Paths.get("src", "test", "resources", "test_lock", "file1.txt");
        boolean exists = FileHelper.lockFileExists(path.toFile());
        assertTrue(exists);
    }

    @Test
    public void lockFileExists_returnsFalse() throws Exception {
        Path path = Paths.get("src", "test", "resources", "test_lock", "file2.txt");
        boolean exists = FileHelper.lockFileExists(path.toFile());
        assertFalse(exists);
    }

    @Test
    public void getRelativeFilePathToCwd()
    {
        Path path = Paths.get("src", "test", "resources", "test_lock", "file2.txt");
        String expected = "src/test/resources/test_lock/file2.txt";
        File relativeFile = path.toFile();
        assertTrue(relativeFile.getPath().equals(expected));
        assertEquals(FileHelper.getRelativeFilePathToCwd(relativeFile), expected);

        Path absolutePath = path.toAbsolutePath();
        File absoluteFile = absolutePath.toFile();
        assertFalse(absoluteFile.getPath().startsWith(expected));
        assertTrue(absoluteFile.getPath().endsWith(expected));
        assertEquals(FileHelper.getRelativeFilePathToCwd(absoluteFile), expected);
    }
}


text:
package termios

// #include<stdlib.h>
import "C"

import "syscall"

func open_pty_master() (uintptr, error) {
	rc := C.posix_openpt(syscall.O_NOCTTY | syscall.O_RDWR)
	if rc < 0 {
		return 0, syscall.Errno(rc)
	}
	return uintptr(rc), nil
}

func Ptsname(fd uintptr) (string, error) {
	slavename := C.GoString(C.ptsname(C.int(fd)))
	return slavename, nil
}

func grantpt(fd uintptr) error {
	rc := C.grantpt(C.int(fd))
	if rc == 0 {
		return nil
	}
	return syscall.Errno(rc)
}

func unlockpt(fd uintptr) error {
	rc := C.unlockpt(C.int(fd))
	if rc == 0 {
		return nil
	}
	return syscall.Errno(rc)
}


text:
'use strict';

const _ = require('lodash');

function isRetry(ctx) {
  const attempts = ctx.retryAttempts || [];
  return attempts.length > 0;
}

function isCriticalError(ctx) {
  return ctx.res.statusCode >= 500;
}

function hasElapsedTime(ctx) {
  return !_.isUndefined(_.get(ctx, 'res.elapsedTime'));
}

function getBaseMessage(ctx) {
  return `${ctx.req.getMethod()} ${ctx.req.getUrl()} ${ctx.res.statusCode}`;
}

function createRequestMessage(ctx) {
  const res = ctx.res;

  const message = getBaseMessage(ctx);
  if (hasElapsedTime(ctx)) return `${message} ${res.elapsedTime} ms`;

  return message;
}

function createRetryMessage(ctx) {
  const res = ctx.res;
  const attempts = ctx.retryAttempts;

  const message = `Attempt ${attempts.length} ${getBaseMessage(ctx)}`;
  if (hasElapsedTime(ctx)) return `${message} ${res.elapsedTime} ms`;

  return message;
}

module.exports = (customLogger) => {
  const logger = customLogger || console;

  return async (ctx, next) => {
    await next();

    if (isRetry(ctx) && isCriticalError(ctx)) {
      return logger.warn(createRetryMessage(ctx));
    }
    logger.info(createRequestMessage(ctx));
  };
};


text:
package rngtools;

abstract public class ByteStream implements IByteStream
{
  protected ByteStream() {}

  public static ByteStream create( IBitStream bitStream )
  {
    return new ByteStreamFromBitStream( bitStream );
  }

  public static ByteStream create( IByteStream byteStream )
  {
    return new ByteStreamFromByteStream( byteStream );
  }

  public static ByteStream create( IRNG rng )
  {
    return new ByteStreamFromRNG( rng );
  }

  public long next( int byteCount )
  {
  long ret = 0;

    for (int i=0; i<byteCount; i++)
    {
      ret <<= 8;
      ret |= next();
    }

    return ret;
  }

  public void next( byte b[] )
  {
    next( b, 0, b.length );
  }

  public void next( byte b[], int offset, int amount )
  {
    for (int i=0; i<amount; i++)
      b[offset+i] = (byte) next();
  }
}

class ByteStreamFromBitStream extends ByteStream
{
BitStream bitStream;

  ByteStreamFromBitStream( IBitStream bitStream )
  {
    if (bitStream instanceof BitStream)
      this.bitStream = (BitStream) bitStream;
    else
      this.bitStream = BitStream.create( bitStream );
  }

  @Override
  public int next()
  {
    return bitStream.next( 8 );
  }

  @Override
  public IByteStream deepCopy()
  {
    // TODO Auto-generated method stub
    return null;
  }
}

class ByteStreamFromByteStream extends ByteStream
{
IByteStream byteStream;

  ByteStreamFromByteStream( IByteStream byteStream )
  {
    this.byteStream = byteStream;
  }

  @Override
  public int next()
  {
    return byteStream.next();
  }

  @Override
  public IByteStream deepCopy()
  {
    // TODO Auto-generated method stub
    return byteStream.deepCopy();
  }
}

class ByteStreamFromRNG extends ByteStream
{
IRNG rng;
byte data[];
int position;

  ByteStreamFromRNG( IRNG rng )
  {
    this.rng = rng;
    data = null;
    position = -1;
  }

  @Override
  public int next()
  {
    if (position < 0)
    {
      if (null == data)
        data = rng.next();
      else
        rng.next( data );

      position = data.length - 1;
    }

    return 0xff & (data[position--]);
  }

  @Override
  public IByteStream deepCopy()
  {
    // TODO Auto-generated method stub
    return null;
  }
}


text:
/* crypto/x509/x509cset.c */
/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
 * project 2001.
 */
/* ====================================================================
 * Copyright (c) 2001 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

#include <stdio.h>
#include "cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>

int X509_CRL_set_version(X509_CRL *x, long version)
	{
	if (x == NULL) return(0);
	if (x->crl->version == NULL)
		{
		if ((x->crl->version=M_ASN1_INTEGER_new()) == NULL)
			return(0);
		}
	return(ASN1_INTEGER_set(x->crl->version,version));
	}

int X509_CRL_set_issuer_name(X509_CRL *x, X509_NAME *name)
	{
	if ((x == NULL) || (x->crl == NULL)) return(0);
	return(X509_NAME_set(&x->crl->issuer,name));
	}

int X509_CRL_set_lastUpdate(X509_CRL *x, const ASN1_TIME *tm)
	{
	ASN1_TIME *in;

	if (x == NULL) return(0);
	in=x->crl->lastUpdate;
	if (in != tm)
		{
		in=M_ASN1_TIME_dup(tm);
		if (in != NULL)
			{
			M_ASN1_TIME_free(x->crl->lastUpdate);
			x->crl->lastUpdate=in;
			}
		}
	return(in != NULL);
	}

int X509_CRL_set_nextUpdate(X509_CRL *x, const ASN1_TIME *tm)
	{
	ASN1_TIME *in;

	if (x == NULL) return(0);
	in=x->crl->nextUpdate;
	if (in != tm)
		{
		in=M_ASN1_TIME_dup(tm);
		if (in != NULL)
			{
			M_ASN1_TIME_free(x->crl->nextUpdate);
			x->crl->nextUpdate=in;
			}
		}
	return(in != NULL);
	}

int X509_CRL_sort(X509_CRL *c)
	{
	int i;
	X509_REVOKED *r;
	/* sort the data so it will be written in serial
	 * number order */
	sk_X509_REVOKED_sort(c->crl->revoked);
	for (i=0; i<sk_X509_REVOKED_num(c->crl->revoked); i++)
		{
		r=sk_X509_REVOKED_value(c->crl->revoked,i);
		r->sequence=i;
		}
	c->crl->enc.modified = 1;
	return 1;
	}

int X509_REVOKED_set_revocationDate(X509_REVOKED *x, ASN1_TIME *tm)
	{
	ASN1_TIME *in;

	if (x == NULL) return(0);
	in=x->revocationDate;
	if (in != tm)
		{
		in=M_ASN1_TIME_dup(tm);
		if (in != NULL)
			{
			M_ASN1_TIME_free(x->revocationDate);
			x->revocationDate=in;
			}
		}
	return(in != NULL);
	}

int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial)
	{
	ASN1_INTEGER *in;

	if (x == NULL) return(0);
	in=x->serialNumber;
	if (in != serial)
		{
		in=M_ASN1_INTEGER_dup(serial);
		if (in != NULL)
			{
			M_ASN1_INTEGER_free(x->serialNumber);
			x->serialNumber=in;
			}
		}
	return(in != NULL);
	}


text:
require 'chef/mixin/deep_merge'

class Chef
  class RunList
    include Enumerable

    attr_reader :recipes, :roles, :run_list

    def initialize
      @run_list = Array.new
      @recipes = Array.new
      @roles = Array.new
      @seen_roles = Array.new
    end

    def <<(item)
      type, entry, fentry = parse_entry(item)
      case type
      when 'recipe'
        @recipes << entry unless @recipes.include?(entry)
      when 'role'
        @roles << entry unless @roles.include?(entry)
      end
      @run_list << fentry unless @run_list.include?(fentry)
      self
    end

    def ==(*isequal)
      check_array = nil
      if isequal[0].kind_of?(Chef::RunList)
        check_array = isequal[0].run_list
      else
        check_array = isequal.flatten
      end

      return false if check_array.length != @run_list.length

      check_array.each_index do |i|
        to_check = check_array[i]
        type, name, fname = parse_entry(to_check)
        return false if @run_list[i] != fname
      end

      true
    end

    def to_s
      @run_list.join(", ")
    end

    def empty?
      @run_list.length == 0 ? true : false
    end

    def [](pos)
      @run_list[pos]
    end

    def []=(pos, item)
      type, entry, fentry = parse_entry(item)
      @run_list[pos] = fentry
    end

    def each(&block)
      @run_list.each { |i| block.call(i) }
    end

    def each_index(&block)
      @run_list.each_index { |i| block.call(i) }
    end

    def include?(item)
      type, entry, fentry = parse_entry(item)
      @run_list.include?(fentry)
    end

    def reset!(*args)
      @run_list = Array.new
      @recipes = Array.new
      @roles = Array.new
      args.flatten.each do |item|
        if item.kind_of?(Chef::RunList)
          item.each { |r| self << r }
        else
          self << item
        end
      end
      self
    end

    def remove(item)
      type, entry, fentry = parse_entry(item)
      @run_list.delete_if { |i| i == fentry }
      if type == "recipe"
        @recipes.delete_if { |i| i == entry }
      elsif type == "role"
        @roles.delete_if { |i| i == entry }
      end
      self
    end

    def expand(from='server', couchdb=nil, rest=nil)
      couchdb = couchdb ? couchdb : Chef::CouchDB.new
      recipes = Array.new
      default_attrs = Mash.new
      override_attrs = Mash.new

      @run_list.each do |entry|
        type, name, fname = parse_entry(entry)
        case type
        when 'recipe'
          recipes << name unless recipes.include?(name)
        when 'role'
          role = begin
                   next if @seen_roles.include?(name)
                   @seen_roles << name
                   if from == 'disk' || Chef::Config[:solo]
                     # Load the role from disk
                     Chef::Role.from_disk("#{name}") || raise(Chef::Exceptions::RoleNotFound)
                   elsif from == 'server'
                     # Load the role from the server
                     begin
                       (rest || Chef::REST.new(Chef::Config[:role_url])).get_rest("roles/#{name}")
                     rescue Net::HTTPServerException
                       raise Chef::Exceptions::RoleNotFound if $!.message == '404 "Not Found"'
                       raise
                     end
                   elsif from == 'couchdb'
                     # Load the role from couchdb
                     Chef::Role.cdb_load(name, couchdb) rescue Chef::Exceptions::CouchDBNotFound raise(Chef::Exceptions::RoleNotFound)
                   end
                 rescue Chef::Exceptions::RoleNotFound
                   Chef::Log.error("Role #{name} is in the runlist but does not exist. Skipping expand.")
                   next
                 end
          rec, d, o = role.run_list.expand(from, couchdb, rest)
          rec.each { |r| recipes <<  r unless recipes.include?(r) }
          default_attrs = Chef::Mixin::DeepMerge.merge(default_attrs, Chef::Mixin::DeepMerge.merge(role.default_attributes,d))
          override_attrs = Chef::Mixin::DeepMerge.merge(override_attrs, Chef::Mixin::DeepMerge.merge(role.override_attributes, o))
        end
      end
      return recipes, default_attrs, override_attrs
    end

    def parse_entry(entry)
      case entry
      when /^(.+)\[(.+)\]$/
        [ $1, $2, entry ]
      else
        [ 'recipe', entry, "recipe[#{entry}]" ]
      end
    end

  end
end


text:
namespace Cradiator.Config
{
	/// <summary>
	/// settings for a certain 'view' or group of pojects that belong together
	/// or someone wants to see in 1 screen/ view
	/// </summary>
	// ReSharper disable UnusedMemberInSuper.Global
	public interface IViewSettings
	{
		string URL { get; set; }
		string SkinName { get; set; }
		string ProjectNameRegEx { get; set; }
		string CategoryRegEx { get; set; }
		string ServerNameRegEx { get; set; }
		string ViewName { get; set; }
		bool ShowOnlyBroken { get; set; }
		bool ShowServerName { get; set; }

		//extended settings
		bool ShowOutOfDate { get; set; }
		int OutOfDateDifferenceInMinutes { get; set; }

	}
	// ReSharper restore UnusedMemberInSuper.Global
}


text:
describe
  .configure()
  .skipEdge()
  .run('amp-accordion', function() {
    this.timeout(10000);
    const extensions = ['amp-accordion'];
    const body = `
  <amp-accordion media="(min-width: 500px)" id="media-accordion">

        Title

Bunch of awesome content

  </amp-accordion>
  `;
    describes.integration(
      'amp-accordion',
      {
        body,
        extensions,
      },
      env => {
        let win, iframe, doc;
        beforeEach(() => {
          win = env.win;
          iframe = env.iframe;
          doc = win.document;
          iframe.width = 300;
        });

        it('should respect the media attribute', () => {
          const accordion = doc.getElementById('media-accordion');
          expect(iframe.clientWidth).to.equal(300);
          expect(accordion.className).to.match(
            /i-amphtml-hidden-by-media-query/
          );
          iframe.width = 600;
          expect(iframe.clientWidth).to.equal(600);
          return timeout(200).then(() => {
            expect(accordion.className).to.not.match(
              /i-amphtml-hidden-by-media-query/
            );
          });
        });
      }
    );
  });

/**
 * @param {number} ms
 * @return {!Promise}
 */
function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}


text:
/* CurvatureVolumeMaterial: volume rendering using curvature..
 */

// local
#include "CurvatureVolumeMaterial.h"
#include "HitRecord.h"
#include "Primitive.h"
#include "Scene.h"

// libs
//#include <NrrdIO.h>
#include <itkImage.h>
#include <itkImageFileReader.h>
#include <itkExceptionObject.h>
#include <itkNumericTraits.h>
#include <itkCurvatureAnisotropicDiffusionImageFilter.h>
#include <itkGradientAnisotropicDiffusionImageFilter.h>

// std
#include <cmath>
#include <fstream>
#include <cstdlib>
using namespace std;

void CurvatureVolumeMaterial::preprocess(){}

template<class MatrixType, class VectorType >
MatrixType outer_product( const VectorType & v1, const VectorType & v2 )
{
  MatrixType m;
  for( size_t r=0; r<v1.Size(); ++r )
  {
    for( size_t c=0; c<v2.Size(); ++c )
    {
      m[r][c] = v1[r] * v2[c];
    }
  }
  return m;
}

// dot product between two different vector types
template<class V1, class V2>
float inner_product( const V1 & v1, const V2 & v2 )
{
  float dot = 0.f;
  for(size_t i=0; i<v1.length(); ++i)
  {
    dot += v1[i]*v2[i];
  }
  return dot;
}

Color GoochShade( const Color & objectColor, float normalLightCosine )
{
  // see http://www.cs.northwestern.edu/~ago820/SIG98/paper/node6.html

  Color blue(0.f,0.f,1.f);
  Color yellow(1.f,1.f,0.f);
  Color black(0.f,0.f,0.f);

  float coolPart = 0.15;
  Color objectCool = (1-coolPart)*black + coolPart*objectColor;
  float warmPart = 0.5;
  Color objectWarm = (1-warmPart)*black + warmPart*objectColor;

  float darken = 0.4;
  Color cool = darken*blue + objectCool;
  Color warm = darken*yellow + objectWarm;

  float lightPart = (1+normalLightCosine)/2;
  Color result =  lightPart * cool + (1-lightPart) * warm;

  return result;
}

void CurvatureVolumeMaterial::shade( rgb & result, const RenderContext & context, const ray & r, HitRecord & hit, int depth, double attenuation) const{

  // find texit:
  double t_enter = hit.t, t_exit=t_enter;
  vector3d safety_offset = r.direction() * 1e-2;
  ray r_inside( r.eval( hit.t ) + safety_offset , r.direction() );
  HitRecord hit_inside;
  hit_inside.t = MYMAX;

  hit.prim->intersect( hit_inside , context , r_inside );
  if( hit_inside.t < MYMAX ){ // hit other side
    t_exit = t_enter+hit_inside.t;
  }

  double it = ceil( t_enter / grid_stepsize);
  double t = t_enter;

  Color accum_color(0,0,0);
  double accum_opacity = 0;
  float max_intensity = 0;

  while( t < t_exit ){
    Point pt = r.eval( t );
    Point P = pt - lower;
    P = P / diag;

    for(size_t i=0; i<3; ++i) if(P[i] < 0) P[i] = 0;
    P = P * vector3d( (size1-1) , (size2-1) , (size3-1) );
    Point P_lower = vector3d( floor( P.x() ) , floor( P.y() ) , floor( P.z() ) );
    Point P_diff = P - P_lower;

    int lower_int[3] = { ((int)P_lower.x()) , ((int)P_lower.y()) , ((int)P_lower.z()) };

    // now P in lattice coordinates:
    if( lower_int[0] == (size1-1))
      lower_int[0]--;
    if(lower_int[1] == (size2-1))
      lower_int[1]--;
    if(lower_int[2] == (size3-1))
      lower_int[2]--;

    double value = 0.f;
    if(nearest) // nearest neighbor
    {
      ImageType::IndexType ind = {{ lower_int[0], lower_int[1], lower_int[2] }};
      double v000 = data->GetPixel(ind);
      value = v000;
    }
    else // linear interpolation
    {
      ImageType::IndexType ind = {{ lower_int[0], lower_int[1], lower_int[2] }};
      double v000 = data->GetPixel(ind);
      ind[0]+=1;
      double v100 = data->GetPixel(ind);
      ind[1]+=1;
      double v110 = data->GetPixel(ind);
      ind[2]+=1;
      double v111 = data->GetPixel(ind);
      ind[0]-=1;
      double v011 = data->GetPixel(ind);
      ind[2]-=1;
      double v010 = data->GetPixel(ind);
      ind[1]-=1;
      ind[2]+=1;
      double v001 = data->GetPixel(ind);
      ind[0]+=1;
      double v101 = data->GetPixel(ind);

      value = v000 * (1-P_diff.x())*(1-P_diff.y())*(1-P_diff.z()) +
              v100 * P_diff.x() * (1-P_diff.y())*(1-P_diff.z()) +
              v010 * (1-P_diff.x()) * P_diff.y() * (1-P_diff.z()) +
              v001 * (1-P_diff.x()) * (1-P_diff.y()) * P_diff.z() +
              v101 * P_diff.x() * (1-P_diff.y()) * P_diff.z() +
              v011 * (1-P_diff.x()) * P_diff.y() * P_diff.z() +
              v110 * P_diff.x() * P_diff.y() * (1-P_diff.z()) +
              v111 * P_diff.x() * P_diff.y() * P_diff.z();
    }

    float opacity;
    Color color;
    cmap.lookup( (float)value , opacity , color );

    if( opacity > 0 )
    {

      // get the gradient and hessian for this point:
      ImageType::IndexType ind = {{ lower_int[0], lower_int[1], lower_int[2] }};
      GradientType g = gradient->GetPixel(ind);
      HessianType H = hessian->GetPixel(ind);

      float g_mag = g.GetNorm();
      GradientType n = -g / g_mag;
      MatrixType P;
      P.SetIdentity();
      P = P - outer_product<MatrixType,GradientType>( n, n );
      MatrixType G;
      if(normalFlipped)
        G = P * H.PostMultiply(P);
      else
        G = (P*-1) * H.PostMultiply(P);
      G /= g_mag;

      // convert vector3d to itk::CovariantVector
      GradientType v;
      Vector v_data = r.direction();
      for(size_t vi=0; vi<v.Size(); ++vi)
        v[vi] = v_data[vi];

      float num = v * ( G * v );
      float den = v * ( P * v );

      float k_v = num / (den + itk::NumericTraits<float>::min());

      float T = 0.75 * curvThick; //  ~= num pixels to shade..

      float boundary = std::sqrt( T * k_v * (2-T*k_v) );

      float intersection_cosine = fabs(v * n);

      float fuzzy_boundary = curvThick - T;
      float diff = intersection_cosine - boundary;

      // Convert to gooch shaded color:
      Color lightColor;
      Vector lightDir;
      float lightDistance = context.scene->lights[0]->getLight( lightColor , lightDir , context , pt );
      color = GoochShade( color, inner_product(lightDir, n ) );

      //if( intersection_cosine <= boundary + fuzzy_boundary )
      if( diff <= fuzzy_boundary )
      {
        float interp = 1.f;
        if( diff > 0 )
          interp = 1-diff/fuzzy_boundary;
        color = (1-interp) * color + interp * Color(0.f,0.f,0.f);
      }

    }

    accum_color += color * opacity * (1-accum_opacity);
    accum_opacity += opacity*(1-accum_opacity);

    t += world_stepsize;
  }

  // volume should be "see-through", so now going to cast ray behind it...
  //(may need to add safety small vector to new_r origin.....)
  ray new_r( r.eval( t_exit ) , r.direction() );
  Color exit_color(0,0,0);
  context.scene->render( exit_color , new_r );
  accum_color += exit_color * (1-accum_opacity);

  result = accum_color;
}

/* The following two functions were given to the class from
 * the instructor and TA.
*/

void swap(short& data)
{
  char* p=(char*)&data;
  char tmp=p[0];
  p[0]=p[1];
  p[1]=tmp;
}

CurvatureVolumeMaterial::CurvatureVolumeMaterial(const std::string& data_fn,
                                         const std::string& cmap_fn,
                                         const Point& lower,
                                         const Point& upper,
                                         double grid_stepsize,
                                         float maxopacity,
                                         float curvThickness,
                                         bool flipNormal,
                                         bool nearest_neighbor
                                         )
:cmap(cmap_fn),
 lower(lower),
 upper(upper),
 grid_stepsize(grid_stepsize),
 maxopacity(maxopacity),
 curvThick(curvThickness),
 normalFlipped(flipNormal),
 nearest(nearest_neighbor)
{
  diag = upper-lower;
  bounds[0] = lower;
  bounds[1] = upper;

  typedef itk::ImageFileReader<ImageType> Reader;
  Reader::Pointer reader = Reader::New();
  reader->SetFileName(data_fn);
  try
  {
    reader->Update();
  }
  catch(itk::ExceptionObject e)
  {
    std::cerr << "Error reading file " << data_fn << ": " << e << std::endl;
    exit(1);
  }

  std::cerr << "smoothing data... " << std::endl;
  //typedef itk::CurvatureAnisotropicDiffusionImageFilter<ImageType,ImageType> SmoothFilter;
  typedef itk::GradientAnisotropicDiffusionImageFilter<ImageType,ImageType> SmoothFilter;
  SmoothFilter::Pointer smoother = SmoothFilter::New();
  smoother->SetInput(reader->GetOutput());
  smoother->SetNumberOfIterations(2);
  smoother->SetConductanceParameter(1.2);
	smoother->SetNumberOfThreads(8);
  try
  {
    smoother->Update();
  }
  catch(itk::ExceptionObject e)
  {
    std::cerr << "Error smoothing image: " << e << std::endl;
    exit(1);
  }

  //data = reader->GetOutput();
  data = smoother->GetOutput();

  std::cerr << "computing gradient and hessian... " << std::endl;

  GradientFilter::Pointer gradientFilter = GradientFilter::New();
  gradientFilter->SetSigma(1.0);
  gradientFilter->SetInput( data );
	gradientFilter->SetNumberOfThreads(8);
  gradient = gradientFilter->GetOutput();
  try
  {
    gradientFilter->Update();
  }
  catch(itk::ExceptionObject e)
  {
    std::cerr << "Error computing gradient: " << e << std::endl;
    exit(1);
  }

  HessianFilter::Pointer hessianFilter = HessianFilter::New();
  hessianFilter->SetSigma(1.0);
  hessianFilter->SetInput( data );
	hessianFilter->SetNumberOfThreads(8);
  hessian = hessianFilter->GetOutput();
  try
  {
    hessianFilter->Update();
  }
  catch(itk::ExceptionObject e)
  {
    std::cerr << "Error computing hessian: " << e << std::endl;
    exit(1);
  }

  std::cerr << "done computing gradient and hessian." << std::endl;

  size1 = data->GetLargestPossibleRegion().GetSize()[0];
  size2 = data->GetLargestPossibleRegion().GetSize()[1];
  size3 = data->GetLargestPossibleRegion().GetSize()[2];

  cellsize = diag * Vector(1./(size1-1), 1./(size2-1), 1./(size3-1));

  world_stepsize = cellsize.length()/pow(3, 1./3.) * grid_stepsize;
  std::cerr << "world step size: " << world_stepsize << std::endl;
  cmap.rescale(world_stepsize);

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TweetLib.Utils.Data;

namespace TweetLib.Core.Features.Notifications {
	public sealed class DesktopNotification {
		private const string DefaultHeadLayout = @"<meta charset=""utf-8""><link href=""https://ton.twimg.com/tweetdeck-web/web/dist/bundle.4b1f87e09d.css"" rel=""stylesheet"">";

		public enum Position {
			TopLeft,
			TopRight,
			BottomLeft,
			BottomRight,
			Custom
		}

		public enum Size {
			Auto,
			Custom
		}

		public string ColumnId { get; }
		public string ChirpId { get; }

		public string ColumnTitle { get; }
		public string TweetUrl { get; }
		public string QuoteUrl { get; }

		private readonly string html;
		private readonly int characters;

		public DesktopNotification(string columnId, string chirpId, string title, string html, int characters, string tweetUrl, string quoteUrl) {
			this.ColumnId = columnId;
			this.ChirpId = chirpId;

			this.ColumnTitle = title;
			this.TweetUrl = tweetUrl;
			this.QuoteUrl = quoteUrl;

			this.html = html;
			this.characters = characters;
		}

		public int GetDisplayDuration(int value) {
			return 2000 + Math.Max(1000, value * characters);
		}

		internal string GenerateHtml(string bodyClasses, string? headLayout, string? customStyles, IEnumerable<InjectedString> injections, string[] scripts) { // TODO
			headLayout ??= DefaultHeadLayout;
			customStyles ??= string.Empty;

			StringBuilder build = new StringBuilder(1000);
			build.Append("<!DOCTYPE html>");
			build.Append(headLayout);
			build.Append("<link rel='stylesheet' href='td://resources/notification/notification.css'>");

			if (!string.IsNullOrWhiteSpace(customStyles)) {
				build.Append("");
			}

			build.Append("
");
			build.Append(html);
			build.Append("
");
			build.Append("<tweetduck-script-placeholder>");

			string result = build.ToString();
			return injections.Aggregate(result, static (current, injection) => injection.InjectInto(current)).Replace("<tweetduck-script-placeholder>", GenerateScripts(scripts));
		}

		private string GenerateScripts(string[] scripts) {
			if (scripts.Length == 0) {
				return "";
			}

			StringBuilder build = new StringBuilder();

			foreach (string script in scripts) {
				build.Append("");
			}

			return build.ToString();
		}
	}
}


text:
namespace ProductsByPattern
{
    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;

    public class ProductsByPattern
    {
        public static void Main()
        {
            Console.Write("pattern: ");
            string input = DatabaseEscaping(Console.ReadLine());

            var products = GetProduct(input);
            foreach (var product in products)
            {
                Console.WriteLine(product);
            }
        }

        private static IEnumerable<string> GetProduct(string pattern)
        {
            List<string> result = new List<string>();
            SqlConnection dbCon = new SqlConnection(Settings.Default.ConString);
            dbCon.Open();

            using (dbCon)
            {
                SqlCommand command = new SqlCommand(
                    "SELECT ProductName FROM Products WHERE charindex(@pattern, ProductName) > 0", dbCon);

                command.Parameters.AddWithValue("@pattern", pattern);
                SqlDataReader reader = command.ExecuteReader();
                using (reader)
                {
                    while (reader.Read())
                    {
                        result.Add((string)reader["ProductName"]);
                    }
                }
            }

            return result;
        }

        private static string DatabaseEscaping(string input)
        {
            string symbols = "'%\\_";
            for (int i = 0; i < symbols.Length; i++)
			{
			    input = input.Replace(symbols[i], '\0');
			}

            return input;
        }
    }
}


text:
module.exports = function(left, operator, right) {
	switch (operator) {
		case '>': return left > right;
		case '>=': return left >= right;
		case '<': return left < right;
		case '<=': return left <= right;
		case '=':
		case '==': return left === right;
		case '!':
		case '!=':
		case '<>': return left !== right;
		default:
			throw new Error('Unknown operator ' + operator + '.', '^.');
	}
};


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.MSBuild.Build;

namespace Microsoft.CodeAnalysis.MSBuild
{
    internal interface IProjectFileLoader : ILanguageService
    {
        string Language { get; }
        Task<IProjectFile> LoadProjectFileAsync(
            string path,
            IDictionary<string, string> globalProperties,
            ProjectBuildManager buildManager,
            CancellationToken cancellationToken);
    }
}


text:
<?php
namespace Ifresco\ClientBundle\Controller;

use Ifresco\ClientBundle\Component\Alfresco\Lib\NodeCache;
use Ifresco\ClientBundle\Component\Alfresco\Node;
use Ifresco\ClientBundle\Component\Alfresco\SpacesStore;
use Ifresco\ClientBundle\Security\User;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Ifresco\ClientBundle\Component\Alfresco\REST\RESTTags;
use Ifresco\ClientBundle\Helper\PluginBoot;
use Symfony\Component\Process\Process;

class PluginController extends Controller
{
    public function getPluginsAction(Request $request) {
    	$PluginBoot = new PluginBoot($this->get('kernel')->getRootDir());

    	$Bundles = array();
    	$ExtensionPath = $this->get('kernel')->getRootDir() . '/../shared/Plugin';
    	$ritit = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($ExtensionPath), \RecursiveIteratorIterator::CHILD_FIRST);
    	$r = array();
    	foreach ($ritit as $splFileInfo) {
    		$path = $splFileInfo->isDir()
    		? array($splFileInfo->getFilename() => array())
    		: array($splFileInfo->getFilename());

    		for ($depth = $ritit->getDepth() - 1; $depth >= 0; $depth--) {
    			$path = array($ritit->getSubIterator($depth)->current()->getFilename() => $path);
    		}
    		$r = array_merge_recursive($r, $path);
    	}

    	foreach ($r as $ExtensionBundle) {
    		foreach ($ExtensionBundle as $MainFiles) {
    			if (is_array($MainFiles))
    				continue;

    			if (preg_match("/^.+\Bundle.php$/i",$MainFiles)) {

    				$BundlePathArray = $this->splitAtUpperCase($MainFiles);
    				unset($BundlePathArray[count($BundlePathArray)-1]);

    				$BundleName = join($BundlePathArray, "")."Bundle";
    				$BundleOnlyName = preg_replace("/^Plugin(.*)/","$1",$BundleName);

    				$BundleNamespace = join($BundlePathArray, "\\");
    				$RealBundleName = $BundleNamespace."Bundle";
    				$enabled = false;
    				if ($PluginBoot->inBootConfig($RealBundleName))
    					$enabled = $PluginBoot->getBundleBootConfig($RealBundleName);

    				$config = (object)array("description"=>"","version"=>"","author");
    				$resource = "/config.json";
    				if (file_exists($ExtensionPath."/".$BundleOnlyName.$resource))
    					$config = json_decode(file_get_contents($ExtensionPath."/".$BundleOnlyName.$resource));

    				$Bundles[] = array(
    						"name"=>$BundleOnlyName,
    						"status"=>$enabled,
    						"version"=>(isset($config->version) ? $config->version : ''),
    						"description"=>(isset($config->description) ? $config->description : ''),
    						"author"=>(isset($config->author) ? $config->author : '')
    				);

    			}
    		}
    	}

    	$response = new JsonResponse(array("success"=>true,"plugins"=>$Bundles));
    	return $response;
    }

    public function savePuginStatusAction(Request $request) {
    	$status = $request->get('status');
    	$bundle = $request->get('plugin');

    	if ($status == "true") {
    		$status = true;
    	}
    	else if ($status == "false") {
    		$status = false;
    	}

    	$PluginBoot = new PluginBoot($this->get('kernel')->getRootDir(),$this->get('kernel')->getEnvironment());
    	$PluginBoot->writeInBootConfig("Plugin\\".$bundle,$status,true);
    	$PluginBoot->save();

    	$PluginBoot->cleanUpRouting();
    	error_reporting(E_ALL);
    	ini_set("display_errors", "E_ALL");
    	$this->executeSymfonyCommand("cache:clear","--env=".$this->get('kernel')->getEnvironment());

    	$resp = array("success"=>true);
		/* // THIS DOESNT WORK IN PROD ENV FIX IT WITH DIRTY HACK
    	$response = new JsonResponse($resp);
    	return $response;*/
    	die(json_encode($resp));
    }

    private function splitAtUpperCase($s) {
    	return preg_split('/(?=[A-Z])/', $s, -1, PREG_SPLIT_NO_EMPTY);
    }

    private function executeSymfonyCommand($command,$add="") {
    	$kernel = $this->get('kernel');
    	$application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
    	$application->setAutoExit(false);

    	$options = array('command' => $command, $add);
    	$application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
    }
}


text:
#ifndef SHINY_H
#define SHINY_H

/*---------------------------------------------------------------------------*/

#include "ShinyMacros.h"
#include "ShinyManager.h"

#endif /* end of include guard */


text:
package ca.uqac.lif.bullwinkle.output;

import java.util.ArrayDeque;
import java.util.Deque;

import ca.uqac.lif.bullwinkle.ParseNode;

/**
 * Traverses a parse tree and converts it into a simple XML representation.
 * @author Sylvain Hallé
 */
public class XmlVisitor implements OutputFormatVisitor
{
	/**
	 * A stack keeping the parent nodes
	 */
	private final Deque<String> m_parents;

	/**
	 * A stack keeping the indents
	 */
	private final Deque<String> m_indents;

	/**
	 * A string builder where the output XML is progressively written
	 */
	private final StringBuilder m_output;

	/**
	 * The amount of indentation to add to each nested element
	 */
	private static final String s_indent = "  ";

	/**
	 * The name given to the topmost element of the tree (i.e. the one that
	 * encloses the whole tree)
	 */
	private String m_topElementName = "parsetree";

	/**
	 * The element name used to surround leaf tokens
	 */
	private String m_tokenElementName = "token";

	/**
	 * Creates a new XML visitor
	 */
	public XmlVisitor()
	{
		super();
		m_parents = new ArrayDeque<String>();
		m_indents = new ArrayDeque<String>();
		m_output = new StringBuilder();
		m_indents.push("");
	}

	/**
	 * Sets the element name used to surround the XML parse tree
	 * @param name The element name
	 */
	public void setTopElementName(final String name)
	{
		m_topElementName = name;
	}

	/**
	 * Sets the element name used to surround leaf tokens
	 * @param name The element name
	 */
	public void setTokenElementName(final String name)
	{
		m_tokenElementName = name;
	}

	@Override
	public void visit(ParseNode node)
	{
		String label = node.getValue();
		String current_indent = m_indents.peek() + s_indent;
		if (label == null)
		{
			label = node.getToken();
			m_output.append(current_indent).append("<").append(m_tokenElementName).append(">\n");
			m_indents.push(current_indent);
			current_indent = m_indents.peek();
			m_output.append(current_indent).append(label).append("\n");
			m_parents.push(m_tokenElementName);
		}
		else
		{
			// Remove symbols surrounding the name of a rule
			label = label.replace("<", "");
			label = label.replace(">", "");
			m_output.append(current_indent).append("<").append(label).append(">\n");
			m_parents.push(label);
			m_indents.push(current_indent);
		}
	}

	@Override
	public void pop()
	{
		String element_name = m_parents.pop();
		String current_indent = m_indents.pop();
		m_output.append(current_indent).append("</").append(element_name).append(">\n");
	}

	@Override
	public String toOutputString()
	{
		StringBuilder out = new StringBuilder();
		out.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
		out.append("<!-- File auto-generated by Bullwinkle -->\n");
		out.append("<").append(m_topElementName).append(">\n").append(m_output).append("</").append(m_topElementName).append(">");
		return out.toString();
	}

}