text:
<?php
class Store extends CI_Model
//	This file should be named Store.php (first letter capitalized)
{
	//	Store model for djmblog.com by Dan McKeown http://danmckeown.info -->
	//	copyright 2016 -->
	function add_new_product_supplier($supplierdata)
	{
		if ((isset($supplierdata['suppliers_id'])) && (isset($supplierdata['products_id'])))
		{
			$this->db->insert('products_suppliers', $supplierdata);
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}

	function add_new_supplier($postdata)
	{
		//	the authorization and validation will be handled in the controller
		$this->load->database();

		$this->load->helper('date');
		$newdate = now('America/Los_Angeles');
		$z = date("Y-m-d H:i:s");

		$postdata['created_at'] = $z;
		$postdata['updated_at'] = $z;

		$postdata['created_at_epoch'] = $newdate;	//	this is the backup date mechanism
		$postdata['updated_at_epoch'] = $newdate;

		if (isset($postdata['supplier']))
		{
			$attempt = $this->db->insert('suppliers', $postdata);
			return $attempt;
		}
		else
		{
			return FALSE;
		}
	}

	function add_new_card_provider_process($postdata)
	{
		//	the authorization and validation will be handled in the controller
		$this->load->database();

		$this->load->helper('date');
		$newdate = now('America/Los_Angeles');
		$z = date("Y-m-d H:i:s");

		$postdata['created_at'] = $z;
		$postdata['updated_at'] = $z;

		$postdata['created_at_epoch'] = $newdate;	//	this is the backup date mechanism
		$postdata['updated_at_epoch'] = $newdate;

		if (isset($postdata['name']))
		{
			$attempt = $this->db->insert('card_providers', $postdata);
			return $attempt;
		}
		else
		{
			return FALSE;
		}
	}

	function get_suppliers()
	{
		$this->load->database();
		$q1 = "SELECT * FROM suppliers";

		$query = $this->db->query($q1);

		$allstrains = array();
		$counter = 0;

		foreach ($query->result_array() as $row)
		{
			$temp = array();
			$temp = $row;
		   	$allstrains[$counter] = $temp;
		   	$counter++;
		}
		return $allstrains;
	}

	function get_suppliers_id_via_name($s_name)
	{
		$this->load->database();

		$q1 = "SELECT * FROM suppliers WHERE supplier = ?";
		$query = $this->db->query($q1, array($s_name));

		foreach ($query->result_array() as $row)
		{
			$suppliersID = $row['id'];
		}
		return $suppliersID;
	}

	function add_payment($postdata)
	{
		//	the authorization and validation will be handled in the controller
		$this->load->database();

		$this->load->helper('date');
		$newdate = now('America/Los_Angeles');
		$z = date("Y-m-d H:i:s");

		$postdata['created_at'] = $z;
		$postdata['updated_at'] = $z;

		$postdata['created_at_epoch'] = $newdate;	//	this is the backup date mechanism
		$postdata['updated_at_epoch'] = $newdate;

		unset($postdata['cvv']);	//	the cvv can be checked but not stored

		if ((isset($postdata['card'])) && (isset($postdata['card_providers_id'])) && ((isset($postdata['expiration'])) || (isset($postdata['expires_at']))))
		{
			$attempt = $this->db->insert('card_providers', $postdata);
			return $attempt;
		}
		else
		{
			return FALSE;
		}
	}

	function add_new_product($productdata, $supplierdata)	//	this function is deprecated
	{
		$postdata = $productdata;
		//	the authorization and validation will be handled in the controller
		$this->load->database();

		$this->load->helper('date');
		$newdate = now('America/Los_Angeles');
		$z = date("Y-m-d H:i:s");

		$postdata['created_at'] = $z;
		$postdata['updated_at'] = $z;

		$postdata['created_at_epoch'] = $newdate;	//	this is the backup date mechanism
		$postdata['updated_at_epoch'] = $newdate;

		if (isset($postdata['product']))
		{
			$this->db->insert('products', $postdata);
		}
		else
		{
			return FALSE;
		}

		$products_id = $this->db->insert_id();
		$supplierdata['products_id'] = $products_id;

		if (isset($supplierdata['suppliers_id']))
		{
			$this->db->insert('products_suppliers', $postdata);
			return TRUE;
		}
		else
		{
			return null;
		}
	}

	function get_card_providers()
	{
		$this->load->database();
		$q1 = "SELECT * FROM card_providers";

		$query = $this->db->query($q1);

		$allstrains = array();
		$counter = 0;

		foreach ($query->result_array() as $row)
		{
			$temp = array();
			$temp = $row;
		   	$allstrains[$counter] = $temp;
		   	$counter++;
		}
		return $allstrains;
	}

	function edit_a_product($postdata)
	{
		$this->load->database();
		$this->load->helper('date');
		$newdate = now('America/Los_Angeles');

		$z = date("Y-m-d H:i:s");

		$postdata['updated_at'] = $z;
		$postdata['updated_at_epoch'] = $newdate;

		$p_id = $postdata['id'];
		unset($postdata['id']);

		if (isset($postdata['product'])) {
			$this->db->update('products', $postdata, array('id' => $p_id));
			return TRUE;
		}
		else {
			return FALSE;
		}
	}

	function add_item_to_cart($cartdata)
	{
		$this->load->helper('date');
		$newdate = now('America/Los_Angeles');
		$z = date("Y-m-d H:i:s");

		$postdata = $cartdata;

		$postdata['created_at'] = $z;
		$postdata['updated_at'] = $z;

		$postdata['created_at_epoch'] = $newdate;	//	this is the backup date mechanism
		$postdata['updated_at_epoch'] = $newdate;

		if ((isset($cartdata['users_id'])) && (isset($cartdata['products_id'])))
		{
			$this->load->database();

			$db_array = array($cartdata['users_id'], $cartdata['products_id']);
			$q1 = "SELECT * FROM cart WHERE users_id = ? AND products_id = ?";
			$query = $this->db->query($q1, $db_array);

			foreach ($query->result() as $row)
			{
				$users_id = $row->users_id;
				$quantity = $row->quantity;
				$products_id = $row->products_id;
			}
			if (isset($row))
			{
				//		Eventually users should be able to add more items to their cart but for now 1 at at time
				return FALSE;
			}
			else
			{
				$this->db->insert('cart', $postdata);
				$products_id = $this->db->insert_id();
				return TRUE;
			}
		}
		else
		{
			return null;
		}

		return $products_id;
	}

	function get_tax_rate()
	{
		$this->load->database();
		$q1 = "SELECT * FROM tax_rate ORDER BY created_at DESC LIMIT 1";

		$query = $this->db->query($q1);

		$the_row = $query->row_array();

		return $the_row['rate'];
	}

	function get_payment_methods()
	{
		$this->load->database();
		$q1 = "SELECT * FROM payment_methods ORDER BY created_at DESC";

		$query = $this->db->query($q1);

		return $query;
	}

	function get_user_payment_methods($uid)
	{
		$this->load->database();

		$q1 = "SELECT * FROM payment_methods WHERE users_id = ? ORDER BY created_at DESC";
		$query = $this->db->query($q1, array($uid));

		return $query;
	}

	function processPurchaseItems($cartData, $order, $cash)
	{
		if ($cash['total'] == 0)
		{
			//	populate orders table and get the id from it
			$this->db->insert('orders', $order);
			$orders_id = $this->db->insert_id();

			$this->load->helper('date');
			$newdate = now('America/Los_Angeles');
			$z = date("Y-m-d H:i:s");

			$this->load->helper('user');
			$uid = get_user_id_via_current_login();

			foreach ($cartData as $value)
			{
				$sale = array();
				$sale['orders_id'] = $orders_id;
				$sale['users_id'] = $uid;
				$sale['products_id'] = $value['products_id'];
				$sale_products_id = $value['products_id'];
				$sale['price'] = $value['price'];
				$sale['quantity'] = $value['quantity'];

				$sale['created_at'] = $z;
				$sale['created_at_epoch'] = $newdate;	//	this is the backup date mechanism

				$this->db->insert('sales', $sale);

				//		now this item should be removed from the cart
				$killArray = array('users_id' => $uid, 'products_id' => $sale_products_id);

				$this->db->where($killArray);

				$this->db->delete('cart');
			}
			return TRUE;
		}
		elseif ($cash['total'] > 0.01)
		{
			$this->load->helper('date');
			$newdate = now('America/Los_Angeles');
			$z = date("Y-m-d H:i:s");

			$this->load->helper('user');
			$uid = get_user_id_via_current_login();

			//	populate orders table and get the id from it
			$this->db->insert('orders', $order);
			$orders_id = $this->db->insert_id();

			//	already done: run the payment info; now make a record in the users_payments table
			$subtotal = $cash['subTotal'];
			$tax_rate = $cash['tax_rate'];
			$total = $cash['total'];
			$token = $_POST['stripeToken'];

			$user_payment = array(
	        	'users_id' => $uid,
	       		'subtotal' => $subtotal,
	       		'total' => $total,
	       		'tax_rate' => $tax_rate,
	       		'created_at' => $z,
	       		'hash' => $token,
	       		'orders_id' => $orders_id
				);

			$this->db->insert('users_payments', $user_payment);

			//	use the orders table entry id as orders_id and make a sales table item from each item purchased
			foreach ($cartData as $value)
			{
				$sale = array();
				$sale['orders_id'] = $orders_id;
				$sale['users_id'] = $uid;
				$sale['products_id'] = $value['products_id'];
				$sale_products_id = $value['products_id'];
				$sale['price'] = $value['price'];
				$sale['quantity'] = $value['quantity'];

				$sale['created_at'] = $z;
				$sale['created_at_epoch'] = $newdate;	//	this is the backup date mechanism

				$this->db->insert('sales', $sale);

				//		now this item should be removed from the cart
				$killArray = array('users_id' => $uid, 'products_id' => $sale_products_id);

				$this->db->where($killArray);
				$this->db->delete('cart');
			}
			return TRUE;
		}
		else
		{
			//	no reason to run negative or weird-decimal transactons esp. since the app rounds in the checkout flow
			return null;
		}
	}

	function check_item_for_cart($products_id, $uid)
	{
		$this->load->database();

		$q1 = "SELECT * FROM sales WHERE users_id = ? AND products_id = ? ORDER BY created_at DESC LIMIT 1";
		$query = $this->db->query($q1, array($uid, $products_id));

		$the_row = $query->row_array();

		if ($the_row != null)
		{
			// $q2 = "SELECT * FROM products WHERE id='" . $products_id . "' ORDER BY created_at DESC LIMIT 1";
			// $query2 = $this->db->query($q2);
			$q2 = "SELECT * FROM products WHERE id = ? ORDER BY created_at DESC LIMIT 1";
			$query2 = $this->db->query($q2, array($products_id));
			$next_row = $query2->row_array();
			if ($next_row['digital_bool'] == 'TRUE')
			{
				return TRUE;
			}
			else
			{
				return FALSE; 	// because it is a physical good
			}
		}
		else
		{
			return FALSE;
		}
	}

	function get_a_product_($posts_id)
	{
		$this->load->database();
		$q1 = "SELECT * FROM products WHERE id = ?";
		$query = $this->db->query($q1, array($posts_id));
		return $query;
	}

	function get_user_purchase_list($uid, $posts_id)
	{
		$this->load->database();
		$q10 = "SELECT * FROM sales INNER JOIN products ON sales.products_id=products.id WHERE sales.users_id = ? AND sales.products_id = ?";
		$query0 = $this->db->query($q10, array($uid, $posts_id));
		return $query0;
	}

	function get_all_products_desc()
	{
		$this->load->database();
		$q0 = "SELECT * FROM products ORDER BY id DESC";
		$query0 = $this->db->query($q0);
		return $query0;
	}

	function get_all_products_updated_desc()
	{
		$this->load->database();
		$q0 = "SELECT * FROM products ORDER BY updated_at DESC LIMIT 75";
		$query0 = $this->db->query($q0);
		return $query0;
	}

	function get_cart_of_user($uid)
	{
		$this->load->database();
		$q01 = "SELECT * FROM cart LEFT JOIN products on cart.products_id=products.id WHERE cart.users_id = ?";
		$query01 = $this->db->query($q01, array($uid));
		return $query01;
	}

	function get_a_certain_product($products_id)
	{
		$this->load->database();
		$q2 = "SELECT * FROM products WHERE id = ?";
		$query02 = $this->db->query($q2, array($products_id));
		return $query02;
	}

	function get_cart_data($uid)
	{
		$this->load->database();
		$q01 = "SELECT * FROM cart LEFT JOIN products on cart.products_id=products.id WHERE cart.users_id = ?";
		$query01 = $this->db->query($q01, array($uid));
		return $query01;
	}

	function get_checkout_page_cart_data($uid)	//	same as get_cart_data so should be deprecated
	{
		$this->load->database();
		$q01 = "SELECT * FROM cart LEFT JOIN products on cart.products_id=products.id WHERE cart.users_id = ?";
		$query01 = $this->db->query($q01, array($uid));
		return $query01;
	}

	function get_the_sales_data($uid)
	{
		$this->load->database();
		$q01 = "SELECT * FROM sales LEFT JOIN products on sales.products_id=products.id WHERE sales.users_id = ? ORDER BY sales.id DESC";
		$query01 = $this->db->query($q01, array($uid));
		return $query01;
	}

}


text: DEV: PORT=8000 npm start

redpajama_set_name: RedPajamaGithub


text:
import transformTagsIntoObject from '../transformTagsIntoObject'

describe('transformTagsIntoObject', () => {
  it('should return ignore with description to true', () => {
    expect(transformTagsIntoObject([{ title: 'ignore', content: true }])).toMatchObject({
      ignore: [{ title: 'ignore', description: true }],
    })
  })
})


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Kalmusia schizostoma Hazsl.

### Remarks
null


text:
require 'palaver'

dialog_factory = Palaver::DialogFactory.new

answers = dialog_factory.form {
  text "Simple-entry foos and their texts"
  height 10
  form_height 5
  simple_display_width 30
  simple_text_length 200
  simple_entry :first, "First foo", "Default text for first foo"
  simple_entry :second, "Second foo", "Default text for second foo"
  simple_entry :third, "Third foo", "Default text for third foo"
}.show

answers.keys.each do |k|
  puts "#{k}: #{answers[k]}"
end


text:
Painterro contributors
============================================

* **[Jesfery](https://github.com/Jesfery)**

  * defaultTool param

* **[Ivan Borshchov](https://github.com/ivictbor)**
  * maintainer


text:
#include <string.h>

#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
#include <fontconfig/fontconfig.h>

#include "platform/CCFileUtils.h"
#include "platform/CCPlatformMacros.h"
#define __CC_PLATFORM_IMAGE_CPP__
#include "platform/CCImageCommon_cpp.h"
#include "platform/CCImage.h"
#include "platform/linux/CCApplication.h"

#include "ft2build.h"
#include "CCStdC.h"

#include FT_FREETYPE_H

using namespace std;

// as FcFontMatch is quite an expensive call, cache the results of getFontFile
static std::map<std::string, std::string> fontCache;

struct LineBreakGlyph {
	FT_UInt glyphIndex;
	int paintPosition;
	int glyphWidth;

	int bearingX;
	int kerning;
	int horizAdvance;
};

struct LineBreakLine {
	LineBreakLine() : lineWidth(0) {}

	std::vector<LineBreakGlyph> glyphs;
	int lineWidth;

	void reset() {
		glyphs.clear();
		lineWidth = 0;
	}

	void calculateWidth() {
		lineWidth = 0;
		if ( glyphs.empty() == false ) {
			lineWidth = glyphs.at(glyphs.size() - 1).paintPosition + glyphs.at(glyphs.size() - 1).glyphWidth;
		}
	}
};

NS_CC_BEGIN

class BitmapDC
{
public:
	BitmapDC() {
		libError = FT_Init_FreeType( &library );
		FcInit();
		_data = NULL;
		reset();
	}

	~BitmapDC() {
		FT_Done_FreeType(library);
		FcFini();
		//data will be deleted by Image
//		if (_data) {
//			delete _data;
//		}
        reset();
	}

	void reset() {
		iMaxLineWidth = 0;
		iMaxLineHeight = 0;
		textLines.clear();
	}

    int utf8(char **p)
    {
        if ((**p & 0x80) == 0x00)
        {
            int a = *((*p)++);

            return a;
        }
        if ((**p & 0xE0) == 0xC0)
        {
            int a = *((*p)++) & 0x1F;
            int b = *((*p)++) & 0x3F;

            return (a << 6) | b;
        }
        if ((**p & 0xF0) == 0xE0)
        {
            int a = *((*p)++) & 0x0F;
            int b = *((*p)++) & 0x3F;
            int c = *((*p)++) & 0x3F;

            return (a << 12) | (b << 6) | c;
        }
        if ((**p & 0xF8) == 0xF0)
        {
            int a = *((*p)++) & 0x07;
            int b = *((*p)++) & 0x3F;
            int c = *((*p)++) & 0x3F;
            int d = *((*p)++) & 0x3F;

            return (a << 18) | (b << 12) | (c << 8) | d;
        }
        return 0;
    }

    bool isBreakPoint(FT_UInt currentCharacter, FT_UInt previousCharacter) {
    	if ( previousCharacter == '-' || previousCharacter == '/' || previousCharacter == '\\' ) {
    	   	// we can insert a line break after one of these characters
    	    return true;
    	}
    	return false;
    }

	bool divideString(FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight) {
		const char* pText = sText;
		textLines.clear();
		iMaxLineWidth = 0;

		FT_UInt unicode;
		FT_UInt prevCharacter = 0;
		FT_UInt glyphIndex = 0;
		FT_UInt prevGlyphIndex = 0;
		FT_Vector delta;
		LineBreakLine currentLine;

		int currentPaintPosition = 0;
		int lastBreakIndex = -1;
		bool hasKerning = FT_HAS_KERNING( face );
        while ((unicode=utf8((char**)&pText))) {
            if (unicode == '\n') {
				currentLine.calculateWidth();
				iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth);
				textLines.push_back(currentLine);
				currentLine.reset();
				prevGlyphIndex = 0;
				prevCharacter = 0;
				lastBreakIndex = -1;
				currentPaintPosition = 0;
				continue;
			}

            if ( isBreakPoint(unicode, prevCharacter) ) {
            	lastBreakIndex = currentLine.glyphs.size() - 1;
            }

			glyphIndex = FT_Get_Char_Index(face, unicode);
			if (FT_Load_Glyph(face, glyphIndex, FT_LOAD_DEFAULT)) {
				return false;
			}

			if (isspace(unicode)) {
				currentPaintPosition += face->glyph->metrics.horiAdvance >> 6;
				prevGlyphIndex = glyphIndex;
				prevCharacter = unicode;
				lastBreakIndex = currentLine.glyphs.size();
				continue;
			}

			LineBreakGlyph glyph;
			glyph.glyphIndex = glyphIndex;
			glyph.glyphWidth = face->glyph->metrics.width >> 6;
			glyph.bearingX = face->glyph->metrics.horiBearingX >> 6;
			glyph.horizAdvance = face->glyph->metrics.horiAdvance >> 6;
			glyph.kerning = 0;

			if (prevGlyphIndex != 0 && hasKerning) {
				FT_Get_Kerning(face, prevGlyphIndex, glyphIndex, FT_KERNING_DEFAULT, &delta);
				glyph.kerning = delta.x >> 6;
			}

			if (iMaxWidth > 0 && currentPaintPosition + glyph.bearingX + glyph.kerning + glyph.glyphWidth > iMaxWidth) {

				int glyphCount = currentLine.glyphs.size();
				if ( lastBreakIndex >= 0 && lastBreakIndex < glyphCount && currentPaintPosition + glyph.bearingX + glyph.kerning + glyph.glyphWidth - currentLine.glyphs.at(lastBreakIndex).paintPosition < iMaxWidth ) {
					// we insert a line break at our last break opportunity
					std::vector<LineBreakGlyph> tempGlyphs;
					std::vector<LineBreakGlyph>::iterator it = currentLine.glyphs.begin();
					std::advance(it, lastBreakIndex);
					tempGlyphs.insert(tempGlyphs.begin(), it, currentLine.glyphs.end());
					currentLine.glyphs.erase(it, currentLine.glyphs.end());
					currentLine.calculateWidth();
					iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth);
					textLines.push_back(currentLine);
					currentLine.reset();
					currentPaintPosition = 0;
					for ( it = tempGlyphs.begin(); it != tempGlyphs.end(); it++ ) {
						if ( currentLine.glyphs.empty() ) {
							currentPaintPosition = -(*it).bearingX;
							(*it).kerning = 0;
						}
						(*it).paintPosition = currentPaintPosition + (*it).bearingX + (*it).kerning;
						currentLine.glyphs.push_back((*it));
						currentPaintPosition += (*it).kerning + (*it).horizAdvance;
					}
				} else {
					// the current word is too big to fit into one line, insert line break right here
					currentPaintPosition = 0;
					glyph.kerning = 0;
					currentLine.calculateWidth();
					iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth);
					textLines.push_back(currentLine);
					currentLine.reset();
				}

				prevGlyphIndex = 0;
				prevCharacter = 0;
				lastBreakIndex = -1;
			} else {
				prevGlyphIndex = glyphIndex;
				prevCharacter = unicode;
			}

			if ( currentLine.glyphs.empty() ) {
				currentPaintPosition = -glyph.bearingX;
			}
			glyph.paintPosition = currentPaintPosition + glyph.bearingX + glyph.kerning;
			currentLine.glyphs.push_back(glyph);
			currentPaintPosition += glyph.kerning + glyph.horizAdvance;
		}

		if ( currentLine.glyphs.empty() == false ) {
			currentLine.calculateWidth();
			iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth);
			textLines.push_back(currentLine);
		}
		return true;
	}

	/**
	 * compute the start pos of every line
	 */
	int computeLineStart(FT_Face face, Image::TextAlign eAlignMask, int line) {
				int lineWidth = textLines.at(line).lineWidth;
		if (eAlignMask == Image::TextAlign::CENTER || eAlignMask == Image::TextAlign::TOP || eAlignMask == Image::TextAlign::BOTTOM) {
			return (iMaxLineWidth - lineWidth) / 2;
		} else if (eAlignMask == Image::TextAlign::RIGHT || eAlignMask == Image::TextAlign::TOP_RIGHT || eAlignMask == Image::TextAlign::BOTTOM_RIGHT) {
			return (iMaxLineWidth - lineWidth);
		}

		// left or other situation
		return 0;
	}

	int computeLineStartY( FT_Face face, Image::TextAlign eAlignMask, int txtHeight, int borderHeight ){
		int baseLinePos = ceilf(FT_MulFix( face->bbox.yMax, face->size->metrics.y_scale )/64.0f);
		if (eAlignMask == Image::TextAlign::CENTER || eAlignMask == Image::TextAlign::LEFT || eAlignMask == Image::TextAlign::RIGHT) {
			//vertical center
			return (borderHeight - txtHeight) / 2 + baseLinePos;
		} else if (eAlignMask == Image::TextAlign::BOTTOM_RIGHT || eAlignMask == Image::TextAlign::BOTTOM || eAlignMask == Image::TextAlign::BOTTOM_LEFT) {
			//vertical bottom
			return borderHeight - txtHeight + baseLinePos;
		}

		// top alignment
		return baseLinePos;
	}

    std::string getFontFile(const char* family_name) {
    	std::string fontPath = family_name;

    	std::map<std::string, std::string>::iterator it = fontCache.find(family_name);
    	if ( it != fontCache.end() ) {
    		return it->second;
    	}

    	// check if the parameter is a font file shipped with the application
    	std::string lowerCasePath = fontPath;
    	std::transform(lowerCasePath.begin(), lowerCasePath.end(), lowerCasePath.begin(), ::tolower);
    	if ( lowerCasePath.find(".ttf") != std::string::npos ) {
    		fontPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(fontPath.c_str());

    		FILE *f = fopen(fontPath.c_str(), "r");
    		if ( f ) {
    			fclose(f);
    			fontCache.insert(std::pair<std::string, std::string>(family_name, fontPath));
    			return fontPath;
    		}
    	}

    	// use fontconfig to match the parameter against the fonts installed on the system
    	FcPattern *pattern = FcPatternBuild (0, FC_FAMILY, FcTypeString, family_name, (char *) 0);
    	FcConfigSubstitute(0, pattern, FcMatchPattern);
    	FcDefaultSubstitute(pattern);

    	FcResult result;
    	FcPattern *font = FcFontMatch(0, pattern, &result);
    	if ( font ) {
    		FcChar8 *s = NULL;
    		if ( FcPatternGetString(font, FC_FILE, 0, &s) == FcResultMatch ) {
    			fontPath = (const char*)s;

    			FcPatternDestroy(font);
    			FcPatternDestroy(pattern);

    			fontCache.insert(std::pair<std::string, std::string>(family_name, fontPath));
    			return fontPath;
    		}
    		FcPatternDestroy(font);
    	}
    	FcPatternDestroy(pattern);

    	return family_name;
    }

	bool getBitmap(const char *text, int nWidth, int nHeight, Image::TextAlign eAlignMask, const char * pFontName, float fontSize) {
		if (libError) {
			return false;
		}

		FT_Face face;
		std::string fontfile = getFontFile(pFontName);
		if ( FT_New_Face(library, fontfile.c_str(), 0, &face) ) {
			//no valid font found use default
			if ( FT_New_Face(library, "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 0, &face) ) {
				return false;
			}
		}

		//select utf8 charmap
		if ( FT_Select_Charmap(face, FT_ENCODING_UNICODE) ) {
			FT_Done_Face(face);
			return false;
		}

		if ( FT_Set_Pixel_Sizes(face, fontSize, fontSize) ) {
			FT_Done_Face(face);
			return false;
		}

		if ( divideString(face, text, nWidth, nHeight) == false ) {
			FT_Done_Face(face);
			return false;
		}

		//compute the final line width
		iMaxLineWidth = MAX(iMaxLineWidth, nWidth);

		//compute the final line height
		iMaxLineHeight = ceilf(FT_MulFix( face->bbox.yMax - face->bbox.yMin, face->size->metrics.y_scale )/64.0f);
		int lineHeight = face->size->metrics.height>>6;
		if ( textLines.size() > 0 ) {
			iMaxLineHeight += (lineHeight * (textLines.size() -1));
		}
		int txtHeight = iMaxLineHeight;
		iMaxLineHeight = MAX(iMaxLineHeight, nHeight);

		_data = new unsigned char[iMaxLineWidth * iMaxLineHeight * 4];
		memset(_data,0, iMaxLineWidth * iMaxLineHeight*4);

		int iCurYCursor = computeLineStartY(face, eAlignMask, txtHeight, iMaxLineHeight);

		int lineCount = textLines.size();
		for (int line = 0; line < lineCount; line++) {
			int iCurXCursor = computeLineStart(face, eAlignMask, line);

			int glyphCount = textLines.at(line).glyphs.size();
			for (int i = 0; i < glyphCount; i++) {
				LineBreakGlyph glyph = textLines.at(line).glyphs.at(i);

				if (FT_Load_Glyph(face, glyph.glyphIndex, FT_LOAD_RENDER)) {
					continue;
				}

				FT_Bitmap& bitmap = face->glyph->bitmap;
				int yoffset = iCurYCursor - (face->glyph->metrics.horiBearingY >> 6);
				int xoffset = iCurXCursor + glyph.paintPosition;

				for (int y = 0; y < bitmap.rows; ++y) {
                    int iY = yoffset + y;
                    if (iY>=iMaxLineHeight) {
                        //exceed the height truncate
                        break;
                    }
                    iY *= iMaxLineWidth;

                    int bitmap_y = y * bitmap.width;

					for (int x = 0; x < bitmap.width; ++x) {
						unsigned char cTemp = bitmap.buffer[bitmap_y + x];
						if (cTemp == 0) {
							continue;
						}

						int iX = xoffset + x;

						int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp;
						*(int*) &_data[(iY + iX) * 4 + 0] = iTemp;
					}
				}
			}
			// step to next line
			iCurYCursor += lineHeight;
		}

		//  free face
		FT_Done_Face(face);
		return true;
	}

public:
	FT_Library library;

	unsigned char *_data;
	int libError;
	std::vector<LineBreakLine> textLines;
	int iMaxLineWidth;
	int iMaxLineHeight;
};

