text:
package org.apache.hadoop.hbase.regionserver;

import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.RegionTooBusyException;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * TestHRegion with hbase.busy.wait.duration set to 1000 (1 second).
 * We can't use parameterized test since TestHRegion is old fashion.
 */
@Category(MediumTests.class)
public class TestHRegionBusyWait extends TestHRegion {
  // TODO: This subclass runs all the tests in TestHRegion as well as the test below which means
  // all TestHRegion tests are run twice.
  @Before
  public void setup() throws IOException {
    super.setup();
    conf.set("hbase.busy.wait.duration", "1000");
  }

  /**
   * Test RegionTooBusyException thrown when region is busy
   */
  @Test (timeout=6000)
  public void testRegionTooBusy() throws IOException {
    String method = "testRegionTooBusy";
    byte[] tableName = Bytes.toBytes(method);
    byte[] family = Bytes.toBytes("family");
    region = initHRegion(tableName, method, conf, family);
    final AtomicBoolean stopped = new AtomicBoolean(true);
    Thread t = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          region.lock.writeLock().lock();
          stopped.set(false);
          while (!stopped.get()) {
            Thread.sleep(100);
          }
        } catch (InterruptedException ie) {
        } finally {
          region.lock.writeLock().unlock();
        }
      }
    });
    t.start();
    Get get = new Get(row);
    try {
      while (stopped.get()) {
        Thread.sleep(100);
      }
      region.get(get);
      fail("Should throw RegionTooBusyException");
    } catch (InterruptedException ie) {
      fail("test interrupted");
    } catch (RegionTooBusyException e) {
      // Good, expected
    } finally {
      stopped.set(true);
      try {
        t.join();
      } catch (Throwable e) {
      }

      HRegion.closeHRegion(region);
      region = null;
    }
  }
}


text:
//// [matchReturnTypeInAllBranches.ts]
// Represents a monster who enjoys ice cream
class IceCreamMonster {
    private iceCreamFlavor: string;
    private iceCreamRemaining: number;
    private wantsSprinkles: boolean;
    private soundsWhenEating: string;
    public name: string;
    constructor(iceCreamFlavor: string, wantsSprinkles: boolean, soundsWhenEating: string, name: string) {
        this.iceCreamFlavor = iceCreamFlavor;
        this.iceCreamRemaining = 100;
        this.wantsSprinkles = wantsSprinkles;
        this.soundsWhenEating = soundsWhenEating;
        this.name = name;
    }
    /**
* Tells the IceCreamMonster to eat their ice cre    am!
*
* @param {number} amount The amount of ice cream to e    at.
* @return {boolean} True if ice cream remains, false if there is no more ice cream le    ft.
*/
    public eatIceCream(amount: number): boolean {
        this.iceCreamRemaining -= amount;
        if (this.iceCreamRemaining <= 0)
        {
            this.iceCreamRemaining = 0;
            return false;
        }
        else
        {
            return 12345;
        }
    }
}
var cookieMonster: IceCreamMonster;
cookieMonster = new IceCreamMonster("Chocolate Chip", false, "COOOOOKIE", "Cookie Monster");

//// [matchReturnTypeInAllBranches.js]
// Represents a monster who enjoys ice cream
var IceCreamMonster = /** @class */ (function () {
    function IceCreamMonster(iceCreamFlavor, wantsSprinkles, soundsWhenEating, name) {
        this.iceCreamFlavor = iceCreamFlavor;
        this.iceCreamRemaining = 100;
        this.wantsSprinkles = wantsSprinkles;
        this.soundsWhenEating = soundsWhenEating;
        this.name = name;
    }
    /**
* Tells the IceCreamMonster to eat their ice cre    am!
*
* @param {number} amount The amount of ice cream to e    at.
* @return {boolean} True if ice cream remains, false if there is no more ice cream le    ft.
*/
    IceCreamMonster.prototype.eatIceCream = function (amount) {
        this.iceCreamRemaining -= amount;
        if (this.iceCreamRemaining <= 0) {
            this.iceCreamRemaining = 0;
            return false;
        }
        else {
            return 12345;
        }
    };
    return IceCreamMonster;
}());
var cookieMonster;
cookieMonster = new IceCreamMonster("Chocolate Chip", false, "COOOOOKIE", "Cookie Monster");

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var should = require('chai').should;
var expect = require('chai').expect;
var supertest = require('supertest');

var path = require('path');
var fs = require('fs');
var fileQuery = require('../index.js').fileQuery;
var fileQuerySync = require('../index.js').fileQuerySync;
var baseDir = __dirname;

var repo1FilePath = path.normalize(path.join(baseDir, "/test-folder")).replace(/\\/g, '/');
var repo2FilePath = path.normalize(path.join(baseDir, "/test-folder2")).replace(/\\/g, '/');
var d1FilePath = path.normalize(path.join(repo1FilePath, "/d1")).replace(/\\/g, '/');
var d1Selector = `repo[name="repo1"] dir[filePath="${d1FilePath}"]`;
var d2FilePath = path.normalize(path.join(repo1FilePath, "/d2")).replace(/\\/g, '/');
var d2Selector = `repo[name="repo1"] dir[filePath="${d2FilePath}"]`;
var newDirFilePath = path.normalize(path.join(repo1FilePath, "/newDir")).replace(/\\/g, '/');
var newDirSelector = `repo[name="repo1"] dir[filePath="${newDirFilePath}"]`;

describe('file-query-test-base-module', function () {
    this.timeout(2000);

    var $ = null;

    before(function(done){
        resetTestFolders();
        done();
    });

    it("test pass single rootDir option", function (done) {
        try {
            let $ = fileQuerySync(repo1FilePath);
            expect($('repo').length).to.equal(1);
            expect($('repo>dir[name=d1]').length).to.equal(1);
            done();
        } catch (e) {
            console.error(e);
            throw e;
        }
    });

    it("test debug mode", function (done) {
        try {
            let $ = fileQuerySync(repo1FilePath);
            expect($.option('debug')).to.equal(false);
            $.debug(true);
            expect($.option('debug')).to.equal(true);
            done();
        } catch (e) {
            console.error(e);
            throw e;
        }
    });

    it("test options", function (done) {
        try {
            let $ = fileQuerySync(repo1FilePath);
            expect($.options()['debug']).to.equal(false);
            $.options({'debug': true});
            expect($.options()['debug']).to.equal(true);
            $.option('debug', false);
            expect($.option('debug')).to.equal(false);
            done();
        } catch (e) {
            console.error(e);
            throw e;
        }
    });

    it("test prettyDom", function (done) {
        try {
            let $ = fileQuerySync(repo1FilePath);
            expect($.prettyDom()).to.not.null;
            done();
        } catch (e) {
            console.error(e);
            throw e;
        }
    });
});

