text:
// <copyright company="Aspose Pty Ltd">
//   Copyright (C) 2011-2021 GroupDocs. All Rights Reserved.
// </copyright>

namespace GroupDocs.Metadata.Examples.CSharp.AdvancedUsage.WorkingWithMetadataStandards.Exif
{
    using Formats.Image;
    using Standards.Exif;

    public static class SetCustomExifTag
    {
        /// <summary>
        /// This code sample demonstrates how to add a custom tag to an EXIF package.
        /// </summary>
        public static void Run()
        {
            using (Metadata metadata = new Metadata(Constants.TiffWithExif))
            {
                IExif root = metadata.GetRootPackage() as IExif;
                if (root != null)
                {
                    // Set the EXIF package if it's missing
                    if (root.ExifPackage == null)
                    {
                        root.ExifPackage = new ExifPackage();
                    }

                    // Add a known property
                    root.ExifPackage.Set(new TiffAsciiTag(TiffTagID.Artist, "test artist"));

                    // Add a fully custom property (which is not described in the EXIF specification).
                    // Please note that the chosen ID may intersect with the IDs used by some third party tools.
                    root.ExifPackage.Set(new TiffAsciiTag((TiffTagID)65523, "custom"));

                    metadata.Save(Constants.OutputTiff);
                }
            }
        }
    }
}


text:
package org.scalajs.linker.interface

import org.junit.Test
import org.junit.Assert._

import Fingerprint._

class FingerprintBuilderTest {
  @Test
  def noFields(): Unit = {
    val fingerprint = new FingerprintBuilder("Test0").build()
    assertEquals("Test0()", fingerprint)
  }

  @Test
  def oneField(): Unit = {
    val fingerprint = new FingerprintBuilder("Test1")
      .addField("test1", true)
      .build()
    assertEquals("Test1(test1=true)", fingerprint)
  }