static BitmapDC& sharedBitmapDC()
{
	static BitmapDC s_BmpDC;
	return s_BmpDC;
}

bool Image::initWithString(
		const char * pText,
		int nWidth/* = 0*/,
		int nHeight/* = 0*/,
		TextAlign eAlignMask/* = kAlignCenter*/,
		const char * pFontName/* = nil*/,
		int nSize/* = 0*/)
{
	bool bRet = false;
	do
	{
		CC_BREAK_IF(! pText);

		BitmapDC &dc = sharedBitmapDC();

		//const char* pFullFontName = FileUtils::getInstance()->fullPathFromRelativePath(pFontName);

		CC_BREAK_IF(! dc.getBitmap(pText, nWidth, nHeight, eAlignMask, pFontName, nSize));

		// assign the dc._data to _data in order to save time
		_data = dc._data;
		CC_BREAK_IF(! _data);

		_width = (short)dc.iMaxLineWidth;
		_height = (short)dc.iMaxLineHeight;
        _renderFormat = Texture2D::PixelFormat::RGBA8888;
		_preMulti = true;

		bRet = true;

		dc.reset();
	}while (0);

	//do nothing
	return bRet;
}

NS_CC_END


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cucumber-blueprint</artifactId>
        <groupId>cucumber-blueprint</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>pom</packaging>

    <artifactId>cucumber-blueprint-jvm-parent</artifactId>

    <modules>
        <module>cucumber-blueprint-jvm</module>
        <module>cucumber-blueprint-jvm-example</module>
    </modules>