describe('file-query-test-api', function () {
    this.timeout(5000);

    var $ = null;
    beforeEach(function () {
        resetTestFolders();
        $ = initFileQuery();
    });

    after(function(done){
        resetTestFolders();
        done();
    })

    it("test fileQuery.renameSync", function (done) {
        var selected = $(d1Selector);
        selected.renameSync(selected.attr('name') + ' renamed');
        fs.statSync(d1FilePath+' renamed');
        done();
    });

    it("test fileQuery.renameSync, test invalid filename", function (done) {
        var selected = $(d1Selector);
        try{
            selected.renameSync(selected.attr('name') + ' renamed:');
            fs.statSync(d1FilePath+' renamed:');
            done(new Error('Rename invalid filename should not OK.'));
        } catch (e){
            done();
        }
    });

    it("test fileQuery.rename", function (done) {
        var selected = $(d1Selector).first();
        selected.rename(selected.attr('name') + ' renamed').then(function (context) {
            fs.statSync(d1FilePath+' renamed');
            done();
        }).catch(function (error) {
            console.log('error:', error);
        });
    });

    it("test fileQuery.rename, test invalid filename", function (done) {
        var selected = $(d1Selector).first();
        selected.rename(selected.attr('name') + ' renamed:').then(function (context) {
            done(new Error('Rename invalid filename should not OK.'));
        }).catch(function (error) {
            done();
        });
    });

    it("test fileQuery.moveToDirSync(context: object)", function (done) {
        var dir1FilesCount = $('dir,file', $(d1Selector)).length;
        var dir2FilesCount = $('dir,file', $(d2Selector)).length;
        var selected = $(d1Selector).children('dir,file');

        selected.moveToDirSync($(d2Selector));

        $.fileQuery('refresh');

        expect($('dir,file', $(d1Selector)).length).to.equal(0);
        expect($('dir,file', $(d2Selector)).length).to.equal(dir1FilesCount+dir2FilesCount);
        done();
    });

    it("test fileQuery.moveToDirSync(dest: string)", function (done) {
        var dir1FilesCount = $('dir,file', $(d1Selector)).length;
        var dir2FilesCount = $('dir,file', $(d2Selector)).length;
        var selected = $(d1Selector).children('dir,file');

        selected.moveToDirSync(d2FilePath);

        $.fileQuery('refresh');

        expect($('dir,file', $(d1Selector)).length).to.equal(0);
        expect($('dir,file', $(d2Selector)).length).to.equal(dir1FilesCount+dir2FilesCount);
        done();
    });

    it("test fileQuery.moveToDirSync(dest: string), test dest filepath is repo filepath", function (done) {
        var dirFilesCount = $('dir,file', $(d1Selector)).length;
        var dirFilesCount2 = $('dir,file', $('repo[filepath="'+repo2FilePath+'"]')).length;
        var selected = $(d1Selector).children('dir,file');

        selected.moveToDirSync(repo2FilePath);

        $.fileQuery('refresh');

        expect($('dir,file', $(d1Selector)).length).to.equal(0);
        expect($('dir,file', $('repo[filepath="'+repo2FilePath+'"]')).length).to.equal(dirFilesCount+dirFilesCount2);
        done();
    });

    it("test fileQuery.moveToDirSync(dest: string), test invalid dest filepath", function (done) {
        var dirFilesCount = $('dir,file', $(d1Selector)).length;
        var selected = $(d1Selector).children('dir,file');

        try{
            selected.moveToDirSync(d2FilePath+':');
            done(new Error('Rename invalid filename should not OK.'));
        } catch(e){
            done();
        }
    });

    it("test fileQuery.moveToDir(context: object)", function (done) {
        var dir1FilesCount = $('dir,file', $(d1Selector)).length;
        var dir2FilesCount = $('dir,file', $(d2Selector)).length;
        var selected = $(d1Selector).children('dir,file');

        selected.moveToDir($(d2Selector)).then(function (context) {

            $.fileQuery('refresh');

            expect($('dir,file', $(d1Selector)).length).to.equal(0);
            expect($('dir,file', $(d2Selector)).length).to.equal(dir1FilesCount+dir2FilesCount);
            done();

        }).catch(function (error) {
            console.log('error:', error);
        });
    });

    it("test fileQuery.moveToDir(dest: string)", function (done) {
        var dir1FilesCount = $('dir,file', $(d1Selector)).length;
        var dir2FilesCount = $('dir,file', $(d2Selector)).length;
        var selected = $(d1Selector).children('dir,file');

        selected.moveToDir(d2FilePath).then(function (context) {

            $.fileQuery('refresh');

            expect($('dir,file', $(d1Selector)).length).to.equal(0);
            expect($('dir,file', $(d2Selector)).length).to.equal(dir1FilesCount+dir2FilesCount);
            done();

        }).catch(function (error) {
            console.log('error:', error);
        });
    });

    it("test fileQuery.moveToDir(dest: string), test invalid dest filepath", function (done) {
        var dirFilesCount = $('dir,file', $(d1Selector)).length;
        var selected = $(d1Selector).children('dir,file');

        selected.moveToDir(d2FilePath+":").then(function (context) {
            done(new Error('Rename invalid filename should not OK.'));
        }).catch(function (error) {
            done();
        });
    });

    it("test fileQuery.copyToDirSync(context: object)", function (done) {
        var dir1FilesCount = $('dir,file', $(d1Selector)).length;
        var dir2FilesCount = $('dir,file', $(d2Selector)).length;

        $(d1Selector).children('dir,file').copyToDirSync($(d2Selector));

        $.fileQuery('refresh');
        expect($('dir,file', $(d1Selector)).length).to.equal(dir1FilesCount);
        expect($('dir,file', $(d2Selector)).length).to.equal(dir1FilesCount+dir2FilesCount);
        done();
    });

    it("test fileQuery.copyToDirSync(dest: string)", function (done) {
        var dir1FilesCount = $('dir,file', $(d1Selector)).length;
        var dir2FilesCount = $('dir,file', $(d2Selector)).length;

        $(d1Selector).children('dir,file').copyToDirSync(d2FilePath);

        $.fileQuery('refresh');
        expect($('dir,file', $(d1Selector)).length).to.equal(dir1FilesCount);
        expect($('dir,file', $(d2Selector)).length).to.equal(dir1FilesCount+dir2FilesCount);
        done();
    });

    it("test fileQuery.copyToDirSync(dest: string), test dest filepath is repo filepath", function (done) {
        var dirFilesCount = $('dir,file', $(d1Selector)).length;
        var dirFilesCount2 = $('dir,file', $('repo[filepath="'+repo2FilePath+'"]')).length;

        $(d1Selector).children('dir,file').copyToDirSync(repo2FilePath);

        $.fileQuery('refresh');
        expect($('dir,file', $(d1Selector)).length).to.equal(dirFilesCount);
        expect($('dir,file', $('repo[filepath="'+repo2FilePath+'"]')).length).to.equal(dirFilesCount+dirFilesCount2);
        done();
    });

    it("test fileQuery.copyToDirSync(dest: string), test invalid dest filepath", function (done) {
        var dirFilesCount = $('dir,file', $(d1Selector)).length;

        try{
            $(d1Selector).children('dir,file').copyToDirSync(d2FilePath+':');
            done(new Error('Rename invalid filename should not OK.'));
        } catch(e) {
            done();
        }
    });

    it("test fileQuery.copyToDir(context: object)", function (done) {
        var dir1FilesCount = $('dir,file', $(d1Selector)).length;
        var dir2FilesCount = $('dir,file', $(d2Selector)).length;

        $(d1Selector).children('dir,file').copyToDir($(d2Selector)).then(function (context) {
            $.fileQuery('refresh');
            expect($('dir,file', $(d1Selector)).length).to.equal(dir1FilesCount);
            expect($('dir,file', $(d2Selector)).length).to.equal(dir1FilesCount+dir2FilesCount);
            done();
        }).catch(function (error) {
            console.log('error:', error);
        });
    });

    it("test fileQuery.copyToDir(dest: string)", function (done) {
        var dir1FilesCount = $('dir,file', $(d1Selector)).length;
        var dir2FilesCount = $('dir,file', $(d2Selector)).length;

        $(d1Selector).children('dir,file').copyToDir(d2FilePath).then(function (context) {
            $.fileQuery('refresh');
            expect($('dir,file', $(d1Selector)).length).to.equal(dir1FilesCount);
            expect($('dir,file', $(d2Selector)).length).to.equal(dir1FilesCount+dir2FilesCount);
            done();
        }).catch(function (error) {
            console.log('error:', error);
        });
    });

    it("test fileQuery.copyToDir(dest: string), test invalid dest filepath", function (done) {
        var dirFilesCount = $('dir,file', $(d1Selector)).length;

        $(d1Selector).children('dir,file').copyToDir(d2FilePath+':').then(function (context) {
            done(new Error('Rename invalid filename should not OK.'));
        }).catch(function (error) {
            done();
        });
    });

    it("test fileQuery.deleteSync", function (done) {
        var selected = $(d1Selector).children('dir,file');
        selected.deleteSync();

        $.fileQuery('refresh');

        expect($('dir,file', $(d1Selector)).length).to.equal(0);
        done();
    });

    it("test fileQuery.delete", function (done) {
        var selected = $(d1Selector).children('dir,file');

        selected.delete().then(function () {
            $.fileQuery('refresh');
            expect($('dir,file', $(d1Selector)).length).to.equal(0);
            done();
        }).catch(function (error) {
            console.log('error:', error);
        });
    });

    it("test fileQuery.newDirSync", function (done) {
        var selected = $('repo[name="repo1"]');
        selected.newDirSync('newDir');

        $.fileQuery('refresh');

        expect($(newDirSelector).length).to.equal(1);
        done();
    });

    it("test fileQuery.newDirSync, test invalid dest filepath", function (done) {
        var selected = $('repo[name="repo1"]');
        try{
            selected.newDirSync('newDir:');
            done(new Error('Rename invalid filename should not OK.'));
        } catch(e) {
            done();
        }
    });

    it("test fileQuery.newDir", function (done) {
        var selected = $('repo[name="repo1"]');

        selected.newDir('newDir').then(function (context) {
            $.fileQuery('refresh');
            expect($(newDirSelector).length).to.equal(1);
            done();
        }).catch(function (error) {
            console.log('error:', error);
        });
    });

    it("test fileQuery.newDir, test invalid dest filepath", function (done) {
        var selected = $('repo[name="repo1"]');

        selected.newDir('newDir:').then(function (context) {
            done(new Error('Rename invalid filename should not OK.'));
        }).catch(function (error) {
            done();
        });
    });

    it("test fileQuery.newDirSync, only create new dir for each selected directories. (Ignore selected files)", function (done) {
        var selected = $('repo[name="repo1"]>file[name="f1.txt"]');
        selected.newDirSync('newDir');
        $.fileQuery('refresh');

        expect($('repo[name="repo1"]>dir[name="f1.txt"]').length).to.equal(0);
        done();
    });

    it("test fileQuery.searchInFilesSync", function (done) {
        var selected = $('repo[name="repo1"]');
        var results = selected.searchInFilesSync('abc');
        var resultMap = {};
        var resultCount = 0;
        results.each(function(i, em){
            resultMap[$(em).attr('filePath')] = 1;
            resultCount++;
        })

        expect(resultCount).to.equal(2);
        expect(resultMap).to.contain.all.keys(repo1FilePath+'/f1.txt');
        expect(resultMap).to.contain.all.keys(d1FilePath+'/f3.txt');
        done();
    });

    it("test fileQuery.searchInFiles(searchKey: string)", function (done) {
        var selected = $('repo[name="repo1"]');
        selected.searchInFiles('abc').then(function(results){
            var resultMap = {};
            var resultCount = 0;
            results.each(function(i, em){
                resultMap[$(em).attr('filePath')] = 1;
                resultCount++;
            })

            expect(resultCount).to.equal(2);
            expect(resultMap).to.contain.all.keys(repo1FilePath+'/f1.txt');
            expect(resultMap).to.contain.all.keys(d1FilePath+'/f3.txt');
            done();
        });
    });

    it("test fileQuery.searchInFiles(pattern: Regexp)", function (done) {
        var selected = $('repo[name="repo1"]');
        selected.searchInFiles(/abc/).then(function(results){
            var resultMap = {};
            var resultCount = 0;
            results.each(function(i, em){
                resultMap[$(em).attr('filePath')] = 1;
                resultCount++;
            })

            expect(resultCount).to.equal(2);
            expect(resultMap).to.haveOwnProperty(repo1FilePath+'/f1.txt');
            expect(resultMap).to.haveOwnProperty(d1FilePath+'/f3.txt');
            done();
        });
    });

    it("test fileQuery.searchInFiles, test when selected multiple duplicate paths", function (done) {
        var selected = $('repo[name="repo1"]').add('repo[name="repo3"]');
        selected.searchInFiles('abc').then(function(results){
            var resultMap = {};
            var resultCount = 0;
            results.each(function(i, em){
                resultMap[$(em).attr('filePath')] = 1;
                resultCount++;
            })

            expect(resultCount).to.equal(2);
            expect(resultMap).to.haveOwnProperty(repo1FilePath+'/f1.txt');
            expect(resultMap).to.haveOwnProperty(d1FilePath+'/f3.txt');
            done();
        });
    });
});

function resetTestFolders(){
    let $ = fileQuerySync({
        repos: {
            'repo1': {
                'rootDir': repo1FilePath,
                'excludeFilePaths': ['d1/d3/d4']
            },
            'repo2': {
                'rootDir': repo2FilePath
            },
            'repo3': {
                'rootDir': repo1FilePath
            },
            'backuprepo1': {
                'rootDir': path.join(baseDir, "/test-folder-bak")
            },
            'backuprepo2': {
                'rootDir': path.join(baseDir, "/test-folder-bak2")
            }
        }
    });
    $('*', $('repo[name="repo1"]')).deleteSync();
    $('*', $('repo[name="repo2"]')).deleteSync();
    $('repo[name="backuprepo1"]').children('dir,file').copyToDirSync($('repo[name="repo1"]'));
    $('repo[name="backuprepo2"]').children('dir,file').copyToDirSync($('repo[name="repo2"]'));
}

function initFileQuery() {
    try {
        let $ = fileQuerySync({
            repos: {
                'repo1': {
                    'rootDir': repo1FilePath,
                    'excludeFilePaths': ['d1/d3/d4']
                },
                'repo2': {
                    'rootDir': repo2FilePath
                }
            }
        });
        $.debug(false);
        return $;
    } catch (e) {
        console.error(e);
        throw e;
    }
}


text: import App from './App.js';


text:
import LazyComponent from './lazy-component'
import { LazyCall, LazyRoute, RouteOnDemand } from './lazy-imports'

export { LazyComponent, LazyCall, LazyRoute, RouteOnDemand };

export default LazyComponent;


text:
/**
 *****************************************************************************
 **
 ** @file  example1.cpp
 **
 ** @brief Simple example of LTKCPP that talks to an actual reader
 **
 ** This is sometimes called the "LLRP Hello World" program
 **
 ** The steps:
 **     - Connect to the reader (TCP)
 **     - Make sure the connection status is good
 **     - Clear (scrub) the reader configuration
 **     - Add and enable a ROSpec that does a simple operation
 **         - Uses mostly default settings except for ROReportSpec
 **         - Uses all antennas
 **         - Starts on command
 **         - Runs for 5 seconds
 **         - Reports all accumulated tag observations
 **     - Run the ROSpec 5 times
 **     - Clear (scrub) the reader configuration
 **
 ** This program can be run with zero, one, or two verbose options (-v).
 **     no -v -- Only prints the tag report and errors
 **     -v    -- Also prints one line progress messages
 **     -vv   -- Also prints all LLRP messages as XML text
 **
 *****************************************************************************/

#include <stdio.h>
#include <cstdlib>

#include "ltkcpp.h"

using namespace LLRP;

class CMyApplication
{
  public:
    /** Verbose level, incremented by each -v on command line */
    int                         m_Verbose;

    /** Connection to the LLRP reader */
    CConnection *               m_pConnectionToReader;

    inline
    CMyApplication (void)
     : m_Verbose(0), m_pConnectionToReader(NULL)
    {}

    int
    run (
      char *                    pReaderHostName);

