text:
'use strict';

var express = require('express');
var auth = require('../middleware/auth');
var util = require('util');
var path = require('path');
var common = require('./common');
var fs = require('fs');
var router = express.Router();
var Cooperative = require('../models').cooperatives;
var Log = require('../models').logs;

/**
 * @api {post} /cooperative Create new cooperative
 * @apiGroup Cooperative
 *
 * @apiParam {String} name Cooperative name
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" -d \
 *  '{
 *    "name": "BRF Hamarby",
 *  }' \
 *  http://localhost:3000/api/cooperative
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 0,
 *     "_id": "55f14ce337d4bef728a861ab",
 *     "name": "BRF Hamarby"
 *   }
 */
router.post('/', function(req, res) {
  var cooperative = req.body;
  Cooperative.create(cooperative, res.successRes);

  Log.create({
    // userId: req.user._id,
    category: 'Cooperative',
    type: 'create',
    data: req.body
  });
});

/**
 * @api {get} /cooperative/consumption Get average consumption for cooperatives
 * @apiGroup Cooperative
 *
 * @apiParam {String} name Cooperative name
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X POST -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" -d \
 *  '{
 *    "name": "BRF Hamarby",
 *  }' \
 *  http://localhost:3000/api/cooperative
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 0,
 *     "_id": "55f14ce337d4bef728a861ab",
 *     "name": "BRF Hamarby"
 *   }
 */
router.get('/consumption/:type/:granularity', function(req, res) {
  Cooperative.getAvgConsumption(req.params.type, req.params.granularity, req.query.from, req.query.to, res.successRes);
  Log.create({
    // userId: req.user._id,
    category: 'Cooperative',
    type: 'geAvgConsumption',
    data: {
      params: req.params
    }
  });
});

/**
 * @api {get} /cooperative/:id Fetch an cooperative by id
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X GET -H "Authorization: Bearer $API_TOKEN" \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *   }
 */
router.get('/:id', function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.get(req.params.id, null, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'get',
      data: {
        cooperativeId: req.params.id
      }
    });
  }
});

/**
 * @api {get} /cooperative/ Get list of all cooperatives
 * @apiGroup Cooperative
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X GET -H "Authorization: Bearer $API_TOKEN" \
 *  http://localhost:3000/api/cooperative/
 *
 * @apiSuccessExample {json} Success-Response:
 *   [{
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *     ...
 *   }
 *   ...
 *   ]
 */
router.get('/', function(req, res) {
  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.all(res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'get'
    });
  }
});

/**
 * @api {put} /cooperative/:id Update the cooperative information
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiParam (Body) {String} name Cooperative name
 * @apiParam (Body) {String} email Cooperative contact email
 * @apiParam (Body) {Number} yearOfConst Year of construction of the cooperative
 * @apiParam (Body) {Number} area Area in square meters of the cooperative shared space
 * @apiParam (Body) {Number} numOfApartments Number of apartments in the cooperative
 * @apiParam (Body) {String} ventilationType Ventilation type
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" -d \
 *  '{
 *    "name": "New Cooperative"
 *    "email": "new@example.com"
 *  }' \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *     ...
 *   }
 */
router.put('/:id', function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.update(req.params.id, req.body, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'update',
      data: req.body
    });
  }
});

/**
 * @api {post} /cooperative/:id/meter Add new meter to cooperative
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiParam (Body) {String} meterId Id of the new meter
 * @apiParam (Body) {String} type Type of the new meter (e.g. electricity, heating)
 * @apiParam (Body) {Boolean} useInCalc Whether to use the meter reading in energy calculations
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X PUSH -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" -d \
 *  '{
 *    "meterId": "12341234",
 *    "type": "electricity",
 *    "useInCalc": true
 *  }' \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab/meter
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *     ...
 *   }
 */
router.post('/:id/meter', function(req, res) {

  req.checkParams('id', 'Invalid cooperative id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.addMeter(req.params.id, req.body.meterId, req.body.type, req.body.useInCalc, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'addMeter',
      data: {
        cooperativeId: req.params.id,
        params: req.body
      }
    });
  }
});

/**
 * @api {post} /cooperative/:id/meter Add new cooperative action
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiParam (Body) {String} name Name of the action
 * @apiParam (Body) {Date} date Date when action was taken
 * @apiParam (Body) {String} description Action description
 * @apiParam (Body) {Number} cost Action cost
 * @apiParam (Body) {Number[]} types Action types
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X PUSH -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" -d \
 *  '{
 *    "name": "Ventilation change",
 *    "cost": "120"
 *  }' \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab/action
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *     ...
 *   }
 */
router.post('/:id/action', function(req, res) {

    req.checkParams('id', 'Invalid cooperative id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.addAction(req.params.id, req.body, null, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'addAction',
      data: {
        cooperativeId: req.params.id,
        action: req.body
      }
    });
  }
});

/**
 * @api {put} /cooperative/:id/action/:actionId Update cooperative action
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiParam {String} actionId MongoId of the action
 * @apiParam (Body) {String} name Name of the action
 * @apiParam (Body) {Date} date Date when action was taken
 * @apiParam (Body) {String} description Action description
 * @apiParam (Body) {Number} cost Action cost
 * @apiParam (Body) {Number[]} types Action types
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" -d \
 *  '{
 *    "name": "Ventilation change",
 *    "cost": "120"
 *  }' \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab/action/55f14ce337dlkabef728a861ab
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *     ...
 *   }
 */
router.put('/:id/action/:actionId', function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();
  req.checkParams('actionId', 'Invalid cooperative action id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.updateAction(req.params.id, req.params.actionId, req.body, null, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'updateAction',
      data: {
        cooperativeId: req.params.id,
        actionId: req.params.actionId,
        action: req.body
      }
    });
  }
});

/**
 * @api {delete} /cooperative/:id/action/:actionId Delet cooperative action
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiParam {String} actionId MongoId of the action
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X DELETE -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab/action/55f14ce337dlkabef728a861ab
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *     ...
 *   }
 */
router.delete('/:id/action/:actionId', function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();
  req.checkParams('actionId', 'Invalid cooperative action id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.deleteAction(req.params.id, req.params.actionId, null, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'deleteAction',
      data: {
        cooperativeId: req.params.id,
        actionId: req.params.actionId
      }
    });
  }
});

/**
 * @api {post} /cooperative/:id/action/:actionId/comment Comment cooperative action
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiParam {String} actionId MongoId of the action
 * @apiParam (Body) {String} comment The text of the comment
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" -d \
 *  '{
 *    "comment": "Nice job"
 *  }' \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab/action/55f14ce337dlkabef728a861ab
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *     ...
 *   }
 */
router.post('/:id/action/:actionId/comment', auth.authenticate(), function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();
  req.checkParams('actionId', 'Invalid cooperative action id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.commentAction(req.params.id, req.params.actionId, req.body, req.user, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'commentAction',
      data: {
        cooperativeId: req.params.id,
        actionId: req.params.actionId,
        comment: req.body
      }
    });
  }
});

/**
 * @api {get} /cooperative/:id/action/:actionId/comment Load more comments
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiParam {String} actionId MongoId of the action
 * @apiParam (Query) {String} lastCommentId MongoId of the last comment retrieved
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X PUT -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab/action/55f14ce337dlkabef728a861ab/comment?lastCommentId=65f14ce337dlkabef728a861ab
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *     ...
 *   }
 */
router.get('/:id/action/:actionId/comment', function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();
  req.checkParams('actionId', 'Invalid cooperative action id').isMongoId();
  req.checkQuery('lastCommentId', 'Invalid comment id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.getMoreComments(req.params.id, req.params.actionId, req.query.lastCommentId, null, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'getMoreComments',
      data: {
        cooperativeId: req.params.id,
        actionId: req.params.actionId,
        lastCommentId: req.params.lastCommentId
      }
    });
  }
});

/**
 * @api {delete} /cooperative/:id/action/:actionId/comment/:commentId Delete cooperative action comments
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiParam {String} actionId MongoId of the action
 * @apiParam {String} commentId MongoId of the comment
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X DELETE -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab/action/55f14ce337dlkabef728a861ab/comment/12983ujaw9210
 *
 * @apiSuccessExample {json} Success-Response:
 *   {
 *     "__v": 8,
 *     "_id": "555ef84b2fd41ffc6e078a34",
 *     "date": "2015-07-01T12:04:33.599Z",
 *     "name": "BRF Hamarby"
 *     ...
 *   }
 */
router.delete('/:id/action/:actionId/comment/:commentId', function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();
  req.checkParams('actionId', 'Invalid cooperative action id').isMongoId();
  req.checkParams('commentId', 'Invalid comment id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.deleteActionComment(req.params.id, req.params.actionId, req.params.commentId, null, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'deleteActionComment',
      data: {
        cooperativeId: req.params.id,
        actionId: req.params.actionId,
        commentId: req.params.commentId
      }
    });
  }
});

/*
curl  -X POST http://localhost:3000/api/cooperative/5623feb4fa9bee84098e7ce0/editor -d'{"editorId" : "55f91cacf9b31654b8758efd"}' -H "Content-Type: application/json" | python -m json.tool
*/
router.post('/:id/editor', function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.addEditor(req.params.id, req.body, null, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'addEditor',
      data: {
        cooperativeId: req.params.id,
        editor: req.body
      }
    });
  }
});

/**
 curl  -X DELETE http://localhost:3000/api/cooperative/5623feb4fa9bee84098e7ce0/editor/56240d8a830db5840a70571a | python -m json.tool
*/
router.delete('/:id/editor/:coopEditorId', function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();
  req.checkParams('coopEditorId', 'Invalid cooperative editor id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.deleteEditor(req.params.id, req.params.coopEditorId, null, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'deleteEditor',
      data: {
        cooperativeId: req.params.id,
        coopEditorId: req.params.coopEditorId
      }
    });
  }
});