</project>


text:
// *****************************************************************************
//
//  © Component Factory Pty Ltd 2012. All rights reserved.
//	The software and associated documentation supplied hereunder are the
//  proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy,
//  Seaford, Vic 3198, Australia and are supplied subject to licence terms.
//
//  Version 4.4.1.0 	www.ComponentFactory.com
// *****************************************************************************

using System;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;

namespace ComponentFactory.Krypton.Navigator
{
	/// <summary>
	/// Details providing a KryptonContextMenu instance.
	/// </summary>
    public class KryptonContextMenuEventArgs : KryptonPageEventArgs
	{
		#region Instance Fields
        private KryptonContextMenu _contextMenu;
		#endregion

		#region Identity
		/// <summary>
        /// Initialize a new instance of the KryptonContextMenuEventArgs class.
		/// </summary>
		/// <param name="page">Page effected by event.</param>
		/// <param name="index">Index of page in the owning collection.</param>
        /// <param name="contextMenu">Prepopulated context menu ready for display.</param>
        public KryptonContextMenuEventArgs(KryptonPage page,
                                           int index,
                                           KryptonContextMenu contextMenu)
			: base(page, index)
		{
            _contextMenu = contextMenu;
		}
		#endregion

        #region KryptonContextMenu
        /// <summary>
        /// Gets access to the KryptonContextMenu that is to be shown.
        /// </summary>
        public KryptonContextMenu KryptonContextMenu
        {
            get { return _contextMenu; }
        }
        #endregion
    }
}


text:
/* eslint-disable */
const { getUserMovies } = require('../../models/services/movie');
const ssr = require('../../build/server.js').default;
const movieTransformer = require('../../transformers/movieTransformer');

const get = (req, res) => {
    return res.send(ssr.renderSkeleton());

    getUserMovies(req.user.id).then((movies) => {
        res.send(ssr.render({
            dashboard: {
                library: movieTransformer.transformMany({ movies }).payload,
                isLoaded: true,
            },
        }));
    });
};

module.exports = {
    get,
};


text:
class AddUserTokenToUsers < ActiveRecord::Migration
  def change
  	add_column :users, :user_token, :string
  	add_index  :users, :user_token
  end
end


text:
/*
 */
package com.compomics.pride_asa_pipeline.core.service;

import com.compomics.pride_asa_pipeline.core.logic.modification.ModificationMarshaller;
import com.compomics.pride_asa_pipeline.model.Modification;
import com.compomics.pride_asa_pipeline.core.model.ModificationHolder;
import com.compomics.pride_asa_pipeline.core.util.ResourceUtils;
import java.util.Set;
import static org.junit.Assert.*;
import org.jdom2.JDOMException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 *
 * @author Niels Hulstaert Hulstaert
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:springXMLConfig.xml")
public class ModificationServiceTest {

    @Autowired
    private ModificationMarshaller modificationMarshaller;
    @Autowired
    private DbModificationService dbModificationService;

    /**
     * Test the case where the PRIDE modifications are not conflicting.
     *
     * @throws JDOMException
     */
    @Test
    public void testFilterModifications_1() throws JDOMException {
        Resource modificationsResource = ResourceUtils.getResourceByRelativePath("resources/pride_asap_modifications.xml");
        Resource prideModificationsResource = ResourceUtils.getResourceByRelativePath("conflicting_pride_asap_modifications_1.xml");
        Set<Modification> modifications = modificationMarshaller.unmarshall(modificationsResource);
        Set<Modification> prideModifications = modificationMarshaller.unmarshall(prideModificationsResource);

        //add modifications to to ModificationHolder
        ModificationHolder modificationHolder = new ModificationHolder();
        modificationHolder.addModifications(modifications);

        Set<Modification> conflictingModifications = dbModificationService.filterModifications(modificationHolder, prideModifications);

        //none of the modifications should conflict
        assertTrue(conflictingModifications.isEmpty());
    }

    /**
     * Test the case where the PRIDE modifications are conflicting with the
     * pipeline modifications.
     *
     * @throws JDOMException
     */
    @Test
    public void testFilterModifications_2() throws JDOMException {
        Resource modificationsResource = ResourceUtils.getResourceByRelativePath("resources/pride_asap_modifications.xml");
        Resource prideModificationsResource = ResourceUtils.getResourceByRelativePath("conflicting_pride_asap_modifications_2.xml");
        Set<Modification> modifications = modificationMarshaller.unmarshall(modificationsResource);
        Set<Modification> prideModifications = modificationMarshaller.unmarshall(prideModificationsResource);

        //add modifications to to ModificationHolder
        ModificationHolder modificationHolder = new ModificationHolder();
        modificationHolder.addModifications(modifications);

        Set<Modification> conflictingModifications = dbModificationService.filterModifications(modificationHolder, prideModifications);

        //2 of the 3 PRIDE modifications should conflict
        assertEquals(2, conflictingModifications.size());
    }

    /**
     * Test the case where the PRIDE modifications are conflicting with
     * themselves. Only one of the conflicting modifications should be kept.
     *
     * @throws JDOMException
     */
    @Test
    public void testFilterModifications_3() throws JDOMException {
        Resource modificationsResource = ResourceUtils.getResourceByRelativePath("resources/pride_asap_modifications.xml");
        Resource prideModificationsResource = ResourceUtils.getResourceByRelativePath("conflicting_pride_asap_modifications_3.xml");
        Set<Modification> modifications = modificationMarshaller.unmarshall(modificationsResource);
        Set<Modification> prideModifications = modificationMarshaller.unmarshall(prideModificationsResource);

        //add modifications to to ModificationHolder
        ModificationHolder modificationHolder = new ModificationHolder();
        modificationHolder.addModifications(modifications);

        Set<Modification> conflictingModifications = dbModificationService.filterModifications(modificationHolder, prideModifications);

        //3 of the 5 PRIDE modifications should conflict
        assertEquals(3, conflictingModifications.size());
    }
}


text:
#include "webrtc/audio/audio_receive_stream.h"

#include <string>
#include <utility>