    int
    checkConnectionStatus (void);

    int
    scrubConfiguration (void);

    int
    resetConfigurationToFactoryDefaults (void);

    int
    deleteAllROSpecs (void);

    int
    addROSpec (void);

    int
    enableROSpec (void);

    int
    startROSpec (void);

    int
    awaitAndPrintReport (void);

    void
    printTagReportData (
      CRO_ACCESS_REPORT *       pRO_ACCESS_REPORT);

    void
    printOneTagReportData (
      CTagReportData *          pTagReportData);

    void
    handleReaderEventNotification (
      CReaderEventNotificationData *pNtfData);

    void
    handleAntennaEvent (
      CAntennaEvent *           pAntennaEvent);

    void
    handleReaderExceptionEvent (
      CReaderExceptionEvent *   pReaderExceptionEvent);

    int
    checkLLRPStatus (
      CLLRPStatus *             pLLRPStatus,
      char *                    pWhatStr);

    CMessage *
    transact (
      CMessage *                pSendMsg);

    CMessage *
    recvMessage (
      int                       nMaxMS);

    int
    sendMessage (
      CMessage *                pSendMsg);

    void
    printXMLMessage (
      CMessage *                pMessage);
};

/* BEGIN forward declarations */
int
main (
  int                           ac,
  char *                        av[]);

void
usage (
  char *                        pProgName);
/* END forward declarations */

/**
 *****************************************************************************
 **
 ** @brief  Command main routine
 **
 ** Command synopsis:
 **
 **     example1 [-v[v]] READERHOSTNAME
 **
 ** @exitcode   0               Everything *seemed* to work.
 **             1               Bad usage
 **             2               Run failed
 **
 *****************************************************************************/

int
main (
  int                           ac,
  char *                        av[])
{
    CMyApplication              myApp;
    char *                      pReaderHostName;
    int                         rc;

    /*
     * Process comand arguments, determine reader name
     * and verbosity level.
     */
    if(ac == 2)
    {
        pReaderHostName = av[1];
    }
    else if(ac == 3)
    {
        char *                  p = av[1];

        while(*p)
        {
            switch(*p++)
            {
            case '-':   /* linux conventional option warn char */
            case '/':   /* Windows/DOS conventional option warn char */
                break;

            case 'v':
            case 'V':
                myApp.m_Verbose++;
                break;

            default:
                usage(av[0]);
                /* no return */
                break;
            }
        }

        pReaderHostName = av[2];
    }
    else
    {
        usage(av[0]);
        /* no return */
    }

    /*
     * Run application, capture return value for exit status
     */
    rc = myApp.run(pReaderHostName);

    printf("INFO: Done\n");

    /*
     * Exit with the right status.
     */
    if(0 == rc)
    {
        exit(0);
    }
    else
    {
        exit(2);
    }
    /*NOTREACHED*/
}

/**
 *****************************************************************************
 **
 ** @brief  Print usage message and exit
 **
 ** @param[in]  nProgName       Program name string
 **
 ** @return     none, exits
 **
 *****************************************************************************/

void
usage (
  char *                        pProgName)
{
#ifdef linux
    printf("Usage: %s [-v[v]] READERHOSTNAME\n", pProgName);
    printf("\n");
    printf("Each -v increases verbosity level\n");
#endif /* linux */
#ifdef WIN32
    printf("Usage: %s [/v[v]] READERHOSTNAME\n", pProgName);
    printf("\n");
    printf("Each /v increases verbosity level\n");
#endif /* WIN32 */
    exit(1);
}

/**
 *****************************************************************************
 **
 ** @brief  Run the application
 **
 ** The steps:
 **     - Instantiate connection
 **     - Connect to LLRP reader (TCP)
 **     - Make sure the connection status is good
 **     - Clear (scrub) the reader configuration
 **     - Configure for what we want to do
 **     - Run inventory operation 5 times
 **     - Again, clear (scrub) the reader configuration
 **     - Disconnect from reader
 **     - Destruct connection
 **
 ** @param[in]  pReaderHostName String with reader name
 **
 ** @return      0              Everything worked.
 **             -1              Failed allocation of type registry
 **             -2              Failed construction of connection
 **             -3              Could not connect to reader
 **              1              Reader connection status bad
 **              2              Cleaning reader config failed
 **              3              Adding ROSpec failed
 **              4              Enabling ROSpec failed
 **              5              Something went wrong running the ROSpec
 **
 *****************************************************************************/

int
CMyApplication::run (
  char *                        pReaderHostName)
{
    CTypeRegistry *             pTypeRegistry;
    CConnection *               pConn;
    int                         rc;

    /*
     * Allocate the type registry. This is needed
     * by the connection to decode.
     */
    pTypeRegistry = getTheTypeRegistry();
    if(NULL == pTypeRegistry)
    {
        printf("ERROR: getTheTypeRegistry failed\n");
        return -1;
    }

    /*
     * Construct a connection (LLRP::CConnection).
     * Using a 32kb max frame size for send/recv.
     * The connection object is ready for business
     * but not actually connected to the reader yet.
     */
    pConn = new CConnection(pTypeRegistry, 32u*1024u);
    if(NULL == pConn)
    {
        printf("ERROR: new CConnection failed\n");
        return -2;
    }

    /*
     * Open the connection to the reader
     */
    if(m_Verbose)
    {
        printf("INFO: Connecting to %s....\n", pReaderHostName);
    }

    rc = pConn->openConnectionToReader(pReaderHostName);
    if(0 != rc)
    {
        printf("ERROR: connect: %s (%d)\n", pConn->getConnectError(), rc);
        delete pConn;
        return -3;
    }

    /*
     * Record the pointer to the connection object so other
     * routines can use it.
     */
    m_pConnectionToReader = pConn;

    if(m_Verbose)
    {
        printf("INFO: Connected, checking status....\n");
    }

    /*
     * Commence the sequence and check for errors as we go.
     * See comments for each routine for details.
     * Each routine prints messages.
     */
    rc = 1;
    if(0 == checkConnectionStatus())
    {
        rc = 2;
        if(0 == scrubConfiguration())
        {
            rc = 3;
            if(0 == addROSpec())
            {
                rc = 4;
                if(0 == enableROSpec())
                {
                    int         i;

                    rc = 5;

                    for(i = 1; i <= 5; i++)
                    {
                        printf("INFO: Starting run %d ================\n", i);
                        if(0 != startROSpec())
                        {
                            /* already tattled */
                            break;
                        }
                        if(0 != awaitAndPrintReport())
                        {
                            /* already tattled */
                            break;
                        }
                    }

                    if(5 == i)
                    {
                        rc = 0;
                    }
                }
            }

            /*
             * After we're done, try to leave the reader
             * in a clean state for next use. This is best
             * effort and no checking of the result is done.
             */
            if(m_Verbose)
            {
                printf("INFO: Clean up reader configuration...\n");
            }
            scrubConfiguration();
        }
    }

    if(m_Verbose)
    {
        printf("INFO: Finished\n");
    }

    /*
     * Close the connection and release its resources
     */
    pConn->closeConnectionToReader();
    delete pConn;

    /*
     * Done with the registry.
     */
    delete pTypeRegistry;

    /*
     * When we get here all allocated memory should have been deallocated.
     */

    return rc;
}

/**
 *****************************************************************************
 **
 ** @brief  Await and check the connection status message from the reader
 **
 ** We are expecting a READER_EVENT_NOTIFICATION message that
 ** tells us the connection is OK. The reader is suppose to
 ** send the message promptly upon connection.
 **
 ** If there is already another LLRP connection to the
 ** reader we'll get a bad Status.
 **
 ** The message should be something like:
 **
 **     <READER_EVENT_NOTIFICATION MessageID='0'>
 **       <ReaderEventNotificationData>
 **         <UTCTimestamp>
 **           <Microseconds>1184491439614224</Microseconds>
 **         </UTCTimestamp>
 **         <ConnectionAttemptEvent>
 **           <Status>Success</Status>
 **         </ConnectionAttemptEvent>
 **       </ReaderEventNotificationData>
 **     </READER_EVENT_NOTIFICATION>
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong
 **
 *****************************************************************************/

int
CMyApplication::checkConnectionStatus (void)
{
    CMessage *                  pMessage;
    CREADER_EVENT_NOTIFICATION *pNtf;
    CReaderEventNotificationData *pNtfData;
    CConnectionAttemptEvent *   pEvent;

    /*
     * Expect the notification within 10 seconds.
     * It is suppose to be the very first message sent.
     */
    pMessage = recvMessage(10000);

    /*
     * recvMessage() returns NULL if something went wrong.
     */
    if(NULL == pMessage)
    {
        /* recvMessage already tattled */
        goto fail;
    }

    /*
     * Check to make sure the message is of the right type.
     * The type label (pointer) in the message should be
     * the type descriptor for READER_EVENT_NOTIFICATION.
     */
    if(&CREADER_EVENT_NOTIFICATION::s_typeDescriptor != pMessage->m_pType)
    {
        goto fail;
    }

    /*
     * Now that we are sure it is a READER_EVENT_NOTIFICATION,
     * traverse to the ReaderEventNotificationData parameter.
     */
    pNtf = (CREADER_EVENT_NOTIFICATION *) pMessage;
    pNtfData = pNtf->getReaderEventNotificationData();
    if(NULL == pNtfData)
    {
        goto fail;
    }

    /*
     * The ConnectionAttemptEvent parameter must be present.
     */
    pEvent = pNtfData->getConnectionAttemptEvent();
    if(NULL == pEvent)
    {
        goto fail;
    }

    /*
     * The status in the ConnectionAttemptEvent parameter
     * must indicate connection success.
     */
    if(ConnectionAttemptStatusType_Success != pEvent->getStatus())
    {
        goto fail;
    }

    /*
     * Done with the message
     */
    delete pMessage;

    if(m_Verbose)
    {
        printf("INFO: Connection status OK\n");
    }

    /*
     * Victory.
     */
    return 0;

  fail:
    /*
     * Something went wrong. Tattle. Clean up. Return error.
     */
    printf("ERROR: checkConnectionStatus failed\n");
    delete pMessage;
    return -1;
}

/**
 *****************************************************************************
 **
 ** @brief  Scrub the reader configuration
 **
 ** The steps:
 **     - Try to reset configuration to factory defaults,
 **       this feature is optional and may not be supported
 **       by the reader.
 **     - Delete all ROSpecs
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong
 **
 *****************************************************************************/

int
CMyApplication::scrubConfiguration (void)
{
    if(0 != resetConfigurationToFactoryDefaults())
    {
        return -1;
    }

    if(0 != deleteAllROSpecs())
    {
        return -2;
    }

    return 0;
}

/**
 *****************************************************************************
 **
 ** @brief  Send a SET_READER_CONFIG message that resets the
 **         reader to factory defaults.
 **
 ** NB: The ResetToFactoryDefault semantics vary between readers.
 **     It might have no effect because it is optional.
 **
 ** The message is:
 **
 **     <SET_READER_CONFIG MessageID='101'>
 **       <ResetToFactoryDefault>1</ResetToFactoryDefault>
 **     </SET_READER_CONFIG>
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong
 **
 *****************************************************************************/