/**
 * @api {get} /cooperative/:id/consumption/:type/:granularity Get cooperative consumption
 * @apiGroup Cooperative
 *
 * @apiParam {String} id MongoId of cooperative
 * @apiParam {String} type Consumption type (e.g. electricity, heating)
 * @apiParam {String} granularity Granularity (e.g. year, month)
 * @apiParam {String} from Range date of consumption in YYYYMM-YYYYMM format (MM is optional)
 *
 * @apiExample {curl} Example usage:
 *  # Get API token via /api/user/token
 *  export API_TOKEN=fc35e6b2f27e0f5ef...
 *
 *  curl -i -X GET -H "Content-Type: application/json" -H "Authorization: Bearer $API_TOKEN" \
 *  http://localhost:3000/api/cooperative/55f14ce337d4bef728a861ab/consumption/electricity/month?from=201505-201604
 *
 * @apiSuccessExample {json} Success-Response:
 *   [
 *   5.335204147764095,
 *   3.957101425793908,
 *   3.3761681788723266
 *   ...
 *   ]
 */
router.get('/:id/consumption/:type/:granularity', function(req, res) {
  req.checkParams('id', 'Invalid cooperative id').isMongoId();

  var err;
  if ((err = req.validationErrors())) {
    res.status(500).send('There have been validation errors: ' + util.inspect(err));
  } else {
    Cooperative.getConsumption(req.params.id, req.params.type, req.params.granularity, req.query.from, req.query.to, res.successRes);

    Log.create({
      // userId: req.user._id,
      category: 'Cooperative',
      type: 'geConsumption',
      data: {
        cooperativeId: req.params.id,
        params: req.params
      }
    });
  }
});

module.exports = router;


text:
#ifndef _MACHINE_PROFILE_H_
#define	_MACHINE_PROFILE_H_

#ifdef _KERNEL

/*
 * Config generates something to tell the compiler to align functions on 16
 * byte boundaries.  A strict alignment is good for keeping the tables small.
 */
#define	FUNCTION_ALIGNMENT	16

/*
 * The kernel uses assembler stubs instead of unportable inlines.
 * This is mainly to save a little time when profiling is not enabled,
 * which is the usual case for the kernel.
 */
#define	_MCOUNT_DECL void mcount
#define	MCOUNT

#ifdef GUPROF
#define	CALIB_SCALE	1000
#define	KCOUNT(p,index)	((p)->kcount[(index) \
			 / (HISTFRACTION * sizeof(HISTCOUNTER))])
#define	MCOUNT_DECL(s)
#define	MCOUNT_ENTER(s)
#define	MCOUNT_EXIT(s)
#define	PC_TO_I(p, pc)	((uintfptr_t)(pc) - (uintfptr_t)(p)->lowpc)
#else
#define	MCOUNT_DECL(s)	u_long s;
#ifdef SMP
extern int	mcount_lock;
#define	MCOUNT_ENTER(s)	{ s = read_rflags(); disable_intr(); \
 			  while (!atomic_cmpset_acq_int(&mcount_lock, 0, 1)) \
			  	/* nothing */ ; }
#define	MCOUNT_EXIT(s)	{ atomic_store_rel_int(&mcount_lock, 0); \
			  write_rflags(s); }
#else
#define	MCOUNT_ENTER(s)	{ s = read_rflags(); disable_intr(); }
#define	MCOUNT_EXIT(s)	(write_rflags(s))
#endif
#endif /* GUPROF */

#else /* !_KERNEL */

#define	FUNCTION_ALIGNMENT	4

#define	_MCOUNT_DECL static __inline void _mcount

#ifdef	__GNUC__
#define	MCOUNT								\
void									\
mcount()								\
{									\
	uintfptr_t selfpc, frompc;					\
	/*								\
	 * Find the return address for mcount,				\
	 * and the return address for mcount's caller.			\
	 *								\
	 * selfpc = pc pushed by call to mcount				\
	 */								\
	asm("movq 8(%%rbp),%0" : "=r" (selfpc));			\
	/*								\
	 * frompc = pc pushed by call to mcount's caller.		\
	 * The caller's stack frame has already been built, so %ebp is	\
	 * the caller's frame pointer.  The caller's raddr is in the	\
	 * caller's frame following the caller's caller's frame pointer.\
	 */								\
	asm("movq (%%rbp),%0" : "=r" (frompc));				\
	frompc = ((uintfptr_t *)frompc)[1];				\
	_mcount(frompc, selfpc);					\
}
#else	/* __GNUC__ */
#define	MCOUNT		\
void			\
mcount()		\
{			\
}
#endif	/* __GNUC__ */

typedef	unsigned long	uintfptr_t;

#endif /* _KERNEL */

/*
 * An unsigned integral type that can hold non-negative difference between
 * function pointers.
 */
typedef	u_int	fptrdiff_t;

#ifdef _KERNEL

void	mcount(uintfptr_t frompc, uintfptr_t selfpc);
void	kmupetext(uintfptr_t nhighpc);

#ifdef GUPROF
struct gmonparam;

void	nullfunc_loop_profiled(void);
void	nullfunc_profiled(void);
void	startguprof(struct gmonparam *p);
void	stopguprof(struct gmonparam *p);
#else
#define	startguprof(p)
#define	stopguprof(p)
#endif /* GUPROF */

#else /* !_KERNEL */

#include <sys/cdefs.h>

__BEGIN_DECLS
#ifdef __GNUC__
void	mcount(void) __asm(".mcount");
#endif
static void	_mcount(uintfptr_t frompc, uintfptr_t selfpc);
__END_DECLS

#endif /* _KERNEL */

#ifdef GUPROF
/* XXX doesn't quite work outside kernel yet. */
extern int	cputime_bias;

__BEGIN_DECLS
int	cputime(void);
void	empty_loop(void);
void	mexitcount(uintfptr_t selfpc);
void	nullfunc(void);
void	nullfunc_loop(void);
__END_DECLS
#endif

#endif /* !_MACHINE_PROFILE_H_ */

redpajama_set_name: RedPajamaGithub


text:
"""
setup_serial.py file for MapReduce MPI files with dummy serial MPI library
"""

from distutils.core import setup, Extension

import os, glob
path = os.path.dirname(os.getcwd())
libfiles = glob.glob("%s/src/*.cpp" % path) + \
           glob.glob("%s/mpistubs/*.cpp" % path)

mrmpi_library = Extension("_mrmpi_serial",
                          sources = libfiles,
                          define_macros = [("MPICH_IGNORE_CXX_SEEK",1)],
                          include_dirs = ["../src", "../mpistubs"],
                          )

setup(name = "mrmpi_serial",
      version = "7Apr09",
      author = "Steve Plimpton",
      author_email = "sjplimp@sandia.gov",
      url = "http://www.cs.sandia.gov/mapreduce.html",
      description = """MapReduce MPI library""",
      py_modules = ["mrmpi"],
      ext_modules = [mrmpi_library]
      )


text:
import React          from "react"
import ReactTestUtils from "react-dom/test-utils"

import PronoundSelect from './PronoundSelect'

describe("PronoundSelect", () => {

    it("renders a PronoundSelect", () => {
        const tuRenderer = ReactTestUtils.createRenderer()
        const props = {}
        const pronoundSelect = tuRenderer.render(<PronoundSelect {...props} />)
    })

})


text:
import {
    Component,
    ViewChild,
    AfterViewChecked,
    OnInit,
    OnDestroy
} from '@angular/core';
import { Subscription } from 'rxjs/Rx';

import * as c from '../../++common/index';
import { ChatService } from './chat.service';
import { ChatMessage } from './chat-message';
import { GameService } from '../shared/index';

@Component({
    moduleId: module.id,
    selector: 'pb-chat',
    templateUrl: 'chat.component.html',
    styleUrls: ['chat.component.css']
})
export class ChatComponent implements AfterViewChecked, OnInit, OnDestroy {
    players: Array<c.Player>;

    myMessage: string;
    messages: Array<ChatMessage> = [];

    @ViewChild('messagesContainer')
    messagesContainer: any;

    private messageSubscription: Subscription;
    private gameSubscription: Subscription;

    constructor(
        private chatService: ChatService,
        private gameService: GameService
    ) { }

    ngOnInit() {
        this.messageSubscription = this.chatService.message.subscribe((m: c.Message) =>
            this.messages.push(new ChatMessage(m, this.players))
        );

        this.gameSubscription = this.gameService.game.subscribe((g: c.Game) =>
            this.players = g.players
        );
    }

    ngAfterViewChecked() {
        this.scrollToBottom();
    }

    onSubmit() {
        this.chatService.sendMessage(this.myMessage).subscribe();
        this.myMessage = '';
    }

    ngOnDestroy() {
        this.messageSubscription.unsubscribe();
        this.gameSubscription.unsubscribe();
    }

    private scrollToBottom(): void {
        try {
            this.messagesContainer.nativeElement.scrollTop = this.messagesContainer.nativeElement.scrollHeight;
        } catch (err) {
            console.log(err);
        }
    }
}


text:
Go bindings for libVLC and high-level media player interface.