#include "webrtc/api/call/audio_sink.h"
#include "webrtc/audio/audio_send_stream.h"
#include "webrtc/audio/audio_state.h"
#include "webrtc/audio/conversion.h"
#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
#include "webrtc/modules/rtp_rtcp/include/rtp_rtcp.h"
#include "webrtc/voice_engine/channel_proxy.h"
#include "webrtc/voice_engine/include/voe_base.h"
#include "webrtc/voice_engine/voice_engine_impl.h"

namespace webrtc {

std::string AudioReceiveStream::Config::Rtp::ToString() const {
  std::stringstream ss;
  ss << "{remote_ssrc: " << remote_ssrc;
  ss << ", local_ssrc: " << local_ssrc;
  ss << ", transport_cc: " << (transport_cc ? "on" : "off");
  ss << ", nack: " << nack.ToString();
  ss << ", extensions: [";
  for (size_t i = 0; i < extensions.size(); ++i) {
    ss << extensions[i].ToString();
    if (i != extensions.size() - 1) {
      ss << ", ";
    }
  }
  ss << ']';
  ss << '}';
  return ss.str();
}

std::string AudioReceiveStream::Config::ToString() const {
  std::stringstream ss;
  ss << "{rtp: " << rtp.ToString();
  ss << ", rtcp_send_transport: "
     << (rtcp_send_transport ? "(Transport)" : "null");
  ss << ", voe_channel_id: " << voe_channel_id;
  if (!sync_group.empty()) {
    ss << ", sync_group: " << sync_group;
  }
  ss << '}';
  return ss.str();
}

namespace internal {
AudioReceiveStream::AudioReceiveStream(
    PacketRouter* packet_router,
    const webrtc::AudioReceiveStream::Config& config,
    const rtc::scoped_refptr<webrtc::AudioState>& audio_state,
    webrtc::RtcEventLog* event_log)
    : config_(config),
      audio_state_(audio_state) {
  LOG(LS_INFO) << "AudioReceiveStream: " << config_.ToString();
  RTC_DCHECK_NE(config_.voe_channel_id, -1);
  RTC_DCHECK(audio_state_.get());
  RTC_DCHECK(packet_router);

  module_process_thread_checker_.DetachFromThread();

  VoiceEngineImpl* voe_impl = static_cast<VoiceEngineImpl*>(voice_engine());
  channel_proxy_ = voe_impl->GetChannelProxy(config_.voe_channel_id);
  channel_proxy_->SetRtcEventLog(event_log);
  channel_proxy_->SetLocalSSRC(config.rtp.local_ssrc);
  // TODO(solenberg): Config NACK history window (which is a packet count),
  // using the actual packet size for the configured codec.
  channel_proxy_->SetNACKStatus(config_.rtp.nack.rtp_history_ms != 0,
                                config_.rtp.nack.rtp_history_ms / 20);

  // TODO(ossu): This is where we'd like to set the decoder factory to
  // use. However, since it needs to be included when constructing Channel, we
  // cannot do that until we're able to move Channel ownership into the
  // Audio{Send,Receive}Streams.  The best we can do is check that we're not
  // trying to use two different factories using the different interfaces.
  RTC_CHECK(config.decoder_factory);
  RTC_CHECK_EQ(config.decoder_factory,
               channel_proxy_->GetAudioDecoderFactory());

  channel_proxy_->RegisterExternalTransport(config.rtcp_send_transport);
  channel_proxy_->SetReceiveCodecs(config.decoder_map);

  for (const auto& extension : config.rtp.extensions) {
    if (extension.uri == RtpExtension::kAudioLevelUri) {
      channel_proxy_->SetReceiveAudioLevelIndicationStatus(true, extension.id);
    } else if (extension.uri == RtpExtension::kTransportSequenceNumberUri) {
      channel_proxy_->EnableReceiveTransportSequenceNumber(extension.id);
    } else {
      RTC_NOTREACHED() << "Unsupported RTP extension.";
    }
  }
  // Configure bandwidth estimation.
  channel_proxy_->RegisterReceiverCongestionControlObjects(packet_router);
}

AudioReceiveStream::~AudioReceiveStream() {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  LOG(LS_INFO) << "~AudioReceiveStream: " << config_.ToString();
  if (playing_) {
    Stop();
  }
  channel_proxy_->DisassociateSendChannel();
  channel_proxy_->DeRegisterExternalTransport();
  channel_proxy_->ResetReceiverCongestionControlObjects();
  channel_proxy_->SetRtcEventLog(nullptr);
}

void AudioReceiveStream::Start() {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  if (playing_) {
    return;
  }

  int error = SetVoiceEnginePlayout(true);
  if (error != 0) {
    LOG(LS_ERROR) << "AudioReceiveStream::Start failed with error: " << error;
    return;
  }

  if (!audio_state()->mixer()->AddSource(this)) {
    LOG(LS_ERROR) << "Failed to add source to mixer.";
    SetVoiceEnginePlayout(false);
    return;
  }

  playing_ = true;
}

void AudioReceiveStream::Stop() {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  if (!playing_) {
    return;
  }
  playing_ = false;

  audio_state()->mixer()->RemoveSource(this);
  SetVoiceEnginePlayout(false);
}

webrtc::AudioReceiveStream::Stats AudioReceiveStream::GetStats() const {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  webrtc::AudioReceiveStream::Stats stats;
  stats.remote_ssrc = config_.rtp.remote_ssrc;

  webrtc::CallStatistics call_stats = channel_proxy_->GetRTCPStatistics();
  // TODO(solenberg): Don't return here if we can't get the codec - return the
  //                  stats we *can* get.
  webrtc::CodecInst codec_inst = {0};
  if (!channel_proxy_->GetRecCodec(&codec_inst)) {
    return stats;
  }

  stats.bytes_rcvd = call_stats.bytesReceived;
  stats.packets_rcvd = call_stats.packetsReceived;
  stats.packets_lost = call_stats.cumulativeLost;
  stats.fraction_lost = Q8ToFloat(call_stats.fractionLost);
  stats.capture_start_ntp_time_ms = call_stats.capture_start_ntp_time_ms_;
  if (codec_inst.pltype != -1) {
    stats.codec_name = codec_inst.plname;
    stats.codec_payload_type = rtc::Optional<int>(codec_inst.pltype);
  }
  stats.ext_seqnum = call_stats.extendedMax;
  if (codec_inst.plfreq / 1000 > 0) {
    stats.jitter_ms = call_stats.jitterSamples / (codec_inst.plfreq / 1000);
  }
  stats.delay_estimate_ms = channel_proxy_->GetDelayEstimate();
  stats.audio_level = channel_proxy_->GetSpeechOutputLevelFullRange();

  // Get jitter buffer and total delay (alg + jitter + playout) stats.
  auto ns = channel_proxy_->GetNetworkStatistics();
  stats.jitter_buffer_ms = ns.currentBufferSize;
  stats.jitter_buffer_preferred_ms = ns.preferredBufferSize;
  stats.expand_rate = Q14ToFloat(ns.currentExpandRate);
  stats.speech_expand_rate = Q14ToFloat(ns.currentSpeechExpandRate);
  stats.secondary_decoded_rate = Q14ToFloat(ns.currentSecondaryDecodedRate);
  stats.accelerate_rate = Q14ToFloat(ns.currentAccelerateRate);
  stats.preemptive_expand_rate = Q14ToFloat(ns.currentPreemptiveRate);

  auto ds = channel_proxy_->GetDecodingCallStatistics();
  stats.decoding_calls_to_silence_generator = ds.calls_to_silence_generator;
  stats.decoding_calls_to_neteq = ds.calls_to_neteq;
  stats.decoding_normal = ds.decoded_normal;
  stats.decoding_plc = ds.decoded_plc;
  stats.decoding_cng = ds.decoded_cng;
  stats.decoding_plc_cng = ds.decoded_plc_cng;
  stats.decoding_muted_output = ds.decoded_muted_output;

  return stats;
}

int AudioReceiveStream::GetOutputLevel() const {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  return channel_proxy_->GetSpeechOutputLevel();
}

void AudioReceiveStream::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  channel_proxy_->SetSink(std::move(sink));
}

void AudioReceiveStream::SetGain(float gain) {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  channel_proxy_->SetChannelOutputVolumeScaling(gain);
}

std::vector<RtpSource> AudioReceiveStream::GetSources() const {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  return channel_proxy_->GetSources();
}

AudioMixer::Source::AudioFrameInfo AudioReceiveStream::GetAudioFrameWithInfo(
    int sample_rate_hz,
    AudioFrame* audio_frame) {
  return channel_proxy_->GetAudioFrameWithInfo(sample_rate_hz, audio_frame);
}

int AudioReceiveStream::Ssrc() const {
  return config_.rtp.remote_ssrc;
}

int AudioReceiveStream::PreferredSampleRate() const {
  return channel_proxy_->NeededFrequency();
}

int AudioReceiveStream::id() const {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  return config_.rtp.remote_ssrc;
}

rtc::Optional<Syncable::Info> AudioReceiveStream::GetInfo() const {
  RTC_DCHECK_RUN_ON(&module_process_thread_checker_);
  Syncable::Info info;

  RtpRtcp* rtp_rtcp = nullptr;
  RtpReceiver* rtp_receiver = nullptr;
  channel_proxy_->GetRtpRtcp(&rtp_rtcp, &rtp_receiver);
  RTC_DCHECK(rtp_rtcp);
  RTC_DCHECK(rtp_receiver);

  if (!rtp_receiver->Timestamp(&info.latest_received_capture_timestamp)) {
    return rtc::Optional<Syncable::Info>();
  }
  if (!rtp_receiver->LastReceivedTimeMs(&info.latest_receive_time_ms)) {
    return rtc::Optional<Syncable::Info>();
  }
  if (rtp_rtcp->RemoteNTP(&info.capture_time_ntp_secs,
                          &info.capture_time_ntp_frac,
                          nullptr,
                          nullptr,
                          &info.capture_time_source_clock) != 0) {
    return rtc::Optional<Syncable::Info>();
  }

  info.current_delay_ms = channel_proxy_->GetDelayEstimate();
  return rtc::Optional<Syncable::Info>(info);
}

uint32_t AudioReceiveStream::GetPlayoutTimestamp() const {
  // Called on video capture thread.
  return channel_proxy_->GetPlayoutTimestamp();
}

void AudioReceiveStream::SetMinimumPlayoutDelay(int delay_ms) {
  RTC_DCHECK_RUN_ON(&module_process_thread_checker_);
  return channel_proxy_->SetMinimumPlayoutDelay(delay_ms);
}

void AudioReceiveStream::AssociateSendStream(AudioSendStream* send_stream) {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  if (send_stream) {
    VoiceEngineImpl* voe_impl = static_cast<VoiceEngineImpl*>(voice_engine());
    std::unique_ptr<voe::ChannelProxy> send_channel_proxy =
        voe_impl->GetChannelProxy(send_stream->config().voe_channel_id);
    channel_proxy_->AssociateSendChannel(*send_channel_proxy.get());
  } else {
    channel_proxy_->DisassociateSendChannel();
  }
}

void AudioReceiveStream::SignalNetworkState(NetworkState state) {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
}

bool AudioReceiveStream::DeliverRtcp(const uint8_t* packet, size_t length) {
  // TODO(solenberg): Tests call this function on a network thread, libjingle
  // calls on the worker thread. We should move towards always using a network
  // thread. Then this check can be enabled.
  // RTC_DCHECK(!thread_checker_.CalledOnValidThread());
  return channel_proxy_->ReceivedRTCPPacket(packet, length);
}

void AudioReceiveStream::OnRtpPacket(const RtpPacketReceived& packet) {
  // TODO(solenberg): Tests call this function on a network thread, libjingle
  // calls on the worker thread. We should move towards always using a network
  // thread. Then this check can be enabled.
  // RTC_DCHECK(!thread_checker_.CalledOnValidThread());
  channel_proxy_->OnRtpPacket(packet);
}

const webrtc::AudioReceiveStream::Config& AudioReceiveStream::config() const {
  RTC_DCHECK_RUN_ON(&worker_thread_checker_);
  return config_;
}

VoiceEngine* AudioReceiveStream::voice_engine() const {
  auto* voice_engine = audio_state()->voice_engine();
  RTC_DCHECK(voice_engine);
  return voice_engine;
}

internal::AudioState* AudioReceiveStream::audio_state() const {
  auto* audio_state = static_cast<internal::AudioState*>(audio_state_.get());
  RTC_DCHECK(audio_state);
  return audio_state;
}

int AudioReceiveStream::SetVoiceEnginePlayout(bool playout) {
  ScopedVoEInterface<VoEBase> base(voice_engine());
  if (playout) {
    return base->StartPlayout(config_.voe_channel_id);
  } else {
    return base->StopPlayout(config_.voe_channel_id);
  }
}
}  // namespace internal
}  // namespace webrtc


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