int
CMyApplication::resetConfigurationToFactoryDefaults (void)
{
    CSET_READER_CONFIG *        pCmd;
    CMessage *                  pRspMsg;
    CSET_READER_CONFIG_RESPONSE *pRsp;

    /*
     * Compose the command message
     */
    pCmd = new CSET_READER_CONFIG();
    pCmd->setMessageID(101);
    pCmd->setResetToFactoryDefault(1);

    /*
     * Send the message, expect the response of certain type
     */
    pRspMsg = transact(pCmd);

    /*
     * Done with the command message
     */
    delete pCmd;

    /*
     * transact() returns NULL if something went wrong.
     */
    if(NULL == pRspMsg)
    {
        /* transact already tattled */
        return -1;
    }

    /*
     * Cast to a SET_READER_CONFIG_RESPONSE message.
     */
    pRsp = (CSET_READER_CONFIG_RESPONSE *) pRspMsg;

    /*
     * Check the LLRPStatus parameter.
     */
    if(0 != checkLLRPStatus(pRsp->getLLRPStatus(),
                        "resetConfigurationToFactoryDefaults"))
    {
        /* checkLLRPStatus already tattled */
        delete pRspMsg;
        return -1;
    }

    /*
     * Done with the response message.
     */
    delete pRspMsg;

    /*
     * Tattle progress, maybe
     */
    if(m_Verbose)
    {
        printf("INFO: Configuration reset to factory defaults\n");
    }

    /*
     * Victory.
     */
    return 0;
}

/**
 *****************************************************************************
 **
 ** @brief  Delete all ROSpecs using DELETE_ROSPEC message
 **
 ** Per the spec, the DELETE_ROSPEC message contains an ROSpecID
 ** of 0 to indicate we want all ROSpecs deleted.
 **
 ** The message is
 **
 **     <DELETE_ROSPEC MessageID='102'>
 **       <ROSpecID>0</ROSpecID>
 **     </DELETE_ROSPEC>
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong
 **
 *****************************************************************************/

int
CMyApplication::deleteAllROSpecs (void)
{
    CDELETE_ROSPEC *            pCmd;
    CMessage *                  pRspMsg;
    CDELETE_ROSPEC_RESPONSE *   pRsp;

    /*
     * Compose the command message
     */
    pCmd = new CDELETE_ROSPEC();
    pCmd->setMessageID(102);
    pCmd->setROSpecID(0);               /* All */

    /*
     * Send the message, expect the response of certain type
     */
    pRspMsg = transact(pCmd);

    /*
     * Done with the command message
     */
    delete pCmd;

    /*
     * transact() returns NULL if something went wrong.
     */
    if(NULL == pRspMsg)
    {
        /* transact already tattled */
        return -1;
    }

    /*
     * Cast to a DELETE_ROSPEC_RESPONSE message.
     */
    pRsp = (CDELETE_ROSPEC_RESPONSE *) pRspMsg;

    /*
     * Check the LLRPStatus parameter.
     */
    if(0 != checkLLRPStatus(pRsp->getLLRPStatus(), "deleteAllROSpecs"))
    {
        /* checkLLRPStatus already tattled */
        delete pRspMsg;
        return -1;
    }

    /*
     * Done with the response message.
     */
    delete pRspMsg;

    /*
     * Tattle progress, maybe
     */
    if(m_Verbose)
    {
        printf("INFO: All ROSpecs are deleted\n");
    }

    /*
     * Victory.
     */
    return 0;
}

/**
 *****************************************************************************
 **
 ** @brief  Add our ROSpec using ADD_ROSPEC message
 **
 ** This ROSpec waits for a START_ROSPEC message,
 ** then takes inventory on all antennas for 5 seconds.
 **
 ** The tag report is generated after the ROSpec is done.
 **
 ** This example is deliberately streamlined.
 ** Nothing here configures the antennas, RF, or Gen2.
 ** The current defaults are used. Remember we just reset
 ** the reader to factory defaults (above). Normally an
 ** application would be more precise in configuring the
 ** reader and in its ROSpecs.
 **
 ** Experience suggests that typical ROSpecs are about
 ** double this in size.
 **
 ** The message is
 **
 **     <ADD_ROSPEC MessageID='201'>
 **       <ROSpec>
 **         <ROSpecID>123</ROSpecID>
 **         <Priority>0</Priority>
 **         <CurrentState>Disabled</CurrentState>
 **         <ROBoundarySpec>
 **           <ROSpecStartTrigger>
 **             <ROSpecStartTriggerType>Null</ROSpecStartTriggerType>
 **           </ROSpecStartTrigger>
 **           <ROSpecStopTrigger>
 **             <ROSpecStopTriggerType>Null</ROSpecStopTriggerType>
 **             <DurationTriggerValue>0</DurationTriggerValue>
 **           </ROSpecStopTrigger>
 **         </ROBoundarySpec>
 **         <AISpec>
 **           <AntennaIDs>0</AntennaIDs>
 **           <AISpecStopTrigger>
 **             <AISpecStopTriggerType>Duration</AISpecStopTriggerType>
 **             <DurationTrigger>5000</DurationTrigger>
 **           </AISpecStopTrigger>
 **           <InventoryParameterSpec>
 **             <InventoryParameterSpecID>1234</InventoryParameterSpecID>
 **             <ProtocolID>EPCGlobalClass1Gen2</ProtocolID>
 **           </InventoryParameterSpec>
 **         </AISpec>
 **         <ROReportSpec>
 **           <ROReportTrigger>Upon_N_Tags_Or_End_Of_ROSpec</ROReportTrigger>
 **           <N>0</N>
 **           <TagReportContentSelector>
 **             <EnableROSpecID>0</EnableROSpecID>
 **             <EnableSpecIndex>0</EnableSpecIndex>
 **             <EnableInventoryParameterSpecID>0</EnableInventoryParameterSpecID>
 **             <EnableAntennaID>0</EnableAntennaID>
 **             <EnableChannelIndex>0</EnableChannelIndex>
 **             <EnablePeakRSSI>0</EnablePeakRSSI>
 **             <EnableFirstSeenTimestamp>0</EnableFirstSeenTimestamp>
 **             <EnableLastSeenTimestamp>0</EnableLastSeenTimestamp>
 **             <EnableTagSeenCount>0</EnableTagSeenCount>
 **             <EnableAccessSpecID>0</EnableAccessSpecID>
 **           </TagReportContentSelector>
 **         </ROReportSpec>
 **       </ROSpec>
 **     </ADD_ROSPEC>
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong
 **
 *****************************************************************************/

int
CMyApplication::addROSpec (void)
{
    CROSpecStartTrigger *       pROSpecStartTrigger =
                                    new CROSpecStartTrigger();
    pROSpecStartTrigger->setROSpecStartTriggerType(
                                ROSpecStartTriggerType_Null);

    CROSpecStopTrigger *        pROSpecStopTrigger = new CROSpecStopTrigger();
    pROSpecStopTrigger->setROSpecStopTriggerType(ROSpecStopTriggerType_Null);
    pROSpecStopTrigger->setDurationTriggerValue(0);     /* n/a */

    CROBoundarySpec *           pROBoundarySpec = new CROBoundarySpec();
    pROBoundarySpec->setROSpecStartTrigger(pROSpecStartTrigger);
    pROBoundarySpec->setROSpecStopTrigger(pROSpecStopTrigger);

    CAISpecStopTrigger *        pAISpecStopTrigger = new CAISpecStopTrigger();
    pAISpecStopTrigger->setAISpecStopTriggerType(
            AISpecStopTriggerType_Duration);
    pAISpecStopTrigger->setDurationTrigger(5000);

    CInventoryParameterSpec *   pInventoryParameterSpec =
                                    new CInventoryParameterSpec();
    pInventoryParameterSpec->setInventoryParameterSpecID(1234);
    pInventoryParameterSpec->setProtocolID(AirProtocols_EPCGlobalClass1Gen2);

    llrp_u16v_t                 AntennaIDs = llrp_u16v_t(1);
    AntennaIDs.m_pValue[0] = 0;         /* All */

    CAISpec *                   pAISpec = new CAISpec();
    pAISpec->setAntennaIDs(AntennaIDs);
    pAISpec->setAISpecStopTrigger(pAISpecStopTrigger);
    pAISpec->addInventoryParameterSpec(pInventoryParameterSpec);

    CTagReportContentSelector * pTagReportContentSelector =
                                    new CTagReportContentSelector();
    pTagReportContentSelector->setEnableROSpecID(FALSE);
    pTagReportContentSelector->setEnableSpecIndex(FALSE);
    pTagReportContentSelector->setEnableInventoryParameterSpecID(FALSE);
    pTagReportContentSelector->setEnableAntennaID(FALSE);
    pTagReportContentSelector->setEnableChannelIndex(FALSE);
    pTagReportContentSelector->setEnablePeakRSSI(FALSE);
    pTagReportContentSelector->setEnableFirstSeenTimestamp(FALSE);
    pTagReportContentSelector->setEnableLastSeenTimestamp(FALSE);
    pTagReportContentSelector->setEnableTagSeenCount(FALSE);
    pTagReportContentSelector->setEnableAccessSpecID(FALSE);

    CROReportSpec *             pROReportSpec = new CROReportSpec();
    pROReportSpec->setROReportTrigger(
            ROReportTriggerType_Upon_N_Tags_Or_End_Of_ROSpec);
    pROReportSpec->setN(0);         /* Unlimited */
    pROReportSpec->setTagReportContentSelector(pTagReportContentSelector);

    CROSpec *                   pROSpec = new CROSpec();
    pROSpec->setROSpecID(123);
    pROSpec->setPriority(0);
    pROSpec->setCurrentState(ROSpecState_Disabled);
    pROSpec->setROBoundarySpec(pROBoundarySpec);
    pROSpec->addSpecParameter(pAISpec);
    pROSpec->setROReportSpec(pROReportSpec);

    CADD_ROSPEC *               pCmd;
    CMessage *                  pRspMsg;
    CADD_ROSPEC_RESPONSE *      pRsp;

    /*
     * Compose the command message.
     * N.B.: After the message is composed, all the parameters
     *       constructed, immediately above, are considered "owned"
     *       by the command message. When it is destructed so
     *       too will the parameters be.
     */
    pCmd = new CADD_ROSPEC();
    pCmd->setMessageID(201);
    pCmd->setROSpec(pROSpec);

    /*
     * Send the message, expect the response of certain type
     */
    pRspMsg = transact(pCmd);

    /*
     * Done with the command message.
     * N.B.: And the parameters
     */
    delete pCmd;

    /*
     * transact() returns NULL if something went wrong.
     */
    if(NULL == pRspMsg)
    {
        /* transact already tattled */
        return -1;
    }

    /*
     * Cast to a ADD_ROSPEC_RESPONSE message.
     */
    pRsp = (CADD_ROSPEC_RESPONSE *) pRspMsg;

    /*
     * Check the LLRPStatus parameter.
     */
    if(0 != checkLLRPStatus(pRsp->getLLRPStatus(), "addROSpec"))
    {
        /* checkLLRPStatus already tattled */
        delete pRspMsg;
        return -1;
    }

    /*
     * Done with the response message.
     */
    delete pRspMsg;

    /*
     * Tattle progress, maybe
     */
    if(m_Verbose)
    {
        printf("INFO: ROSpec added\n");
    }

    /*
     * Victory.
     */
    return 0;
}

/**
 *****************************************************************************
 **
 ** @brief  Enable our ROSpec using ENABLE_ROSPEC message
 **
 ** Enable the ROSpec that was added above.
 **
 ** The message we send is:
 **     <ENABLE_ROSPEC MessageID='202'>
 **       <ROSpecID>123</ROSpecID>
 **     </ENABLE_ROSPEC>
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong
 **
 *****************************************************************************/