The package can be useful for adding multimedia capabilities to applications
through the provided player interfaces. It relies on Go modules in order to
mirror each supported major version of [libVLC](https://www.videolan.org/vlc/libvlc.html).

Documentation for v3, which implements bindings for libVLC 3.X, can be found on [pkg.go.dev](https://pkg.go.dev/github.com/adrg/libvlc-go/v3).
Documentation for v2, which implements bindings for libVLC 2.X, can be found on [pkg.go.dev](https://pkg.go.dev/github.com/adrg/libvlc-go/v2).

Example applications:

* [GUI media player](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk3_player)
* [GUI screen recorder](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk3_screen_recorder)
* [GUI equalizer](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk3_equalizer)
* [GUI media discovery](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk3_media_discovery)

## Prerequisites

The libVLC development files are required. Instructions for installing the
VLC SDK on multiple operating systems can be found on the wiki pages of this project.

- [Install on Linux](https://github.com/adrg/libvlc-go/wiki/Install-on-Linux)
- [Install on Windows](https://github.com/adrg/libvlc-go/wiki/Install-on-Windows)
- [Install on macOS](https://github.com/adrg/libvlc-go/wiki/Install-on-macOS)

## Installation

In order to support multiple versions of libVLC, the package contains a Go
module for each major version of the API. Choose an installation option
depending on the version of libVLC you want to use.

**libVLC v3.X**

```bash
go get github.com/adrg/libvlc-go/v3
```

**libVLC v2.X**

```bash
go get github.com/adrg/libvlc-go/v2

# Build for libVLC < v2.2.0
go build -tags legacy
```

All versions above also work for projects which are not using Go modules.
However, consider switching to modules.

## Examples

* [GTK 3 media player](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk3_player) (using [gotk3](https://github.com/gotk3/gotk3))
* [GTK 3 screen recorder](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk3_screen_recorder) (using [gotk3](https://github.com/gotk3/gotk3))
* [GTK 3 media discovery](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk3_media_discovery) (using [gotk3](https://github.com/gotk3/gotk3))
* [GTK 3 equalizer](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk3_equalizer) (using [gotk3](https://github.com/gotk3/gotk3))
* [GTK 2 media player](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk2_player) (using [go-gtk](https://github.com/mattn/go-gtk))
* [GTK 2 screen recorder](https://github.com/adrg/libvlc-go-examples/tree/master/v3/gtk2_screen_recorder) (using [go-gtk](https://github.com/mattn/go-gtk))
* [Basic player usage](https://github.com/adrg/libvlc-go-examples/blob/master/v3/player/player.go)
* [Basic list player usage](https://github.com/adrg/libvlc-go-examples/tree/master/v3/list_player/list_player.go)
* [Handling events](https://github.com/adrg/libvlc-go-examples/tree/master/v3/event_handling/event_handling.go)
* [Retrieve media tracks](https://github.com/adrg/libvlc-go-examples/blob/master/v3/media_tracks/media_tracks.go)
* [Retrieve media information](https://github.com/adrg/libvlc-go-examples/blob/master/v3/media_information/media_information.go)
* [Display screen as player media](https://github.com/adrg/libvlc-go-examples/blob/master/v3/display_screen_media/display_screen_media.go)
* [Stream media to Chromecast](https://github.com/adrg/libvlc-go-examples/blob/master/v3/chromecast_streaming/chromecast_streaming.go)
* [Player equalizer usage](https://github.com/adrg/libvlc-go-examples/blob/master/v3/equalizer/equalizer.go)

Examples for all supported API versions can be found at https://github.com/adrg/libvlc-go-examples.

## Usage

```go
package main

import (
    "log"

    vlc "github.com/adrg/libvlc-go/v3"
)

func main() {
    // Initialize libVLC. Additional command line arguments can be passed in
    // to libVLC by specifying them in the Init function.
    if err := vlc.Init("--no-video", "--quiet"); err != nil {
        log.Fatal(err)
    }
    defer vlc.Release()

    // Create a new player.
    player, err := vlc.NewPlayer()
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        player.Stop()
        player.Release()
    }()

    // Add a media file from path or from URL.
    // Set player media from path:
    // media, err := player.LoadMediaFromPath("localpath/test.mp4")
    // Set player media from URL:
    media, err := player.LoadMediaFromURL("http://stream-uk1.radioparadise.com/mp3-32")
    if err != nil {
        log.Fatal(err)
    }
    defer media.Release()

    // Retrieve player event manager.
    manager, err := player.EventManager()
    if err != nil {
        log.Fatal(err)
    }

    // Register the media end reached event with the event manager.
    quit := make(chan struct{})
    eventCallback := func(event vlc.Event, userData interface{}) {
        close(quit)
    }

    eventID, err := manager.Attach(vlc.MediaPlayerEndReached, eventCallback, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer manager.Detach(eventID)

    // Start playing the media.
    err = player.Play()
    if err != nil {
        log.Fatal(err)
    }

    <-quit
}
```

## In action

A list of projects using libvlc-go, in alphabetical order. If you want to
showcase your project in this section, please create a pull request with it.

- [Alio](https://github.com/fenimore/alio) - Command-line music player with Emacs style key bindings.
- [Tripbot](https://github.com/adanalife/tripbot) - An ongoing 24/7 slow-TV art project.

## Stargazers over time

[![Stargazers over time](https://starchart.cc/adrg/libvlc-go.svg)](https://starchart.cc/adrg/libvlc-go)

## Contributing

Contributions in the form of pull requests, issues or just general feedback,
are always welcome.
See [CONTRIBUTING.MD](CONTRIBUTING.md).

**Contributors**:
[adrg](https://github.com/adrg),
[fenimore](https://github.com/fenimore),
[tarrsalah](https://github.com/tarrsalah),
[danielpellon](https://github.com/danielpellon),
[patknight](https://github.com/patknight),
[sndnvaps](https://github.com/sndnvaps).

## Discord server

libvlc-go is part of the libVLC Discord Community [server](https://discord.gg/3h3K3JF). Feel free to come say hello!

## References

For more information see the
[libVLC](https://www.videolan.org/developers/vlc/doc/doxygen/html/group__libvlc.html) documentation.

## License

Copyright (c) 2018 Adrian-George Bostan.

This project is licensed under the [MIT license](https://opensource.org/licenses/MIT).
See [LICENSE](LICENSE) for more details.


text:
<?php

namespace Oro\Bundle\FormBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

class FormGuesserCompilerPass implements CompilerPassInterface
{
    /**
     * @param ContainerBuilder $container
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('form.extension')) {
            return;
        }

        // need to sort guessers according to priority
        $guessers = array();
        foreach ($container->findTaggedServiceIds('form.type_guesser') as $id => $attributes) {
            foreach ($attributes as $eachTag) {
                $priority = !empty($eachTag['priority']) ? $eachTag['priority'] : 0;
                $guessers[$id] = $priority;
            }
        }

        arsort($guessers, SORT_NUMERIC);

        $formExtension = $container->getDefinition('form.extension');
        $formExtension->replaceArgument(3, array_keys($guessers));
    }
}


text:
import boto3
from moto import mock_cloudformation, mock_ecs, mock_autoscaling, mock_s3
import json

from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from tests import EXAMPLE_AMI_ID

depends_on_template_list = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources": {
        "ECSCluster": {
            "Type": "AWS::ECS::Cluster",
            "Properties": {"ClusterName": "test-cluster"},
        },
        "AutoScalingGroup": {
            "Type": "AWS::AutoScaling::AutoScalingGroup",
            "Properties": {
                "AutoScalingGroupName": "test-scaling-group",
                "DesiredCapacity": 1,
                "MinSize": 1,
                "MaxSize": 50,
                "LaunchConfigurationName": "test-launch-config",
                "AvailabilityZones": ["us-east-1a"],
            },
            "DependsOn": ["ECSCluster", "LaunchConfig"],
        },
        "LaunchConfig": {
            "Type": "AWS::AutoScaling::LaunchConfiguration",
            "Properties": {
                "LaunchConfigurationName": "test-launch-config",
                "ImageId": EXAMPLE_AMI_ID,
                "InstanceType": "t2.medium",
            },
        },
    },
}

depends_on_template_string = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources": {
        "AutoScalingGroup": {
            "Type": "AWS::AutoScaling::AutoScalingGroup",
            "Properties": {
                "AutoScalingGroupName": "test-scaling-group",
                "DesiredCapacity": 1,
                "MinSize": 1,
                "MaxSize": 50,
                "LaunchConfigurationName": "test-launch-config",
                "AvailabilityZones": ["us-east-1a"],
            },
            "DependsOn": "LaunchConfig",
        },
        "LaunchConfig": {
            "Type": "AWS::AutoScaling::LaunchConfiguration",
            "Properties": {
                "LaunchConfigurationName": "test-launch-config",
                "ImageId": EXAMPLE_AMI_ID,
                "InstanceType": "t2.medium",
            },
        },
    },
}

def make_chained_depends_on_template():
    depends_on_template_linked_dependencies = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Resources": {
            "Bucket1": {
                "Type": "AWS::S3::Bucket",
                "Properties": {"BucketName": "test-bucket-0-us-east-1"},
            },
        },
    }

    for i in range(1, 10):
        depends_on_template_linked_dependencies["Resources"]["Bucket" + str(i)] = {
            "Type": "AWS::S3::Bucket",
            "Properties": {"BucketName": "test-bucket-" + str(i) + "-us-east-1"},
            "DependsOn": ["Bucket" + str(i - 1)],
        }

    return json.dumps(depends_on_template_linked_dependencies)

depends_on_template_list_json = json.dumps(depends_on_template_list)
depends_on_template_string_json = json.dumps(depends_on_template_string)

@mock_cloudformation
@mock_autoscaling
@mock_ecs
def test_create_stack_with_depends_on():
    boto3.client("cloudformation", region_name="us-east-1").create_stack(
        StackName="depends_on_test", TemplateBody=depends_on_template_list_json
    )

    autoscaling = boto3.client("autoscaling", region_name="us-east-1")
    autoscaling_group = autoscaling.describe_auto_scaling_groups()["AutoScalingGroups"][
        0
    ]
    assert autoscaling_group["AutoScalingGroupName"] == "test-scaling-group"
    assert autoscaling_group["DesiredCapacity"] == 1
    assert autoscaling_group["MinSize"] == 1
    assert autoscaling_group["MaxSize"] == 50
    assert autoscaling_group["AvailabilityZones"] == ["us-east-1a"]

    launch_configuration = autoscaling.describe_launch_configurations()[
        "LaunchConfigurations"
    ][0]
    assert launch_configuration["LaunchConfigurationName"] == "test-launch-config"

    ecs = boto3.client("ecs", region_name="us-east-1")
    cluster_arn = ecs.list_clusters()["clusterArns"][0]
    assert cluster_arn == f"arn:aws:ecs:us-east-1:{ACCOUNT_ID}:cluster/test-cluster"

@mock_cloudformation
@mock_autoscaling
def test_create_stack_with_depends_on_string():
    boto3.client("cloudformation", region_name="us-east-1").create_stack(
        StackName="depends_on_string_test", TemplateBody=depends_on_template_string_json
    )

    autoscaling = boto3.client("autoscaling", region_name="us-east-1")
    autoscaling_group = autoscaling.describe_auto_scaling_groups()["AutoScalingGroups"][
        0
    ]
    assert autoscaling_group["AutoScalingGroupName"] == "test-scaling-group"
    assert autoscaling_group["DesiredCapacity"] == 1
    assert autoscaling_group["MinSize"] == 1
    assert autoscaling_group["MaxSize"] == 50
    assert autoscaling_group["AvailabilityZones"] == ["us-east-1a"]

    launch_configuration = autoscaling.describe_launch_configurations()[
        "LaunchConfigurations"
    ][0]
    assert launch_configuration["LaunchConfigurationName"] == "test-launch-config"

@mock_cloudformation
@mock_s3
def test_create_chained_depends_on_stack():
    boto3.client("cloudformation", region_name="us-east-1").create_stack(
        StackName="linked_depends_on_test",
        TemplateBody=make_chained_depends_on_template(),
    )

    s3 = boto3.client("s3", region_name="us-east-1")
    bucket_response = s3.list_buckets()["Buckets"]

    assert sorted([bucket["Name"] for bucket in bucket_response]) == [
        "test-bucket-" + str(i) + "-us-east-1" for i in range(1, 10)
    ]


text:
package billapp.persistence;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jf
 */
public class DB {
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;

    /**
     * Default constructor
     */
    public DB() {
    }

    /**
     * Get connection
     * @return connection
     */
    public Connection getConnection() {
        return connection;
    }

    /**
     * Set connection
     * @param connection connection
     */
    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    /**
     * Get Query Statement
     * @return Query Statement
     */
    public Statement getStatement() {
        return statement;
    }

    /**
     * set Query Statement
     * @param statement Query Statement
     */
    public void setStatement(Statement statement) {
        this.statement = statement;
    }

    /**
     * Get Result set
     * @return Result set
     */
    public ResultSet getResultSet() {
        return resultSet;
    }

    /**
     * Set Result set
     * @param resultSet Result set
     */
    public void setResultSet(ResultSet resultSet) {
        this.resultSet = resultSet;
    }

    /**
     * Connect to DB
     * @param dbFilename Database filename (+ path)
     * @return True = connected
     */
    public boolean connectMSAccess(String dbFilename) {
        boolean connected = false;
        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
            this.setConnection(DriverManager.getConnection("jdbc:ucanaccess://"
                    + dbFilename));
            connected = true;
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return connected;
    }

    /**
     * Work with DB (SELECT, INSERT, UPDATE, DELETE)
     * @param query Query Statement (TABLE)
     * @return True = Successful query
     */
    public boolean execute(String query) {
        boolean result = false;

        try {
            this.setStatement(this.getConnection().createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY));
            this.getStatement().execute(query);
            this.setResultSet(this.getStatement().getResultSet());
            result = true;
        } catch (SQLException ex) {
            Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
}


text:
//
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {FormsModule} from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatIconModule} from '@angular/material/icon';
import {MatInputModule} from '@angular/material/input';
import {Sort} from '@angular/material/sort';
import {MatTableModule} from '@angular/material/table';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {BehaviorSubject, ReplaySubject} from 'rxjs';

import {Interval, Layer} from '../../models';

import {IntervalTable} from './interval_table';
import * as jumpToTime from './jump_to_time';
import {mockThreadIntervals, verifySorting} from './table_helpers_test';
import {ThreadTableModule} from './thread_table_module';

try {
  TestBed.initTestEnvironment(
      BrowserDynamicTestingModule, platformBrowserDynamicTesting());
} catch {
  // Ignore exceptions when calling it multiple times.
}

/**
 * Initializes the properties for a given IntervalTable.
 *
 * @param component is the table component to initialize.
 */
export function setupIntervalTable(component: IntervalTable) {
  component.data = new BehaviorSubject<Interval[]>([]);
  component.preview = new BehaviorSubject<Interval|undefined>(undefined);
  component.layers = new BehaviorSubject<Array<BehaviorSubject<Layer>>>([]);
  component.sort = new BehaviorSubject<Sort>({active: '', direction: ''});
  component.tab = new BehaviorSubject<number>(0);
  component.jumpToTimeNs = new ReplaySubject<number>();
}

function createTableWithMockData(): ComponentFixture<IntervalTable> {
  const fixture = TestBed.createComponent(IntervalTable);
  const component = fixture.componentInstance;
  setupIntervalTable(component);
  component.data.next(mockThreadIntervals());
  fixture.detectChanges();

  return fixture;
}

describe('IntervalTable', () => {
  beforeEach(waitForAsync(() => {
    document.body.style.width = '500px';
    document.body.style.height = '500px';
    TestBed
        .configureTestingModule({
          imports: [
            BrowserAnimationsModule, FormsModule, MatFormFieldModule,
            MatInputModule, MatTableModule, MatIconModule, ThreadTableModule
          ],
        })
        .compileComponents();
  }));

  it('should create', () => {
    const fixture = createTableWithMockData();
    expect(fixture.componentInstance).toBeTruthy();
  });

  it('should jump to time', () => {
    const fixture = createTableWithMockData();
    const component = fixture.componentInstance;

    const jumpSpy = spyOn(jumpToTime, 'jumpToTime');

    const firstJumpNs = 3000;
    component.jumpToTimeNs.next(firstJumpNs);
    expect(jumpSpy).toHaveBeenCalledWith(component.dataSource, firstJumpNs);
    expect(jumpSpy).toHaveBeenCalledTimes(1);

    const secondJumpNs = 5000;
    component.jumpToTimeNs.next(secondJumpNs);
    expect(jumpSpy).toHaveBeenCalledWith(component.dataSource, secondJumpNs);
    expect(jumpSpy).toHaveBeenCalledTimes(2);
  });

  it('should filter', () => {
    const fixture = createTableWithMockData();
    const component = fixture.componentInstance;
    expect(component.dataSource.data.length)
        .toBeGreaterThanOrEqual(component.pageSize);

    const rowCount = component.dataSource.filteredData.length;

    component.filter.next('Running');
    fixture.detectChanges();
    const filteredRowCount = component.dataSource.filteredData.length;

    component.toggleFiltering();
    fixture.detectChanges();

    const inverseFilterRowCount = component.dataSource.filteredData.length;
    expect(filteredRowCount + inverseFilterRowCount).toBe(rowCount);
  });

  it('should allow sorting', () => {
    const fixture = createTableWithMockData();
    const expectedColumns =
        ['cpu', 'state', 'startTimeNs', 'endTimeNs', 'duration'];
    verifySorting(
        fixture.nativeElement, fixture.componentInstance.dataSource,
        expectedColumns);
  });
});


text:
package com.github.dactiv.orm.core.hibernate.support;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.dactiv.common.utils.CollectionUtils;
import com.github.dactiv.common.utils.ReflectionUtils;
import com.github.dactiv.orm.core.Page;
import com.github.dactiv.orm.core.PageRequest;
import com.github.dactiv.orm.core.PageRequest.Sort;
import com.github.dactiv.orm.core.PropertyFilter;
import com.github.dactiv.orm.core.RestrictionNames;
import com.github.dactiv.orm.core.hibernate.CriterionBuilder;
import com.github.dactiv.orm.core.hibernate.HibernateRestrictionBuilder;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.internal.AbstractQueryImpl;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.springframework.util.Assert;

import com.google.common.collect.Lists;

/**
 * {@link BasicHibernateDao}基础扩展类。包含对{@link PropertyFilter}的支持。或其他查询的支持
 *
 * @author maurice
 *
 * @param <T> ORM对象
 * @param <PK> 主键Id类型
 */
@SuppressWarnings({"rawtypes","unchecked"})
public class HibernateSupportDao<T,PK extends Serializable> extends BasicHibernateDao<T, PK>{

	public HibernateSupportDao(){

	}

	public HibernateSupportDao(Class<T> entityClass){
		super(entityClass);
	}

	/**
	 * 获取实体的总记录数
	 *
	 * @return long
	 */
	public long entityCount(PropertyFilter...filters) {
		return (Long) createCriteria(Lists.newArrayList(filters)).setProjection(Projections.rowCount()).uniqueResult();
	}

	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 *
	 * @param c Criteria对象
	 *
	 * @return long
	 */
	protected long countCriteriaResult( Criteria c) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtils.getFieldValue(impl,"orderEntries");
			ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 执行Count查询
		Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
		long totalCount = (totalCountObject != null) ? totalCountObject : 0;

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}

		try {
			ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return totalCount;
	}

	/**
	 * 根据{@link PropertyFilter}创建Criteria
	 *
	 * @param filters 属性过滤器
	 *
	 * @return {@link Criteria}
	 */
	protected Criteria createCriteria(List<PropertyFilter> filters,Order ...orders) {

		Criteria criteria = createCriteria();

		if (CollectionUtils.isEmpty(filters)) {
			return criteria;
		}
		for (PropertyFilter filter : filters) {
			criteria.add(createCriterion(filter));
		}
		setOrderToCriteria(criteria, orders);
		return criteria;
	}

	/**
	 * 通过{@link PropertyFilter} 创建 Criterion
	 *
	 * @param filter 属性过滤器
	 *
	 * @return {@link Criterion}
	 */
	protected Criterion createCriterion(PropertyFilter filter) {
		if (filter == null) {
			return null;
		}
		return HibernateRestrictionBuilder.getRestriction(filter);
	}

	/**
	 * 根据{@link PropertyFilter} 查询全部
	 *
	 * @param filters 属性过滤器
	 *
	 * @return List
	 */
	public List<T> findByPropertyFilter(List<PropertyFilter> filters,Order... orders) {

		return createCriteria(filters,orders).list();
	}

	/**
	 * 通过orm实体属性名称查询全部
	 *
	 * @param propertyName orm实体属性名称
	 * @param value 值
	 *
	 * @return List
	 */
	public List<T> findByProperty(String propertyName,Object value) {
		return findByProperty(propertyName, value, RestrictionNames.EQ);
	}

	/**
	 * 通过orm实体属性名称查询全部
	 *
	 * @param propertyName orm实体属性名称
	 * @param value 值
	 * @param restrictionName 约束名称,参考{@link CriterionBuilder}的实现类
	 *
	 * @return List
	 */
	public List<T> findByProperty(String propertyName,Object value,String restrictionName,Order ...orders) {
		Criterion criterion = HibernateRestrictionBuilder.getRestriction(propertyName, value, restrictionName);
		Criteria criteria = createCriteria(criterion);
		setOrderToCriteria(criteria, orders);
		return createCriteria(criterion).list();
	}

	/**
	 * 通过criterion数组查询全部
	 *
	 * @param criterions criterion数组
	 *
	 * @return Object
	 */
	public T findByCriterion(Criterion[] criterions,Order ...orders){
		Criteria criteria = createCriteria(criterions);
		setOrderToCriteria(criteria, orders);
		return (T)criteria.uniqueResult();
	}

	/**
	 * 通过{@link PropertyFilter} 查询单个orm实体
	 *
	 * @param filters 属性过滤器
	 *
	 * @return Object
	 *
	 */
	public T findUniqueByPropertyFilter(List<PropertyFilter> filters) {
		return (T) createCriteria(filters).uniqueResult();
	}

	/**
	 * 通过criterion数组查询单个orm实体
	 *
	 * @param criterions criterion数组
	 *
	 * @return Object
	 */
	public T findUniqueByCriterion(Criterion[] criterions){
		Criteria criteria = createCriteria(criterions);
		return (T)criteria.uniqueResult();
	}

	/**
	 * 通过orm实体的属性名称查询单个orm实体
	 *
	 * @param propertyName 属性名称
	 * @param value 值
	 *
	 * @return Object
	 */
	public T findUniqueByProperty(String propertyName,Object value) {
		return findUniqueByProperty(propertyName,value,RestrictionNames.EQ);
	}

	/**
	 * 通过orm实体的属性名称查询单个orm实体
	 *
	 * @param propertyName 属性名称
	 * @param value 值
	 * @param restrictionName 约束名称 参考{@link CriterionBuilder}的所有实现类
	 *
	 * @return Object
	 */
	public T findUniqueByProperty(String propertyName,Object value,String restrictionName) {
		Criterion criterion = HibernateRestrictionBuilder.getRestriction(propertyName, value, restrictionName);
		Criteria criteria = createCriteria(criterion);
		return (T) criteria.uniqueResult();
	}

	/**
	 * 通过{@link PropertyFilter}和分页请求参数获取分页对象
	 *
	 * @param request 分页请求参数
	 * @param filters 属性过滤器集合
	 *
	 * @return {@link Page}
	 */
	public Page<T> findPage(PageRequest request,List<PropertyFilter> filters) {
		Criteria c = createCriteria(filters);
		return findPage(request,c);
	}

	/**
	 * 根据分页参数与Criteria获取分页对象
	 *
	 * @param request 分页请求参数
	 * @param c Criteria对象
	 *
	 * @return {@link Page}
	 */
	public Page<T> findPage(PageRequest request, Criteria c) {

		Page<T> page = new Page<T>(request);

		if (request == null) {
			return page;
		}

		if (request.isCountTotal()) {
			long totalCount = countCriteriaResult(c);
			page.setTotalItems(totalCount);
		}

		setPageRequestToCriteria(c, request);

		List result = c.list();
		page.setResult(result);

		return page;
	}

	/**
	 * 通过分页参数与HQL语句获取分页对象
	 *
	 * @param request 分页请求参数
	 * @param queryOrNamedQuery hql 或者Hibernate的NamedQuery
	 * @param values 值
	 *
	 * @return {@link Page}
	 */
	public <X> Page<X> findPage(PageRequest request,String queryOrNamedQuery,Object... values) {

		Query query = createQuery(queryOrNamedQuery, values);

		return findPage(request,query);
	}

	/**
	 * 通过分页参数与HQL语句获取分页对象
	 *
	 * @param request 分页请求参数
	 * @param queryString HQL语句
	 * @param values 值
	 *
	 * @return {@link Page}
	 */
	public <X> Page<X> findPage(PageRequest request, String queryString,Map<String,Object> values) {

		Query query = createQuery(queryString, values);

		return findPage(request, query);
	}

	/**
	 * 根据分页请求参数与Query获取分页请求对象
	 *
	 * @param request 分页请求参数对象
	 * @param query Hibernate Query
	 *
	 * @return {@link Page}
	 */
	public <X> Page<X> findPage(PageRequest request, Query query) {
		Page<X> page = new Page<X>(request);

		if (request == null) {
			return page;
		}

		AbstractQueryImpl impl = (AbstractQueryImpl) query;

		String queryString = setPageRequestToHql(impl.getQueryString(),request);
		ReflectionUtils.setFieldValue(impl, "queryString", queryString);

		if (request.isCountTotal()) {
			long totalCount = 0;

			if (impl.hasNamedParameters()) {
				Map<String,TypedValue> map = ReflectionUtils.getFieldValue(impl, "namedParameters");
				Map<String, Object> values = new HashMap<String, Object>();

				for (Map.Entry<String, TypedValue> entry:map.entrySet()) {
					values.put(entry.getKey(), entry.getValue().getValue());
				}

				totalCount = countHqlResult(impl.getQueryString(), values);

			} else {
				List<Object> values = ReflectionUtils.invokeGetterMethod(impl, "values");
				totalCount = countHqlResult(impl.getQueryString(), values.toArray());

			}

			page.setTotalItems(totalCount);
		}

		impl.setFirstResult(request.getOffset());
		impl.setMaxResults(request.getPageSize());

		List result = impl.list();
		page.setResult(result);

		return page;
	}

	/**
	 * 在HQL的后面添加分页参数定义的orderBy, 辅助函数.
	 */
	protected String setPageRequestToHql( String hql, PageRequest pageRequest) {

		if (CollectionUtils.isEmpty(pageRequest.getSort())) {
			return hql;
		}

		StringBuilder builder = new StringBuilder(hql);
		builder.append(" order by");

		for (Sort orderBy : pageRequest.getSort()) {
			builder.append(String.format(" %s %s,", orderBy.getProperty(), orderBy.getDir()));
		}

		builder.deleteCharAt(builder.length() - 1);

		return builder.toString();
	}

	/**
	 * 设置分页参数到Criteria对象,辅助函数.
	 *
	 * @param c Hibernate Criteria
	 * @param pageRequest 分页请求参数
	 *
	 * @return {@link Criteria}
	 */
	protected Criteria setPageRequestToCriteria( Criteria c,  PageRequest pageRequest) {
		Assert.isTrue(pageRequest.getPageSize() > 0, "分页大小必须大于0");

		c.setFirstResult(pageRequest.getOffset());
		c.setMaxResults(pageRequest.getPageSize());

		if (pageRequest.isOrderBySetted()) {
			for (Sort sort : pageRequest.getSort()) {
				Order order = null;
				if (sort.getDir().equals(Sort.ASC)) {
					order = Order.asc(sort.getProperty());
				} else {
					order = Order.desc(sort.getProperty());
				}
				c.addOrder(order);
			}
		}

		return c;
	}

}


text:
package jlibs.core.net;

/**
 * @author Santhosh Kumar T
 */
public enum Protocol{
    TCP(-1, false, "Transmission Control Protocol"),
    SSL(-1, true, "Secure Socket Layer"),
    FTP(21, false, "File Transfer Protocol"),
    SSH(22, true, "Secure Shell"),
    TELNET(23, false, "Telnet protocol"),
    SMTP(25, false, "Simple Mail Transfer Protocol"),
    HTTP(80, false, "Hypertext Transfer Protocol"),
    HTTPS(443, true, "Hypertext Transfer Protocol Secure"),
    POP3(110, false, "Post Office Protocol v3"),
    IMAP(143, false, "Internet Message Access Protocol"),
    RMI(1099, false, "Remote Method Invocation"),
    CVS(2401, false, "Concurrent Versions System"),
    SVN(3690, false, "Subversion"),
    ;

    private int port;
    private String displayName;
    private boolean secured;
    Protocol(int port, boolean secured, String displayName){
        this.port = port;
        this.secured = secured;
        this.displayName = displayName;
    }

    public boolean secured(){
        return secured;
    }
    public int port(){
        return port;
    }
    public String displayName(){
        return displayName;
    }
}


text:
namespace ids
{
	//
	class standby_property
	{
	public:
		//
		standby_property(HIDS camera_handle) :
			camera_handle(camera_handle)
		{

		}

		// Gets if the camera supports standby mode.
		bool_t supported() const
		{
			ULONG result = is_CameraStatus(
				this->camera_handle,
				IS_STANDBY_SUPPORTED,
				IS_GET_STATUS);
			//detail::throw_on_error(this->camera_handle, static_cast<INT>(result));
			return result == 1;
		}

		bool_t get() const
		{
			ULONG result = is_CameraStatus(
				this->camera_handle,
				IS_STANDBY,
				IS_GET_STATUS);
			//detail::throw_on_error(this->camera_handle, static_cast<INT>(result));
			return result == 1;
		}

		void set(bool_t value) const
		{
			ULONG result = is_CameraStatus(
				this->camera_handle,
				IS_STANDBY,
				static_cast<ULONG>(value));
			detail::throw_on_error(this->camera_handle, static_cast<INT>(result));
		}

	private:
		const HIDS camera_handle;
	};
}


text:
"""Steps for behavioral style tests are defined in this module.

Each step is defined by the string decorating it. This string is used
to call the step in "*.feature" file.

"""
from __future__ import unicode_literals

import wrappers
from behave import when, then
from textwrap import dedent

@when('we prepare the test data')
def step_prepare_data(context):
    """Create table, insert a record."""
    context.cli.sendline('drop table if exists a;')
    wrappers.wait_prompt(context)
    context.cli.sendline(
        'create table a(x integer, y real, z numeric(10, 4));')
    wrappers.expect_pager(context, 'CREATE TABLE\r\n', timeout=2)
    context.cli.sendline('''insert into a(x, y, z) values(1, 1.0, 1.0);''')
    wrappers.expect_pager(context, 'INSERT 0 1\r\n', timeout=2)

@when('we set expanded {mode}')
def step_set_expanded(context, mode):
    """Set expanded to mode."""
    context.cli.sendline('\\' + 'x {}'.format(mode))
    wrappers.expect_exact(context, 'Expanded display is', timeout=2)
    wrappers.wait_prompt(context)

@then('we see {which} data selected')
def step_see_data(context, which):
    """Select data from expanded test table."""
    if which == 'expanded':
        wrappers.expect_pager(
            context,
            dedent('''\
                -[ RECORD 1 ]-------------------------\r
                x | 1\r
                y | 1.0\r
                z | 1.0000\r
                SELECT 1\r
            '''),
            timeout=1)
    else:
        wrappers.expect_pager(
            context,
            dedent('''\
                +-----+-----+--------+\r
                | x   | y   | z      |\r
                |-----+-----+--------|\r
                | 1   | 1.0 | 1.0000 |\r
                +-----+-----+--------+\r
                SELECT 1\r
            '''),
            timeout=1)


text:
layout: post
title: "The Play Framework at LinkedIn"
tags:
- External Writing
- Play
thumbnail_path: "projects/play-framework-linkedin.jpg"
external_url: "http://engineering.linkedin.com/play/play-framework-linkedin"
---

A blog post I wrote on the LinkedIn Engineering Blog about [{{ page.title }}]({{ page.external_url }})::

{% include figure.html path=page.thumbnail_path caption=page.title url=page.external_url %}


text:
package core

import (
	"errors"
	"path"
	"path/filepath"
	"sort"
	"time"
)

type DBFiles struct {
	Time time.Time
	Path string
}

var ErrUnknownPath = errors.New("Unknown path format.")

func RecGlob(db *DB) ([]DBFiles, error) {
	return dbGlob(db, recExt)
}

func FixGlob(db *DB) ([]DBFiles, error) {
	return dbGlob(db, FixExt)
}

/*
func dbGlob(db *DB, ext string) ([]DBFiles, error) {
	var lenExt = len(ext)
	var lenTime = len(pathTimeFormat) + lenExt
	globPath := path.Join(db.Path, db.Name, "*", "*"+ext)
	matches, err := filepath.Glob(globPath)
	if err != nil {
		return nil, err
	}
	sort.Strings(matches)
	files := make([]DBFiles, len(matches))
	for i, p := range matches {
		if len(p) <= lenTime {
			return nil, ErrUnknownPath
		}
		t, err := time.ParseInLocation(pathTimeFormat, p[len(p)-lenTime:len(p)-lenExt], time.Local)
		if err != nil {
			return nil, err
		}
		files[i] = DBFiles{Time: t, Path: p}
	}
	return files, nil
}
*/

const pathTimeFormat = "20060102/150405"

type dbPathTime struct {
	ext     string
	lenExt  int
	lenTime int
	TimeFmt string
}

func dbGlob(db *DB, ext string) ([]DBFiles, error) {
	f := &dbPathTime{
		ext:     ext,
		lenExt:  len(ext),
		lenTime: len(pathTimeFormat) + len(ext),
		TimeFmt: pathTimeFormat,
	}
	globPath := path.Join(db.Path, db.Name, "*", "*"+ext)
	return Glob(globPath, f.pathToTime)
}

func Glob(globPath string, pathToTime func(string) (time.Time, error)) ([]DBFiles, error) {
	matches, err := filepath.Glob(globPath)
	if err != nil {
		return nil, err
	}
	sort.Strings(matches)
	files := make([]DBFiles, len(matches))
	for i, p := range matches {
		t, err := pathToTime(p)
		if err != nil {
			return nil, err
		}
		files[i] = DBFiles{Time: t, Path: p}
	}
	return files, nil
}

// "path/to/20060102/150405.拡張子" の時間をパースする
func (f *dbPathTime) pathToTime(p string) (time.Time, error) {
	if len(p) <= f.lenTime {
		return time.Time{}, ErrUnknownPath
	}
	return time.ParseInLocation(f.TimeFmt, p[len(p)-f.lenTime:len(p)-f.lenExt], time.Local)
}


text:
using CMS.DocumentEngine.Types.DancingGoatMvc;

using DancingGoat.Models.Products;

namespace DancingGoat.Models.Coffees
{
    public class CoffeeViewModel : ITypedProductViewModel
    {
        public int Altitude { get; set; }

        public string Country { get; set; }

        public string Farm { get; set; }

        public bool IsDecaf { get; set; }

        public string Processing { get; set; }

        public string Variety { get; set; }

        public static CoffeeViewModel GetViewModel(Coffee coffee)
        {
            return new CoffeeViewModel
            {
                Altitude = coffee.Fields.Altitude,
                Country = coffee.Fields.Country,
                Farm = coffee.Fields.Farm,
                IsDecaf = coffee.Fields.IsDecaf,
                Processing = coffee.Fields.Processing,
                Variety = coffee.Fields.Variety
            };
        }
    }
}


text:
package com.google.ads.googleads.v11.common;

public final class UserListsProto {
  private UserListsProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_SimilarUserListInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_SimilarUserListInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_CrmBasedUserListInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_CrmBasedUserListInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_UserListRuleInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_UserListRuleInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_UserListRuleItemGroupInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_UserListRuleItemGroupInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_UserListRuleItemInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_UserListRuleItemInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_UserListDateRuleItemInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_UserListDateRuleItemInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_UserListNumberRuleItemInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_UserListNumberRuleItemInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_UserListStringRuleItemInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_UserListStringRuleItemInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_CombinedRuleUserListInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_CombinedRuleUserListInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_ExpressionRuleUserListInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_ExpressionRuleUserListInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_FlexibleRuleOperandInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_FlexibleRuleOperandInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_FlexibleRuleUserListInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_FlexibleRuleUserListInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_RuleBasedUserListInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_RuleBasedUserListInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_LogicalUserListInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_LogicalUserListInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_UserListLogicalRuleInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_UserListLogicalRuleInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_LogicalUserListOperandInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_LogicalUserListOperandInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_BasicUserListInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_BasicUserListInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_common_UserListActionInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_common_UserListActionInfo_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n0google/ads/googleads/v11/common/user_l" +
      "ists.proto\022\037google.ads.googleads.v11.com" +
      "mon\032Cgoogle/ads/googleads/v11/enums/cust" +
      "omer_match_upload_key_type.proto\032Egoogle" +
      "/ads/googleads/v11/enums/user_list_combi" +
      "ned_rule_operator.proto\032Cgoogle/ads/goog" +
      "leads/v11/enums/user_list_crm_data_sourc" +
      "e_type.proto\032Fgoogle/ads/googleads/v11/e" +
      "nums/user_list_date_rule_item_operator.p" +
      "roto\032Egoogle/ads/googleads/v11/enums/use" +
      "r_list_flexible_rule_operator.proto\032Dgoo" +
      "gle/ads/googleads/v11/enums/user_list_lo" +
      "gical_rule_operator.proto\032Hgoogle/ads/go" +
      "ogleads/v11/enums/user_list_number_rule_" +
      "item_operator.proto\032Cgoogle/ads/googlead" +
      "s/v11/enums/user_list_prepopulation_stat" +
      "us.proto\0328google/ads/googleads/v11/enums" +
      "/user_list_rule_type.proto\032Hgoogle/ads/g" +
      "oogleads/v11/enums/user_list_string_rule" +
      "_item_operator.proto\"E\n\023SimilarUserListI" +
      "nfo\022\033\n\016seed_user_list\030\002 \001(\tH\000\210\001\001B\021\n\017_see" +
      "d_user_list\"\235\002\n\024CrmBasedUserListInfo\022\023\n\006" +
      "app_id\030\004 \001(\tH\000\210\001\001\022r\n\017upload_key_type\030\002 \001" +
      "(\0162Y.google.ads.googleads.v11.enums.Cust" +
      "omerMatchUploadKeyTypeEnum.CustomerMatch" +
      "UploadKeyType\022q\n\020data_source_type\030\003 \001(\0162" +
      "W.google.ads.googleads.v11.enums.UserLis" +
      "tCrmDataSourceTypeEnum.UserListCrmDataSo" +
      "urceTypeB\t\n\007_app_id\"\302\001\n\020UserListRuleInfo" +
      "\022X\n\trule_type\030\001 \001(\0162E.google.ads.googlea" +
      "ds.v11.enums.UserListRuleTypeEnum.UserLi" +
      "stRuleType\022T\n\020rule_item_groups\030\002 \003(\0132:.g" +
      "oogle.ads.googleads.v11.common.UserListR" +
      "uleItemGroupInfo\"f\n\031UserListRuleItemGrou" +
      "pInfo\022I\n\nrule_items\030\001 \003(\01325.google.ads.g" +
      "oogleads.v11.common.UserListRuleItemInfo" +
      "\"\306\002\n\024UserListRuleItemInfo\022\021\n\004name\030\005 \001(\tH" +
      "\001\210\001\001\022W\n\020number_rule_item\030\002 \001(\0132;.google." +
      "ads.googleads.v11.common.UserListNumberR" +
      "uleItemInfoH\000\022W\n\020string_rule_item\030\003 \001(\0132" +
      ";.google.ads.googleads.v11.common.UserLi" +
      "stStringRuleItemInfoH\000\022S\n\016date_rule_item" +
      "\030\004 \001(\01329.google.ads.googleads.v11.common" +
      ".UserListDateRuleItemInfoH\000B\013\n\trule_item" +
      "B\007\n\005_name\"\331\001\n\030UserListDateRuleItemInfo\022o" +
      "\n\010operator\030\001 \001(\0162].google.ads.googleads." +
      "v11.enums.UserListDateRuleItemOperatorEn" +
      "um.UserListDateRuleItemOperator\022\022\n\005value" +
      "\030\004 \001(\tH\000\210\001\001\022\033\n\016offset_in_days\030\005 \001(\003H\001\210\001\001" +
      "B\010\n\006_valueB\021\n\017_offset_in_days\"\257\001\n\032UserLi" +
      "stNumberRuleItemInfo\022s\n\010operator\030\001 \001(\0162a" +
      ".google.ads.googleads.v11.enums.UserList" +
      "NumberRuleItemOperatorEnum.UserListNumbe" +
      "rRuleItemOperator\022\022\n\005value\030\003 \001(\001H\000\210\001\001B\010\n" +
      "\006_value\"\257\001\n\032UserListStringRuleItemInfo\022s" +
      "\n\010operator\030\001 \001(\0162a.google.ads.googleads." +
      "v11.enums.UserListStringRuleItemOperator" +
      "Enum.UserListStringRuleItemOperator\022\022\n\005v" +
      "alue\030\003 \001(\tH\000\210\001\001B\010\n\006_value\"\243\002\n\030CombinedRu" +
      "leUserListInfo\022G\n\014left_operand\030\001 \001(\01321.g" +
      "oogle.ads.googleads.v11.common.UserListR" +
      "uleInfo\022H\n\rright_operand\030\002 \001(\01321.google." +
      "ads.googleads.v11.common.UserListRuleInf" +
      "o\022t\n\rrule_operator\030\003 \001(\0162].google.ads.go" +
      "ogleads.v11.enums.UserListCombinedRuleOp" +
      "eratorEnum.UserListCombinedRuleOperator\"" +
      "]\n\032ExpressionRuleUserListInfo\022?\n\004rule\030\001 " +
      "\001(\01321.google.ads.googleads.v11.common.Us" +
      "erListRuleInfo\"\226\001\n\027FlexibleRuleOperandIn" +
      "fo\022?\n\004rule\030\001 \001(\01321.google.ads.googleads." +
      "v11.common.UserListRuleInfo\022!\n\024lookback_" +
      "window_days\030\002 \001(\003H\000\210\001\001B\027\n\025_lookback_wind" +
      "ow_days\"\306\002\n\030FlexibleRuleUserListInfo\022~\n\027" +
      "inclusive_rule_operator\030\001 \001(\0162].google.a" +
      "ds.googleads.v11.enums.UserListFlexibleR" +
      "uleOperatorEnum.UserListFlexibleRuleOper" +
      "ator\022T\n\022inclusive_operands\030\002 \003(\01328.googl" +
      "e.ads.googleads.v11.common.FlexibleRuleO" +
      "perandInfo\022T\n\022exclusive_operands\030\003 \003(\01328" +
      ".google.ads.googleads.v11.common.Flexibl" +
      "eRuleOperandInfo\"\306\003\n\025RuleBasedUserListIn" +
      "fo\022y\n\024prepopulation_status\030\001 \001(\0162[.googl" +
      "e.ads.googleads.v11.enums.UserListPrepop" +
      "ulationStatusEnum.UserListPrepopulationS" +
      "tatus\022Z\n\027flexible_rule_user_list\030\005 \001(\01329" +
      ".google.ads.googleads.v11.common.Flexibl" +
      "eRuleUserListInfo\022\\\n\027combined_rule_user_" +
      "list\030\002 \001(\01329.google.ads.googleads.v11.co" +
      "mmon.CombinedRuleUserListInfoH\000\022`\n\031expre" +
      "ssion_rule_user_list\030\004 \001(\0132;.google.ads." +
      "googleads.v11.common.ExpressionRuleUserL" +
      "istInfoH\000B\026\n\024rule_based_user_list\"^\n\023Log" +
      "icalUserListInfo\022G\n\005rules\030\001 \003(\01328.google" +
      ".ads.googleads.v11.common.UserListLogica" +
      "lRuleInfo\"\334\001\n\027UserListLogicalRuleInfo\022m\n" +
      "\010operator\030\001 \001(\0162[.google.ads.googleads.v" +
      "11.enums.UserListLogicalRuleOperatorEnum" +
      ".UserListLogicalRuleOperator\022R\n\rrule_ope" +
      "rands\030\002 \003(\0132;.google.ads.googleads.v11.c" +
      "ommon.LogicalUserListOperandInfo\"B\n\032Logi" +
      "calUserListOperandInfo\022\026\n\tuser_list\030\002 \001(" +
      "\tH\000\210\001\001B\014\n\n_user_list\"Y\n\021BasicUserListInf" +
      "o\022D\n\007actions\030\001 \003(\01323.google.ads.googlead" +
      "s.v11.common.UserListActionInfo\"c\n\022UserL" +
      "istActionInfo\022\033\n\021conversion_action\030\003 \001(\t" +
      "H\000\022\034\n\022remarketing_action\030\004 \001(\tH\000B\022\n\020user" +
      "_list_actionB\356\001\n#com.google.ads.googlead" +
      "s.v11.commonB\016UserListsProtoP\001ZEgoogle.g" +
      "olang.org/genproto/googleapis/ads/google" +
      "ads/v11/common;common\242\002\003GAA\252\002\037Google.Ads" +
      ".GoogleAds.V11.Common\312\002\037Google\\Ads\\Googl" +
      "eAds\\V11\\Common\352\002#Google::Ads::GoogleAds" +
      "::V11::Commonb\006proto3"
    };
    descriptor = com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          com.google.ads.googleads.v11.enums.CustomerMatchUploadKeyTypeProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.UserListCombinedRuleOperatorProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.UserListCrmDataSourceTypeProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.UserListDateRuleItemOperatorProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.UserListFlexibleRuleOperatorProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.UserListLogicalRuleOperatorProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.UserListNumberRuleItemOperatorProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.UserListPrepopulationStatusProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.UserListRuleTypeProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.UserListStringRuleItemOperatorProto.getDescriptor(),
        });
    internal_static_google_ads_googleads_v11_common_SimilarUserListInfo_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_google_ads_googleads_v11_common_SimilarUserListInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_SimilarUserListInfo_descriptor,
        new java.lang.String[] { "SeedUserList", "SeedUserList", });
    internal_static_google_ads_googleads_v11_common_CrmBasedUserListInfo_descriptor =
      getDescriptor().getMessageTypes().get(1);
    internal_static_google_ads_googleads_v11_common_CrmBasedUserListInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_CrmBasedUserListInfo_descriptor,
        new java.lang.String[] { "AppId", "UploadKeyType", "DataSourceType", "AppId", });
    internal_static_google_ads_googleads_v11_common_UserListRuleInfo_descriptor =
      getDescriptor().getMessageTypes().get(2);
    internal_static_google_ads_googleads_v11_common_UserListRuleInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_UserListRuleInfo_descriptor,
        new java.lang.String[] { "RuleType", "RuleItemGroups", });
    internal_static_google_ads_googleads_v11_common_UserListRuleItemGroupInfo_descriptor =
      getDescriptor().getMessageTypes().get(3);
    internal_static_google_ads_googleads_v11_common_UserListRuleItemGroupInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_UserListRuleItemGroupInfo_descriptor,
        new java.lang.String[] { "RuleItems", });
    internal_static_google_ads_googleads_v11_common_UserListRuleItemInfo_descriptor =
      getDescriptor().getMessageTypes().get(4);
    internal_static_google_ads_googleads_v11_common_UserListRuleItemInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_UserListRuleItemInfo_descriptor,
        new java.lang.String[] { "Name", "NumberRuleItem", "StringRuleItem", "DateRuleItem", "RuleItem", "Name", });
    internal_static_google_ads_googleads_v11_common_UserListDateRuleItemInfo_descriptor =
      getDescriptor().getMessageTypes().get(5);
    internal_static_google_ads_googleads_v11_common_UserListDateRuleItemInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_UserListDateRuleItemInfo_descriptor,
        new java.lang.String[] { "Operator", "Value", "OffsetInDays", "Value", "OffsetInDays", });
    internal_static_google_ads_googleads_v11_common_UserListNumberRuleItemInfo_descriptor =
      getDescriptor().getMessageTypes().get(6);
    internal_static_google_ads_googleads_v11_common_UserListNumberRuleItemInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_UserListNumberRuleItemInfo_descriptor,
        new java.lang.String[] { "Operator", "Value", "Value", });
    internal_static_google_ads_googleads_v11_common_UserListStringRuleItemInfo_descriptor =
      getDescriptor().getMessageTypes().get(7);
    internal_static_google_ads_googleads_v11_common_UserListStringRuleItemInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_UserListStringRuleItemInfo_descriptor,
        new java.lang.String[] { "Operator", "Value", "Value", });
    internal_static_google_ads_googleads_v11_common_CombinedRuleUserListInfo_descriptor =
      getDescriptor().getMessageTypes().get(8);
    internal_static_google_ads_googleads_v11_common_CombinedRuleUserListInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_CombinedRuleUserListInfo_descriptor,
        new java.lang.String[] { "LeftOperand", "RightOperand", "RuleOperator", });
    internal_static_google_ads_googleads_v11_common_ExpressionRuleUserListInfo_descriptor =
      getDescriptor().getMessageTypes().get(9);
    internal_static_google_ads_googleads_v11_common_ExpressionRuleUserListInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_ExpressionRuleUserListInfo_descriptor,
        new java.lang.String[] { "Rule", });
    internal_static_google_ads_googleads_v11_common_FlexibleRuleOperandInfo_descriptor =
      getDescriptor().getMessageTypes().get(10);
    internal_static_google_ads_googleads_v11_common_FlexibleRuleOperandInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_FlexibleRuleOperandInfo_descriptor,
        new java.lang.String[] { "Rule", "LookbackWindowDays", "LookbackWindowDays", });
    internal_static_google_ads_googleads_v11_common_FlexibleRuleUserListInfo_descriptor =
      getDescriptor().getMessageTypes().get(11);
    internal_static_google_ads_googleads_v11_common_FlexibleRuleUserListInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_FlexibleRuleUserListInfo_descriptor,
        new java.lang.String[] { "InclusiveRuleOperator", "InclusiveOperands", "ExclusiveOperands", });
    internal_static_google_ads_googleads_v11_common_RuleBasedUserListInfo_descriptor =
      getDescriptor().getMessageTypes().get(12);
    internal_static_google_ads_googleads_v11_common_RuleBasedUserListInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_RuleBasedUserListInfo_descriptor,
        new java.lang.String[] { "PrepopulationStatus", "FlexibleRuleUserList", "CombinedRuleUserList", "ExpressionRuleUserList", "RuleBasedUserList", });
    internal_static_google_ads_googleads_v11_common_LogicalUserListInfo_descriptor =
      getDescriptor().getMessageTypes().get(13);
    internal_static_google_ads_googleads_v11_common_LogicalUserListInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_LogicalUserListInfo_descriptor,
        new java.lang.String[] { "Rules", });
    internal_static_google_ads_googleads_v11_common_UserListLogicalRuleInfo_descriptor =
      getDescriptor().getMessageTypes().get(14);
    internal_static_google_ads_googleads_v11_common_UserListLogicalRuleInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_UserListLogicalRuleInfo_descriptor,
        new java.lang.String[] { "Operator", "RuleOperands", });
    internal_static_google_ads_googleads_v11_common_LogicalUserListOperandInfo_descriptor =
      getDescriptor().getMessageTypes().get(15);
    internal_static_google_ads_googleads_v11_common_LogicalUserListOperandInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_LogicalUserListOperandInfo_descriptor,
        new java.lang.String[] { "UserList", "UserList", });
    internal_static_google_ads_googleads_v11_common_BasicUserListInfo_descriptor =
      getDescriptor().getMessageTypes().get(16);
    internal_static_google_ads_googleads_v11_common_BasicUserListInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_BasicUserListInfo_descriptor,
        new java.lang.String[] { "Actions", });
    internal_static_google_ads_googleads_v11_common_UserListActionInfo_descriptor =
      getDescriptor().getMessageTypes().get(17);
    internal_static_google_ads_googleads_v11_common_UserListActionInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_common_UserListActionInfo_descriptor,
        new java.lang.String[] { "ConversionAction", "RemarketingAction", "UserListAction", });
    com.google.ads.googleads.v11.enums.CustomerMatchUploadKeyTypeProto.getDescriptor();
    com.google.ads.googleads.v11.enums.UserListCombinedRuleOperatorProto.getDescriptor();
    com.google.ads.googleads.v11.enums.UserListCrmDataSourceTypeProto.getDescriptor();
    com.google.ads.googleads.v11.enums.UserListDateRuleItemOperatorProto.getDescriptor();
    com.google.ads.googleads.v11.enums.UserListFlexibleRuleOperatorProto.getDescriptor();
    com.google.ads.googleads.v11.enums.UserListLogicalRuleOperatorProto.getDescriptor();
    com.google.ads.googleads.v11.enums.UserListNumberRuleItemOperatorProto.getDescriptor();
    com.google.ads.googleads.v11.enums.UserListPrepopulationStatusProto.getDescriptor();
    com.google.ads.googleads.v11.enums.UserListRuleTypeProto.getDescriptor();
    com.google.ads.googleads.v11.enums.UserListStringRuleItemOperatorProto.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
import typing

import pika
import pika.exceptions

class RabbitMQ(object):

    def __init__(self, amqp_url: str):
        self.amqp_url = amqp_url
        self.connection = None
        self.channel = None
        self.is_open = False

    def open(self):
        '''
        don't open connection until inside thread!
        '''
        if self.is_open:
            return
        self.connection = pika.BlockingConnection(
            pika.URLParameters(self.amqp_url))
        self.channel = self.connection.channel()
        self.is_open = True

    def bind(self, exchange: str, routing_key: str, queue: str, durable: bool = True):
        self.channel.exchange_declare(
            exchange=exchange, exchange_type='topic', durable=durable)
        self.channel.queue_declare(queue=queue, durable=durable)
        self.channel.queue_bind(queue, exchange, routing_key=routing_key)

    def cancel(self):
        self.channel.cancel()

    def close(self):
        try:
            if self.connection is not None:
                self.connection.close()
        except pika.exceptions.AMQPError:
            pass
        finally:
            self.is_open = False

    def __repr__(self):
        return self.amqp_url

class MQProducer(RabbitMQ):

    def publish(self, exchange: str, routing_key: str, body: str,
                properties: pika.BasicProperties = None, mandatory: bool = True):
        if properties is None:
            properties = pika.BasicProperties(content_type='application/json')
        self.channel.basic_publish(exchange=exchange,
                                   routing_key=routing_key,
                                   body=body,
                                   properties=properties,
                                   mandatory=mandatory)

class MQConsumer(RabbitMQ):

    def open(self, prefetch: int = 200):
        """
        :param prefetch: prefetch count of message
        """
        super(MQConsumer, self).open()
        self.channel.basic_qos(prefetch_count=prefetch)

    def consume(self, queue: str):
        for method_frame, properties, body in self.channel.consume(queue):
            return method_frame, properties, body.decode('utf-8')

    def basic_consume(self, queue: str, on_message_callback: typing.Callable):
        self.channel.basic_consume(queue, on_message_callback)

    def start_consuming(self):
        self.channel.start_consuming()

    def stop_consuming(self):
        self.channel.stop_consuming()

    def ack(self, delivery_tag):
        self.channel.basic_ack(delivery_tag)


text:
package org.apache.calcite.rel.metadata.janino;

public final class GeneratedMetadata_TableReferencesHandler
  implements org.apache.calcite.rel.metadata.BuiltInMetadata.TableReferences.Handler {
  private final Object methodKey0 =
      new org.apache.calcite.rel.metadata.janino.DescriptiveCacheKey("Set Handler.getTableReferences()");
  public final org.apache.calcite.rel.metadata.RelMdTableReferences provider0;
  public GeneratedMetadata_TableReferencesHandler(
      org.apache.calcite.rel.metadata.RelMdTableReferences provider0) {
    this.provider0 = provider0;
  }
  public org.apache.calcite.rel.metadata.MetadataDef getDef() {
    return provider0.getDef();
  }
  public java.util.Set getTableReferences(
      org.apache.calcite.rel.RelNode r,
      org.apache.calcite.rel.metadata.RelMetadataQuery mq) {
    while (r instanceof org.apache.calcite.rel.metadata.DelegatingMetadataRel) {
      r = ((org.apache.calcite.rel.metadata.DelegatingMetadataRel) r).getMetadataDelegateRel();
    }
    final Object key;
    key = methodKey0;
    final Object v = mq.map.get(r, key);
    if (v != null) {
      if (v == org.apache.calcite.rel.metadata.NullSentinel.ACTIVE) {
        throw new org.apache.calcite.rel.metadata.CyclicMetadataException();
      }
      if (v == org.apache.calcite.rel.metadata.NullSentinel.INSTANCE) {
        return null;
      }
      return (java.util.Set) v;
    }
    mq.map.put(r, key,org.apache.calcite.rel.metadata.NullSentinel.ACTIVE);
    try {
      final java.util.Set x = getTableReferences_(r, mq);
      mq.map.put(r, key, org.apache.calcite.rel.metadata.NullSentinel.mask(x));
      return x;
    } catch (java.lang.Exception e) {
      mq.map.row(r).clear();
      throw e;
    }
  }

  private java.util.Set getTableReferences_(
      org.apache.calcite.rel.RelNode r,
      org.apache.calcite.rel.metadata.RelMetadataQuery mq) {
    if (r instanceof org.apache.calcite.plan.volcano.RelSubset) {
      return provider0.getTableReferences((org.apache.calcite.plan.volcano.RelSubset) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.Aggregate) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.Aggregate) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.Calc) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.Calc) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.Exchange) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.Exchange) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.Filter) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.Filter) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.Join) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.Join) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.Project) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.Project) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.Sample) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.Sample) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.SetOp) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.SetOp) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.Sort) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.Sort) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.TableModify) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.TableModify) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.TableScan) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.TableScan) r, mq);
    } else if (r instanceof org.apache.calcite.rel.core.Window) {
      return provider0.getTableReferences((org.apache.calcite.rel.core.Window) r, mq);
    } else if (r instanceof org.apache.calcite.rel.RelNode) {
      return provider0.getTableReferences((org.apache.calcite.rel.RelNode) r, mq);
    } else {
            throw new java.lang.IllegalArgumentException("No handler for method [public abstract java.util.Set org.apache.calcite.rel.metadata.BuiltInMetadata$TableReferences$Handler.getTableReferences(org.apache.calcite.rel.RelNode,org.apache.calcite.rel.metadata.RelMetadataQuery)] applied to argument of type [" + r.getClass() + "]; we recommend you create a catch-all (RelNode) handler");
    }
  }

}