namespace Geb.Image
{
    public static class ImageExtensions
    {
    }
}


text:
<?php
require '../assets/db2.php';
session_start();

$id = Crypt::Decrypt($_GET['id']);

$link = Db::open();

$stmt = $link -> prepare("SELECT FileName, Movies.MovieID, Runtime, Certificate, Description, Genre, Title, ReleaseDate,
                        (SELECT TalentName FROM MovieTalent LEFT JOIN Talent ON Talent.TalentID = MovieTalent.TalentID WHERE MovieTalent.RoleID = 1 AND MovieTalent.MovieID = Movies.MovieID) AS Director,
                        (SELECT TalentName FROM MovieTalent LEFT JOIN Talent ON Talent.TalentID = MovieTalent.TalentID WHERE MovieTalent.RoleID = 2 AND MovieTalent.MovieID = Movies.MovieID) AS Producer,
                        (SELECT TalentName FROM MovieTalent LEFT JOIN Talent ON Talent.TalentID = MovieTalent.TalentID WHERE MovieTalent.RoleID = 3 AND MovieTalent.MovieID = Movies.MovieID) AS Screenwriter
                        FROM Movies LEFT JOIN Genres ON Genres.GenreID = Movies.GenreID LEFT JOIN ArtWork ON ArtWork.MovieID = Movies.MovieID AND ArtWork.CoverArt = 1 WHERE Movies.MovieID = ?");

$stmt -> bind_param('i', $id);

$stmt -> bind_result($FileName, $MovieID, $Runtime, $Certificate, $Description, $Genre, $Title, $ReleaseDate, $director, $Producer, $Screenwriter);

$stmt -> execute();

$stmt -> fetch();

$titles = "";

    $titles .= "
";
    $titles .= "" . $Title . "	";
    $titles .= "" . $ReleaseDate . "	";
    $titles .= "" . $Runtime . "	";
    $titles .= "" . $Genre . "	";
    $titles .= "" . $Certificate . "	";
    $titles .= "" . $Description . "	";
    $titles .= "
";

    $titles .= "
";
    $titles .= "" . $Title . "	";
    $titles .= "" . $ReleaseDate . "	";
    $titles .= "" . $Runtime . "	";
    $titles .= "" . $Genre . "	";
    $titles .= "" . $Certificate . "	";
    $titles .= "" . $Description . "	";
    $titles .= "" . $director . "	";
    $titles .= "
";

$stmt -> close();

$stmt = $link -> prepare("SELECT Characters, TalentName FROM MovieTalent LEFT JOIN Talent ON Talent.TalentID = MovieTalent.TalentID WHERE MovieID = ? AND RoleID = 4");

$stmt -> bind_param('i', $id);

$stmt -> bind_result($Characters, $TalentName);

$stmt -> execute();

$talents = "";
while($stmt -> fetch()){
    $talents .= "
";
    $talents .= "" . $Characters . "	";
    $talents .= "" . $TalentName . "	";
    $talents .= "
";
};

$stmt -> close();

$stmt = $link -> prepare("SELECT TalentName FROM MovieTalent LEFT JOIN Talent ON Talent.TalentID = MovieTalent.TalentID LEFT JOIN Roles ON Roles.RoleID = MovieTalent.RoleID LEFT JOIN Movies ON Movies.MovieID = MovieTalent.MovieID WHERE MovieTalent.RoleID = ?");

$stmt -> bind_param('i', $id);

$stmt -> bind_result($TalentName);

//Check cover art in the db later for dups!!
$CoverArt = 1;

if ($_SERVER["REQUEST_METHOD"] == "POST"){
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOK = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    //Image check:
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOK = 1;
        } else {
            echo "File is not an image!";
            $uploadOK = 0;
        }
    }

    //does file exist?
    if (file_exists($target_file)) {
        echo "Sorry, file already exists";
        $uploadOK = 0;
    }

    //file size
    if ($_FILES["fileToUpload"]["size"] > 4718592) {
        echo "Sorry, file is to large";
        $uploadOK = 0;
    }

    //Only allow certain formats
    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
        echo "Sorry, only jpeg, jpeg, png and gif are allowed";
    }

    //is $uploadOK set to 0 by error
    if ($uploadOK == 0) {
        echo "Sorry, your file was not uploaded";
        //Is everything ok?, if so try and upload the file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ".basename($_FILES["fileToUpload"]["name"]). " has been uploaded!";

            $stmt = $link -> prepare("INSERT INTO ArtWork(MovieID, CoverArt, FileName) VALUES (?,?,?)");

            $stmt -> bind_param("iis", $MovieID, $CoverArt, basename($_FILES["fileToUpload"]["name"]));

            $stmt -> execute();

        } else {
            echo "Sorry there was an error!";
        }
    }
}

$link -> close();

?>

    <link href="/assets/dist/css/bootstrap.css" rel="stylesheet">

            <img src="uploads/<?= $FileName ?>" style="height: 317px; width: 214px;">
            <form method="post" enctype="multipart/form-data">

Upload Cover Photo:

                    <input type="file" name="fileToUpload" id="fileToUpload">

                    <input type="submit" value="Upload Image" name="submit">

                    Home
                    <a class="btn btn-danger" href="edit.php?id=<?=Crypt::encrypt($MovieID)?>">Edit

            </form>

<?=$Title?>

Description

            <?=$Description?>

Director

            <?=$director?>

Producer

            <?=$Producer?>

Screen Writer

            <?=$Screenwriter?>


text:
<?php

namespace Catalogue\Support\Traits;

use Library\Models\Library;

trait HasManyLibraries
{
    /**
     * Get the library objects for this resource.
     *
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function libraries()
    {
        return $this->hasMany(Library::class);
    }
}


text:
require 'rails_helper'

describe RefreshFeedJobState, type: :model do

  context 'validations' do

    it 'always belongs to a user' do
      refresh_feed_job_state = FactoryGirl.build :refresh_feed_job_state, user_id: nil
      expect(refresh_feed_job_state).not_to be_valid
    end

    it 'always belongs to a feed' do
      refresh_feed_job_state = FactoryGirl.build :refresh_feed_job_state, feed_id: nil
      expect(refresh_feed_job_state).not_to be_valid
    end
  end

  context 'default values' do

    it 'defaults to state RUNNING when created' do
      refresh_feed_job_state = FactoryGirl.create :refresh_feed_job_state
      expect(refresh_feed_job_state.state).to eq RefreshFeedJobState::RUNNING
    end

  end

end


text:
while getopts p:c: option
do
        case "${option}"
        in
                p) OPERATION=${OPTARG};;
                c) CONFIG_FILE=${OPTARG};;
        esac
done

### Trim leading whitespaces ###
OPERATION="${OPERATION##*( )}"
CONFIG_FILE="${CONFIG_FILE##*( )}"

#Get the Consumer Group Name for the Consumer Instance
CONSUMER_GROUP_NAME=`grep 'consumerGroupName=' $CONFIG_FILE | head -1 | cut -d "=" -f2 | tr -d ' '`

#Get the topic for the Consumer Instance
KAFKA_TOPIC=`grep 'topic=' $CONFIG_FILE | head -1 | cut -d "=" -f2 | tr -d ' '`

#Get the topic partition for the Consumer Instance
TOPIC_PARTITION=`grep 'partition=' $CONFIG_FILE | head -1 | cut -d "=" -f2 | tr -d ' '`

# Setup variables
#Get the relative directory from which this script is run
base_dir_relative=$(dirname $0)/..

#Get the absolute directory from which this scriprt is run
base_dir=$(cd $(dirname $base_dir_relative); pwd)/$(basename $base_dir_relative)

# create logs directory if it doesnt exist
LOG_DIR=$base_dir/logs
if [ ! -d $LOG_DIR ]; then
        mkdir $LOG_DIR
fi

# create logs directory if it doesnt exist
PROCESS_LOG_DIR=$base_dir/processLogs
if [ ! -d $PROCESS_DIR ]; then
        mkdir $PROCESS_DIR
fi

#Get the path where jsvc binary is available
EXEC=$base_dir/scripts/jsvc

#Get all the dependent library jars into classpath
for file in $base_dir/lib/dep-jars/*.jar;
do
  libClassPath=$libClassPath:$file
done

#Get the standalone consumer jar in the bin directory into the classpath
for file in $base_dir/bin/*.jar;
do
  libClassPath=$libClassPath:$file
done

#get the config dir and the base_dir into the classpath. This is needed to make the config file searchable
CLASS_PATH=$libClassPath:$base_dir"/config":$base_dir

#This is the main class from which the Consumer Daemon is started. PLEASE DONT CHANGE THIS !!
CLASS=org.elasticsearch.kafka.consumer.daemon.KafkaConsumerDaemon

#User as which the Consumer Daemon has to be run
USER=kraj

#This file stores the Process ID of the Consumer Daemon
PID=$PROCESS_LOG_DIR/$CONSUMER_GROUP_NAME"_"$KAFKA_TOPIC"_"$TOPIC_PARTITION".pid"

#This file contains the info when starting|stopping|restarting the consumer daemon
LOG_OUT=$PROCESS_LOG_DIR/$CONSUMER_GROUP_NAME"_"$KAFKA_TOPIC"_"$TOPIC_PARTITION".out"

#This file contains the errors when starting|stopping|restarting the consumer daemon
LOG_ERR=$PROCESS_LOG_DIR/$CONSUMER_GROUP_NAME"_"$KAFKA_TOPIC"_"$TOPIC_PARTITION".err"

echo $PID
echo $LOG_OUT
echo $LOG_ERR

case "$OPERATION" in
    start)
        do_start $CONFIG_FILE
            ;;
    stop)
        do_stop
            ;;
    restart)
        if [ -f "$PID" ]; then
            do_stop
            do_start $CONFIG_FILE
        else
            echo "Consumer Daemon not running, will do nothing."
            exit 1
        fi
            ;;
    *)
            echo "Usage: consumer.sh -p {start|stop|restart} -c <path_for_configFile_for_the_consumer_instance>" >&2
            exit 3
            ;;
esac

do_start()
{
      #echo $EXEC -home "$JAVA_HOME" -cp $CLASS_PATH -user $USER -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID $CLASS $1 $2
      echo "Starting the Consume Daemon. Please wait......"
      $EXEC -home "$JAVA_HOME" -cp $CLASS_PATH -user $USER -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID $CLASS $1
      echo "*** Start attempt completed.,"
      echo "*** Please check "$LOG_OUT" file for start confirmation and "
      echo $LOG_ERR" for errors in case of failure ***"
}

do_stop()
{
      #echo $EXEC -home "$JAVA_HOME" -cp $CLASS_PATH -user $USER -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID -stop $CLASS
      echo "Stopping the Consumer Daemon. Please wait......"
      $EXEC -home "$JAVA_HOME" -cp $CLASS_PATH -user $USER -outfile $LOG_OUT -errfile $LOG_ERR -pidfile $PID -verbose -stop $CLASS
      echo "*** Stop attempt completed.,"
      echo "*** Please check "$LOG_OUT" file for stop confirmation and "
      echo $LOG_ERR" for errors in case of failure ***"
}


text:
define(
   ({
    _widgetLabel: "Rita",
    selectDrawMode: "Välj ritläge",
    clear: "Rensa",
    point: "Punkt",
    line: "Linje",
    polyline: "Polylinje",
    freehandPolyline: "Frihandspolylinje",
    triangle: "Triangel",
    extent: "Utbredningsområde",
    circle: "Cirkel",
    ellipse: "Ellips",
    polygon: "Polygon",
    freehandPolygon: "Frihandspolygon",
    text: "Text",
    style: "Format",
    alpha: "Transparens",
    width: "Bredd",
    size: "Storlek",
    color: "Färg",
    markerColor: "Markeringsfärg",
    outlineColor: "Konturfärg",
    lineColor: "Linjefärg",
    fillColor: "Fyllningsfärg",
    showMeasurements: "Visa mått",
    areaUnits: "Areaenheter",
    distanceUnits: "Distansenheter",
    kilometers: "Kilometer",
    miles: "Engelska mil",
    meters: "Meter",
    feet: "Fot",
    yards: "Yard",
    squareKilometers: "Kvadratkilometer",
    squareMiles: "Square miles",
    acres: "Tunnland",
    hectares: "Hektar",
    squareMeters: "Kvadratmeter",
    squareFeet: "Square feet",
    squareYards: "Square yards",
    undo: "Ångra",
    redo: "Upprepa",
    results: "Resultat",
    points: "Punkter",
    lines: "Linjer",
    areas: "Ytor"
  })
);


text:
<?php
/**
 * The template for displaying all single posts.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 *
 * @package Talon
 */

get_header(); ?>