int
CMyApplication::enableROSpec (void)
{
    CENABLE_ROSPEC *            pCmd;
    CMessage *                  pRspMsg;
    CENABLE_ROSPEC_RESPONSE *   pRsp;

    /*
     * Compose the command message
     */
    pCmd = new CENABLE_ROSPEC();
    pCmd->setMessageID(202);
    pCmd->setROSpecID(123);

    /*
     * Send the message, expect the response of certain type
     */
    pRspMsg = transact(pCmd);

    /*
     * Done with the command message
     */
    delete pCmd;

    /*
     * transact() returns NULL if something went wrong.
     */
    if(NULL == pRspMsg)
    {
        /* transact already tattled */
        return -1;
    }

    /*
     * Cast to a ENABLE_ROSPEC_RESPONSE message.
     */
    pRsp = (CENABLE_ROSPEC_RESPONSE *) pRspMsg;

    /*
     * Check the LLRPStatus parameter.
     */
    if(0 != checkLLRPStatus(pRsp->getLLRPStatus(), "enableROSpec"))
    {
        /* checkLLRPStatus already tattled */
        delete pRspMsg;
        return -1;
    }

    /*
     * Done with the response message.
     */
    delete pRspMsg;

    /*
     * Tattle progress, maybe
     */
    if(m_Verbose)
    {
        printf("INFO: ROSpec enabled\n");
    }

    /*
     * Victory.
     */
    return 0;
}

/**
 *****************************************************************************
 **
 ** @brief  Start our ROSpec using START_ROSPEC message
 **
 ** Start the ROSpec that was added above.
 **
 ** The message we send is:
 **     <START_ROSPEC MessageID='203'>
 **       <ROSpecID>123</ROSpecID>
 **     </START_ROSPEC>
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong
 **
 *****************************************************************************/

int
CMyApplication::startROSpec (void)
{
    CSTART_ROSPEC *             pCmd;
    CMessage *                  pRspMsg;
    CSTART_ROSPEC_RESPONSE *    pRsp;

    /*
     * Compose the command message
     */
    pCmd = new CSTART_ROSPEC();
    pCmd->setMessageID(202);
    pCmd->setROSpecID(123);

    /*
     * Send the message, expect the response of certain type
     */
    pRspMsg = transact(pCmd);

    /*
     * Done with the command message
     */
    delete pCmd;

    /*
     * transact() returns NULL if something went wrong.
     */
    if(NULL == pRspMsg)
    {
        /* transact already tattled */
        return -1;
    }

    /*
     * Cast to a START_ROSPEC_RESPONSE message.
     */
    pRsp = (CSTART_ROSPEC_RESPONSE *) pRspMsg;

    /*
     * Check the LLRPStatus parameter.
     */
    if(0 != checkLLRPStatus(pRsp->getLLRPStatus(), "startROSpec"))
    {
        /* checkLLRPStatus already tattled */
        delete pRspMsg;
        return -1;
    }

    /*
     * Done with the response message.
     */
    delete pRspMsg;

    /*
     * Tattle progress
     */
    if(m_Verbose)
    {
        printf("INFO: ROSpec started\n");
    }

    /*
     * Victory.
     */
    return 0;
}

/**
 *****************************************************************************
 **
 ** @brief  Receive and print the RO_ACCESS_REPORT
 **
 ** Receive messages until an RO_ACCESS_REPORT is received.
 ** Time limit is 7 seconds. We expect a report within 5 seconds.
 **
 ** This shows how to determine the type of a received message.
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong
 **
 *****************************************************************************/

int
CMyApplication::awaitAndPrintReport (void)
{
    int                         bDone = 0;
    int                         retVal = 0;

    /*
     * Keep receiving messages until done or until
     * something bad happens.
     */
    while(!bDone)
    {
        CMessage *              pMessage;
        const CTypeDescriptor * pType;

        /*
         * Wait up to 7 seconds for a message. The report
         * should occur within 5 seconds.
         */
        pMessage = recvMessage(7000);
        if(NULL == pMessage)
        {
            /*
             * Did not receive a message within a reasonable
             * amount of time. recvMessage() already tattled
             */
            retVal = -2;
            bDone = 1;
            continue;
        }

        /*
         * What happens depends on what kind of message
         * received. Use the type label (m_pType) to
         * discriminate message types.
         */
        pType = pMessage->m_pType;

        /*
         * Is it a tag report? If so, print it out.
         */
        if(&CRO_ACCESS_REPORT::s_typeDescriptor == pType)
        {
            CRO_ACCESS_REPORT * pNtf;

            pNtf = (CRO_ACCESS_REPORT *) pMessage;

            printTagReportData(pNtf);
            bDone = 1;
            retVal = 0;
        }

        /*
         * Is it a reader event? This example only recognizes
         * AntennaEvents.
         */
        else if(&CREADER_EVENT_NOTIFICATION::s_typeDescriptor == pType)
        {
            CREADER_EVENT_NOTIFICATION *pNtf;
            CReaderEventNotificationData *pNtfData;

            pNtf = (CREADER_EVENT_NOTIFICATION *) pMessage;

            pNtfData = pNtf->getReaderEventNotificationData();
            if(NULL != pNtfData)
            {
                handleReaderEventNotification(pNtfData);
            }
            else
            {
                /*
                 * This should never happen. Using continue
                 * to keep indent depth down.
                 */
                printf("WARNING: READER_EVENT_NOTIFICATION without data\n");
            }
        }

        /*
         * Hmmm. Something unexpected. Just tattle and keep going.
         */
        else
        {
            printf("WARNING: Ignored unexpected message during monitor: %s\n",
                pType->m_pName);
        }

        /*
         * Done with the received message
         */
        delete pMessage;
    }

    return retVal;
}

/**
 *****************************************************************************
 **
 ** @brief  Helper routine to print a tag report
 **
 ** The report is printed in list order, which is arbitrary.
 **
 ** TODO: It would be cool to sort the list by EPC and antenna,
 **       then print it.
 **
 ** @return     void
 **
 *****************************************************************************/

void
CMyApplication::printTagReportData (
  CRO_ACCESS_REPORT *           pRO_ACCESS_REPORT)
{
    std::list<CTagReportData *>::iterator Cur;
    unsigned int                nEntry = 0;

    /*
     * Loop through and count the number of entries
     */
    for(
        Cur = pRO_ACCESS_REPORT->beginTagReportData();
        Cur != pRO_ACCESS_REPORT->endTagReportData();
        Cur++)
    {
        nEntry++;
    }

    printf("INFO: %u tag report entries\n", nEntry);

    /*
     * Loop through again and print each entry.
     */
    for(
        Cur = pRO_ACCESS_REPORT->beginTagReportData();
        Cur != pRO_ACCESS_REPORT->endTagReportData();
        Cur++)
    {
        printOneTagReportData(*Cur);
    }
}

/**
 *****************************************************************************
 **
 ** @brief  Helper routine to print one tag report entry on one line
 **
 ** @return     void
 **
 *****************************************************************************/

void
CMyApplication::printOneTagReportData (
  CTagReportData *              pTagReportData)
{
    const CTypeDescriptor *     pType;
    char                        aBuf[64];

    /*
     * Print the EPC. It could be an 96-bit EPC_96 parameter
     * or an variable length EPCData parameter.
     */

    CParameter *                pEPCParameter =
                                    pTagReportData->getEPCParameter();

    if(NULL != pEPCParameter)
    {
        char *              p = aBuf;
        llrp_u96_t          my_u96;
        llrp_u1v_t          my_u1v;
        llrp_u8_t *         pValue = NULL;
        unsigned int        n, i;

        pType = pEPCParameter->m_pType;
        if(&CEPC_96::s_typeDescriptor == pType)
        {
            CEPC_96             *pEPC_96;

            pEPC_96 = (CEPC_96 *) pEPCParameter;
            my_u96 = pEPC_96->getEPC();
            pValue = my_u96.m_aValue;
            n = 12u;
        }
        else if(&CEPCData::s_typeDescriptor == pType)
        {
            CEPCData *          pEPCData;

            pEPCData = (CEPCData *) pEPCParameter;
            my_u1v = pEPCData->getEPC();
            pValue = my_u1v.m_pValue;
            n = (my_u1v.m_nBit + 7u) / 8u;
        }

        if(NULL != pValue)
        {
            for(i = 0; i < n; i++)
            {
                if(0 < i && i%2 == 0)
                {
                    *p++ = '-';
                }
                sprintf(p, "%02X", pValue[i]);
                while(*p) p++;
            }
        }
        else
        {
            strcpy(aBuf, "---unknown-epc-data-type---");
        }
    }
    else
    {
        strcpy(aBuf, "---missing-epc-data---");
    }
    printf("%-32s", aBuf);

    /*
     * End of line
     */
    printf("\n");
}

/**
 *****************************************************************************
 **
 ** @brief  Handle a ReaderEventNotification
 **
 ** Handle the payload of a READER_EVENT_NOTIFICATION message.
 ** This routine simply dispatches to handlers of specific
 ** event types.
 **
 ** @return     void
 **
 *****************************************************************************/

void
CMyApplication::handleReaderEventNotification (
  CReaderEventNotificationData *pNtfData)
{
    CAntennaEvent *             pAntennaEvent;
    CReaderExceptionEvent *     pReaderExceptionEvent;
    int                         nReported = 0;

    pAntennaEvent = pNtfData->getAntennaEvent();
    if(NULL != pAntennaEvent)
    {
        handleAntennaEvent(pAntennaEvent);
        nReported++;
    }

    pReaderExceptionEvent = pNtfData->getReaderExceptionEvent();
    if(NULL != pReaderExceptionEvent)
    {
        handleReaderExceptionEvent(pReaderExceptionEvent);
        nReported++;
    }

    /*
     * Similarly handle other events here:
     *      HoppingEvent
     *      GPIEvent
     *      ROSpecEvent
     *      ReportBufferLevelWarningEvent
     *      ReportBufferOverflowErrorEvent
     *      RFSurveyEvent
     *      AISpecEvent
     *      ConnectionAttemptEvent
     *      ConnectionCloseEvent
     *      Custom
     */

    if(0 == nReported)
    {
        printf("NOTICE: Unexpected (unhandled) ReaderEvent\n");
    }
}

/**
 *****************************************************************************
 **
 ** @brief  Handle an AntennaEvent
 **
 ** An antenna was disconnected or (re)connected. Tattle.
 **
 ** @return     void
 **
 *****************************************************************************/

void
CMyApplication::handleAntennaEvent (
  CAntennaEvent *               pAntennaEvent)
{
    EAntennaEventType           eEventType;
    llrp_u16_t                  AntennaID;
    char *                      pStateStr;

    eEventType = pAntennaEvent->getEventType();
    AntennaID = pAntennaEvent->getAntennaID();

    switch(eEventType)
    {
    case AntennaEventType_Antenna_Disconnected:
        pStateStr = "disconnected";
        break;

    case AntennaEventType_Antenna_Connected:
        pStateStr = "connected";
        break;

    default:
        pStateStr = "?unknown-event?";
        break;
    }

    printf("NOTICE: Antenna %d is %s\n", AntennaID, pStateStr);
}

/**
 *****************************************************************************
 **
 ** @brief  Handle a ReaderExceptionEvent
 **
 ** Something has gone wrong. There are lots of details but
 ** all this does is print the message, if one.
 **
 ** @return     void
 **
 *****************************************************************************/