  @Test
  def multipleFields(): Unit = {
    val fingerprint = new FingerprintBuilder("Test2")
      .addField("test1", Some(1): Option[Int])
      .addField("test2", None: Option[Int])
      .addField("test3", List.empty[Int])
      .addField("test4", List(1, 2, 3))
      .build()
    assertEquals(
        "Test2(test1=Some(1),test2=None,test3=List(),test4=List(1,2,3))",
        fingerprint)
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.baliset.util;

import java.io.*;

public class WindowsCapabilities extends NoCapabilities
{

  @Override public String revealPathCapability()
  {
    return "Show in Explorer";
  }
  @Override public String openInBrowserCapability()
  {
    return "Open in Browser";
  }

  @Override public void revealPath(String path)
  {
    try {
      new ProcessBuilder("explorer", "/select,"+path).start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override public void openInBrowser(String path)
  {
    try {
      new ProcessBuilder("explorer", path).start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}


text:
#include "GMMEditor.h"
#include "MLEstimator.h"

namespace Bavieca {

// constructor
GMMEditor::GMMEditor(HMMManager *hmmManager, MAccumulatorPhysical *mAccumulatorPhysical)
{
	m_hmmManager = hmmManager;
	m_mAccumulatorPhysical = mAccumulatorPhysical;
	m_iDim = hmmManager->getFeatureDimensionality();
	m_iCovarianceModeling = hmmManager->getCovarianceModelling();
	m_iCovarianceElements = HMMManager::getCovarianceElements(m_iDim,m_iCovarianceModeling);
	m_iHMMStates = -1;
	m_hmmStates = hmmManager->getHMMStates(&m_iHMMStates);
}

// destructor
GMMEditor::~GMMEditor()
{
	if (m_mGaussianInfo != NULL) {
		delete [] m_mGaussianInfo;
	}
}

// initialize the editor
void GMMEditor::initialize() {

	m_mGaussianInfo = new MGaussianInfo[m_iHMMStates];
	int iHMMState = -1;
	int iGaussian = -1;
	for(MAccumulatorPhysical::iterator it = m_mAccumulatorPhysical->begin() ; it != m_mAccumulatorPhysical->end() ; ++it) {
		Accumulator::getPhysicalAccumulatorValues(it->first,iHMMState,iGaussian);
		GaussianInfo gaussianInfo;
		gaussianInfo.dOccupation = it->second->getOccupation();
		gaussianInfo.bMerged = false;
		m_mGaussianInfo[iHMMState].insert(MGaussianInfo::value_type(m_hmmStates[iHMMState]->getMixture()(iGaussian),gaussianInfo));
	}
}

// merge Gaussian components in the mixture
void GMMEditor::mixtureMerge(float fMinimumGaussianOccupation, float fMinimumGaussianWeight, float fCovarianceFlooringRatio) {

	// compute the covariance floor
	Vector<double> vCovarianceFloor(m_iDim);
	MLEstimator::computeCovarianceFloor(m_hmmManager,*m_mAccumulatorPhysical,
		fCovarianceFlooringRatio,vCovarianceFloor);

	for(int i=0 ; i < m_iHMMStates ; ++i) {
		mixtureMerge(m_hmmStates[i],fMinimumGaussianOccupation,fMinimumGaussianWeight,vCovarianceFloor);
	}
}

// merge Gaussian components with not enough training data associated
// when a Gaussian is split into two gaussians, and the parameters of the newly created
// Gaussian components are reestimated (iteration), it is possible that one of the gaussians
// has very low occupation, in that case we need to merge that Gaussian to the closest one
void GMMEditor::mixtureMerge(HMMState *hmmState, float fMinimumGaussianOccupation,
	float fMinimumGaussianWeight, Vector<double> &vCovarianceFloor) {

	assert(hmmState->getMixture().getNumberComponents() >= 1);

	MGaussianInfo &mGaussianInfo = m_mGaussianInfo[hmmState->getId()];

	// check that there are multiple Gaussian components
	if (hmmState->getMixture().getNumberComponents() == 1) {
		mGaussianInfo[hmmState->getMixture()(0)].bMerged = false;
		return;
	}

	// allocate memory for the accumulators
	Vector<float> vMean(m_iDim);
	Vector<float> vCovariance(m_iDim);

	// (1) find Gaussian components with occupation/weight below the threshold and merge them to the nearest one
	bool bMerged = false;
	do {
		bMerged = false;
		for(unsigned int g = 0 ; g < hmmState->getMixture().getNumberComponents() ; ++g) {
			Gaussian *gaussian1 = hmmState->getMixture()(g);
			GaussianInfo *gaussianInfo1 = &mGaussianInfo[gaussian1];
			if ((gaussianInfo1->dOccupation < fMinimumGaussianOccupation) ||
				(gaussian1->weight() < fMinimumGaussianWeight)) {
				int iGaussianClosest = -1;
				// case 1: a single Gaussian (it can happen after all the Gaussian components are merged to one)
				if (hmmState->getMixture().getNumberComponents() == 1) {
					// warning: the HMM-state has just one Gaussian with little data, it will be poorly estimated
					break;
				}
				// case 2: two Gaussian components, there is no need to compute the distance, just merge them
				else if (hmmState->getMixture().getNumberComponents() == 2) {
					iGaussianClosest = (g+1)%2;
				}
				// case 3: more than two Gaussian -> find the closest gaussian to the poorly trained one
				else {
					// compute the determinant of the covariance matrix of the Gaussian to merge
					double dCovarianceDet1 = gaussian1->covarianceDiag().sumLog();
					// find the closest gaussian
					double dDistanceSmallest = DBL_MAX;
					for(unsigned int h = 0 ; h < hmmState->getMixture().getNumberComponents() ; ++h) {
						if (h == g) {
							continue;
						}
						Gaussian *gaussian2 = hmmState->getMixture()(h);
						GaussianInfo *gaussianInfo2 = &mGaussianInfo[gaussian2];
						// compute the distance between the gaussians
						// determinant of the second gaussian
						double dCovarianceDet2 = gaussian2->covarianceDiag().sumLog();
						// compute the counts
						double dDenominator = gaussianInfo1->dOccupation+gaussianInfo2->dOccupation;
						double d1 = gaussianInfo1->dOccupation/dDenominator;
						double d2 = gaussianInfo2->dOccupation/dDenominator;
						// compute the determinant of the covariance matrix resulting from merging both gaussians
						double dCovarianceDetMerged = 0.0;
						for(int i = 0 ; i < m_iDim ; ++i) {
							dCovarianceDetMerged += log((d1*gaussian1->covarianceDiag()(i))+(d2*gaussian2->covarianceDiag()(i))+(d1*d2*(   (gaussian1->mean()(i)-gaussian2->mean()(i))*(gaussian1->mean()(i)-gaussian2->mean()(i)))));
						}
						// compute the distance
						double dDistance = (((gaussianInfo1->dOccupation+gaussianInfo2->dOccupation)/2.0)*dCovarianceDetMerged) - ((gaussianInfo1->dOccupation/2.0)*dCovarianceDet1) - ((gaussianInfo2->dOccupation/2.0)*dCovarianceDet2);
						assert(finite(dDistance));
						if (dDistance <= dDistanceSmallest) {
							dDistanceSmallest = dDistance;
							iGaussianClosest = h;
						}
					}
				}
				// (3) merge the "less-robust" gaussian with the closest one
				assert(iGaussianClosest != -1);
				// merge the gaussians
				int h = iGaussianClosest;
				assert(g != (unsigned int)h);
				Gaussian *gaussian2 = hmmState->getMixture()(h);
				GaussianInfo *gaussianInfo2 = &mGaussianInfo[gaussian2];
				// compute the counts
				double dDenominator = gaussianInfo1->dOccupation+gaussianInfo2->dOccupation;
				double d1 = gaussianInfo1->dOccupation/dDenominator;
				double d2 = gaussianInfo2->dOccupation/dDenominator;
				// compute the new mean and covariance
				vMean.zero();
				vMean.add((float)d1,gaussian1->mean());
				vMean.add((float)d2,gaussian2->mean());
				vCovariance.zero();
				vCovariance.add((float)d1,gaussian1->covarianceDiag());
				vCovariance.add((float)d2,gaussian2->covarianceDiag());
				Vector<float> vAux(gaussian1->mean());
				vAux.add(-1.0,gaussian2->mean());
				vAux.squareElements();
				vCovariance.add((float)(d1*d2),vAux);
				vCovariance.floor(vCovarianceFloor);
				// copy the mean and covariance
				gaussian1->mean().copy(vMean);
				gaussian1->covarianceDiag().copy(vCovariance);
				// compute the new weight
				gaussian1->weight() += gaussian2->weight();
				// accumulate occupancy (this is an iterative bottom-up clustering, occupancy might still be below threshold)
				gaussianInfo1->dOccupation += gaussianInfo2->dOccupation;
				// mark the new gaussian as "merged" so it wont be split next
				gaussianInfo1->bMerged = true;
				// remove the gaussian component
				hmmState->getMixture().removeGaussianComponent(h);
				mGaussianInfo.erase(mGaussianInfo.find(gaussian2));
				bMerged = true;
				break;
			}
		}
	} while(bMerged);

	assert(mGaussianInfo.size() == hmmState->getMixture().getNumberComponents());

	// sanity check: make sure all the gaussians have an occupancy and weight above the threshold
	if (hmmState->getMixture().getNumberComponents() > 1) {
		for(unsigned int g = 0 ; g < hmmState->getMixture().getNumberComponents() ; ++g) {
			Gaussian *gaussian = hmmState->getMixture()(g);
			GaussianInfo *gaussianInfo = &mGaussianInfo[gaussian];
			assert(gaussian->weight() >= fMinimumGaussianWeight);
			assert(gaussianInfo->dOccupation >= fMinimumGaussianOccupation);
		}
	}
}

// add Gaussian components to each mixture
int GMMEditor::mixtureIncrement(int iIncrement, int iSplittingCriterion,
	bool bAllowMultipleSplitsPerComponent, float fMinimumGaussianOccupation, float fSplittingEpsilon) {

	int iOriginal = 0;
	int iAdded = 0;
	for(int i=0 ; i < m_iHMMStates ; ++i) {
		iOriginal += m_hmmStates[i]->getMixture().getNumberComponents();
		iAdded += mixtureIncrement(m_hmmStates[i],iIncrement,iSplittingCriterion,bAllowMultipleSplitsPerComponent,
			fMinimumGaussianOccupation,fSplittingEpsilon);
	}

	if (iAdded > 0) {
		m_hmmManager->setSingleGaussian(false);
	}

	return iAdded;
}

// double the number of Gaussian components in the mixture (if possible)
int GMMEditor::mixtureDouble(float fMinimumGaussianOccupation, float fSplittingEpsilon) {

	int iOriginal = 0;
	int iAdded = 0;
	for(int i=0 ; i < m_iHMMStates ; ++i) {
		iOriginal += m_hmmStates[i]->getMixture().getNumberComponents();
		iAdded += mixtureDouble(m_hmmStates[i],fMinimumGaussianOccupation,fSplittingEpsilon);
	}

	if (iAdded > 0) {
		m_hmmManager->setSingleGaussian(false);
	}

	return iAdded;
}

// add a Gaussian to the mixture that models the emission probability of the state
// note: there is no need to floor the covariance of the new components, since they stay the same
int GMMEditor::mixtureIncrement(HMMState *hmmState, int iIncrement, int iSplittingCriterion,
	bool bAllowMultipleSplitsPerComponent, float fMinimumGaussianOccupation, float fSplittingEpsilon) {

	assert(hmmState->getMixture().getNumberComponents() > 0);
	assert(iIncrement > 0);

	MGaussianInfo &mGaussianInfo = m_mGaussianInfo[hmmState->getId()];
	int iAdded = 0;			// number of components already added to the mixture

	// initialize splitting weights if needed
	if (iSplittingCriterion == SPLITTING_CRITERION_HEAVIEST_MIXTURE_COMPONENT) {
		for(unsigned int m = 0 ; m < hmmState->getMixture().getNumberComponents() ; ++m) {
			Gaussian *gaussian = hmmState->getMixture()(m);
			// the weight for mixture increment determines which Gaussian will be split next
			// a Gaussian that has already been split gets its weight substracted by one, what makes it
			// very unlikely to be split again
			gaussian->weightMixtureIncrement() = gaussian->weight();
		}
	}

	while(iAdded < iIncrement) {

		int iGaussianToSplit = 0;
		// case 1: there are multiple gaussians: select the mixture to split
		if (hmmState->getMixture().getNumberComponents() > 1) {
			iGaussianToSplit = -1;
			switch(iSplittingCriterion) {
				case SPLITTING_CRITERION_LARGEST_AVERAGE_VARIANCE: {
					double dGeometricMean = 0.0;
					double dGeometricMeanHighest = -DBL_MAX;
					// for each gaussian compute the geometric mean of the variance
					for(unsigned int m = 0 ; m < hmmState->getMixture().getNumberComponents() ; ++m) {
						Gaussian *gaussian = hmmState->getMixture()(m);
						GaussianInfo *gaussianInfo = &mGaussianInfo[gaussian];
						// do not split gaussians that were just merged
						if (gaussianInfo->bMerged) {
							continue;
						}
						// the occupation must be at least two times the minimum gaussian occupation
						if (gaussianInfo->dOccupation < 2.0*fMinimumGaussianOccupation) {
							continue;
						}
						// compute the geometric mean of the covariance (log-average)
						dGeometricMean = gaussian->covarianceDiag().sumLog();
						dGeometricMean /= ((float)m_iDim);
						dGeometricMean = exp(dGeometricMean);
						// check if the geometic mean of the covariance is the largest one so far
						if (dGeometricMean > dGeometricMeanHighest) {
							dGeometricMeanHighest = dGeometricMean;
							iGaussianToSplit = m;
						}
					}
					break;
				}
				case SPLITTING_CRITERION_HEAVIEST_MIXTURE_COMPONENT: {
					// find the heaviest mixture
					float fWeightMax = -FLT_MAX;
					int iComponentHeaviest = -1;
					for(unsigned int m = 0 ; m < hmmState->getMixture().getNumberComponents() ; ++m) {
						Gaussian *gaussian = hmmState->getMixture()(m);
						GaussianInfo *gaussianInfo = &mGaussianInfo[gaussian];
						// do not split gaussians that were just merged
						if (gaussianInfo->bMerged) {
							continue;
						}
						// the occupation must be at least two times the minimum gaussian occupation
						if (gaussianInfo->dOccupation < 2.0*fMinimumGaussianOccupation) {
							continue;
						}
						// find the heaviest mixture
						if (gaussian->weightMixtureIncrement() > fWeightMax) {
							iComponentHeaviest = m;
							fWeightMax = gaussian->weightMixtureIncrement();
						}
					}
					if (iComponentHeaviest != -1) {
						hmmState->getMixture()(iComponentHeaviest)->weightMixtureIncrement()--;
						iGaussianToSplit = iComponentHeaviest;
					}
					break;
				}
				default: {
					assert(0);
				}
			}
			// finish in case there are no mixtures to split
			if (iGaussianToSplit == -1) {
				return iAdded;
			}
		}
		// case 2: just one Gaussian: it will be splitted, just check that the occupation count is big enough
		else {
			assert(hmmState->getMixture().getNumberComponents() == 1);
			GaussianInfo *gaussianInfo = &mGaussianInfo[hmmState->getMixture()(0)];
			// do not split Gaussian components that were just merged
			if (gaussianInfo->bMerged) {
				return iAdded;
			}
			// the occupation must be at least two times the minimum Gaussian occupation
			if (gaussianInfo->dOccupation < 2*fMinimumGaussianOccupation) {
				return iAdded;
			}
		}

		Gaussian *gaussianToSplit = hmmState->getMixture()(iGaussianToSplit);
		GaussianInfo *gaussianToSplitInfo = &mGaussianInfo[gaussianToSplit];
		GaussianInfo gaussianInfo;
		gaussianInfo.bMerged = false;
		gaussianInfo.dOccupation = 0.0;
		assert(gaussianToSplitInfo->dOccupation >= 2*fMinimumGaussianOccupation);

		// (2) split the mixture by creating two new mixtures, the new mixtures have a perturbed mean (+/-0.X standard deviations), identical variance and half the weight
		Gaussian *gaussian = new Gaussian(m_iDim,m_hmmManager->getCovarianceModelling());
		// mark both Gaussian components as merged so in case that multiple splits are
		// done we do not split a Gaussian that results from a split
		if (bAllowMultipleSplitsPerComponent == false) {
			gaussianInfo.bMerged = true;
			gaussianToSplitInfo->bMerged = true;
		}
		// compute the new mean and keep the covariance identical
		Vector<double> vPerturbation(gaussianToSplit->covarianceDiag());
		vPerturbation.sqrt();
		gaussian->mean().copy(gaussianToSplit->mean());
		gaussian->mean().add(1.0f*fSplittingEpsilon,vPerturbation);
		gaussianToSplit->mean().add(-1.0f*fSplittingEpsilon,vPerturbation);
		gaussian->covarianceDiag().copy(gaussianToSplit->covarianceDiag());
		// divide the weight and occupation by two
		gaussianToSplit->weight() /= 2.0;
		gaussianToSplitInfo->dOccupation /= 2.0;
		gaussian->weight() = gaussianToSplit->weight();
		gaussianInfo.dOccupation = gaussianToSplitInfo->dOccupation;
		hmmState->getMixture().addGaussianComponent(gaussian);
		mGaussianInfo.insert(MGaussianInfo::value_type(gaussian,gaussianInfo));
		++iAdded;
	}

	assert(hmmState->getMixture().getNumberComponents() == mGaussianInfo.size());

	return iAdded;
}

// double the number of Gaussian components in the mixture
// there is no need to select which Gaussian components will be split, since all of them will (except those
// that were just merged or dont have enough occupation)
int GMMEditor::mixtureDouble(HMMState *hmmState, float fMinimumGaussianOccupation, float fSplittingEpsilon) {

	assert(hmmState->getMixture().getNumberComponents() > 0);
	int iAdded = 0;

	MGaussianInfo &mGaussianInfo = m_mGaussianInfo[hmmState->getId()];

	// split all the Gaussian components except those that were just merged
	int iGaussiansOriginal = hmmState->getMixture().getNumberComponents();
	for(int g = 0 ; g < iGaussiansOriginal ; ++g) {

		Gaussian *gaussian1 = hmmState->getMixture()(g);
		GaussianInfo *gaussianInfo1 = &mGaussianInfo[gaussian1];

		// skip components with not enough occupation or those that were just merged
		if ((gaussianInfo1->dOccupation < 2.0f*fMinimumGaussianOccupation) ||
			(gaussianInfo1->bMerged)) {
			continue;
		}

		// split the mixture by creating two new mixtures, the new mixtures have a perturbed mean (+/-0.X standard deviations), identical variance and half the weight
		Gaussian *gaussian2 = new Gaussian(m_iDim,m_hmmManager->getCovarianceModelling());
		GaussianInfo gaussianInfo2;
		gaussianInfo2.bMerged = false;
		gaussianInfo2.dOccupation = 0.0;
		// compute the new mean and keep the covariance identical
		Vector<double> vPerturbation(gaussian1->covarianceDiag());
		vPerturbation.sqrt();
		gaussian2->mean().copy(gaussian1->mean());
		gaussian2->mean().add(1.0f*fSplittingEpsilon,vPerturbation);
		gaussian1->mean().add(-1.0f*fSplittingEpsilon,vPerturbation);
		gaussian2->covarianceDiag().copy(gaussian1->covarianceDiag());
		gaussian1->weight() /= 2.0f;
		gaussianInfo1->dOccupation /= 2.0f;
		gaussian2->weight() = gaussian1->weight();
		gaussianInfo2.dOccupation = gaussianInfo1->dOccupation;
		hmmState->getMixture().addGaussianComponent(gaussian2);
		mGaussianInfo.insert(MGaussianInfo::value_type(gaussian2,gaussianInfo2));
		++iAdded;
	}

	assert(hmmState->getMixture().getNumberComponents() == mGaussianInfo.size());

	return iAdded;
}

};	// end-of-namespace


text:
 File Brew

Overview

Sending files over the internet is hard. File Brew makes it easy. Users can send files to each other peer to peer using just their browsers. Just drop in a file, and send your friend a link! File Brew will be built using WebTorrent, turning your browser into a client on a peer-to-peer network!

Site Map

* Send File
* Receive File

User Stories

1. As a user, I can send a file by dropping a file and sending a link.

Research Topics

WebTorrent

Use WebTorrent, a BitTorrent client in the browser written using the WebRTC API. A user can turn their browser into a peer on the network by dropping a file into their browser. A magnet link is created and will be sent to the server to be hashed and turned into a URI that references the file.

React

The page will be built using React components. This includes the page overlay, drop-zone, coffee cup image, and progress bar.

AJAX

I will use AJAX to send asynchronous requests to the server for hashing, or magnet link retrieval.

Redis

I will be using Redis as a durable, in memory key-value store from hashes to magnet URIs.

Heroku

I will be using Heroku to host this site.


text:
/*!
    \file  gd32f1x0_dbg.c
    \brief dbg driver
*/

/*
    Copyright (C) 2016 GigaDevice

    2014-12-26, V1.0.0, firmware for GD32F1x0(x=3,5)
    2016-01-15, V2.0.0, firmware for GD32F1x0(x=3,5,7,9)
    2016-04-30, V3.0.0, firmware update for GD32F1x0(x=3,5,7,9)
*/

#include "gd32f1x0_dbg.h"

/*!
    \brief      read DBG_ID code register
    \param[in]  none
    \param[out] none
    \retval     DBG_ID code
*/
uint32_t dbg_id_get(void)
{
    return DBG_ID;
}

/*!
    \brief      enable DBG_CTL0 peripheral behavior when the mcu is in debug mode
    \param[in]  dbg_ctl0_periph: DBG_CTL0 peripheral
                for gd32f130 or gd32f150 devices, this parameter can be any combination of
                the following values:
      \arg        DBG_CTL0_SLEEP_HOLD: keep debugger connection during sleep mode
      \arg        DBG_CTL0_DEEPSLEEP_HOLD: keep debugger connection during deepsleep mode
      \arg        DBG_CTL0_STDBY_HOLD: keep debugger connection during standby mode
      \arg        DBG_CTL0_FWDGT_HOLD: debug fwdgt kept when core is halted
      \arg        DBG_CTL0_WWDGT_HOLD: debug wwdgt kept when core is halted
      \arg        DBG_CTL0_TM0_HOLD: timer0 counter kept when core is halted
      \arg        DBG_CTL0_TM1_HOLD: timer1 counter kept when core is halted
      \arg        DBG_CTL0_TM2_HOLD: timer2 counter kept when core is halted
      \arg        DBG_CTL0_I2C0_HOLD: hold i2c0 smbus when core is halted
      \arg        DBG_CTL0_I2C1_HOLD: hold i2c1 smbus when core is halted
      \arg        DBG_CTL0_I2C2_HOLD: hold i2c2 smbus when core is halted
      \arg        DBG_CTL0_TM5_HOLD: hold timer5 counter when core is halted
      \arg        DBG_CTL0_TM13_HOLD: hold timer13 counter when core is halted

                for  gd32f170 or gd32f190 devices, this parameter can be any combination of
                the following values:
      \arg        DBG_CTL0_SLEEP_HOLD: keep debugger connection during sleep mode
      \arg        DBG_CTL0_DEEPSLEEP_HOLD: keep debugger connection during deepsleep mode
      \arg        DBG_CTL0_STDBY_HOLD: keep debugger connection during standby mode
      \arg        DBG_CTL0_FWDGT_HOLD: debug fwdgt kept when core is halted
      \arg        DBG_CTL0_WWDGT_HOLD: debug wwdgt kept when core is halted
      \arg        DBG_CTL0_TM0_HOLD: timer0 counter kept when core is halted
      \arg        DBG_CTL0_TM1_HOLD: timer1 counter kept when core is halted
      \arg        DBG_CTL0_TM2_HOLD: timer2 counter kept when core is halted
      \arg        DBG_CTL0_CAN0_HOLD: can0 counter kept when core is halted
      \arg        DBG_CTL0_I2C0_HOLD: hold i2c0 smbus when core is halted
      \arg        DBG_CTL0_I2C1_HOLD: hold i2c1 smbus when core is halted
      \arg        DBG_CTL0_I2C2_HOLD: hold i2c2 smbus when core is halted
      \arg        DBG_CTL0_TM5_HOLD: hold timer5 counter when core is halted
      \arg        DBG_CTL0_CAN1_HOLD: hold can1 counter when core is halted
      \arg        DBG_CTL0_TM13_HOLD: hold timer13 counter when core is halted
    \param[out] none
    \retval     none
*/
void dbg_ctl0_periph_enable(uint32_t dbg_ctl0_periph)
{
    DBG_CTL0 |= dbg_ctl0_periph;
}

/*!
    \brief      disable DBG_CTL0 peripheral behavior when the mcu is in debug mode
    \param[in]  dbg_ctl0_periph: DBG_CTL0 peripheral
                for gd32f130 or gd32f150 devices, this parameter can be any combination of
                the following values:
        \arg      DBG_CTL0_SLEEP_HOLD: keep debugger disconnection during sleep mode
        \arg      DBG_CTL0_DEEPSLEEP_HOLD: keep debugger disconnection during deepsleep mode
        \arg      DBG_CTL0_STDBY_HOLD: keep debugger disconnection during standby mode
        \arg      DBG_CTL0_FWDGT_HOLD: debug fwdgt is not kept when core is halted
        \arg      DBG_CTL0_WWDGT_HOLD: debug wwdgt is not kept when core is halted
        \arg      DBG_CTL0_TM0_HOLD: timer0 counter is not kept when core is halted
        \arg      DBG_CTL0_TM1_HOLD: timer1 counter is not kept when core is halted
        \arg      DBG_CTL0_TM2_HOLD: timer2 counter is not kept when core is halted
        \arg      DBG_CTL0_I2C0_HOLD: donot hold i2c0 smbus when core is halted
        \arg      DBG_CTL0_I2C1_HOLD: donot hold i2c1 smbus when core is halted
        \arg      DBG_CTL0_I2C2_HOLD: donot hold i2c2 smbus when core is halted
        \arg      DBG_CTL0_TM5_HOLD: donot hold timer5 counter when core is halted
        \arg      DBG_CTL0_TM13_HOLD: donot hold timer13 counter when core is halted

                for gd32f170 or gd32f190 devices, this parameter can be any combination of
                the following values:
        \arg      DBG_CTL0_SLEEP_HOLD: keep debugger disconnection during sleep mode
        \arg      DBG_CTL0_DEEPSLEEP_HOLD: keep debugger disconnection during deepsleep mode
        \arg      DBG_CTL0_STDBY_HOLD: keep debugger disconnection during standby mode
        \arg      DBG_CTL0_FWDGT_HOLD: debug fwdgt is not kept when core is halted
        \arg      DBG_CTL0_WWDGT_HOLD: debug wwdgt is not kept when core is halted
        \arg      DBG_CTL0_TM0_HOLD: timer0 counter is not kept when core is halted
        \arg      DBG_CTL0_TM1_HOLD: timer1 counter is not kept when core is halted
        \arg      DBG_CTL0_TM2_HOLD: timer2 counter is not kept when core is halted
        \arg      DBG_CTL0_CAN0_HOLD: can0 counter is not kept when core is halted
        \arg      DBG_CTL0_I2C0_HOLD: donot hold i2c0 SMBUS when core is halted
        \arg      DBG_CTL0_I2C1_HOLD: donot hold i2c1 SMBUS when core is halted
        \arg      DBG_CTL0_I2C2_HOLD: donot hold i2c2 SMBUS when core is halted
        \arg      DBG_CTL0_TM5_HOLD: donot hold timer5 counter when core is halted
        \arg      DBG_CTL0_CAN1_HOLD: donot hold can1 counter when core is halted
        \arg      DBG_CTL0_TM13_HOLD: donot hold timer13 counter when core is halted
    \param[out] none
    \retval     none
*/
void dbg_ctl0_periph_disable(uint32_t dbg_ctl0_periph)
{
    DBG_CTL0 &= ~dbg_ctl0_periph;
}

/*!
    \brief      enable DBG_CTL1 peripheral behavior when the mcu is in debug mode
    \param[in]  dbg_ctl1_periph: DBG_CTL1 peripheral
      \arg        DBG_CTL1_RTC_HOLD: hold rtc calendar and wakeup counter when core is halted
      \arg        DBG_CTL1_TM14_HOLD: hold timer14 counter when core is halted
      \arg        DBG_CTL1_TM15_HOLD: hold timer15 counter when core is halted
      \arg        DBG_CTL1_TM16_HOLD: hold timer16 counter when core is halted
    \param[out] none
    \retval     none
*/
void dbg_ctl1_periph_enable(uint32_t dbg_ctl1_periph)
{
    DBG_CTL1 |= dbg_ctl1_periph;
}

/*!
    \brief      disable DBG_CTL1 peripheral behavior when the mcu is in debug mode
    \param[in]  dbg_ctl1_periph: DBG_CTL1 peripheral
      \arg      DBG_CTL1_RTC_HOLD: donot hold rtc calendar and wakeup counter when core is halted
      \arg      DBG_CTL1_TM14_HOLD: donot hold timer14 counter when core is halted
      \arg      DBG_CTL1_TM15_HOLD: donot hold timer15 counter when core is halted
      \arg      DBG_CTL1_TM16_HOLD: donot hold timer16 counter when core is halted
    \param[out] none
    \retval     none
*/
void dbg_ctl1_periph_disable(uint32_t dbg_ctl1_periph)
{
    DBG_CTL1 &= ~dbg_ctl1_periph;
}


text:
__author__ = 'max'

from instance import DependencyInstance
import data_utils

class CoNLLReader(object):
    def __init__(self, file_path, word_alphabet, char_alphabet, pos_alphabet, type_alphabet):
        self.__source_file = open(file_path, 'r')
        self.__word_alphabet = word_alphabet
        self.__char_alphabet = char_alphabet
        self.__pos_alphabet = pos_alphabet
        self.__type_alphabet = type_alphabet

    def close(self):
        self.__source_file.close()

    def getNext(self, normalize_digits=True):
        lines = []
        line = self.__source_file.readline()
        while line is not None and len(line.strip()) > 0:
            line = line.strip()
            line = line.decode('utf-8')
            lines.append(line.split('\t'))
            line = self.__source_file.readline()

        length = len(lines)
        if length == 0:
            return None

        words = []
        word_ids = []
        char_seqs = []
        char_id_seqs = []
        postags = []
        pos_ids = []
        types = []
        type_ids = []
        heads = []

        words.append(data_utils.ROOT)
        word_ids.append(self.__word_alphabet.get_index(data_utils.ROOT))
        char_seqs.append([data_utils.ROOT_CHAR,])
        char_id_seqs.append([self.__char_alphabet.get_index(data_utils.ROOT_CHAR),])
        postags.append(data_utils.ROOT_POS)
        pos_ids.append(self.__pos_alphabet.get_index(data_utils.ROOT_POS))
        types.append(data_utils.ROOT_TYPE)
        type_ids.append(self.__type_alphabet.get_index(data_utils.ROOT_TYPE))
        heads.append(-1)

        for tokens in lines:
            chars = []
            char_ids = []
            for char in tokens[1]:
                chars.append(char)
                char_ids.append(self.__char_alphabet.get_index(char))
            if len(chars) > data_utils.MAX_CHAR_LENGTH:
                chars = chars[:data_utils.MAX_CHAR_LENGTH]
                char_ids = char_ids[:data_utils.MAX_CHAR_LENGTH]
            char_seqs.append(chars)
            char_id_seqs.append(char_ids)

            word = data_utils.DIGIT_RE.sub(b"0", tokens[1]) if normalize_digits else tokens[1]
            pos = tokens[4]
            head = int(tokens[6])
            type = tokens[7]

            words.append(word)
            word_ids.append(self.__word_alphabet.get_index(word))

            postags.append(pos)
            pos_ids.append(self.__pos_alphabet.get_index(pos))

            types.append(type)
            type_ids.append(self.__type_alphabet.get_index(type))

            heads.append(head)

        return DependencyInstance(words, word_ids, char_seqs, char_id_seqs, postags, pos_ids, heads, types, type_ids)


text:
package jlibs.nio.http.msg;

import jlibs.core.lang.ImpossibleException;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

/**
 * @author Santhosh Kumar Tekuri
 */
public class SOAP11FaultPayload extends EncodablePayload{
    public final Throwable thr;
    public final boolean showStackTrace;
    public SOAP11FaultPayload(Throwable thr, boolean showStackTrace){
        super("text/xml; charset=UTF-8");
        this.thr = thr;
        this.showStackTrace = showStackTrace;
    }

    private static XMLOutputFactory factory = XMLOutputFactory.newInstance();
    private static final String PREFIX = "soap";
    private static final String URI = "http://schemas.xmlsoap.org/soap/envelope/";

    protected String getFaultActor(){
        return "";
    }

    protected String getErrorCode(Throwable detail){
        return detail.getMessage()==null ? detail.getClass().getSimpleName() : detail.getMessage();
    }

    @Override
    public void writeTo(OutputStream out) throws IOException{
        Status status = thr instanceof Status ? (Status)thr : Status.INTERNAL_SERVER_ERROR;
        Throwable detail = thr;
        if(thr instanceof Status && thr.getCause()!=null)
            detail = thr.getCause();

        String faultCode = status.isClientError() ? "soap:Client" : "soap:Server";
        String faultString = status.getMessage();
        String faultActor = getFaultActor();
        String errorCode = getErrorCode(detail);

        XMLStreamWriter xml = null;
        try{
            xml = factory.createXMLStreamWriter(out);
            xml.writeStartDocument();

            xml.writeStartElement(PREFIX, "Envelope", URI);
            xml.setPrefix(PREFIX, URI);
            xml.writeNamespace(PREFIX, URI);
            xml.writeAttribute(PREFIX, URI, "encodingStyle", "http://schemas.xmlsoap.org/soap/encoding/");
            xml.writeStartElement(PREFIX, "Body", URI);
            xml.writeStartElement(PREFIX, "Fault", URI);
            xml.writeStartElement("faultcode");
            xml.writeCharacters(faultCode);
            xml.writeEndElement();

            xml.writeStartElement("faultstring");
            xml.writeCharacters(faultString);
            xml.writeEndElement();

            xml.writeStartElement("faultactor");
            xml.writeCharacters(faultActor);
            xml.writeEndElement();

            xml.writeStartElement("detail");
            xml.writeStartElement("source");
            xml.writeStartElement("errorcode");
            xml.writeCharacters(errorCode);
            xml.writeEndElement(/*errorcode*/);

            if(detail!=null && showStackTrace){
                xml.writeStartElement("trace");
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(bout);
                thr.printStackTrace(ps);
                ps.close();
                xml.writeCharacters(bout.toString());
                xml.writeEndElement();
            }

            xml.writeEndElement(/*source*/);
            xml.writeEndElement(/*detail*/);
            xml.writeEndElement(/*Fault*/);
            xml.writeEndElement(/*Body*/);
            xml.writeEndElement(/*Envelope*/);
            xml.writeEndDocument();
            xml.close();
        }catch(XMLStreamException ex){
            throw new ImpossibleException(ex);
        }finally{
            try{
                if(xml!=null)
                    xml.close();
            }catch(XMLStreamException ex){
                throw new ImpossibleException(ex);
            }
        }
    }
}


text:
#import <iWorkImport/TSCH3DGLFBO.h>

@interface TSCH3DGLFBO (TSCH3DGLESLayerFBO)
+ (id)FBOFromContext:(id)arg1 attributes:(const struct FramebufferAttributes *)arg2 eaglLayer:(id)arg3;
@end


text:
require 'i18n/hygiene/key_usage_checker'

describe I18n::Hygiene::KeyUsageChecker do

  let(:checker_instance) do
    I18n::Hygiene::KeyUsageChecker.new(
      directories: ["you", "only", "yolo", "once"]
    )
  end

  describe '#used?' do
    context "shelling out" do
      context "not excluding files" do
        before do
          expect(checker_instance).to receive(:`).with("grep --recursive my.key you only yolo once | wc -l").and_return(wc_result)
        end

        context "wc is zero" do
          let(:wc_result) { "0" }

          it "returns false" do
            expect(checker_instance.used?("my.key")).to eql false
          end

          context "key with recongised plural suffix" do
            it "chops plural suffix off and returns false" do
              expect(checker_instance).to receive(:fully_qualified_key_used?).with("my.key.zero").and_call_original.ordered
              expect(checker_instance).to receive(:fully_qualified_key_used?).with("my.key").and_call_original.ordered
              expect(checker_instance.used?("my.key.zero")).to eql false
            end
          end
        end

        context "wc is greater than zero" do
          let(:wc_result) { "3" }

          it "returns true" do
            expect(checker_instance.used?("my.key")).to eql true
          end

          context "key with recongised plural suffix" do
            it "chops plural suffix off and returns true" do
              expect(checker_instance).to receive(:fully_qualified_key_used?).with("my.key.zero").and_call_original.ordered
              expect(checker_instance).to receive(:fully_qualified_key_used?).with("my.key").and_call_original.ordered
              expect(checker_instance.used?("my.key.zero")).to eql true
            end
          end
        end
      end

      context "excluding files" do
        let(:checker_instance) do
          I18n::Hygiene::KeyUsageChecker.new(
            directories: ["app"],
            exclude_files: ["ignored.file"]
          )
        end

        it "excludes the expected file(s)" do
          expect(checker_instance).to receive(:`).with("grep --recursive my.key --exclude=\"ignored.file\" app | wc -l").and_return("1")

          checker_instance.used?("my.key")
        end
      end

      context "provided file extensions" do
        let(:checker_instance) do
          I18n::Hygiene::KeyUsageChecker.new(
            directories: ["app"],
            file_extensions: ["rb", "jsx"]
          )
        end

        it "only looks in files that are in the given directories which have the given file extensions" do
          expect(checker_instance).to receive(:`).with("grep --recursive my.key --include=\"*.rb\" --include=\"*.jsx\" app | wc -l").and_return("1")

          checker_instance.used?("my.key")
        end
      end
    end
  end
end


text:
package org.gol;

import static org.assertj.core.api.Assertions.assertThat;
import static org.gol.util.NeighboursGenerator.generateNeighboursWithNumberOfAliveCell;

import java.util.Collection;
import java.util.Collections;

import org.gol.rules.Action;
import org.gol.rules.IRule;
import org.gol.rules.UnderPopulationRule;
import org.junit.Test;

public class UnderPopulationRuleTest {
	private IRule rule = new UnderPopulationRule();

	@Test
	public void givenAliveCellWithNoAliveNeighboursCellShouldDie() {
		Collection<Cell> neighbours = generateNeighboursWithNumberOfAliveCell(0);

		Action result = rule.whatNext(Cell.ALIVE(), neighbours);

		assertThat(result).isEqualTo(Action.DIE);
	}

	@Test
	public void givenAliveCellWithOneAliveNeighbourCellShouldDie() {
		Collection<Cell> neighbours = generateNeighboursWithNumberOfAliveCell(1);

		Action result = rule.whatNext(Cell.ALIVE(), neighbours);

		assertThat(result).isEqualTo(Action.DIE);
	}

	@Test
	public void givenAliveCellWithTwoAliveNeighboursNothingShouldHappenToCell() {
		Collection<Cell> neighbours = generateNeighboursWithNumberOfAliveCell(2);

		Action result = rule.whatNext(Cell.ALIVE(), neighbours);

		assertThat(result).isEqualTo(Action.NOTHING);
	}

	@Test
	public void givenDeadCellNothingShouldHappenToCell() {
		Action result = rule.whatNext(Cell.DEAD(), Collections.emptyList());

		assertThat(result).isEqualTo(Action.NOTHING);
	}
}


text:
<?php

/**
 * Consoler
 * Sinatra-like application builder for the console
 *
 * @author justim
 **/
class Consoler
{
	// option attributes
	const OPTION_ORIGINAL = 'original';
	const OPTION_LONG     = 'long';
	const OPTION_SHORT    = 'short';
	const OPTION_ARGUMENT = 'argument';
	const OPTION_VALUE    = 'value';
	const OPTION_OPTIONAL = 'optional';
	const OPTION_FILTER   = 'filter';
	const OPTION_ALIAS    = 'alias';
	const OPTION_ALIASES  = 'aliases';

	// parsed option attributes
	const ARGUMENT_TYPE    = 'type';
	const ARGUMENT_NAME    = 'name';
	const ARGUMENT_VALUE   = 'value';
	const ARGUMENT_OPTIONS = 'options';

	// parsed option attribute values
	const ARGUMENT_TYPE_MULTIPLE = 'multiple';
	const ARGUMENT_TYPE_SINGLE   = 'single';
	const ARGUMENT_TYPE_VALUE    = 'value';
	const ARGUMENT_TYPE_ARGUMENT = 'argument';

	// default values for empty optionals
	const DEFAULTS_VALUE = null;
	const DEFAULTS_SHORT = 0;
	const DEFAULTS_LONG  = false;

	// list of available commands
	private $_commands = [];

	// should we handle exception internally (used for testing)
	private $_handleExceptions = true;

	// when handling exception, should we exit after the error/usage message
	private $_exitOnFailure = true;

	// streams used for in and output
	private $_streams = [
		'in'  => STDIN,
		'out' => STDOUT,
		'err' => STDERR,
	];

	// available filters
	private $_filters = [];

	public function __construct()
	{
		$this->_filters = [
			'file' => [$this, '_isFile'],
			'dir'  => [$this, '_isDirectory'],
		];
	}

	/**
	 * Set whether we should handle expections internally (useful for testing)
	 * @param boolean
	 */
	public function setHandleExceptions($flag)
	{
		$this->_handleExceptions = (bool) $flag;

		return $this;
	}

	public function setExitOnFailure($flag)
	{
		$this->_exitOnFailure = (bool) $flag;

		return $this;
	}

	public function setStreams(array $streams)
	{
		foreach ($streams as $type => $stream)
		{
			$this->setStream($type, $stream);
		}

		return $this;
	}

	public function setStream($type, $stream)
	{
		if (is_resource($stream) || is_callable($stream))
		{
			$this->_streams[$type] = $stream;
		}
		else
		{
			throw new \InvalidArgumentException('Invalid stream for "' . $type . '"');
		}

		return $this;
	}

	public function __call($command, $arguments)
	{
		$action = array_pop($arguments);
		if (is_object($action) && is_callable([$action, '__consolerInvoke']))
		{
			$action = [$action, '__consolerInvoke'];
		}
		else if (is_callable($action) === false)
		{
			throw new \BadMethodCallException('Action needs to be specified');
		}

		$options = (string) current($arguments);

		return $this->_addCommand($command, $options, $action);
	}

	public function __invoke()
	{
		return $this->__call(null, func_get_args());
	}

	public function run($args = null)
	{
		if ($args === null)
		{
			$args = $_SERVER['argv'];
			array_shift($args); // remove script name
		}

		try
		{
			$result = $this->_run($args);

			if (!$result)
			{
				$this->usage();
			}
		}
		catch (\Exception $e)
		{
			if ($this->_handleExceptions)
			{
				$error = $this->_createErrorHelper();
				$error($e->getMessage());
				$this->usage();

				// exit helper is impossible to test, it will crash phpunit
				// @codeCoverageIgnoreStart
				if ($this->_exitOnFailure)
				{
					$exit = $this->_createExitHelper();
					$exit();
				}
				// @codeCoverageIgnoreEnd

				$result = false;
			}
			else
			{
				throw $e;

			// brace will never ever be reached
			// @codeCoverageIgnoreStart
			}
			// @codeCoverageIgnoreEnd
		}

		return $result;
	}

	private function _optionAsString($options, $currentOptions)
	{
		$option = '';

		if ($currentOptions[self::OPTION_LONG])
		{
			$option .= '--';
		}

		if ($currentOptions[self::OPTION_SHORT])
		{
			$option .= '-';
		}

		$option .= $currentOptions[self::OPTION_ORIGINAL];

		if (isset($currentOptions[self::OPTION_ALIASES]))
		{
			foreach ($currentOptions[self::OPTION_ALIASES] as $alias)
			{
				$option .= '|' . $this->_optionAsString($options, $options[$alias]);
			}
		}

		if ($currentOptions[self::OPTION_VALUE])
		{
			$option .= '=';
		}

		return $option;
	}

	public function usage()
	{
		$error = $this->_createErrorHelper();
		$lines = ['Usage:'];

		foreach ($this->_commands as $command)
		{
			$line = '';

			if (!empty($command['command']))
			{
				$line .= ' ' . $command['command'];
			}

			$i = 0;
			$optional = null;

			$filteredOptions = array_values(array_filter($command['options'], function($item)
			{
				return !isset($item[self::OPTION_ALIAS]);
			}));

			foreach ($filteredOptions as $name => $options)
			{
				$line .= ' ';

				if (!$optional && $options[self::OPTION_OPTIONAL])
				{
					$optional = $options['optional'];
					$line .= '[';
				}

				$line .= $this->_optionAsString($command['options'], $options);

				if ($options[self::OPTION_OPTIONAL])
				{
					if (!isset($filteredOptions[$i + 1]) || $filteredOptions[$i + 1][self::OPTION_OPTIONAL] !== $optional)
					{
						$line .= ']';
						$optional = null;
					}
				}

				$i++;
			}

			if (!empty($command['description']))
			{
				$line .= ' -- ' . $command['description'];
			}

			$lines[] = $line;
		}

		$error(implode("\n", $lines));
	}

	private function _run($args, array $rawOptions = [])
	{
		$argsWithoutCommand = array_slice($args, 1);

		// last first
		foreach (array_reverse($this->_commands) as $command)
		{
			if ($command['command'] === null || isset($args[0]) && $command['command'] === $args[0])
			{
				$commandArgs = $command['command'] === null ? $args : $argsWithoutCommand;
				$matchedOptions = $this->_matchCommandArguments($commandArgs, $command['options']);

				if ($matchedOptions !== null)
				{
					foreach ($command['options'] as $optionName => $option)
					{
						if ($option[self::OPTION_FILTER])
						{
							$this->_filters[$option[self::OPTION_FILTER]]($matchedOptions[$optionName]);
						}
					}

					$this->_dispatch($command['action'], $commandArgs, $matchedOptions);
					return true;
				}
			}
		}

		return false;
	}

	private function _dispatch(Callable $callback, $args, $options)
	{
		$reflection = $this->_createReflectionClass($callback);
		$functionParameters = $reflection->getParameters();

		$parameterHelper = $this->_createParameterHelper([$options]);

		$args = [];
		$i = 0;
		foreach ($functionParameters as $parameter)
		{
			$name = strtolower($parameter->getName());

			switch ($name)
			{
				case 'print':    $args[$i] = $this->_createPrintHelper();    break;
				case 'error':    $args[$i] = $this->_createErrorHelper();    break;
				case 'ask':      $args[$i] = $this->_createAskHelper();      break;
				case 'confirm':  $args[$i] = $this->_createConfirmHelper();  break;
				case 'password': $args[$i] = $this->_createPasswordHelper(); break;
				case 'file':     $args[$i] = $this->_createFileHelper();     break;
				case 'exit':     $args[$i] = $this->_createExitHelper();     break;
				case 'table':    $args[$i] = $this->_createTableHelper();    break;
				default:         $args[$i] = $parameterHelper($name);        break;
			}

			++$i;
		}

		return call_user_func_array($callback, $args);
	}

	private function _addCommand($command, $options, Callable $action)
	{
		$tokenizedOptions = $this->_tokenizeOptions($options);

		$this->_commands[] = [
			'command' => $command,
			'options' => $tokenizedOptions['options'],
			'description' => $tokenizedOptions['description'],
			'action' => $action,
		];

		return $this;
	}

	/**
	 * Generate options based on our string format
	 * @param string format of options/arguments
	 *  -a          - short option
	 *  -zed        - multiple short options
	 *  --bear      - long option
	 *  run         - argument
	 *  -g=         - = indicates it should be followed by a value
	 *  [--magic]   - with square brackets its optional
	 *
	 * ex.: run -a -zed --noop
	 *
	 * @return list with option definitions
	 *       [ 'name' => [
	 *            'long' => bool,         // long option
	 *            'short' => bool,        // short option
	 *            'argument' => bool,     // option is a argument
	 *            'value' => bool,        // value is expected
	 *            'optional' => int|null, // optional
	 *            'filter' => string      // filter index
	 *            ['alias' => bool,]      // alias
	 *            ['aliases' => [],]      // list of aliases
	 *        ], ... ]
	 */
	private function _tokenizeOptions($rawOptions)
	{
		$options = $rawOptions;
		$description = null;
		$tokenizedOptions = [];

		if (preg_match('/(^| )-- (?<description>.*)$/', $options, $matches))
		{
			$description = $matches['description'];
			$options = substr($options, 0, -strlen($matches[0]));
		}

		$options = array_filter(array_map('trim', explode(' ', $options)));
		$optionalTracker = ['tracking' => false, 'index' => 0];

		while ($option = array_shift($options))
		{
			$tokenizedOption = $this->_tokenizeOption($option, $optionalTracker);

			if ($tokenizedOption['option'][self::OPTION_SHORT] && strlen($tokenizedOption['name']) > 1)
			{
				foreach (str_split($tokenizedOption['name']) as $shortOptionName)
				{
					array_unshift($options, '-' . $shortOptionName . ($tokenizedOption['option'][self::OPTION_VALUE] ? '=' : ''));
				}
			}
			else
			{
				$tokenizedOptions = $this->_mergeTokenizedOptions($tokenizedOptions, $tokenizedOption);
			}
		}

		if ($optionalTracker['tracking'])
		{
			throw new \InvalidArgumentException('Missing closing optional token');
		}

		return ['description' => $description, 'options' => $tokenizedOptions];
	}

	private function _mergeTokenizedOptions($tokenizedOptions, $tokenizedOption)
	{
		$aliases = [];

		foreach ($tokenizedOption['aliases'] as $alias => $aliasOptions)
		{
			if (isset($tokenizedOptions[$aliasOptions['name']]))
			{
				throw new \InvalidArgumentException('Duplicate option');
			}

			$aliases[] = $aliasOptions['name'];
			$aliasOptions['option'][self::OPTION_ALIAS] = $tokenizedOption['name'];
			$tokenizedOptions[$aliasOptions['name']] = $aliasOptions['option'];
		}

		if (isset($tokenizedOptions[$tokenizedOption['name']]))
		{
			throw new \InvalidArgumentException('Duplicate option');
		}

		$tokenizedOption['option'][self::OPTION_ALIASES] = $aliases;
		$tokenizedOptions[$tokenizedOption['name']] = $tokenizedOption['option'];

		return $tokenizedOptions;
	}

	private function _tokenizeOption($rawOption, &$optionalTracker)
	{
		list($option, $optional) = $this->_tokenizeOptionOptional($rawOption, $optionalTracker);
		list($option, $long)     = $this->_tokenizeOptionLong($option);
		list($option, $short)    = $this->_tokenizeOptionShort($option);
		list($option, $value)    = $this->_tokenizeOptionValue($option, $long, $short);
		list($option, $filter)   = $this->_tokenizeOptionFilter($option, $long, $short);
		list($option, $aliases)  = $this->_tokenizeOptionAliases($option);

		if (empty($option))
		{
			throw new \InvalidArgumentException('Option must have a name');
		}

		if ($long && $short)
		{
			throw new \InvalidArgumentException('Option can not be a long and a short option');
		}

		if ($short && strlen($option) > 1 && !empty($aliases))
		{
			throw new \InvalidArgumentException('No aliases allowed for multi option');
		}

		if (!$short && !$long && !empty($aliases))
		{
			throw new \InvalidArgumentException('Aliases only allowed for options');
		}

		// options can have weird values, variable don't
		// it might cause some troubles when keys become the same..
		$normalizedName = $this->_normalizedOptionName($option);

		return [
			'name' => $normalizedName,
			'option' => [
				self::OPTION_ORIGINAL => $option, // remaining option part is the name
				self::OPTION_LONG     => $long,
				self::OPTION_SHORT    => $short,
				self::OPTION_ARGUMENT => !$short && !$long,
				self::OPTION_VALUE    => $value,
				self::OPTION_OPTIONAL => $optional,
				self::OPTION_FILTER   => $filter,
			],
			'aliases' => $aliases,
		];
	}

	private function _tokenizeOptionOptional($rawOption, &$optionalTracker)
	{
		$option = $rawOption;

		if (substr($option, 0, 1) === '[')
		{
			if (!$optionalTracker['tracking'])
			{
				$optionalTracker['tracking'] = true;
				$optionalTracker['index']++;
				$option = substr($option, 1);
			}
			else
			{
				throw new \InvalidArgumentException('Nested optionals are not allowed');
			}
		}

		$optional = $optionalTracker['tracking'] ? $optionalTracker['index'] : null;

		if (substr($option, -1, 1) === ']')
		{
			if ($optionalTracker['tracking'])
			{
				$optionalTracker['tracking'] = false;
				$option = substr($option, 0, -1);
			}
			else
			{
				throw new \InvalidArgumentException('Unopened optional');
			}
		}

		return [$option, $optional];
	}

	private function _tokenizeOptionLong($option)
	{
		if (substr($option, 0, 2) === '--')
		{
			$long = true;
			$option = substr($option, 2);
		}
		else
		{
			$long = false;
		}

		return [$option, $long];
	}

	private function _tokenizeOptionShort($option)
	{
		if (substr($option, 0, 1) === '-')
		{
			$short = true;
			$option = substr($option, 1);
		}
		else
		{
			$short = false;
		}

		return [$option, $short];
	}

	private function _tokenizeOptionValue($option, $long, $short)
	{
		$value = false;

		if (substr($option, -1) === '=')
		{
			if (!$short && !$long)
			{
				throw new \InvalidArgumentException('Argument can\'t have a value');
			}

			$value = true;
			$option = substr($option, 0, -1);
		}

		return [$option, $value];
	}

	private function _tokenizeOptionFilter($option, $long, $short)
	{
		$filter = null;

		if (!$short && !$long && preg_match('/^(?<filter>\w+):(?<option>.*)$/', $option, $matches))
		{
			if (!isset($this->_filters[$matches['filter']]) || !is_callable($this->_filters[$matches['filter']]))
			{
				throw new \InvalidArgumentException('Invalid filter: ' . $matches['filter']);
			}

			$filter = $matches['filter'];
			$option = $matches['option'];
		}

		return [$option, $filter];
	}

	private function _tokenizeOptionAliases($option)
	{
		$aliases = explode('|', $option);
		$option = array_shift($aliases);

		$aliases = array_map(function($option)
		{
			list($option, $long)     = $this->_tokenizeOptionLong($option);
			list($option, $short)    = $this->_tokenizeOptionShort($option);

			$normalizedName = $this->_normalizedOptionName($option);

			return [
				'name' => $normalizedName,
				'option' => [
					self::OPTION_ORIGINAL => $option, // remaining option part is the name
					self::OPTION_LONG     => $long,
					self::OPTION_SHORT    => $short,

					// we don't care because it's an alias
					self::OPTION_ARGUMENT => false,
					self::OPTION_VALUE    => false,
					self::OPTION_OPTIONAL => null,
					self::OPTION_FILTER   => null,
				],
			];
		}, $aliases);

		return [$option, $aliases];
	}

	/**
	 * Parse command arguments against a list of possible options
	 * @param array raw arguments
	 * @param array generated options
	 */
	private function _matchCommandArguments($args, $options)
	{
		$parseOptions = true;
		$matchedOptions = [];
		$argumentValues = [];

		while ($arg = array_shift($args))
		{
			if ($parseOptions)
			{
				if ($arg === '--')
				{
					$parseOptions = false;
					continue;
				}

				$analyzed = $this->_analyzeArgvValue($options, $matchedOptions, $arg, $args);

				if ($analyzed === null)
				{
					return null;
				}
				else if ($analyzed[self::ARGUMENT_TYPE] === self::ARGUMENT_TYPE_MULTIPLE)
				{
					foreach ($analyzed[self::ARGUMENT_OPTIONS] as $optionsMultiple)
					{
						$matchedOptions[$optionsMultiple[self::ARGUMENT_NAME]] = $optionsMultiple[self::ARGUMENT_VALUE];
					}
				}
				else if ($analyzed[self::ARGUMENT_TYPE] === self::ARGUMENT_TYPE_ARGUMENT)
				{
					$argumentValues[] = $analyzed[self::ARGUMENT_VALUE];
				}
				else
				{
					$matchedOptions[$analyzed[self::ARGUMENT_NAME]] = $analyzed[self::ARGUMENT_VALUE];
				}

				if ($analyzed[self::ARGUMENT_TYPE] === self::ARGUMENT_TYPE_VALUE)
				{
					array_shift($args);
				}
			}
			else
			{
				$argumentValues[] = $arg;
			}
		}

		list($matchedArguments, $remainingArguments) = $this->_matchArguments($options, $argumentValues);
		$matchedOptions += $matchedArguments;

		// give optional options a default value
		$matchedOptions = $this->_fillDefaults($matchedOptions, $options);

		// we need to match all expected options
		if ($matchedOptions !== null && count($matchedOptions) === count($options))
		{
			$matchedOptions['remaining'] = $remainingArguments;
			return $matchedOptions;
		}
		else
		{
			return null;
		}
	}

	private function _analyzeArgvValue($options, $matchOptions, $arg, $args)
	{
		$long = false;
		$short = false;
		$name = null;

		if (strpos($arg, '--') === 0)
		{
			$long = true;
			$name = substr($arg, 2);
		}
		else if (strpos($arg, '-') === 0)
		{
			$short = true;
			$name = substr($arg, 1);
		}

		if ($name !== null)
		{
			$normalizedName = $this->_normalizedOptionName($name);

			if (isset($options[$normalizedName][self::OPTION_ALIAS]))
			{
				$name = $options[$normalizedName][self::OPTION_ALIAS];

				$long = $options[$name][self::OPTION_LONG];
				$short = $options[$name][self::OPTION_SHORT];
			}
		}

		if ($long)
		{
			return $this->_analyzeArgvValueLong($options, $name, $args);
		}
		else if ($short)
		{
			return $this->_analyzeArgvValueShort($options, $matchOptions, $name, $args);
		}
		else
		{
			return [
				self::ARGUMENT_TYPE  => self::ARGUMENT_TYPE_ARGUMENT,
				self::ARGUMENT_NAME  => null,
				self::ARGUMENT_VALUE => $arg,
			];
		}
	}

	private function _analyzeArgvValueLong($options, $rawArgName, $args)
	{
		$normalizedArgName = $this->_normalizedOptionName($rawArgName);
		$result = null;

		if (isset($options[$normalizedArgName]) &&
			$options[$normalizedArgName][self::OPTION_ORIGINAL] === $rawArgName &&
			$options[$normalizedArgName][self::OPTION_LONG])
		{
			if ($options[$normalizedArgName][self::OPTION_VALUE])
			{
				if (isset($args[0]))
				{
					$result = [
						self::ARGUMENT_TYPE  => self::ARGUMENT_TYPE_VALUE,
						self::ARGUMENT_NAME  => $normalizedArgName,
						self::ARGUMENT_VALUE => $args[0],
					];
				}
			}
			else
			{
				$result = [
					self::ARGUMENT_TYPE  => self::ARGUMENT_TYPE_SINGLE,
					self::ARGUMENT_NAME  => $normalizedArgName,
					self::ARGUMENT_VALUE => true,
				];
			}
		}

		return $result;
	}

	private function _analyzeArgvValueShort($options, $matchOptions, $rawFullArg, $args)
	{
		$normalizedFullArg = $this->_normalizedOptionName($rawFullArg);
		$result = null;

		if (strlen($normalizedFullArg) === 1 &&
			isset($options[$normalizedFullArg]) &&
			$options[$normalizedFullArg][self::OPTION_ORIGINAL] === $rawFullArg &&
		    $options[$normalizedFullArg][self::OPTION_SHORT] &&
			$options[$normalizedFullArg][self::OPTION_VALUE])
		{
			if (isset($args[0]))
			{
				$result = [
					self::ARGUMENT_TYPE  => self::ARGUMENT_TYPE_VALUE,
					self::ARGUMENT_NAME  => $normalizedFullArg,
					self::ARGUMENT_VALUE => $args[0],
				];
			}
		}
		else if (strlen($normalizedFullArg) >= 1)
		{
			$mergeMatchOptions = [];

			foreach (str_split($normalizedFullArg) as $argShort)
			{
				if (isset($options[$argShort]) &&
					$options[$argShort][self::OPTION_SHORT])
				{
					if (!isset($mergeMatchOptions[$argShort]))
					{
						$mergeMatchOptions[$argShort] = [
							self::ARGUMENT_TYPE  => self::ARGUMENT_TYPE_SINGLE,
							self::ARGUMENT_NAME  => $argShort,
							self::ARGUMENT_VALUE => (isset($matchOptions[$argShort]) ? $matchOptions[$argShort] : 0) + 1,
						];
					}
					else
					{
						$mergeMatchOptions[$argShort][self::ARGUMENT_VALUE] += 1;
					}
				}
			}

			if (!empty($mergeMatchOptions))
			{
				$result = [
					self::ARGUMENT_TYPE    => self::ARGUMENT_TYPE_MULTIPLE,
					self::ARGUMENT_OPTIONS => $mergeMatchOptions,
				];
			}
		}

		return $result;
	}

	private function _matchArguments($options, $argumentValues)
	{
		$matchedArguments = [];

		list($optionalsBefore, $optionalsBeforeTracker) =
			$this->_matchArgumentsOptionalsBefore($options, $argumentValues);

		foreach ($optionalsBefore as $mandatoryArgName => $optionals)
		{
			foreach ($optionals as $optional)
			{
				foreach ($optional as $g)
				{
					if ($g['include'])
					{
						$matchedArguments[$g['name']] = array_shift($argumentValues);
					}
				}
			}

			$matchedArguments[$mandatoryArgName] = array_shift($argumentValues);
		}

		foreach ($optionalsBeforeTracker as $p)
		{
			foreach ($p as $o)
			{
				$value = array_shift($argumentValues);

				if ($value === null)
				{
					break 2;
				}
				else
				{
					$matchedArguments[$o['name']] = $value;
				}
			}
		}

		return [$matchedArguments, $argumentValues];
	}

	private function _matchArgumentsOptionalsBefore($options, $argumentValues)
	{
		$optionalsBefore = [];
		$optionalsBeforeTracker = [];

		foreach ($options as $name => $option)
		{
			if ($option[self::OPTION_ARGUMENT])
			{
				if ($option[self::OPTION_OPTIONAL])
				{
					if (!isset($optionalsBeforeTracker[$option[self::OPTION_OPTIONAL]]))
					{
						$optionalsBeforeTracker[$option[self::OPTION_OPTIONAL]] = [];
					}

					$optionalsBeforeTracker[$option[self::OPTION_OPTIONAL]][] = ['include' => false, 'name' => $name];
				}
				else
				{
					$optionalsBefore[$name] = $optionalsBeforeTracker;
					$optionalsBeforeTracker = [];
				}
			}
		}

		$optionalsBefore = $this->_matchArgumentsOptionalsBeforeMatcher($optionalsBefore, $argumentValues);
		return [$optionalsBefore, $optionalsBeforeTracker];
	}

	private function _matchArgumentsOptionalsBeforeMatcher($optionalsBefore, $argumentValues)
	{
		$mandatoriesMatched = count($optionalsBefore);
		$total = 0;

		foreach ($optionalsBefore as &$optionals)
		{
			uksort($optionals, function($l, $r) { return count($r) - count($l); });

			foreach ($optionals as &$before)
			{
				if (($total + count($before) + $mandatoriesMatched) <= count($argumentValues))
				{
					$total += count($before);

					foreach ($before as &$val)
					{
						$val['include'] = true;
					}
				}
			}

			ksort($optionals);
		}

		return $optionalsBefore;
	}

	/**
	 * Fill all remaining options with their defaults, makes sure the grouped optional are really grouped
	 * @param array list of the currently matched options
	 * @param array config for this command
	 * @return array|null list of matched options filled with options, or null of failure
	 */
	private function _fillDefaults($matchedOptions, $options)
	{
		foreach ($options as $name => $option)
		{
			if (isset($option[self::OPTION_ALIAS]))
			{
				continue;
			}
			else if ($option[self::OPTION_OPTIONAL])
			{
				if (!isset($matchedOptions[$name]))
				{
					if ($option[self::OPTION_VALUE] || $option[self::OPTION_ARGUMENT])
					{
						$matchedOptions[$name] = self::DEFAULTS_VALUE;
					}
					else if ($option[self::OPTION_SHORT])
					{
						$matchedOptions[$name] = self::DEFAULTS_SHORT;
					}
					else
					{
						$matchedOptions[$name] = self::DEFAULTS_LONG;
					}

					$matchedOptions = $this->_fillAliases($matchedOptions, $name, $option, $options);
				}
				else
				{
					$matchedOptions = $this->_fillAliases($matchedOptions, $name, $option, $options);

					foreach ($options as $optionName => $optionOptions)
					{
						if ($optionOptions[self::OPTION_OPTIONAL] === $option[self::OPTION_OPTIONAL])
						{
							if (!isset($matchedOptions[$optionName]))
							{
								// when grouping optionals, its all or nothing
								return null;
							}
						}
					}
				}
			}
			else
			{
				$matchedOptions = $this->_fillAliases($matchedOptions, $name, $option, $options);
			}
		}

		return $matchedOptions;
	}

	private function _fillAliases($matchedOptions, $name, $option, $options)
	{
		if (isset($option[self::OPTION_ALIASES]))
		{
			foreach ($option[self::OPTION_ALIASES] as $alias)
			{
				if (array_key_exists($name, $matchedOptions))
				{
					$matchedOptions[$alias] = $matchedOptions[$name];
				}
			}
		}

		return $matchedOptions;
	}

	/**
	 * Print to a stream
	 * @param resource|Callable
	 * @param string the content
	 * @param [mixed] optional extra parameters
	 */
	private function _streamOut($stream, $content)
	{
		$args = array_slice(func_get_args(), 1);

		if (is_callable($stream))
		{
			call_user_func_array($stream, $args);
		}
		else
		{
			array_unshift($args, $stream);
			call_user_func_array('fprintf', $args);
		}
	}

	/**
	 * Get the contents of the incoming stream
	 * @return string
	 */
	private function _streamIn()
	{
		if (is_callable($this->_streams['in']))
		{
			return $this->_streams['in']();
		}
		else
		{
			return preg_replace('/(\r|\r\n|\n)$/', '', fgets($this->_streams['in']));
		}
	}

	/**
	 * Create a helper to print a message to a resource
	 * @param resource ex. STDOUT
	 */
	private function _createResourcePrinterHelper($resource)
	{
		return function($text, $overwritable = false) use ($resource)
		{
			$text .= $overwritable ? "\x0D" : "\n";
			$this->_streamOut($resource, $text);
			return true;
		};
	}

	/**
	 * Create a helper to print a message to STDOUT
	 */
	private function _createPrintHelper()
	{
		return $this->_createResourcePrinterHelper($this->_streams['out']);
	}

	/**
	 * Create a helper to print a message to STDERR
	 */
	private function _createErrorHelper()
	{
		return $this->_createResourcePrinterHelper($this->_streams['err']);
	}

	/**
	 * Create a helper to ask for input
	 */
	private function _createAskHelper()
	{
		return function($label)
		{
			$this->_streamOut($this->_streams['out'], $label);
			return $this->_streamIn();
		};
	}

	/**
	 * Create a helper to confirm something by answer with `y` or `n`
	 */
	private function _createConfirmHelper()
	{
		return function($label, $default = null)
		{
			$ask = $this->_createAskHelper();

			$yes = strcasecmp($default, 'y') === 0 ? 'Y' : 'y';
			$no = strcasecmp($default, 'n') === 0 ? 'N' : 'n';
			$label = rtrim($label) . ' [' . $yes . '/' . $no . '] ';

			do
			{
				$response = strtolower($ask($label));

				if (empty($response) && $default !== null)
				{
					$response = $default === 'y' ? 'y' : 'n';
				}
			}
			while ($response !== 'y' && $response !== 'n');

			return $response === 'y';
		};
	}

	/**
	 * Create a helper to ask for a password, password will stay hidden
	 *
	 * @codeCoverageIgnore - password helper is impossible to test, due to its dependency of a real shell
	 */
	private function _createPasswordHelper()
	{
		return function($label)
		{
			$sttyMode = shell_exec('stty -g');
			shell_exec('stty -echo');

			$this->_streamOut($this->_streams['err'], $label);
			$password = $this->_streamIn();
			$this->_streamOut($this->_streams['err'], "\n");

			shell_exec(sprintf('stty %s', $sttyMode));

			return $password;
		};
	}

	/**
	 * Create a helper to keep asking for a filename, until a existing file is given
	 */
	private function _createFileHelper()
	{
		return function($label, $errorMessage = 'Invalid file')
		{
			$ask = $this->_createAskHelper();
			$error = $this->_createErrorHelper();

			do
			{
				$filename = $ask($label);
			}
			while (!file_exists(getcwd() . '/' . $filename) && $error($errorMessage));

			return $filename;
		};
	}

	/**
	 * Create a helper to terminate your app, with an optional error message
	 * - with error message the status code is 1, without it its 0
	 *
	 * @codeCoverageIgnore - exit helper is impossible to test, it will crash phpunit
	 */
	private function _createExitHelper()
	{
		return function($errorMessage = null)
		{
			if ($errorMessage === null)
			{
				exit;
			}
			else if (is_int($errorMessage))
			{
				exit($errorMessage);
			}
			else
			{
				$error = $this->_createErrorHelper();
				$error($errorMessage);
				exit(1);
			}
		};
	}

	private function _createTableHelper()
	{
		return function($data)
		{
			if (count(call_user_func_array('array_diff', array_map('array_keys', $data))) > 0)
			{
				throw new \InvalidArgumentException('Table helper: Keys should be the same on all rows');
			}

			$output = $this->_createPrintHelper();

			$tableInfo = [];
			foreach ($data as $record)
			{
				foreach ($record as $name => $value)
				{
					$tableInfo[$name] = [
						'numeric' => (@$tableInfo[$name]['width'] ?: true) && is_numeric($value),
						'width' => max(@$tableInfo[$name]['width'] ?: 0, strlen($value)),
					];
				}
			}

			$row = function($in, $option = 'row') use ($tableInfo, $output)
			{
				$line = '|';

				foreach ($in as $name => $value)
				{
					$line .= ' ' . str_pad(
						$value,
						$tableInfo[$name]['width'],
						' ',
						$tableInfo[$name]['numeric'] && $option === 'row' ? STR_PAD_LEFT : STR_PAD_RIGHT
						) . ' |';
				}

				$output($line);

				if ($option === 'underline')
				{
					$line = '+';

					foreach ($tableInfo as $name => $info)
					{
						$line .= str_repeat('-', $info['width'] + 2) . '+';
					}

					$output($line);
				}
			};

			$row(array_combine(array_keys($tableInfo), array_keys($tableInfo)), 'underline');

			foreach ($data as $record)
			{
				$row($record);
			}
		};
	}

	/**
	 * Helper function to create a reflection(method|function) class
	 * @param Callable
	 */
	private function _createReflectionClass(Callable $callback)
	{
		if (is_array($callback))
		{
			return new ReflectionMethod($callback[0], $callback[1]);
		}
		else if (is_string($callback) && strpos($callback, '::') !== false)
		{
			list($class, $method) = explode('::', $callback);
			return new ReflectionMethod($class, $method);
		}
		else if (method_exists($callback, '__invoke'))
		{
			return new ReflectionMethod($callback, '__invoke');
		}
		else
		{
			return new ReflectionFunction($callback);
		}
	}

	/**
	 * Create a helper for a list of sources to get their value and a default
	 */
	private function _createParameterHelper(array $sources)
	{
		$combinedSources = [];

		// combine the sources
		foreach ($sources as $source)
		{
			$combinedSources += $source;
		}

		return function($name = null, $default = null) use ($combinedSources)
		{
			if (array_key_exists($name, $combinedSources))
			{
				return $combinedSources[$name];
			}
			else
			{
				return $default;
			}
		};
	}

	private function _isFile($value)
	{
		if (!file_exists(getcwd() . '/' . $value))
		{
			throw new \InvalidArgumentException('File does not exist: ' . $value);
		}

		if (!is_file(getcwd() . '/' . $value))
		{
			throw new \InvalidArgumentException('Invalid file: ' . $value);
		}
	}

	private function _isDirectory($value)
	{
		if (!file_exists(getcwd() . '/' . $value))
		{
			throw new \InvalidArgumentException('Directory does not exist: ' . $value);
		}

		if (!is_dir(getcwd() . '/' . $value))
		{
			throw new \InvalidArgumentException('Invalid directory: ' . $value);
		}
	}

	private function _normalizedOptionName($optionName)
	{
		return preg_replace('/(^[^a-z_]|[^a-z0-9_])*/i', '', $optionName);
	}
}


text:
Partial Public Class MainForm
    ''' <summary>
    ''' Required designer variable.
    ''' </summary>
    Private components As System.ComponentModel.IContainer = Nothing

    ''' <summary>
    ''' Clean up any resources being used.
    ''' </summary>
    ''' <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing AndAlso (components IsNot Nothing) Then
            components.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub

    #Region "Windows Form Designer generated code"

    ''' <summary>
    ''' Required method for Designer support - do not modify
    ''' the contents of this method with the code editor.
    ''' </summary>
    Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Dim resources As New System.ComponentModel.ComponentResourceManager(GetType(MainForm))
        Me.menuStrip = New System.Windows.Forms.MenuStrip()
        Me.fileToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
        Me.exitToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem()
        Me.toolStrip = New System.Windows.Forms.ToolStrip()
        Me.buttonOpen = New System.Windows.Forms.ToolStripButton()
        Me.toolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator()
        Me.buttonPrint = New System.Windows.Forms.ToolStripButton()
        Me.statusStrip = New System.Windows.Forms.StatusStrip()
        Me.toolStripStatusLabel = New System.Windows.Forms.ToolStripStatusLabel()
        Me.splitContainer = New System.Windows.Forms.SplitContainer()
        Me.propertyGrid = New System.Windows.Forms.PropertyGrid()
        Me.label1 = New System.Windows.Forms.Label()
        Me.customListView = New SolidEdge.Draft.BatchPrint.CustomListView()
        Me.columnHeader1 = (CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader))
        Me.menuStrip.SuspendLayout()
        Me.toolStrip.SuspendLayout()
        Me.statusStrip.SuspendLayout()
        DirectCast(Me.splitContainer, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.splitContainer.Panel1.SuspendLayout()
        Me.splitContainer.Panel2.SuspendLayout()
        Me.splitContainer.SuspendLayout()
        Me.SuspendLayout()
        '
        ' menuStrip
        '
        Me.menuStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() { Me.fileToolStripMenuItem})
        Me.menuStrip.Location = New System.Drawing.Point(0, 0)
        Me.menuStrip.Name = "menuStrip"
        Me.menuStrip.Size = New System.Drawing.Size(784, 24)
        Me.menuStrip.TabIndex = 0
        Me.menuStrip.Text = "menuStrip1"
        '
        ' fileToolStripMenuItem
        '
        Me.fileToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() { Me.exitToolStripMenuItem})
        Me.fileToolStripMenuItem.Name = "fileToolStripMenuItem"
        Me.fileToolStripMenuItem.Size = New System.Drawing.Size(37, 20)
        Me.fileToolStripMenuItem.Text = "&File"
        '
        ' exitToolStripMenuItem
        '
        Me.exitToolStripMenuItem.Name = "exitToolStripMenuItem"
        Me.exitToolStripMenuItem.Size = New System.Drawing.Size(92, 22)
        Me.exitToolStripMenuItem.Text = "&Exit"
'INSTANT VB NOTE: The following InitializeComponent event wireup was converted to a 'Handles' clause:
'ORIGINAL LINE: this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
        '
        ' toolStrip
        '
        Me.toolStrip.Enabled = False
        Me.toolStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() { Me.buttonOpen, Me.toolStripSeparator1, Me.buttonPrint})
        Me.toolStrip.Location = New System.Drawing.Point(0, 24)
        Me.toolStrip.Name = "toolStrip"
        Me.toolStrip.Size = New System.Drawing.Size(784, 25)
        Me.toolStrip.TabIndex = 1
        '
        ' buttonOpen
        '
        Me.buttonOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
        Me.buttonOpen.Image = My.Resources.FolderOpen_16x16_72
        Me.buttonOpen.ImageTransparentColor = System.Drawing.Color.Magenta
        Me.buttonOpen.Name = "buttonOpen"
        Me.buttonOpen.Size = New System.Drawing.Size(23, 22)
        Me.buttonOpen.Text = "Select from folder"
'INSTANT VB NOTE: The following InitializeComponent event wireup was converted to a 'Handles' clause:
'ORIGINAL LINE: this.buttonOpen.Click += new System.EventHandler(this.buttonOpen_Click);
        '
        ' toolStripSeparator1
        '
        Me.toolStripSeparator1.Name = "toolStripSeparator1"
        Me.toolStripSeparator1.Size = New System.Drawing.Size(6, 25)
        '
        ' buttonPrint
        '
        Me.buttonPrint.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
        Me.buttonPrint.Image = My.Resources.Print_16x16
        Me.buttonPrint.ImageTransparentColor = System.Drawing.Color.Magenta
        Me.buttonPrint.Name = "buttonPrint"
        Me.buttonPrint.Size = New System.Drawing.Size(23, 22)
        Me.buttonPrint.Text = "Print"
'INSTANT VB NOTE: The following InitializeComponent event wireup was converted to a 'Handles' clause:
'ORIGINAL LINE: this.buttonPrint.Click += new System.EventHandler(this.buttonPrint_Click);
        '
        ' statusStrip
        '
        Me.statusStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() { Me.toolStripStatusLabel})
        Me.statusStrip.Location = New System.Drawing.Point(0, 539)
        Me.statusStrip.Name = "statusStrip"
        Me.statusStrip.Size = New System.Drawing.Size(784, 22)
        Me.statusStrip.TabIndex = 2
        Me.statusStrip.Text = "statusStrip1"
        '
        ' toolStripStatusLabel
        '
        Me.toolStripStatusLabel.Name = "toolStripStatusLabel"
        Me.toolStripStatusLabel.Size = New System.Drawing.Size(769, 17)
        Me.toolStripStatusLabel.Spring = True
        Me.toolStripStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        ' splitContainer
        '
        Me.splitContainer.Dock = System.Windows.Forms.DockStyle.Fill
        Me.splitContainer.Location = New System.Drawing.Point(0, 49)
        Me.splitContainer.Name = "splitContainer"
        '
        ' splitContainer.Panel1
        '
        Me.splitContainer.Panel1.Controls.Add(Me.customListView)
        '
        ' splitContainer.Panel2
        '
        Me.splitContainer.Panel2.Controls.Add(Me.propertyGrid)
        Me.splitContainer.Panel2.Controls.Add(Me.label1)
        Me.splitContainer.Size = New System.Drawing.Size(784, 490)
        Me.splitContainer.SplitterDistance = 534
        Me.splitContainer.TabIndex = 4
        '
        ' propertyGrid
        '
        Me.propertyGrid.Dock = System.Windows.Forms.DockStyle.Fill
        Me.propertyGrid.Location = New System.Drawing.Point(0, 23)
        Me.propertyGrid.Name = "propertyGrid"
        Me.propertyGrid.PropertySort = System.Windows.Forms.PropertySort.Alphabetical
        Me.propertyGrid.Size = New System.Drawing.Size(246, 467)
        Me.propertyGrid.TabIndex = 0
        Me.propertyGrid.ToolbarVisible = False
        '
        ' label1
        '
        Me.label1.BackColor = System.Drawing.SystemColors.ActiveCaption
        Me.label1.Dock = System.Windows.Forms.DockStyle.Top
        Me.label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (CByte(0)))
        Me.label1.ForeColor = System.Drawing.Color.White
        Me.label1.Location = New System.Drawing.Point(0, 0)
        Me.label1.Name = "label1"
        Me.label1.Padding = New System.Windows.Forms.Padding(3, 0, 0, 0)
        Me.label1.Size = New System.Drawing.Size(246, 23)
        Me.label1.TabIndex = 1
        Me.label1.Text = "DraftPrintUtilityOptions"
        Me.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        ' customListView
        '
        Me.customListView.AllowDrop = True
        Me.customListView.Columns.AddRange(New System.Windows.Forms.ColumnHeader() { Me.columnHeader1})
        Me.customListView.Dock = System.Windows.Forms.DockStyle.Fill
        Me.customListView.Enabled = False
        Me.customListView.Location = New System.Drawing.Point(0, 0)
        Me.customListView.Name = "customListView"
        Me.customListView.Size = New System.Drawing.Size(534, 490)
        Me.customListView.TabIndex = 3
        Me.customListView.UseCompatibleStateImageBehavior = False
        Me.customListView.UseExplorerTheme = True
        Me.customListView.View = System.Windows.Forms.View.Details
'INSTANT VB NOTE: The following InitializeComponent event wireup was converted to a 'Handles' clause:
'ORIGINAL LINE: this.customListView.SelectedIndexChanged += new System.EventHandler(this.customListView_SelectedIndexChanged);
        '
        ' columnHeader1
        '
        Me.columnHeader1.Text = "File"
        Me.columnHeader1.Width = 780
        '
        ' MainForm
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(784, 561)
        Me.Controls.Add(Me.splitContainer)
        Me.Controls.Add(Me.statusStrip)
        Me.Controls.Add(Me.toolStrip)
        Me.Controls.Add(Me.menuStrip)
        Me.Font = New System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (CByte(0)))
        Me.Icon = (DirectCast(resources.GetObject("$this.Icon"), System.Drawing.Icon))
        Me.MainMenuStrip = Me.menuStrip
        Me.Name = "MainForm"
        Me.Text = "Batch Print"
'INSTANT VB NOTE: The following InitializeComponent event wireup was converted to a 'Handles' clause:
'ORIGINAL LINE: this.Load += new System.EventHandler(this.MainForm_Load);
        Me.menuStrip.ResumeLayout(False)
        Me.menuStrip.PerformLayout()
        Me.toolStrip.ResumeLayout(False)
        Me.toolStrip.PerformLayout()
        Me.statusStrip.ResumeLayout(False)
        Me.statusStrip.PerformLayout()
        Me.splitContainer.Panel1.ResumeLayout(False)
        Me.splitContainer.Panel2.ResumeLayout(False)
        DirectCast(Me.splitContainer, System.ComponentModel.ISupportInitialize).EndInit()
        Me.splitContainer.ResumeLayout(False)
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

    #End Region

    Private menuStrip As System.Windows.Forms.MenuStrip
    Private toolStrip As System.Windows.Forms.ToolStrip
    Private statusStrip As System.Windows.Forms.StatusStrip
    Private fileToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
    Private WithEvents exitToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
    Private WithEvents buttonPrint As System.Windows.Forms.ToolStripButton
    Private WithEvents customListView As CustomListView
    Private columnHeader1 As System.Windows.Forms.ColumnHeader
    Private WithEvents buttonOpen As System.Windows.Forms.ToolStripButton
    Private toolStripSeparator1 As System.Windows.Forms.ToolStripSeparator
    Private splitContainer As System.Windows.Forms.SplitContainer
    Private propertyGrid As System.Windows.Forms.PropertyGrid
    Private toolStripStatusLabel As System.Windows.Forms.ToolStripStatusLabel
    Private label1 As System.Windows.Forms.Label
End Class


text:
#pragma once

/* Generic header includes */
#include <aws/firehose/FirehoseErrors.h>
#include <aws/core/client/GenericClientConfiguration.h>
#include <aws/core/client/AWSError.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/client/AsyncCallerContext.h>
#include <aws/core/http/HttpTypes.h>
#include <aws/firehose/FirehoseEndpointProvider.h>
#include <future>
#include <functional>
/* End of generic header includes */

/* Service model headers required in FirehoseClient header */
#include <aws/firehose/model/CreateDeliveryStreamResult.h>
#include <aws/firehose/model/DeleteDeliveryStreamResult.h>
#include <aws/firehose/model/DescribeDeliveryStreamResult.h>
#include <aws/firehose/model/ListDeliveryStreamsResult.h>
#include <aws/firehose/model/ListTagsForDeliveryStreamResult.h>
#include <aws/firehose/model/PutRecordResult.h>
#include <aws/firehose/model/PutRecordBatchResult.h>
#include <aws/firehose/model/StartDeliveryStreamEncryptionResult.h>
#include <aws/firehose/model/StopDeliveryStreamEncryptionResult.h>
#include <aws/firehose/model/TagDeliveryStreamResult.h>
#include <aws/firehose/model/UntagDeliveryStreamResult.h>
#include <aws/firehose/model/UpdateDestinationResult.h>
/* End of service model headers required in FirehoseClient header */

namespace Aws
{
  namespace Http
  {
    class HttpClient;
    class HttpClientFactory;
  } // namespace Http

  namespace Utils
  {
    template< typename R, typename E> class Outcome;

    namespace Threading
    {
      class Executor;
    } // namespace Threading
  } // namespace Utils

  namespace Auth
  {
    class AWSCredentials;
    class AWSCredentialsProvider;
  } // namespace Auth

  namespace Client
  {
    class RetryStrategy;
  } // namespace Client

  namespace Firehose
  {
    using FirehoseClientConfiguration = Aws::Client::GenericClientConfiguration<false>;
    using FirehoseEndpointProviderBase = Aws::Firehose::Endpoint::FirehoseEndpointProviderBase;
    using FirehoseEndpointProvider = Aws::Firehose::Endpoint::FirehoseEndpointProvider;

    namespace Model
    {
      /* Service model forward declarations required in FirehoseClient header */
      class CreateDeliveryStreamRequest;
      class DeleteDeliveryStreamRequest;
      class DescribeDeliveryStreamRequest;
      class ListDeliveryStreamsRequest;
      class ListTagsForDeliveryStreamRequest;
      class PutRecordRequest;
      class PutRecordBatchRequest;
      class StartDeliveryStreamEncryptionRequest;
      class StopDeliveryStreamEncryptionRequest;
      class TagDeliveryStreamRequest;
      class UntagDeliveryStreamRequest;
      class UpdateDestinationRequest;
      /* End of service model forward declarations required in FirehoseClient header */

      /* Service model Outcome class definitions */
      typedef Aws::Utils::Outcome<CreateDeliveryStreamResult, FirehoseError> CreateDeliveryStreamOutcome;
      typedef Aws::Utils::Outcome<DeleteDeliveryStreamResult, FirehoseError> DeleteDeliveryStreamOutcome;
      typedef Aws::Utils::Outcome<DescribeDeliveryStreamResult, FirehoseError> DescribeDeliveryStreamOutcome;
      typedef Aws::Utils::Outcome<ListDeliveryStreamsResult, FirehoseError> ListDeliveryStreamsOutcome;
      typedef Aws::Utils::Outcome<ListTagsForDeliveryStreamResult, FirehoseError> ListTagsForDeliveryStreamOutcome;
      typedef Aws::Utils::Outcome<PutRecordResult, FirehoseError> PutRecordOutcome;
      typedef Aws::Utils::Outcome<PutRecordBatchResult, FirehoseError> PutRecordBatchOutcome;
      typedef Aws::Utils::Outcome<StartDeliveryStreamEncryptionResult, FirehoseError> StartDeliveryStreamEncryptionOutcome;
      typedef Aws::Utils::Outcome<StopDeliveryStreamEncryptionResult, FirehoseError> StopDeliveryStreamEncryptionOutcome;
      typedef Aws::Utils::Outcome<TagDeliveryStreamResult, FirehoseError> TagDeliveryStreamOutcome;
      typedef Aws::Utils::Outcome<UntagDeliveryStreamResult, FirehoseError> UntagDeliveryStreamOutcome;
      typedef Aws::Utils::Outcome<UpdateDestinationResult, FirehoseError> UpdateDestinationOutcome;
      /* End of service model Outcome class definitions */

      /* Service model Outcome callable definitions */
      typedef std::future<CreateDeliveryStreamOutcome> CreateDeliveryStreamOutcomeCallable;
      typedef std::future<DeleteDeliveryStreamOutcome> DeleteDeliveryStreamOutcomeCallable;
      typedef std::future<DescribeDeliveryStreamOutcome> DescribeDeliveryStreamOutcomeCallable;
      typedef std::future<ListDeliveryStreamsOutcome> ListDeliveryStreamsOutcomeCallable;
      typedef std::future<ListTagsForDeliveryStreamOutcome> ListTagsForDeliveryStreamOutcomeCallable;
      typedef std::future<PutRecordOutcome> PutRecordOutcomeCallable;
      typedef std::future<PutRecordBatchOutcome> PutRecordBatchOutcomeCallable;
      typedef std::future<StartDeliveryStreamEncryptionOutcome> StartDeliveryStreamEncryptionOutcomeCallable;
      typedef std::future<StopDeliveryStreamEncryptionOutcome> StopDeliveryStreamEncryptionOutcomeCallable;
      typedef std::future<TagDeliveryStreamOutcome> TagDeliveryStreamOutcomeCallable;
      typedef std::future<UntagDeliveryStreamOutcome> UntagDeliveryStreamOutcomeCallable;
      typedef std::future<UpdateDestinationOutcome> UpdateDestinationOutcomeCallable;
      /* End of service model Outcome callable definitions */
    } // namespace Model

    class FirehoseClient;

    /* Service model async handlers definitions */
    typedef std::function<void(const FirehoseClient*, const Model::CreateDeliveryStreamRequest&, const Model::CreateDeliveryStreamOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > CreateDeliveryStreamResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::DeleteDeliveryStreamRequest&, const Model::DeleteDeliveryStreamOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DeleteDeliveryStreamResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::DescribeDeliveryStreamRequest&, const Model::DescribeDeliveryStreamOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DescribeDeliveryStreamResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::ListDeliveryStreamsRequest&, const Model::ListDeliveryStreamsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListDeliveryStreamsResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::ListTagsForDeliveryStreamRequest&, const Model::ListTagsForDeliveryStreamOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListTagsForDeliveryStreamResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::PutRecordRequest&, const Model::PutRecordOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > PutRecordResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::PutRecordBatchRequest&, const Model::PutRecordBatchOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > PutRecordBatchResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::StartDeliveryStreamEncryptionRequest&, const Model::StartDeliveryStreamEncryptionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > StartDeliveryStreamEncryptionResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::StopDeliveryStreamEncryptionRequest&, const Model::StopDeliveryStreamEncryptionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > StopDeliveryStreamEncryptionResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::TagDeliveryStreamRequest&, const Model::TagDeliveryStreamOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > TagDeliveryStreamResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::UntagDeliveryStreamRequest&, const Model::UntagDeliveryStreamOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > UntagDeliveryStreamResponseReceivedHandler;
    typedef std::function<void(const FirehoseClient*, const Model::UpdateDestinationRequest&, const Model::UpdateDestinationOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > UpdateDestinationResponseReceivedHandler;
    /* End of service model async handlers definitions */
  } // namespace Firehose
} // namespace Aws


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
namespace Org.Apache.REEF.Bridge.Core.Common.Driver
{
    /// <summary>
    /// The interface that initializes the driver client.
    /// </summary>
    internal interface IDriverClientService
    {
        /// <summary>
        /// Start the driver client service.
        /// </summary>
        void Start();

        /// <summary>
        /// Await for termination.
        /// </summary>
        void AwaitTermination();
    }
}


text:
<?php

class MY_Controller extends MX_Controller {

    public $appconfig;

    function __construct() {
        parent::__construct();
        $this->appconfig = $this->Appconfig->get_all()->result();
    }

    public function uploadimage($config) {
        $this->load->helper('directory');
        $config = $config;
        $this->load->library('upload', $config);
        $this->upload->do_upload('image');
        return strlen($this->upload->display_errors()) == 0 || !strcmp($this->upload->display_errors(), '<p>' . $this->lang->line('upload_no_file_selected') . '</p>');
    }

    public function prepareRegistrationData() {
        $items = [];
        foreach ($this->input->post() as $key => $value) {
            if ($key == 'CustPassword') {
                continue;
            }

            $items[] = $key;
        }
        $data = elements($items, $this->input->post());
        $data['CustPassword'] = md5($this->input->post('CustPassword'));
        return $data;
    }

    public function prepareData() {
        $items = [];
        foreach ($this->input->post() as $key => $value) {
            if ($key == 'submit_form' || $key == 'id') {
                continue;
            }
            $items[] = $key;
        }
        $data = elements($items, $this->input->post());
        return $data;
    }

}


text:
class CreateImportPromotionInfos < ActiveRecord::Migration
  def change
    create_table :spree_import_promotion_infos do |t|
      t.timestamps
    end
  end
end


text:
outdir=$PREFIX/share/$PKG_NAME
mkdir -p $outdir
mkdir -p $PREFIX/bin
cp BamStats-assembly-1.0.1.jar $outdir/BamStats-assembly-1.0.1.jar
cp $RECIPE_DIR/biopet-bamstats.py $outdir/biopet-bamstats
ln -s $outdir/biopet-bamstats $PREFIX/bin


text:
define.class("$server/composition",
  function (require, exports, $ui$, screen, view, $behaviors$, draggable) {
    var assert = (require('$system/lib/chai.js')).assert;
    var results = [];

    this.render = function() {
      var v1 = view({
        x:5, y:10, width:100, height:150, bgcolor:'green',

        atConstructor: function() {results.push('atConstructor v1');},
        init: function() {results.push('init v1');},
        render: function() {results.push('render v1'); return [v1sub];},
        atRender: function() {results.push('atRender v1');},
        atChildrenRendered: function() {results.push('atChildrenRendered v1');}
      });

      var v1sub = view({
        x:5, y:5, width:20, height:20, bgcolor:'yellow',

        atConstructor: function() {results.push('atConstructor v1sub');},
        init: function() {results.push('init v1sub');},
        render: function() {results.push('render v1sub');},
        atRender: function() {results.push('atRender v1sub');},
        atChildrenRendered: function() {results.push('atChildrenRendered v1sub');}
      });

      var v2 = view({
        x:105, y:10, width:50, height:75, bgcolor:'green',

        atConstructor: function() {results.push('atConstructor v2');},
        init: function() {results.push('init v2');},
        render: function() {results.push('render v2');},
        atRender: function() {results.push('atRender v2');},
        atChildrenRendered: function() {results.push('atChildrenRendered v2');}
      });

      var s = screen({
        name: 'default',
        atConstructor: function() {results.push('atConstructor screen');},
        init: function() {results.push('init screen');},
        render: function() {results.push('render screen'); return [v1, v2];},
        atRender: function() {results.push('atRender screen');},
        atChildrenRendered: function() {
          results.push('atChildrenRendered screen');

          var expected = [
            // Construct Phase
              'atConstructor v1',
                'atConstructor v1sub',
              'atConstructor v2',
            'atConstructor screen',

            // Render Phase
            'init screen',
            'render screen',
            'atRender screen',
              'init v1',
              'render v1',
              'atRender v1',
                'init v1sub',
                'render v1sub',
                'atRender v1sub',
                'atChildrenRendered v1sub',
              'atChildrenRendered v1',
              'init v2',
              'render v2',
              'atRender v2',
              'atChildrenRendered v2',
            'atChildrenRendered screen'
          ];
          assert.equal(results.join(','), expected.join(','), 'All functions should have been called in the correct order.');
          console.log('Tests Ran');
        }
      });

      return[s];
    };
  }
);


text:
@foreach ($model->galleries as $gallery)
    @if($gallery->status)

        @if($gallery->title)

{{ $gallery->title }}

        @endif
        {!! $gallery->present()->body !!}
        @include('galleries::public._thumbs', ['model' => $gallery])

    @endif
@endforeach


text:
package com.amazonaws.services.codebuild.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.codebuild.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * StartBuildRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class StartBuildRequestMarshaller {

    private static final MarshallingInfo<String> PROJECTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("projectName").build();
    private static final MarshallingInfo<String> SOURCEVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("sourceVersion").build();
    private static final MarshallingInfo<StructuredPojo> ARTIFACTSOVERRIDE_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("artifactsOverride").build();
    private static final MarshallingInfo<List> ENVIRONMENTVARIABLESOVERRIDE_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("environmentVariablesOverride").build();
    private static final MarshallingInfo<String> BUILDSPECOVERRIDE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("buildspecOverride").build();
    private static final MarshallingInfo<Integer> TIMEOUTINMINUTESOVERRIDE_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("timeoutInMinutesOverride").build();

    private static final StartBuildRequestMarshaller instance = new StartBuildRequestMarshaller();

    public static StartBuildRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(StartBuildRequest startBuildRequest, ProtocolMarshaller protocolMarshaller) {

        if (startBuildRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(startBuildRequest.getProjectName(), PROJECTNAME_BINDING);
            protocolMarshaller.marshall(startBuildRequest.getSourceVersion(), SOURCEVERSION_BINDING);
            protocolMarshaller.marshall(startBuildRequest.getArtifactsOverride(), ARTIFACTSOVERRIDE_BINDING);
            protocolMarshaller.marshall(startBuildRequest.getEnvironmentVariablesOverride(), ENVIRONMENTVARIABLESOVERRIDE_BINDING);
            protocolMarshaller.marshall(startBuildRequest.getBuildspecOverride(), BUILDSPECOVERRIDE_BINDING);
            protocolMarshaller.marshall(startBuildRequest.getTimeoutInMinutesOverride(), TIMEOUTINMINUTESOVERRIDE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}