		<?php
		while ( have_posts() ) : the_post();

			get_template_part( 'template-parts/content', 'single' );

			the_post_navigation();

			// If comments are open or we have at least one comment, load up the comment template.
			if ( comments_open() || get_comments_number() ) :
				comments_template();
			endif;

		endwhile; // End of the loop.
		?>

<?php
if ( get_theme_mod('fullwidth_single', 0) != 1 ) :
	get_sidebar();
endif; ?>

<?php get_footer(); ?>


text:
// SPDX-License-Identifier: BSD-3-Clause
package org.xbill.DNS;

import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import lombok.SneakyThrows;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.xbill.DNS.AsyncSemaphore.Permit;
import org.xbill.DNS.utils.base64;

/**
 * Proof-of-concept DNS over HTTP (DoH) resolver.
 * This class is not suitable for high load scenarios because of the shortcomings of Java's built-in
 * HTTP clients. For more control, implement your own {@link Resolver} using e.g. OkHttp.
 *
 *
On Java 8, it uses HTTP/1.1, which is against the recommendation of RFC 8484 to use HTTP/2 and
 * thus slower. On Java 11 or newer, HTTP/2 is always used, but the built-in HttpClient has its own
 * issues with connection handling.
 *
 *
As of 2020-09-13, the following limits of public resolvers for HTTP/2 were observed:
 *
https://cloudflare-dns.com/dns-query: max streams=250, idle timeout=400s
 *
https://dns.google/dns-query: max streams=100, idle timeout=240s
 *
 * @since 3.0
 */
@Slf4j
public final class DohResolver implements Resolver {
  private static final boolean USE_HTTP_CLIENT;
  private static final Map<Executor, Object> httpClients =
      Collections.synchronizedMap(new WeakHashMap<>());
  private final SSLSocketFactory sslSocketFactory;

  private static Object defaultHttpRequestBuilder;
  private static Method publisherOfByteArrayMethod;
  private static Method requestBuilderTimeoutMethod;
  private static Method requestBuilderCopyMethod;
  private static Method requestBuilderUriMethod;
  private static Method requestBuilderBuildMethod;
  private static Method requestBuilderPostMethod;

  private static Method httpClientNewBuilderMethod;
  private static Method httpClientBuilderTimeoutMethod;
  private static Method httpClientBuilderExecutorMethod;
  private static Method httpClientBuilderBuildMethod;
  private static Method httpClientSendAsyncMethod;

  private static Method byteArrayBodyPublisherMethod;
  private static Method httpResponseBodyMethod;
  private static Method httpResponseStatusCodeMethod;

  private boolean usePost = false;
  private Duration timeout = Duration.ofSeconds(5);
  private String uriTemplate;
  private final Duration idleConnectionTimeout;
  private OPTRecord queryOPT = new OPTRecord(0, 0, 0);
  private TSIG tsig;
  private Executor defaultExecutor = ForkJoinPool.commonPool();

  /**
   * Maximum concurrent HTTP/2 streams or HTTP/1.1 connections.
   *
   *
rfc7540#section-6.5.2 recommends a minimum of 100 streams for HTTP/2.
   */
  private final AsyncSemaphore maxConcurrentRequests;

  private final AtomicLong lastRequest = new AtomicLong(0);
  private final AsyncSemaphore initialRequestLock = new AsyncSemaphore(1);

  private static final String APPLICATION_DNS_MESSAGE = "application/dns-message";

  static {
    boolean initSuccess = false;
    if (!System.getProperty("java.version").startsWith("1.")) {
      try {
        Class<?> httpClientBuilderClass = Class.forName("java.net.http.HttpClient$Builder");
        Class<?> httpClientClass = Class.forName("java.net.http.HttpClient");
        Class<?> httpVersionEnum = Class.forName("java.net.http.HttpClient$Version");
        Class<?> httpRequestBuilderClass = Class.forName("java.net.http.HttpRequest$Builder");
        Class<?> httpRequestClass = Class.forName("java.net.http.HttpRequest");
        Class<?> bodyPublishersClass = Class.forName("java.net.http.HttpRequest$BodyPublishers");
        Class<?> bodyPublisherClass = Class.forName("java.net.http.HttpRequest$BodyPublisher");
        Class<?> httpResponseClass = Class.forName("java.net.http.HttpResponse");
        Class<?> bodyHandlersClass = Class.forName("java.net.http.HttpResponse$BodyHandlers");
        Class<?> bodyHandlerClass = Class.forName("java.net.http.HttpResponse$BodyHandler");

        // HttpClient.Builder
        httpClientBuilderTimeoutMethod =
            httpClientBuilderClass.getDeclaredMethod("connectTimeout", Duration.class);
        httpClientBuilderExecutorMethod =
            httpClientBuilderClass.getDeclaredMethod("executor", Executor.class);
        httpClientBuilderBuildMethod = httpClientBuilderClass.getDeclaredMethod("build");

        // HttpClient
        httpClientNewBuilderMethod = httpClientClass.getDeclaredMethod("newBuilder");
        httpClientSendAsyncMethod =
            httpClientClass.getDeclaredMethod("sendAsync", httpRequestClass, bodyHandlerClass);

        // HttpRequestBuilder
        Method requestBuilderHeaderMethod =
            httpRequestBuilderClass.getDeclaredMethod("header", String.class, String.class);
        Method requestBuilderVersionMethod =
            httpRequestBuilderClass.getDeclaredMethod("version", httpVersionEnum);
        requestBuilderTimeoutMethod =
            httpRequestBuilderClass.getDeclaredMethod("timeout", Duration.class);
        requestBuilderUriMethod = httpRequestBuilderClass.getDeclaredMethod("uri", URI.class);
        requestBuilderCopyMethod = httpRequestBuilderClass.getDeclaredMethod("copy");
        requestBuilderBuildMethod = httpRequestBuilderClass.getDeclaredMethod("build");
        requestBuilderPostMethod =
            httpRequestBuilderClass.getDeclaredMethod("POST", bodyPublisherClass);

        // HttpRequest
        Method requestBuilderNewBuilderMethod = httpRequestClass.getDeclaredMethod("newBuilder");

        // BodyPublishers
        publisherOfByteArrayMethod =
            bodyPublishersClass.getDeclaredMethod("ofByteArray", byte[].class);

        // BodyPublisher
        byteArrayBodyPublisherMethod = bodyHandlersClass.getDeclaredMethod("ofByteArray");

        // HttpResponse
        httpResponseBodyMethod = httpResponseClass.getDeclaredMethod("body");
        httpResponseStatusCodeMethod = httpResponseClass.getDeclaredMethod("statusCode");

        // defaultHttpRequestBuilder = HttpRequest.newBuilder();
        // defaultHttpRequestBuilder.version(HttpClient.Version.HTTP_2);
        // defaultHttpRequestBuilder.header("Content-Type", "application/dns-message");
        // defaultHttpRequestBuilder.header("Accept", "application/dns-message");
        defaultHttpRequestBuilder = requestBuilderNewBuilderMethod.invoke(null);
        @SuppressWarnings({"unchecked", "rawtypes"})
        Enum<?> http2Version = Enum.valueOf((Class<Enum>) httpVersionEnum, "HTTP_2");
        requestBuilderVersionMethod.invoke(defaultHttpRequestBuilder, http2Version);
        requestBuilderHeaderMethod.invoke(
            defaultHttpRequestBuilder, "Content-Type", APPLICATION_DNS_MESSAGE);
        requestBuilderHeaderMethod.invoke(
            defaultHttpRequestBuilder, "Accept", APPLICATION_DNS_MESSAGE);
        initSuccess = true;
      } catch (ClassNotFoundException
          | NoSuchMethodException
          | IllegalAccessException
          | InvocationTargetException e) {
        // fallback to Java 8
        log.warn("Java >= 11 detected, but HttpRequest not available");
      }
    }

    USE_HTTP_CLIENT = initSuccess;
  }

  /**
   * Creates a new DoH resolver that performs lookups with HTTP GET and the default timeout (5s).
   *
   * @param uriTemplate the URI to use for resolving, e.g. {@code https://dns.google/dns-query}
   */
  public DohResolver(String uriTemplate) {
    this(uriTemplate, 100, Duration.ofMinutes(2));
  }