void
CMyApplication::handleReaderExceptionEvent (
  CReaderExceptionEvent *       pReaderExceptionEvent)
{
    llrp_utf8v_t                Message;

    Message = pReaderExceptionEvent->getMessage();

    if(0 < Message.m_nValue && NULL != Message.m_pValue)
    {
        printf("NOTICE: ReaderException '%.*s'\n",
             Message.m_nValue, Message.m_pValue);
    }
    else
    {
        printf("NOTICE: ReaderException but no message\n");
    }
}

/**
 *****************************************************************************
 **
 ** @brief  Helper routine to check an LLRPStatus parameter
 **         and tattle on errors
 **
 ** Helper routine to interpret the LLRPStatus subparameter
 ** that is in all responses. It tattles on an error, if one,
 ** and tries to safely provide details.
 **
 ** This simplifies the code, above, for common check/tattle
 ** sequences.
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong, already tattled
 **
 *****************************************************************************/

int
CMyApplication::checkLLRPStatus (
  CLLRPStatus *                 pLLRPStatus,
  char *                        pWhatStr)
{
    /*
     * The LLRPStatus parameter is mandatory in all responses.
     * If it is missing there should have been a decode error.
     * This just makes sure (remember, this program is a
     * diagnostic and suppose to catch LTKC mistakes).
     */
    if(NULL == pLLRPStatus)
    {
        printf("ERROR: %s missing LLRP status\n", pWhatStr);
        return -1;
    }

    /*
     * Make sure the status is M_Success.
     * If it isn't, print the error string if one.
     * This does not try to pretty-print the status
     * code. To get that, run this program with -vv
     * and examine the XML output.
     */
    if(StatusCode_M_Success != pLLRPStatus->getStatusCode())
    {
        llrp_utf8v_t            ErrorDesc;

        ErrorDesc = pLLRPStatus->getErrorDescription();

        if(0 == ErrorDesc.m_nValue)
        {
            printf("ERROR: %s failed, no error description given\n",
                pWhatStr);
        }
        else
        {
            printf("ERROR: %s failed, %.*s\n",
                pWhatStr, ErrorDesc.m_nValue, ErrorDesc.m_pValue);
        }
        return -2;
    }

    /*
     * Victory. Everything is fine.
     */
    return 0;
}

/**
 *****************************************************************************
 **
 ** @brief  Wrapper routine to do an LLRP transaction
 **
 ** Wrapper to transact a request/resposne.
 **     - Print the outbound message in XML if verbose level is at least 2
 **     - Send it using the LLRP_Conn_transact()
 **     - LLRP_Conn_transact() receives the response or recognizes an error
 **     - Tattle on errors, if any
 **     - Print the received message in XML if verbose level is at least 2
 **     - If the response is ERROR_MESSAGE, the request was sufficiently
 **       misunderstood that the reader could not send a proper reply.
 **       Deem this an error, free the message.
 **
 ** The message returned resides in allocated memory. It is the
 ** caller's obligtation to free it.
 **
 ** @return     ==NULL          Something went wrong, already tattled
 **             !=NULL          Pointer to a message
 **
 *****************************************************************************/

CMessage *
CMyApplication::transact (
  CMessage *                    pSendMsg)
{
    CConnection *               pConn = m_pConnectionToReader;
    CMessage *                  pRspMsg;

    /*
     * Print the XML text for the outbound message if
     * verbosity is 2 or higher.
     */
    if(1 < m_Verbose)
    {
        printf("\n===================================\n");
        printf("INFO: Transact sending\n");
        printXMLMessage(pSendMsg);
    }

    /*
     * Send the message, expect the response of certain type.
     * If LLRP::CConnection::transact() returns NULL then there was
     * an error. In that case we try to print the error details.
     */
    pRspMsg = pConn->transact(pSendMsg, 5000);

    if(NULL == pRspMsg)
    {
        const CErrorDetails *   pError = pConn->getTransactError();

        printf("ERROR: %s transact failed, %s\n",
            pSendMsg->m_pType->m_pName,
            pError->m_pWhatStr ? pError->m_pWhatStr : "no reason given");

        if(NULL != pError->m_pRefType)
        {
            printf("ERROR: ... reference type %s\n",
                pError->m_pRefType->m_pName);
        }

        if(NULL != pError->m_pRefField)
        {
            printf("ERROR: ... reference field %s\n",
                pError->m_pRefField->m_pName);
        }

        return NULL;
    }

    /*
     * Print the XML text for the inbound message if
     * verbosity is 2 or higher.
     */
    if(1 < m_Verbose)
    {
        printf("\n- - - - - - - - - - - - - - - - - -\n");
        printf("INFO: Transact received response\n");
        printXMLMessage(pRspMsg);
    }

    /*
     * If it is an ERROR_MESSAGE (response from reader
     * when it can't understand the request), tattle
     * and declare defeat.
     */
    if(&CERROR_MESSAGE::s_typeDescriptor == pRspMsg->m_pType)
    {
        const CTypeDescriptor * pResponseType;

        pResponseType = pSendMsg->m_pType->m_pResponseType;

        printf("ERROR: Received ERROR_MESSAGE instead of %s\n",
            pResponseType->m_pName);
        delete pRspMsg;
        pRspMsg = NULL;
    }

    return pRspMsg;
}

/**
 *****************************************************************************
 **
 ** @brief  Wrapper routine to receive a message
 **
 ** This can receive notifications as well as responses.
 **     - Recv a message using the LLRP_Conn_recvMessage()
 **     - Tattle on errors, if any
 **     - Print the message in XML if verbose level is at least 2
 **
 ** The message returned resides in allocated memory. It is the
 ** caller's obligtation to free it.
 **
 ** @param[in]  nMaxMS          -1 => block indefinitely
 **                              0 => just peek at input queue and
 **                                   socket queue, return immediately
 **                                   no matter what
 **                             >0 => ms to await complete frame
 **
 ** @return     ==NULL          Something went wrong, already tattled
 **             !=NULL          Pointer to a message
 **
 *****************************************************************************/

CMessage *
CMyApplication::recvMessage (
  int                           nMaxMS)
{
    CConnection *               pConn = m_pConnectionToReader;
    CMessage *                  pMessage;

    /*
     * Receive the message subject to a time limit
     */
    pMessage = pConn->recvMessage(nMaxMS);

    /*
     * If LLRP::CConnection::recvMessage() returns NULL then there was
     * an error. In that case we try to print the error details.
     */
    if(NULL == pMessage)
    {
        const CErrorDetails *   pError = pConn->getRecvError();

        printf("ERROR: recvMessage failed, %s\n",
            pError->m_pWhatStr ? pError->m_pWhatStr : "no reason given");

        if(NULL != pError->m_pRefType)
        {
            printf("ERROR: ... reference type %s\n",
                pError->m_pRefType->m_pName);
        }

        if(NULL != pError->m_pRefField)
        {
            printf("ERROR: ... reference field %s\n",
                pError->m_pRefField->m_pName);
        }

        return NULL;
    }

    /*
     * Print the XML text for the inbound message if
     * verbosity is 2 or higher.
     */
    if(1 < m_Verbose)
    {
        printf("\n===================================\n");
        printf("INFO: Message received\n");
        printXMLMessage(pMessage);
    }

    return pMessage;
}

/**
 *****************************************************************************
 **
 ** @brief  Wrapper routine to send a message
 **
 ** Wrapper to send a message.
 **     - Print the message in XML if verbose level is at least 2
 **     - Send it using the LLRP_Conn_sendMessage()
 **     - Tattle on errors, if any
 **
 ** @param[in]  pSendMsg        Pointer to message to send
 **
 ** @return     ==0             Everything OK
 **             !=0             Something went wrong, already tattled
 **
 *****************************************************************************/

int
CMyApplication::sendMessage (
  CMessage *                    pSendMsg)
{
    CConnection *               pConn = m_pConnectionToReader;

    /*
     * Print the XML text for the outbound message if
     * verbosity is 2 or higher.
     */
    if(1 < m_Verbose)
    {
        printf("\n===================================\n");
        printf("INFO: Sending\n");
        printXMLMessage(pSendMsg);
    }

    /*
     * If LLRP::CConnection::sendMessage() returns other than RC_OK
     * then there was an error. In that case we try to print
     * the error details.
     */
    if(RC_OK != pConn->sendMessage(pSendMsg))
    {
        const CErrorDetails *   pError = pConn->getSendError();

        printf("ERROR: %s sendMessage failed, %s\n",
            pSendMsg->m_pType->m_pName,
            pError->m_pWhatStr ? pError->m_pWhatStr : "no reason given");

        if(NULL != pError->m_pRefType)
        {
            printf("ERROR: ... reference type %s\n",
                pError->m_pRefType->m_pName);
        }

        if(NULL != pError->m_pRefField)
        {
            printf("ERROR: ... reference field %s\n",
                pError->m_pRefField->m_pName);
        }

        return -1;
    }

    /*
     * Victory
     */
    return 0;
}

/**
 *****************************************************************************
 **
 ** @brief  Helper to print a message as XML text
 **
 ** Print a LLRP message as XML text
 **
 ** @param[in]  pMessage        Pointer to message to print
 **
 ** @return     void
 **
 *****************************************************************************/

void
CMyApplication::printXMLMessage (
  CMessage *                    pMessage)
{
    char                        aBuf[100*1024];

    /*
     * Convert the message to an XML string.
     * This fills the buffer with either the XML string
     * or an error message. The return value could
     * be checked.
     */

    pMessage->toXMLString(aBuf, sizeof aBuf);

    /*
     * Print the XML Text to the standard output.
     */
    printf("%s", aBuf);
}


text:
using namespace std;

/// <summary>
/// Shows some help information about commands.
/// </summary>
class CommandHelp : public ICommand
{
public:
	CommandHelp();
	~CommandHelp();

	bool shouldRunThisCommand(ParsedCommand* Parsed);
	void run(ParsedCommand* Parsed);
	string* getName();
	string* getHelp();
};


text:
package org.subethamail.entity.i;

import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

/**
 * All the possible permissions on a mailing list.
 *
 * @author Jeff Schnitzer
 */
public enum Permission
{
	EDIT_ROLES("Edit and reassign roles and permissions.  This should not be granted to non-owners."),
	DELETE_ARCHIVES("Delete messages from the archive."),
	EDIT_SETTINGS("Edit the name, description, and major configuration options of the list."),
	EDIT_FILTERS("Add, remove, and change the properties of mail filters."),
	EDIT_NOTES("Create and edit administrative notes for subscribers."),
	EDIT_SUBSCRIPTIONS("Change other people's delivery address or unsubscribe them from the mailing list."),
	MASS_SUBSCRIBE("Subscribe other people to the mailing list."),
	APPROVE_SUBSCRIPTIONS("Approve subscription requests."),
	APPROVE_MESSAGES("Approve messages which have been held for administrative approval."),
	IMPORT_MESSAGES("Import messages for a list. Allows direct recording of messages into the archives with no delivery."),
	VIEW_NOTES("Read administrative notes that have been placed on subscribers."),
	VIEW_ROLES("View roles of members on the list subscribers page."),
	VIEW_SUBSCRIBERS("View the list of subscribers to the mailing list."),
	VIEW_ADDRESSES("See the real email addresses of members in the archives and subscriber list."),
	VIEW_ARCHIVES("Read and search the archives of the mailing list."),
	POST("Post messages to a mailing list, either by emailing the list address or from the archives.");

	/** A set that contains all permissions */
	public static final Set<Permission> ALL;
	static
	{
		Set<Permission> tmp = new TreeSet<Permission>();

		for (Permission p : Permission.values())
			tmp.add(p);

		ALL = Collections.unmodifiableSet(tmp);
	}