  /**
   * Creates a new DoH resolver that performs lookups with HTTP GET and the default timeout (5s).
   *
   * @param uriTemplate the URI to use for resolving, e.g. {@code https://dns.google/dns-query}
   * @param maxConcurrentRequests Maximum concurrent HTTP/2 streams for Java 11+ or HTTP/1.1
   *     connections for Java 8. On Java 8 this cannot exceed the system property {@code
   *     http.maxConnections}.
   * @param idleConnectionTimeout Max. idle time for HTTP/2 connections until a request is
   *     serialized. Applies to Java 11+ only.
   * @since 3.3
   */
  public DohResolver(
      String uriTemplate, int maxConcurrentRequests, Duration idleConnectionTimeout) {
    this.uriTemplate = uriTemplate;
    this.idleConnectionTimeout = idleConnectionTimeout;
    if (maxConcurrentRequests <= 0) {
      throw new IllegalArgumentException("maxConcurrentRequests must be > 0");
    }
    if (!USE_HTTP_CLIENT) {
      try {
        int javaMaxConn = Integer.parseInt(System.getProperty("http.maxConnections", "5"));
        if (maxConcurrentRequests > javaMaxConn) {
          maxConcurrentRequests = javaMaxConn;
        }
      } catch (NumberFormatException nfe) {
        // well, use what we got
      }
    }
    this.maxConcurrentRequests = new AsyncSemaphore(maxConcurrentRequests);
    try {
      sslSocketFactory = SSLContext.getDefault().getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
  }

  @SneakyThrows
  private Object getHttpClient(Executor executor) {
    return httpClients.computeIfAbsent(
        executor,
        key -> {
          try {
            // return HttpClient.newBuilder()
            //   .connectTimeout(timeout).
            //   .executor(executor)
            //   .build();
            Object httpClientBuilder = httpClientNewBuilderMethod.invoke(null);
            httpClientBuilderTimeoutMethod.invoke(httpClientBuilder, timeout);
            httpClientBuilderExecutorMethod.invoke(httpClientBuilder, key);
            return httpClientBuilderBuildMethod.invoke(httpClientBuilder);
          } catch (IllegalAccessException | InvocationTargetException e) {
            log.warn("Could not create a HttpClient with for Executor {}", key, e);
            return null;
          }
        });
  }

  /** Not implemented. Specify the port in {@link #setUriTemplate(String)} if required. */
  @Override
  public void setPort(int port) {
    // Not implemented, port is part of the URI
  }

  /** Not implemented. */
  @Override
  public void setTCP(boolean flag) {
    // Not implemented, HTTP is always TCP
  }

  /** Not implemented. */
  @Override
  public void setIgnoreTruncation(boolean flag) {
    // Not implemented, protocol uses TCP and doesn't have truncation
  }

  /**
   * Sets the EDNS information on outgoing messages.
   *
   * @param version The EDNS version to use. 0 indicates EDNS0 and -1 indicates no EDNS.
   * @param payloadSize ignored
   * @param flags EDNS extended flags to be set in the OPT record.
   * @param options EDNS options to be set in the OPT record
   */
  @Override
  public void setEDNS(int version, int payloadSize, int flags, List<EDNSOption> options) {
    switch (version) {
      case -1:
        queryOPT = null;
        break;

      case 0:
        queryOPT = new OPTRecord(0, 0, version, flags, options);
        break;

      default:
        throw new IllegalArgumentException("invalid EDNS version - must be 0 or -1 to disable");
    }
  }

  @Override
  public void setTSIGKey(TSIG key) {
    this.tsig = key;
  }

  @Override
  public void setTimeout(Duration timeout) {
    this.timeout = timeout;
    httpClients.clear();
  }

  @Override
  public Duration getTimeout() {
    return timeout;
  }

  @Override
  public CompletionStage<Message> sendAsync(Message query) {
    return sendAsync(query, defaultExecutor);
  }

  @Override
  public CompletionStage<Message> sendAsync(Message query, Executor executor) {
    if (USE_HTTP_CLIENT) {
      return sendAsync11(query, executor);
    }

    return sendAsync8(query, executor);
  }

  private CompletionStage<Message> sendAsync8(final Message query, Executor executor) {
    byte[] queryBytes = prepareQuery(query).toWire();
    String url = getUrl(queryBytes);
    long startTime = System.nanoTime();
    return maxConcurrentRequests
        .acquire(timeout)
        .handleAsync(
            (permit, ex) -> {
              if (ex != null) {
                return this.<Message>timeoutFailedFuture(query, ex);
              } else {
                try {
                  SendAndGetMessageBytesResponse result =
                      sendAndGetMessageBytes(url, queryBytes, startTime);
                  Message response;
                  if (result.rc == Rcode.NOERROR) {
                    response = new Message(result.responseBytes);
                    verifyTSIG(query, response, result.responseBytes, tsig);
                  } else {
                    response = new Message(0);
                    response.getHeader().setRcode(result.rc);
                  }

                  response.setResolver(this);
                  return CompletableFuture.completedFuture(response);
                } catch (SocketTimeoutException e) {
                  return this.<Message>timeoutFailedFuture(query, e);
                } catch (IOException e) {
                  return this.<Message>failedFuture(e);
                } finally {
                  permit.release();
                }
              }
            },
            executor)
        .thenCompose(Function.identity());
  }

  @Value
  private static class SendAndGetMessageBytesResponse {
    int rc;
    byte[] responseBytes;
  }

  private SendAndGetMessageBytesResponse sendAndGetMessageBytes(
      String url, byte[] queryBytes, long startTime) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    if (conn instanceof HttpsURLConnection) {
      ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
    }

    Duration remainingTimeout = timeout.minus(System.nanoTime() - startTime, ChronoUnit.NANOS);
    conn.setConnectTimeout((int) remainingTimeout.toMillis());
    conn.setReadTimeout((int) remainingTimeout.toMillis());
    conn.setRequestMethod(usePost ? "POST" : "GET");
    conn.setRequestProperty("Content-Type", APPLICATION_DNS_MESSAGE);
    conn.setRequestProperty("Accept", APPLICATION_DNS_MESSAGE);
    if (usePost) {
      conn.setDoOutput(true);
      conn.getOutputStream().write(queryBytes);
    }

    int rc = conn.getResponseCode();
    if (rc < 200 || rc >= 300) {
      discardStream(conn.getInputStream());
      discardStream(conn.getErrorStream());
      return new SendAndGetMessageBytesResponse(Rcode.SERVFAIL, null);
    }

    try (InputStream is = conn.getInputStream()) {
      int length = conn.getContentLength();
      if (length > -1) {
        byte[] responseBytes = new byte[conn.getContentLength()];
        int r;
        int offset = 0;
        while ((r = is.read(responseBytes, offset, responseBytes.length - offset)) > 0) {
          offset += r;
          remainingTimeout = timeout.minus(System.nanoTime() - startTime, ChronoUnit.NANOS);
          if (remainingTimeout.isNegative()) {
            throw new SocketTimeoutException();
          }
        }
        if (offset < responseBytes.length) {
          throw new EOFException("Could not read expected content length");
        }
        return new SendAndGetMessageBytesResponse(Rcode.NOERROR, responseBytes);
      } else {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
          byte[] buffer = new byte[4096];
          int r;
          while ((r = is.read(buffer, 0, buffer.length)) > 0) {
            remainingTimeout = timeout.minus(System.nanoTime() - startTime, ChronoUnit.NANOS);
            if (remainingTimeout.isNegative()) {
              throw new SocketTimeoutException();
            }
            bos.write(buffer, 0, r);
          }
          return new SendAndGetMessageBytesResponse(Rcode.NOERROR, bos.toByteArray());
        }
      }
    } catch (IOException ioe) {
      discardStream(conn.getErrorStream());
      throw ioe;
    }
  }

  private void discardStream(InputStream es) throws IOException {
    if (es != null) {
      try (InputStream in = es) {
        byte[] buf = new byte[4096];
        while (in.read(buf) > 0) {
          // discard
        }
      } catch (IOException ioe) {
        // ignore
      }
    }
  }

  private CompletionStage<Message> sendAsync11(final Message query, Executor executor) {
    long startTime = System.nanoTime();
    byte[] queryBytes = prepareQuery(query).toWire();
    String url = getUrl(queryBytes);

    // var requestBuilder = defaultHttpRequestBuilder.copy();
    // requestBuilder.uri(URI.create(url));
    Object requestBuilder;
    try {
      requestBuilder = requestBuilderCopyMethod.invoke(defaultHttpRequestBuilder);
      requestBuilderUriMethod.invoke(requestBuilder, URI.create(url));
      if (usePost) {
        // requestBuilder.POST(HttpRequest.BodyPublishers.ofByteArray(queryBytes));
        requestBuilderPostMethod.invoke(
            requestBuilder, publisherOfByteArrayMethod.invoke(null, queryBytes));
      }
    } catch (IllegalAccessException | InvocationTargetException e) {
      return failedFuture(e);
    }

    // check if this request needs to be done synchronously because of HttpClient's stupidity to
    // not use the connection pool for HTTP/2 until one connection is successfully established,
    // which could lead to hundreds of connections (and threads with the default executor)
    Duration remainingTimeout = timeout.minus(System.nanoTime() - startTime, ChronoUnit.NANOS);
    return initialRequestLock
        .acquire(remainingTimeout)
        .handle(
            (initialRequestPermit, initialRequestEx) -> {
              if (initialRequestEx != null) {
                return this.<Message>timeoutFailedFuture(query, initialRequestEx);
              } else {
                return sendAsync11WithInitialRequestPermit(
                    query, executor, startTime, requestBuilder, initialRequestPermit);
              }
            })
        .thenCompose(Function.identity());
  }

  private CompletionStage<Message> sendAsync11WithInitialRequestPermit(
      Message query,
      Executor executor,
      long startTime,
      Object requestBuilder,
      Permit initialRequestPermit) {
    long lastRequestTime = lastRequest.get();
    boolean isInitialRequest =
        (lastRequestTime < System.nanoTime() - idleConnectionTimeout.toNanos());
    if (!isInitialRequest) {
      initialRequestPermit.release();
    }

    // check if we already exceeded the query timeout while checking the initial connection
    Duration remainingTimeout = timeout.minus(System.nanoTime() - startTime, ChronoUnit.NANOS);
    if (remainingTimeout.isNegative()) {
      if (isInitialRequest) {
        initialRequestPermit.release();
      }
      return timeoutFailedFuture(query, null);
    }

    // Lock a HTTP/2 stream. Another stupidity of HttpClient to not simply queue the
    // request, but fail with an IOException which also CLOSES the connection... *facepalm*
    return maxConcurrentRequests
        .acquire(remainingTimeout)
        .handle(
            (maxConcurrentRequestPermit, maxConcurrentRequestEx) -> {
              if (maxConcurrentRequestEx != null) {
                if (isInitialRequest) {
                  initialRequestPermit.release();
                }
                return this.<Message>timeoutFailedFuture(query, maxConcurrentRequestEx);
              } else {
                return sendAsync11WithConcurrentRequestPermit(
                    query,
                    executor,
                    startTime,
                    requestBuilder,
                    initialRequestPermit,
                    isInitialRequest,
                    maxConcurrentRequestPermit);
              }
            })
        .thenCompose(Function.identity());
  }

  private CompletionStage<Message> sendAsync11WithConcurrentRequestPermit(
      Message query,
      Executor executor,
      long startTime,
      Object requestBuilder,
      Permit initialRequestPermit,
      boolean isInitialRequest,
      Permit maxConcurrentRequestPermit) {
    // check if the stream lock acquisition took too long
    Duration remainingTimeout = timeout.minus(System.nanoTime() - startTime, ChronoUnit.NANOS);
    if (remainingTimeout.isNegative()) {
      if (isInitialRequest) {
        initialRequestPermit.release();
      }
      maxConcurrentRequestPermit.release();
      return timeoutFailedFuture(query, null);
    }

    // var httpRequest = requestBuilder.timeout(remainingTimeout).build();
    // var bodyHandler = HttpResponse.BodyHandlers.ofByteArray();
    // return getHttpClient(executor).sendAsync(httpRequest, bodyHandler)
    try {
      Object httpClient = getHttpClient(executor);
      requestBuilderTimeoutMethod.invoke(requestBuilder, remainingTimeout);
      Object httpRequest = requestBuilderBuildMethod.invoke(requestBuilder);
      Object bodyHandler = byteArrayBodyPublisherMethod.invoke(null);
      CompletableFuture<Message> f =
          ((CompletableFuture<?>)
                  httpClientSendAsyncMethod.invoke(httpClient, httpRequest, bodyHandler))
              .whenComplete(
                  (result, ex) -> {
                    if (ex == null) {
                      lastRequest.set(startTime);
                    }
                    maxConcurrentRequestPermit.release();
                    if (isInitialRequest) {
                      initialRequestPermit.release();
                    }
                  })
              .handleAsync(
                  (response, ex) -> {
                    if (ex != null) {
                      if (ex.getCause().getClass().getSimpleName().equals("HttpTimeoutException")) {
                        return this.<Message>timeoutFailedFuture(query, ex.getCause());
                      } else {
                        return this.<Message>failedFuture(ex);
                      }
                    } else {
                      try {
                        Message responseMessage;
                        // int rc = response.statusCode();
                        int rc = (int) httpResponseStatusCodeMethod.invoke(response);
                        if (rc >= 200 && rc < 300) {
                          // byte[] responseBytes = response.body();
                          byte[] responseBytes = (byte[]) httpResponseBodyMethod.invoke(response);
                          responseMessage = new Message(responseBytes);
                          verifyTSIG(query, responseMessage, responseBytes, tsig);
                        } else {
                          responseMessage = new Message();
                          responseMessage.getHeader().setRcode(Rcode.SERVFAIL);
                        }

                        responseMessage.setResolver(this);
                        return CompletableFuture.completedFuture(responseMessage);
                      } catch (IOException | IllegalAccessException | InvocationTargetException e) {
                        return this.<Message>failedFuture(e);
                      }
                    }
                  },
                  executor)
              .thenCompose(Function.identity());
      return TimeoutCompletableFuture.compatTimeout(
          f, remainingTimeout.toMillis(), TimeUnit.MILLISECONDS);
    } catch (IllegalAccessException | InvocationTargetException e) {
      return failedFuture(e);
    }
  }

  private <T> CompletableFuture<T> failedFuture(Throwable e) {
    CompletableFuture<T> f = new CompletableFuture<>();
    f.completeExceptionally(e);
    return f;
  }

  private <T> CompletableFuture<T> timeoutFailedFuture(Message query, Throwable inner) {
    return failedFuture(
        new IOException(
            "Query "
                + query.getHeader().getID()
                + " for "
                + query.getQuestion().getName()
                + "/"
                + Type.string(query.getQuestion().getType())
                + " timed out",
            inner));
  }