	/** */
	private String pretty;
	private String description;

	/**
	 * Makes the pretty form which is mixed case and converts
	 * underscores to spaces.
	 */
	private Permission(String description)
	{
		this.description = description;

		// Now set up the pretty
		String original = this.toString();
		StringBuffer buf = new StringBuffer(original.length());

		boolean lowerNext = false;

		for (int i=0; i<original.length(); i++)
		{
			char ch = original.charAt(i);

			if (ch == '_')
			{
				lowerNext = false;
				buf.append(' ');
			}
			else if (lowerNext)
			{
				buf.append(Character.toLowerCase(ch));
			}
			else
			{
				buf.append(ch);
				lowerNext = true;
			}
		}

		this.pretty = buf.toString();
	}

	/** */
	public String getPretty()
	{
		return this.pretty;
	}

	public String getDescription()
	{
		return this.description;
	}
}


text:
const test = require('ava')
const { ElemType } = require('../index')

test('test #1', t => {
  class Input extends ElemType
  {
    static tagName = 'input'

    static class = 'Input'
  }

  class Test extends ElemType
  {
    static class = 'Test'

    state = {
      step : 0,
      mode : 'on',
    }

    render() {
      const mode = this.state.mode
      switch(this.state.step) {
        case 0:
          this.classList = ['foo', null, 'bar']
          return new Input({
            classList : ['one', null, 'two'],
          })
        case 1:
          this.classList = [
            mode === 'off' && 'foo',
            mode === 'on' && 'bat',
          ]
          return new Input({
            classList : [
              mode === 'off' && 'one',
              mode === 'on' && 'three',
            ],
          })
        case 2:
          this.classList = 'foo baz'
          return new Input({
            classList : 'one four',
          })
        case 3:
          this.classList = null
          return new Input
      }
    }
  }

  const elem = Test.render()

  t.is(elem.toString(), '
<input class="Input one two">
')

  elem.setState({ step : 1 })

  t.is(elem.toString(), '
<input class="Input three">
')

  elem.setState({ mode : 'off' })

  t.is(elem.toString(), '
<input class="Input one">
')

  elem.setState({ step : 2 })

  t.is(elem.toString(), '
<input class="Input one four">
')

  elem.setState({ step : 3 })

  t.is(elem.toString(), '
<input class="Input">
')
})

test('test #2', t => {
  class Test extends ElemType
  {
    static class = 'Test'

    render() {
      this.classList = ['foo', 'bar']
    }
  }

  const elem = Test.render({
    classList : ['bat', 'baz'],
  })

  t.is(elem.toString(), '

')
})


text:
package wechat.menu;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.DBUtils;
import util.ServerContext;
import wechat.access.AccessTokenManager;
import wechat.utils.Constants;
import wechat.HttpClientHelper;
import wechat.utils.URLManager;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by wangronghua on 14-3-18.
 */
public class MenuUtils {
  protected final static Logger LOG = LoggerFactory.getLogger(HttpClientHelper.class);

  public static String getRedirectUrl(String url) throws UnsupportedEncodingException {
    return ServerContext.getDomainName() + "/wechat/redirect.action?url=" + URLEncoder.encode(url, "UTF-8");
  }

  public static String getOAuthUrl(String url) throws UnsupportedEncodingException {
    return URLManager.getUrl_OAuthRedirect(ServerContext.getDomainName() + url, ServerContext.getAppID());
  }

  public static boolean create(InputStream in) {
    Map resultMap = HttpClientHelper.post(URLManager.getUrl_MenuCreate(AccessTokenManager.getToken(DBUtils.getDBFlag())), in);
    if(null != resultMap && (Integer)(resultMap.get(Constants.ERR_CODE)) == 0) {
      return true;
    }
    if(null != resultMap.get(Constants.ERR_CODE)) {
      LOG.error("Error while getting token from server, errcode:{};{}", String.valueOf(resultMap.get(Constants.ERR_CODE)), String.valueOf(resultMap.get(Constants.ERR_CODE)));
    }
    return false;
  }

  public static boolean create(File file) {
    try {
      InputStream inputStream = new FileInputStream(file);
      return create(inputStream);
    } catch (FileNotFoundException e) {
      LOG.error("File not found", e);
      return false;
    }
  }

  public static boolean create(WechatMenu menu) {
    if(null != menu) {
      String jsonMenu = menu.toJson();
      try {
        return create(new ByteArrayInputStream(jsonMenu.getBytes("UTF-8")));
      } catch(UnsupportedEncodingException e){
        LOG.error(e.getMessage());
        return false;
      }
    } else {
      LOG.error("Menu object is null!");
      return false;
    }

  }
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

#include "HAL/Power.hpp"
#include "ChipObject.h"

static tPower *power = NULL;

static void initializePower(int32_t *status) {
	if(power == NULL) {
		power = tPower::create(status);
	}
}

extern "C" {

/**
 * Get the roboRIO input voltage
 */
float getVinVoltage(int32_t *status) {
	initializePower(status);
	return power->readVinVoltage(status) / 4.096f * 0.025733f - 0.029f;
}

/**
 * Get the roboRIO input current
 */
float getVinCurrent(int32_t *status) {
	initializePower(status);
	return power->readVinCurrent(status) / 4.096f * 0.017042 - 0.071f;
}

/**
 * Get the 6V rail voltage
 */
float getUserVoltage6V(int32_t *status) {
	initializePower(status);
	return power->readUserVoltage6V(status) / 4.096f * 0.007019f - 0.014f;
}

/**
 * Get the 6V rail current
 */
float getUserCurrent6V(int32_t *status) {
	initializePower(status);
	return power->readUserCurrent6V(status) / 4.096f * 0.005566f - 0.009f;
}

/**
 * Get the active state of the 6V rail
 */
bool getUserActive6V(int32_t *status) {
	initializePower(status);
	return power->readStatus_User6V(status) == 4;
}

/**
 * Get the fault count for the 6V rail
 */
int getUserCurrentFaults6V(int32_t *status) {
	initializePower(status);
	return (int)power->readFaultCounts_OverCurrentFaultCount6V(status);
}

/**
 * Get the 5V rail voltage
 */
float getUserVoltage5V(int32_t *status) {
	initializePower(status);
	return power->readUserVoltage5V(status) / 4.096f * 0.005962f - 0.013f;
}

/**
 * Get the 5V rail current
 */
float getUserCurrent5V(int32_t *status) {
	initializePower(status);
	return power->readUserCurrent5V(status) / 4.096f * 0.001996f - 0.002f;
}

/**
 * Get the active state of the 5V rail
 */
bool getUserActive5V(int32_t *status) {
	initializePower(status);
	return power->readStatus_User5V(status) == 4;
}

/**
 * Get the fault count for the 5V rail
 */
int getUserCurrentFaults5V(int32_t *status) {
	initializePower(status);
	return (int)power->readFaultCounts_OverCurrentFaultCount5V(status);
}

unsigned char getUserStatus5V(int32_t *status) {
	initializePower(status);
	return power->readStatus_User5V(status);
}

/**
 * Get the 3.3V rail voltage
 */
float getUserVoltage3V3(int32_t *status) {
	initializePower(status);
	return power->readUserVoltage3V3(status) / 4.096f * 0.004902f - 0.01f;
}

/**
 * Get the 3.3V rail current
 */
float getUserCurrent3V3(int32_t *status) {
	initializePower(status);
	return power->readUserCurrent3V3(status) / 4.096f * 0.002486f - 0.003f;
}

/**
 * Get the active state of the 3.3V rail
 */
bool getUserActive3V3(int32_t *status) {
	initializePower(status);
	return power->readStatus_User3V3(status) == 4;
}

/**
 * Get the fault count for the 3.3V rail
 */
int getUserCurrentFaults3V3(int32_t *status) {
	initializePower(status);
	return (int)power->readFaultCounts_OverCurrentFaultCount3V3(status);
}

}  // extern "C"


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Error</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

<?php echo $heading; ?>

                        <?php echo $message; ?>


text:
package org.jenkinsci.plugins.github.status.sources;

import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.jenkinsci.plugins.github.extension.status.GitHubStatusResultSource;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kohsuke.github.GHCommitState;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

/**
 * @author lanwen (Merkushev Kirill)
 */
@RunWith(DataProviderRunner.class)
public class DefaultStatusResultSourceTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock(answer = Answers.RETURNS_MOCKS)
    private Run run;

    @Mock(answer = Answers.RETURNS_MOCKS)
    private TaskListener listener;

    @DataProvider
    public static Object[][] results() {
        return new Object[][]{
                {Result.SUCCESS, GHCommitState.SUCCESS},
                {Result.UNSTABLE, GHCommitState.FAILURE},
                {Result.FAILURE, GHCommitState.ERROR},
                {null, GHCommitState.PENDING},
        };
    }

    @Test
    @UseDataProvider("results")
    public void shouldReturnConditionalResult(Result actual, GHCommitState expected) throws Exception {
        when(run.getResult()).thenReturn(actual);

        GitHubStatusResultSource.StatusResult result = new DefaultStatusResultSource().get(run, listener);
        assertThat("state", result.getState(), is(expected));
    }

}


text:
var registerComponent = require('../core/component').registerComponent;
var utils = require('../utils/');

registerComponent('laser-controls', {
  schema: {
    hand: {default: 'right'}
  },

  init: function () {
    var config = this.config;
    var data = this.data;
    var el = this.el;
    var self = this;

    // Set all controller models.
    el.setAttribute('daydream-controls', {hand: data.hand});
    el.setAttribute('gearvr-controls', {hand: data.hand});
    el.setAttribute('oculus-go-controls', {hand: data.hand});
    el.setAttribute('oculus-touch-controls', {hand: data.hand});
    el.setAttribute('vive-controls', {hand: data.hand});
    el.setAttribute('vive-focus-controls', {hand: data.hand});
    el.setAttribute('windows-motion-controls', {hand: data.hand});

    // Wait for controller to connect, or have a valid pointing pose, before creating ray
    el.addEventListener('controllerconnected', createRay);
    el.addEventListener('controllerdisconnected', hideRay);
    el.addEventListener('controllermodelready', function (evt) {
      createRay(evt);
      self.modelReady = true;
    });

    function createRay (evt) {
      var controllerConfig = config[evt.detail.name];

      if (!controllerConfig) { return; }

      // Show the line unless a particular config opts to hide it, until a controllermodelready
      // event comes through.
      var raycasterConfig = utils.extend({
        showLine: true
      }, controllerConfig.raycaster || {});

      // The controllermodelready event contains a rayOrigin that takes into account
      // offsets specific to the loaded model.
      if (evt.detail.rayOrigin) {
        raycasterConfig.origin = evt.detail.rayOrigin.origin;
        raycasterConfig.direction = evt.detail.rayOrigin.direction;
        raycasterConfig.showLine = true;
      }

      // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
      // config applied from a controllermodelready event.
      if (evt.detail.rayOrigin || !self.modelReady) {
        el.setAttribute('raycaster', raycasterConfig);
      } else {
        el.setAttribute('raycaster', 'showLine', true);
      }

      el.setAttribute('cursor', utils.extend({
        fuse: false
      }, controllerConfig.cursor));
    }

    function hideRay () {
      el.setAttribute('raycaster', 'showLine', false);
    }
  },

  config: {
    'daydream-controls': {
      cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']}
    },

    'gearvr-controls': {
      cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
      raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
    },

    'oculus-go-controls': {
      cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
      raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
    },

    'oculus-touch-controls': {
      cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
      raycaster: {origin: {x: 0, y: 0, z: 0}}
    },

    'vive-controls': {
      cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
    },

    'vive-focus-controls': {
      cursor: {downEvents: ['trackpaddown', 'triggerdown'], upEvents: ['trackpadup', 'triggerup']}
    },

    'windows-motion-controls': {
      cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
      raycaster: {showLine: false}
    }
  }
});


text:
KERN=aes
ALG=aes

CFLAGS?=-O3 -Wall -Wno-unused-label

SRCS=$(KERN).c local_support.c ../../common/support.c
FILES=$(SRCS) $(KERN).h ../../common/support.h

$(KERN): $(FILES) ../../common/harness.c
	$(CC) $(CFLAGS) -I../../common -o $(KERN) $(SRCS) ../../common/harness.c

run: $(KERN) input.data check.data
	./$(KERN) input.data check.data

generate: $(FILES) generate.c
	$(CC) $(CFLAGS) -I../../common -o generate $(SRCS) generate.c
	./generate

hls: $(KERN).c $(KERN).h
	vivado_hls hls.tcl

clean:
	rm -f $(KERN) generate output.data

# For the tracer makefile
ACCEL_NAME = aes-aes
TEST_BIN = $(ACCEL_NAME)
export TRACE_OUTPUT_DIR=$(ACCEL_NAME)
ifndef WORKLOAD
  export WORKLOAD=aes256_encrypt_ecb
endif
include ../../common/Makefile.tracer
include ../../common/Makefile.gem5


text:
const path = require('path');
const prettierConf = require('./prettier.config.js');

module.exports = {
  parser: '@babel/eslint-parser',
  parserOptions: {
    babelOptions: {
      configFile: path.resolve(__dirname, '.babelrc.json'),
    },
  },
  extends: ['airbnb/base', 'prettier'],
  rules: {
    'prettier/prettier': ['error', prettierConf],

    // But we want the following
    'no-multi-spaces': ['error', { exceptions: { ImportDeclaration: true } }],
    'no-param-reassign': ['error', { props: false }],
    'no-unused-vars': ['error', { args: 'none' }],
    'prefer-destructuring': 0,
    'import/no-extraneous-dependencies': 0, // Needed for tests
    // 'no-mixed-operators': 'error', // Wish we can put it back with prettier

    // Not for us
    'jsx-a11y/label-has-for': 0,
    'no-console': 0,
    'no-plusplus': 0,
    'no-underscore-dangle': 0,
    'import/no-named-as-default': 0,
    'import/no-named-as-default-member': 0,

    // Introduced with new eslint
    // and no time to fix them...
    // [...]
    'linebreak-style': 0,
  },
  plugins: ['prettier'],
  globals: {
    __BASE_PATH__: false,
    VRFrameData: true,
  },
  settings: {
    'import/resolver': {
      webpack: {
        config: {
          resolve: {
            alias: {
              // Since vtk.js examples are written as if the vtk.js package is a dependency,
              // we need to resolve example imports as if they were referencing vtk.js/Sources.
              // the Examples/Utilities hack allows for imports from those folders, since our
              // last alias overrides vtk.js/* paths to point to vtk.js/Sources/*.
              'vtk.js/Data': path.resolve(__dirname, 'Data'),
              'vtk.js/Examples': path.resolve(__dirname, 'Examples'),
              'vtk.js/Utilities': path.resolve(__dirname, 'Utilities'),
              'vtk.js/Sources': path.resolve(__dirname, 'Sources'),
              'vtk.js': path.resolve(__dirname, 'Sources'),
              '@kitware/vtk.js': path.resolve(__dirname, 'Sources'),
            },
          },
        },
      },
    },
  },
  env: {
    es6: true,
    browser: true,
  },
  ignorePatterns: [
    // ignore old Actor example
    '**/example_/*.js',
    // ignore js files in utilities
    'Utilities/**/*.js',
  ],
};


text:
AutoML API
===========

orca.automl.auto_estimator
---------------------------

A general estimator supports automatic model tuning. It allows users to fit and search the best hyperparameter for their model.

.. automodule:: zoo.orca.automl.auto_estimator
    :members:
    :show-inheritance:

orca.automl.hp
----------------------------------------

Sampling specs to be used in search space configuration.

.. automodule:: zoo.orca.automl.hp
    :members:
    :show-inheritance:

automl.metrics
----------------------------

Evaluate unscaled metrics between y true value and y predicted value.

.. automodule:: zoo.orca.automl.metrics
    :members:
    :show-inheritance:


text:
package com.github.badoualy.telegram.tl.api;

import com.github.badoualy.telegram.tl.TLContext;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.github.badoualy.telegram.tl.StreamUtils.readInt;
import static com.github.badoualy.telegram.tl.StreamUtils.readLong;
import static com.github.badoualy.telegram.tl.StreamUtils.writeInt;
import static com.github.badoualy.telegram.tl.StreamUtils.writeLong;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT64;

/**
 * @author Yannick Badoual yann.badoual@gmail.com
 * @see http://github.com/badoualy/kotlogram
 */
public class TLMessageActionGameScore extends TLAbsMessageAction {

    public static final int CONSTRUCTOR_ID = 0x92a72876;

    protected long gameId;

    protected int score;

    private final String _constructor = "messageActionGameScore#92a72876";

    public TLMessageActionGameScore() {
    }

    public TLMessageActionGameScore(long gameId, int score) {
        this.gameId = gameId;
        this.score = score;
    }

    @Override
    public void serializeBody(OutputStream stream) throws IOException {
        writeLong(gameId, stream);
        writeInt(score, stream);
    }

    @Override
    @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
    public void deserializeBody(InputStream stream, TLContext context) throws IOException {
        gameId = readLong(stream);
        score = readInt(stream);
    }

    @Override
    public int computeSerializedSize() {
        int size = SIZE_CONSTRUCTOR_ID;
        size += SIZE_INT64;
        size += SIZE_INT32;
        return size;
    }

    @Override
    public String toString() {
        return _constructor;
    }

    @Override
    public int getConstructorId() {
        return CONSTRUCTOR_ID;
    }

    public long getGameId() {
        return gameId;
    }

    public void setGameId(long gameId) {
        this.gameId = gameId;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}


text:
package shadow.test.parse;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import shadow.Main;

import java.util.ArrayList;

public class ParserTests {

    private ArrayList<String> args = new ArrayList<String>();

    @BeforeEach
    public void setup() throws Exception {
        args.add("--typecheck");

        String os = System.getProperty("os.name").toLowerCase();

        args.add("-c");
        if( os.contains("windows") )
            args.add("windows.xml");
        else if( os.contains("mac") )
            args.add("mac.xml");
        else
            args.add("linux.xml");
    }

    @Test
    public void testAttributes() throws Exception {
        args.add("tests/parser/attributes/Attributes.shadow");
        Main.run(args.toArray(new String[] { }));
    }

}


text:
* This is a sample code of my posts -  [*Strategy Pattern*](https://seahub.github.io/2017/02/18/Strategy-Pattern/)
* Mainly to discuss one of the design patterns —— Strategy Pattern
* Welcome to my blog using this sample code!
* Also, sincerely hope you to contribute to this repository!
* Blog Link:https://seahub.github.io
* Author:SeaHub(Seahubc@gmail.com || Seahubc@qq.com)


text:
package org.runmyprocess.sec;

import org.runmyprocess.json.JSONObject;

public class Response {

	private JSONObject data;
	private int status;
	/**
	 * Gets all the response information in a single JSONObject structure
	 * @return
	 */
	public JSONObject getObjectResponse() {
		JSONObject reply = new JSONObject();
		reply=data.copy();
		reply.put("SECStatus", this.status);
		return reply;
	}
	/**
	 * Gets the data from the response
	 * @return
	 */
	public JSONObject getData() {
		return data;
	}
	/**
	 * Sets the data object
	 * @param data
	 */
	public void setData(JSONObject data) {
		this.data = data;
	}
	/**
	 * gets the status of the response (http and custom codes)
	 * @return
	 */
	public int getStatus() {
		return status;
	}
	/**
	 * Sets the status code of the response
	 * @param status
	 */
	public void setStatus(int status) {
		this.status = status;
	}

}


text:
package org.androidtransfuse.experiment.generators;

import com.sun.codemodel.*;
import org.androidtransfuse.analysis.repository.BundlePropertyBuilderRepository;
import org.androidtransfuse.analysis.repository.ParcelerPropertyBuilder;
import org.androidtransfuse.experiment.ComponentDescriptor;
import org.androidtransfuse.gen.ClassGenerationUtil;
import org.androidtransfuse.gen.UniqueVariableNamer;
import org.androidtransfuse.intentFactory.FragmentFactory;

import javax.inject.Inject;

/**
 * @author John Ericksen
 */
public class FragmentFactoryGenerator extends AbstractExtraFactoryGenerator {

    private static final String BUILD_FRAGMENT = "build";

    private final ClassGenerationUtil generationUtil;
    private final UniqueVariableNamer namer;

    @Inject
    public FragmentFactoryGenerator(ClassGenerationUtil generationUtil, UniqueVariableNamer namer, BundlePropertyBuilderRepository repository, ParcelerPropertyBuilder parcelerPropertyBuilder) {
        super(generationUtil, namer, repository, parcelerPropertyBuilder);
        this.generationUtil = generationUtil;
        this.namer = namer;
    }

    @Override
    public String getName() {
        return "FragmentFactory Generator";
    }

    @Override
    protected void setupClass(ComponentDescriptor descriptor, JDefinedClass factoryClass) {
        factoryClass._implements(generationUtil.ref(FragmentFactory.class).narrow(generationUtil.ref(descriptor.getPackageClass())));
    }

    protected void createMethods(ComponentDescriptor descriptor, JDefinedClass factoryClass, JFieldVar bundle) {
        JClass targetRef = generationUtil.ref(descriptor.getPackageClass());
        JBlock buildMethodBody = factoryClass.method(JMod.PUBLIC, targetRef, BUILD_FRAGMENT).body();

        JVar fragmentVar = buildMethodBody.decl(targetRef, namer.generateName(targetRef), JExpr._new(targetRef));
        buildMethodBody.invoke(fragmentVar, "setArguments").arg(bundle);

        buildMethodBody._return(fragmentVar);
    }
}


text:
.usi-zoom {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '1');
}
.usi-follow {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '2');
}
.usi-ripple_one {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '3');
}
.usi-ripple_all {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '4');
}
.usi-glue {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '5');
}
.usi-marker {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '6');
}
.usi-cut {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '7');
}
.usi-mouse_select {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '8');
}
.usi-selection {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '9');
}
.usi-mute {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '0');
}
.usi-fader {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'q');
}
.usi-ultraschall {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '´');
}
.usi-ultraschall-full {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'ß');
}
.usi-tape {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'w');
}
.usi-trim {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'e');
}
.usi-idea {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'r');
}
.usi-music {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'a');
}
.usi-mic {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 's');
}
.usi-coffee {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'd');
}
.usi-onAir {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'f');
}
.usi-grid {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'y');
}
.usi-export {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'x');
}
.usi-mp3 {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'c');
}
.usi-folder {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'v');
}
.usi-link {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 't');
}
.usi-unlink {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'z');
}
.usi-txtlable {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'u');
}
.usi-txt {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'i');
}
.usi-newitem {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'o');
}
.usi-newregion {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = 'p');
}
.usi-studio-link {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '#');
}
.usi-soundboard {
  *zoom: expression(this.runtimeStyle['zoom'] = '1', this.innerHTML = '+');
}