  private String getUrl(byte[] queryBytes) {
    String url = uriTemplate;
    if (!usePost) {
      url += "?dns=" + base64.toString(queryBytes, true);
    }
    return url;
  }

  private Message prepareQuery(Message query) {
    Message preparedQuery = query.clone();
    preparedQuery.getHeader().setID(0);
    if (queryOPT != null && preparedQuery.getOPT() == null) {
      preparedQuery.addRecord(queryOPT, Section.ADDITIONAL);
    }

    if (tsig != null) {
      tsig.apply(preparedQuery, null);
    }

    return preparedQuery;
  }

  private void verifyTSIG(Message query, Message response, byte[] b, TSIG tsig) {
    if (tsig == null) {
      return;
    }

    int error = tsig.verify(response, b, query.getGeneratedTSIG());
    log.debug(
        "TSIG verify for query {}, {}/{}: {}",
        query.getHeader().getID(),
        query.getQuestion().getName(),
        Type.string(query.getQuestion().getType()),
        Rcode.TSIGstring(error));
  }

  /** Returns {@code true} if the HTTP method POST to resolve, {@code false} if GET is used. */
  public boolean isUsePost() {
    return usePost;
  }

  /**
   * Sets the HTTP method to use for resolving.
   *
   * @param usePost {@code true} to use POST, {@code false} to use GET (the default).
   */
  public void setUsePost(boolean usePost) {
    this.usePost = usePost;
  }

  /** Gets the current URI used for resolving. */
  public String getUriTemplate() {
    return uriTemplate;
  }

  /** Sets the URI to use for resolving, e.g. {@code https://dns.google/dns-query} */
  public void setUriTemplate(String uriTemplate) {
    this.uriTemplate = uriTemplate;
  }

  /**
   * Gets the default {@link Executor} for request handling, defaults to {@link
   * ForkJoinPool#commonPool()}.
   *
   * @since 3.3
   * @deprecated not applicable if {@link #sendAsync(Message, Executor)} is used.
   */
  @Deprecated
  public Executor getExecutor() {
    return defaultExecutor;
  }

  /**
   * Sets the default {@link Executor} for request handling.
   *
   * @param executor The new {@link Executor}, can be {@code null} (which is equivalent to {@link
   *     ForkJoinPool#commonPool()}).
   * @since 3.3
   * @deprecated Use {@link #sendAsync(Message, Executor)}.
   */
  @Deprecated
  public void setExecutor(Executor executor) {
    this.defaultExecutor = executor == null ? ForkJoinPool.commonPool() : executor;
    httpClients.clear();
  }

  @Override
  public String toString() {
    return "DohResolver {" + (usePost ? "POST " : "GET ") + uriTemplate + "}";
  }
}


text:
package org.apache.hadoop.chukwa.extraction.demux;

import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.apache.hadoop.chukwa.conf.ChukwaConfiguration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
import java.util.List;
import org.apache.hadoop.chukwa.extraction.CHUKWA_CONSTANT;
import org.apache.hadoop.chukwa.util.HierarchyDataType;
import org.apache.hadoop.fs.PathFilter;

// TODO
// First version of the Spill
// need some polishing

public class MoveToRepository implements CHUKWA_CONSTANT{
  static Logger log = Logger.getLogger(MoveToRepository.class);

  static ChukwaConfiguration conf = null;
  static FileSystem fs = null;
  static final String HadoopLogDir = "_logs";
  static final String hadoopTempDir = "_temporary";
  static SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd");
  static Calendar calendar = Calendar.getInstance();

  static void processClusterDirectory(Path srcDir, String destDir)
      throws Exception {
    log.info("processClusterDirectory (" + srcDir.getName() + "," + destDir
        + ")");
    FileStatus fstat = fs.getFileStatus(srcDir);

    if (!fstat.isDir()) {
      throw new IOException(srcDir + " is not a directory!");
    } else {
      FileStatus[] datasourceDirectories = fs.listStatus(srcDir);

      for (FileStatus datasourceDirectory : datasourceDirectories) {
        log.info(datasourceDirectory.getPath() + " isDir?"
            + datasourceDirectory.isDir());
        if (!datasourceDirectory.isDir()) {
          throw new IOException(
              "Top level datasource directory should be a directory :"
                  + datasourceDirectory.getPath());
        }

        PathFilter filter = new PathFilter()
        {public boolean accept(Path file) {
          return file.getName().endsWith(".evt");
        }  };
        List<FileStatus> eventfiles = HierarchyDataType.globStatus(fs, datasourceDirectory.getPath(),filter,true);
        for (FileStatus eventfile : eventfiles){
          Path datatypeDir = eventfile.getPath().getParent();
          String dirName = HierarchyDataType.getDataType(datatypeDir, srcDir);

          Path destPath = new Path(destDir + "/" + dirName);
          log.info("dest directory path: " + destPath);
          log.info("processClusterDirectory processing Datasource: (" + dirName
              + ")");
          StringBuilder dtDir = new StringBuilder(srcDir.toString()).append("/").append(dirName);
          log.debug("srcDir: " + dtDir.toString());
          processDatasourceDirectory(srcDir.toString(), new Path(dtDir.toString()), destDir + "/" + dirName);
        }
      }
    }
  }

  static void processDatasourceDirectory(String clusterpath, Path srcDir,
      String destDir) throws Exception {

    Path cPath = new Path(clusterpath);
    String cluster = cPath.getName();

    String fileName = null;
    int fileDay = 0;
    int fileHour = 0;
    int fileMin = 0;

    FileStatus[] recordFiles = fs.listStatus(srcDir);
    for (FileStatus recordFile : recordFiles) {
      // dataSource_20080915_18_15.1.evt
      // <datasource>_<yyyyMMdd_HH_mm>.1.evt

      fileName = recordFile.getPath().getName();
      log.info("processDatasourceDirectory processing RecordFile: (" + fileName
          + ")");
      log.info("fileName: " + fileName);

      int l = fileName.length();
      String dataSource = HierarchyDataType.getDataType(srcDir, cPath);
      log.info("Datasource: " + dataSource);

      if (fileName.endsWith(".D.evt")) {
        // Hadoop_dfs_datanode_20080919.D.evt

        fileDay = Integer.parseInt(fileName.substring(l - 14, l - 6));
        writeRecordFile(destDir + "/" + fileDay + "/", recordFile.getPath(),
                dataSource.replace("/", HIERARCHY_CONNECTOR) + "_" + fileDay);
      } else if (fileName.endsWith(".H.evt")) {
        // Hadoop_dfs_datanode_20080925_1.H.evt
        // Hadoop_dfs_datanode_20080925_12.H.evt

        String day = null;
        String hour = null;
        if (fileName.charAt(l - 8) == '_') {
          day = fileName.substring(l - 16, l - 8);
          log.info("day->" + day);
          hour = "" + fileName.charAt(l - 7);
          log.info("hour->" + hour);
        } else {
          day = fileName.substring(l - 17, l - 9);
          log.info("day->" + day);
          hour = fileName.substring(l - 8, l - 6);
          log.info("hour->" + hour);
        }
        fileDay = Integer.parseInt(day);
        fileHour = Integer.parseInt(hour);
        // rotate there so spill
        writeRecordFile(destDir + "/" + fileDay + "/" + fileHour + "/",
                recordFile.getPath(), dataSource.replace("/", HIERARCHY_CONNECTOR) + "_" + fileDay + "_" + fileHour);
        // mark this directory for daily rotate
        addDirectory4Rolling(true, fileDay, fileHour, cluster, dataSource);
      } else if (fileName.endsWith(".R.evt")) {
        if (fileName.charAt(l - 11) == '_') {
          fileDay = Integer.parseInt(fileName.substring(l - 19, l - 11));
          fileHour = Integer.parseInt("" + fileName.charAt(l - 10));
          fileMin = Integer.parseInt(fileName.substring(l - 8, l - 6));
        } else {
          fileDay = Integer.parseInt(fileName.substring(l - 20, l - 12));
          fileHour = Integer.parseInt(fileName.substring(l - 11, l - 9));
          fileMin = Integer.parseInt(fileName.substring(l - 8, l - 6));
        }

        log.info("fileDay: " + fileDay);
        log.info("fileHour: " + fileHour);
        log.info("fileMin: " + fileMin);
        writeRecordFile(destDir + "/" + fileDay + "/" + fileHour + "/"
            + fileMin, recordFile.getPath(), HierarchyDataType.trimSlash(dataSource).replace("/", HIERARCHY_CONNECTOR) + "_" + fileDay + "_"
            + fileHour + "_" + fileMin);
        // mark this directory for hourly rotate
        addDirectory4Rolling(false, fileDay, fileHour, cluster, dataSource);
      } else {
        throw new RuntimeException("Wrong fileName format! [" + fileName + "]");
      }
    }
  }

  static void addDirectory4Rolling(boolean isDailyOnly, int day, int hour,
      String cluster, String dataSource) throws IOException {
    // TODO get root directory from config
    String rollingDirectory = "/chukwa/rolling/";

    Path path = new Path(rollingDirectory + "/daily/" + day + "/" + cluster
        + "/" + dataSource);
    if (!fs.exists(path)) {
      fs.mkdirs(path);
    }

    if (!isDailyOnly) {
      path = new Path(rollingDirectory + "/hourly/" + day + "/" + hour + "/"
          + cluster + "/" + dataSource);
      if (!fs.exists(path)) {
        fs.mkdirs(path);
      }
    }
  }

  static void writeRecordFile(String destDir, Path recordFile, String fileName)
      throws IOException {
    boolean done = false;
    int count = 1;
    do {
      Path destDirPath = new Path(destDir);
      Path destFilePath = new Path(destDir + "/" + fileName + "." + count
          + ".evt");

      if (!fs.exists(destDirPath)) {
        fs.mkdirs(destDirPath);
        log.info(">>>>>>>>>>>> create Dir" + destDirPath);
      }

      if (!fs.exists(destFilePath)) {
        log.info(">>>>>>>>>>>> Before Rename" + recordFile + " -- "
            + destFilePath);
        boolean rename = fs.rename(recordFile,destFilePath);
        done = true;
        log.info(">>>>>>>>>>>> after Rename" + destFilePath + " , rename:"+rename);
      }
      count++;

      if (count > 1000) {
        log.warn("too many files in this directory: " + destDir);
      }
    } while (!done);
  }

  static boolean checkRotate(String directoryAsString,
      boolean createDirectoryIfNotExist) throws IOException {
    Path directory = new Path(directoryAsString);
    boolean exist = fs.exists(directory);

    if (!exist) {
      if (createDirectoryIfNotExist == true) {
        fs.mkdirs(directory);
      }
      return false;
    } else {
      return fs.exists(new Path(directoryAsString + "/rotateDone"));
    }
  }

  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    conf = new ChukwaConfiguration();
    String fsName = conf.get("writer.hdfs.filesystem");
    fs = FileSystem.get(new URI(fsName), conf);

    Path srcDir = new Path(args[0]);
    String destDir = args[1];

    log.info("Start MoveToRepository main()");

    FileStatus fstat = fs.getFileStatus(srcDir);

    if (!fstat.isDir()) {
      throw new IOException(srcDir + " is not a directory!");
    } else {
      FileStatus[] clusters = fs.listStatus(srcDir);
      // Run a moveOrMerge on all clusters
      String name = null;
      for (FileStatus cluster : clusters) {
        name = cluster.getPath().getName();
        // Skip hadoop M/R outputDir
        if ((name.intern() == HadoopLogDir.intern())
            || (name.intern() == hadoopTempDir.intern())) {
          continue;
        }
        log
            .info("main procesing Cluster (" + cluster.getPath().getName()
                + ")");
        processClusterDirectory(cluster.getPath(), destDir + "/"
            + cluster.getPath().getName());

        // Delete the demux's cluster dir
        FileUtil.fullyDelete(fs, cluster.getPath());
      }
    }

    log.info("Done with MoveToRepository main()");

  }

}