text:
<?php

abstract class BaseGgMemberRwalletRecord extends BaseObject  implements Persistent {

	protected static $peer;

	protected $id;

	protected $uid = '0';

	protected $aid = '0';

	protected $type;

	protected $amount = 0;

	protected $bal = 0;

	protected $descr;

	protected $cdate;

	protected $alreadyInSave = false;

	protected $alreadyInValidation = false;

	public function getId()
	{

		return $this->id;
	}

	public function getUid()
	{

		return $this->uid;
	}

	public function getAid()
	{

		return $this->aid;
	}

	public function getType()
	{

		return $this->type;
	}

	public function getAmount()
	{

		return $this->amount;
	}

	public function getBal()
	{

		return $this->bal;
	}

	public function getDescr()
	{

		return $this->descr;
	}

	public function getCdate($format = 'Y-m-d H:i:s')
	{

		if ($this->cdate === null || $this->cdate === '') {
			return null;
		} elseif (!is_int($this->cdate)) {
						$ts = strtotime($this->cdate);
			if ($ts === -1 || $ts === false) { 				throw new PropelException("Unable to parse value of [cdate] as date/time value: " . var_export($this->cdate, true));
			}
		} else {
			$ts = $this->cdate;
		}
		if ($format === null) {
			return $ts;
		} elseif (strpos($format, '%') !== false) {
			return strftime($format, $ts);
		} else {
			return date($format, $ts);
		}
	}

	public function setId($v)
	{

						if ($v !== null && !is_string($v)) {
			$v = (string) $v;
		}

		if ($this->id !== $v) {
			$this->id = $v;
			$this->modifiedColumns[] = GgMemberRwalletRecordPeer::ID;
		}

	}

	public function setUid($v)
	{

						if ($v !== null && !is_string($v)) {
			$v = (string) $v;
		}

		if ($this->uid !== $v || $v === '0') {
			$this->uid = $v;
			$this->modifiedColumns[] = GgMemberRwalletRecordPeer::UID;
		}

	}

	public function setAid($v)
	{

						if ($v !== null && !is_string($v)) {
			$v = (string) $v;
		}

		if ($this->aid !== $v || $v === '0') {
			$this->aid = $v;
			$this->modifiedColumns[] = GgMemberRwalletRecordPeer::AID;
		}

	}

	public function setType($v)
	{

						if ($v !== null && !is_string($v)) {
			$v = (string) $v;
		}

		if ($this->type !== $v) {
			$this->type = $v;
			$this->modifiedColumns[] = GgMemberRwalletRecordPeer::TYPE;
		}

	}

	public function setAmount($v)
	{

		if ($this->amount !== $v || $v === 0) {
			$this->amount = $v;
			$this->modifiedColumns[] = GgMemberRwalletRecordPeer::AMOUNT;
		}

	}

	public function setBal($v)
	{

		if ($this->bal !== $v || $v === 0) {
			$this->bal = $v;
			$this->modifiedColumns[] = GgMemberRwalletRecordPeer::BAL;
		}

	}

	public function setDescr($v)
	{

						if ($v !== null && !is_string($v)) {
			$v = (string) $v;
		}

		if ($this->descr !== $v) {
			$this->descr = $v;
			$this->modifiedColumns[] = GgMemberRwalletRecordPeer::DESCR;
		}

	}

	public function setCdate($v)
	{

		if ($v !== null && !is_int($v)) {
			$ts = strtotime($v);
			if ($ts === -1 || $ts === false) { 				throw new PropelException("Unable to parse date/time value for [cdate] from input: " . var_export($v, true));
			}
		} else {
			$ts = $v;
		}
		if ($this->cdate !== $ts) {
			$this->cdate = $ts;
			$this->modifiedColumns[] = GgMemberRwalletRecordPeer::CDATE;
		}

	}

	public function hydrate(ResultSet $rs, $startcol = 1)
	{
		try {

			$this->id = $rs->getString($startcol + 0);

			$this->uid = $rs->getString($startcol + 1);

			$this->aid = $rs->getString($startcol + 2);

			$this->type = $rs->getString($startcol + 3);

			$this->amount = $rs->getFloat($startcol + 4);

			$this->bal = $rs->getFloat($startcol + 5);

			$this->descr = $rs->getString($startcol + 6);

			$this->cdate = $rs->getTimestamp($startcol + 7, null);

			$this->resetModified();

			$this->setNew(false);

						return $startcol + 8;
		} catch (Exception $e) {
			throw new PropelException("Error populating GgMemberRwalletRecord object", $e);
		}
	}

	public function delete($con = null)
	{
		if ($this->isDeleted()) {
			throw new PropelException("This object has already been deleted.");
		}

		if ($con === null) {
			$con = Propel::getConnection(GgMemberRwalletRecordPeer::DATABASE_NAME);
		}

		try {
			$con->begin();
			GgMemberRwalletRecordPeer::doDelete($this, $con);
			$this->setDeleted(true);
			$con->commit();
		} catch (PropelException $e) {
			$con->rollback();
			throw $e;
		}
	}

	public function save($con = null)
	{
		if ($this->isDeleted()) {
			throw new PropelException("You cannot save an object that has been deleted.");
		}

		if ($con === null) {
			$con = Propel::getConnection(GgMemberRwalletRecordPeer::DATABASE_NAME);
		}

		try {
			$con->begin();
			$affectedRows = $this->doSave($con);
			$con->commit();
			return $affectedRows;
		} catch (PropelException $e) {
			$con->rollback();
			throw $e;
		}
	}

	protected function doSave($con)
	{
		$affectedRows = 0; 		if (!$this->alreadyInSave) {
			$this->alreadyInSave = true;

						if ($this->isModified()) {
				if ($this->isNew()) {
					$pk = GgMemberRwalletRecordPeer::doInsert($this, $con);
					$affectedRows += 1;
					$this->setId($pk);
					$this->setNew(false);
				} else {
					$affectedRows += GgMemberRwalletRecordPeer::doUpdate($this, $con);
				}
				$this->resetModified(); 			}

			$this->alreadyInSave = false;
		}
		return $affectedRows;
	}

	protected $validationFailures = array();

	public function getValidationFailures()
	{
		return $this->validationFailures;
	}

	public function validate($columns = null)
	{
		$res = $this->doValidate($columns);
		if ($res === true) {
			$this->validationFailures = array();
			return true;
		} else {
			$this->validationFailures = $res;
			return false;
		}
	}

	protected function doValidate($columns = null)
	{
		if (!$this->alreadyInValidation) {
			$this->alreadyInValidation = true;
			$retval = null;

			$failureMap = array();

			if (($retval = GgMemberRwalletRecordPeer::doValidate($this, $columns)) !== true) {
				$failureMap = array_merge($failureMap, $retval);
			}

			$this->alreadyInValidation = false;
		}

		return (!empty($failureMap) ? $failureMap : true);
	}

	public function getByName($name, $type = BasePeer::TYPE_PHPNAME)
	{
		$pos = GgMemberRwalletRecordPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
		return $this->getByPosition($pos);
	}

	public function getByPosition($pos)
	{
		switch($pos) {
			case 0:
				return $this->getId();
				break;
			case 1:
				return $this->getUid();
				break;
			case 2:
				return $this->getAid();
				break;
			case 3:
				return $this->getType();
				break;
			case 4:
				return $this->getAmount();
				break;
			case 5:
				return $this->getBal();
				break;
			case 6:
				return $this->getDescr();
				break;
			case 7:
				return $this->getCdate();
				break;
			default:
				return null;
				break;
		} 	}

	public function toArray($keyType = BasePeer::TYPE_PHPNAME)
	{
		$keys = GgMemberRwalletRecordPeer::getFieldNames($keyType);
		$result = array(
			$keys[0] => $this->getId(),
			$keys[1] => $this->getUid(),
			$keys[2] => $this->getAid(),
			$keys[3] => $this->getType(),
			$keys[4] => $this->getAmount(),
			$keys[5] => $this->getBal(),
			$keys[6] => $this->getDescr(),
			$keys[7] => $this->getCdate(),
		);
		return $result;
	}

	public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME)
	{
		$pos = GgMemberRwalletRecordPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
		return $this->setByPosition($pos, $value);
	}

	public function setByPosition($pos, $value)
	{
		switch($pos) {
			case 0:
				$this->setId($value);
				break;
			case 1:
				$this->setUid($value);
				break;
			case 2:
				$this->setAid($value);
				break;
			case 3:
				$this->setType($value);
				break;
			case 4:
				$this->setAmount($value);
				break;
			case 5:
				$this->setBal($value);
				break;
			case 6:
				$this->setDescr($value);
				break;
			case 7:
				$this->setCdate($value);
				break;
		} 	}

	public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
	{
		$keys = GgMemberRwalletRecordPeer::getFieldNames($keyType);

		if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]);
		if (array_key_exists($keys[1], $arr)) $this->setUid($arr[$keys[1]]);
		if (array_key_exists($keys[2], $arr)) $this->setAid($arr[$keys[2]]);
		if (array_key_exists($keys[3], $arr)) $this->setType($arr[$keys[3]]);
		if (array_key_exists($keys[4], $arr)) $this->setAmount($arr[$keys[4]]);
		if (array_key_exists($keys[5], $arr)) $this->setBal($arr[$keys[5]]);
		if (array_key_exists($keys[6], $arr)) $this->setDescr($arr[$keys[6]]);
		if (array_key_exists($keys[7], $arr)) $this->setCdate($arr[$keys[7]]);
	}

	public function buildCriteria()
	{
		$criteria = new Criteria(GgMemberRwalletRecordPeer::DATABASE_NAME);

		if ($this->isColumnModified(GgMemberRwalletRecordPeer::ID)) $criteria->add(GgMemberRwalletRecordPeer::ID, $this->id);
		if ($this->isColumnModified(GgMemberRwalletRecordPeer::UID)) $criteria->add(GgMemberRwalletRecordPeer::UID, $this->uid);
		if ($this->isColumnModified(GgMemberRwalletRecordPeer::AID)) $criteria->add(GgMemberRwalletRecordPeer::AID, $this->aid);
		if ($this->isColumnModified(GgMemberRwalletRecordPeer::TYPE)) $criteria->add(GgMemberRwalletRecordPeer::TYPE, $this->type);
		if ($this->isColumnModified(GgMemberRwalletRecordPeer::AMOUNT)) $criteria->add(GgMemberRwalletRecordPeer::AMOUNT, $this->amount);
		if ($this->isColumnModified(GgMemberRwalletRecordPeer::BAL)) $criteria->add(GgMemberRwalletRecordPeer::BAL, $this->bal);
		if ($this->isColumnModified(GgMemberRwalletRecordPeer::DESCR)) $criteria->add(GgMemberRwalletRecordPeer::DESCR, $this->descr);
		if ($this->isColumnModified(GgMemberRwalletRecordPeer::CDATE)) $criteria->add(GgMemberRwalletRecordPeer::CDATE, $this->cdate);

		return $criteria;
	}

	public function buildPkeyCriteria()
	{
		$criteria = new Criteria(GgMemberRwalletRecordPeer::DATABASE_NAME);

		$criteria->add(GgMemberRwalletRecordPeer::ID, $this->id);

		return $criteria;
	}

	public function getPrimaryKey()
	{
		return $this->getId();
	}

	public function setPrimaryKey($key)
	{
		$this->setId($key);
	}

	public function copyInto($copyObj, $deepCopy = false)
	{

		$copyObj->setUid($this->uid);

		$copyObj->setAid($this->aid);

		$copyObj->setType($this->type);

		$copyObj->setAmount($this->amount);

		$copyObj->setBal($this->bal);

		$copyObj->setDescr($this->descr);

		$copyObj->setCdate($this->cdate);

		$copyObj->setNew(true);

		$copyObj->setId(NULL);
	}

	public function copy($deepCopy = false)
	{
				$clazz = get_class($this);
		$copyObj = new $clazz();
		$this->copyInto($copyObj, $deepCopy);
		return $copyObj;
	}

	public function getPeer()
	{
		if (self::$peer === null) {
			self::$peer = new GgMemberRwalletRecordPeer();
		}
		return self::$peer;
	}

}


text:
<?php
namespace Encryption\PwGen;

class pwgen
{
    // Flags for the pwgen function
    const PW_DIGITS = 0x0001;
    const PW_UPPERS = 0x0002; // At least one upper letter
    const PW_SYMBOLS = 0x0004;
    const PW_AMBIGUOUS = 0x0008;

    // Flags for the pwgen element
    const CONSONANT = 0x0001;
    const VOWEL = 0x0002;
    const DIPHTHONG = 0x0004;
    const NOT_FIRST = 0x0008;
    const NO_VOWELS = 0x0010;

    private $pwgen;
    private $pwgen_flags;
    private $password;
    private $pw_length;

    private static $initialized = false; // static block alread called?
    private static $elements;
    private static $pw_ambiguous;
    private static $pw_symbols;
    private static $pw_digits;
    private static $pw_uppers;
    private static $pw_lowers;
    private static $pw_vowels;

    /**
     * @param length    Length of the generated password. Default: 8
     * @param secure    Generate completely random, hard-to-memorize passwords. These should only
     *             be used for machine passwords, since otherwise it's almost guaranteed that
     *             users will simply write the password on a piece of paper taped to the monitor...
     * @param numerals    Include at least one number in the password. This is the default.
     * @param capitalize    Include at least one capital letter in the password. This is the default.
     * @param ambiguous    Don't use characters that could be confused by the user when printed,
     *             such as 'l' and '1', or '0' or 'O'. This reduces the number of possible
     *            passwords significantly, and as such reduces the quality of the passwords.
     *            It may be useful for users who have bad vision, but in general use of this
     *            option is not recommended.
     * @param no-vowels    Generate random passwords that do not contain vowels or numbers that might be
     *             mistaken for vowels. It provides less secure passwords to allow system
     *             administrators to not have to worry with random passwords accidentally contain
     *             offensive substrings.
     * @param symbols    Include at least one special character in the password.
     */
    public function __construct(
        $length = 8,
        $secure = false,
        $numerals = true,
        $capitalize = true,
        $ambiguous = false,
        $no_vovels = false,
        $symbols = false
    ) {
        self::initializeStaticVars();

        $this->pwgen = 'pwPhonemes';

        $this->setLength($length);
        $this->setSecure($secure);
        $this->setNumerals($numerals);
        $this->setCapitalize($capitalize);
        $this->setAmbiguous($ambiguous);
        $this->setNoVovels($no_vovels);
        $this->setSymbols($symbols);
    }

    /**
     * Length of the generated password. Default: 8
     */
    public function setLength($length)
    {
        if (is_numeric($length) && $length > 0) {
            $this->pw_length = $length;
            if ($this->pw_length < 5) {
                $this->pwgen = 'pwRand';
            }
            if ($this->pw_length <=  2) {
                $this->setCapitalize(false);
            }
            if ($this->pw_length <=  1) {
                $this->setNumerals(false);
            }
        } else {
            $this->pw_length = 8;
        }

        return $this;
    }

    /**
     * Generate completely random, hard-to-memorize passwords. These should only used for machine passwords,
     * since otherwise it's almost guaranteed that users will simply write the password on a piece of paper
     * taped to the monitor...
     * Please note that this function implies that you want passwords which include symbols, numerals and
     * capital letters.
     */
    public function setSecure($secure)
    {
        if ($secure) {
            $this->pwgen = 'pwRand';
            $this->setNumerals(true);
            $this->setCapitalize(true);
        } else {
            $this->pwgen = 'pwPhonemes';
        }

        return $this;
    }

    /**
     * Include at least one number in the password. This is the default.
     */
    public function setNumerals($numerals)
    {
        if ($numerals) {
            $this->pwgen_flags |= self::PW_DIGITS;
        } else {
            $this->pwgen_flags &= ~self::PW_DIGITS;
        }

        return $this;
    }

    /**
     * Include at least one capital letter in the password. This is the default.
     */
    public function setCapitalize($capitalize)
    {
        if ($capitalize) {
            $this->pwgen_flags |= self::PW_UPPERS;
        } else {
            $this->pwgen_flags &= ~self::PW_UPPERS;
        }

        return $this;
    }

    /**
     * Don't use characters that could be confused by the user when printed, such as 'l' and '1', or '0' or
     * 'O'. This reduces the number of possible passwords significantly, and as such reduces the quality of
     * the passwords. It may be useful for users who have bad vision, but in general use of this option is
     * not recommended.
     */
    public function setAmbiguous($ambiguous)
    {
        if ($ambiguous) {
            $this->pwgen_flags |= self::PW_AMBIGUOUS;
        } else {
            $this->pwgen_flags &= ~self::PW_AMBIGUOUS;
        }

        return $this;
    }

    /**
     * Generate random passwords that do not contain vowels or numbers that might be mistaken for vowels. It
     * provides less secure passwords to allow system administrators to not have to worry with random
     * passwords accidentally contain offensive substrings.
     */
    public function setNoVovels($no_vovels)
    {
        if ($no_vovels) {
            $this->pwgen = 'pwRand';
            $this->pwgen_flags |= self::NO_VOWELS | self::PW_DIGITS | self::PW_UPPERS;
        } else {
            $this->pwgen = 'pwPhonemes';
            $this->pwgen_flags &= ~self::NO_VOWELS;
        }

        return $this;
    }

    public function setSymbols($symbols)
    {
        if ($symbols) {
            $this->pwgen_flags |= self::PW_SYMBOLS;
        } else {
            $this->pwgen_flags &= ~self::PW_SYMBOLS;
        }

        return $this;
    }

    public function generate()
    {
        if ($this->pwgen ==  'pwPhonemes') {
            $this->pwPhonemes();
        } else { // $this->pwgen == 'pwRand'
            $this->pwRand();
        }

        return $this->password;
    }

    private function pwPhonemes()
    {
        $this->password = array();

        do {
            $feature_flags = $this->pwgen_flags;
            $c = 0;
            $prev = 0;
            $should_be = self::myRand(0, 1) ? self::VOWEL : self::CONSONANT;
            $first = 1;

            while ($c < $this->pw_length) {
                $i = self::myRand(0, count(self::$elements)-1);
                $str = self::$elements[$i]->str;
                $len = strlen($str);
                $flags = self::$elements[$i]->flags;

                // Filter on the basic type of the next element
                if (($flags & $should_be) ==  0) {
                    continue;
                }
                // Handle the NOT_FIRST flag
                if ($first && ($flags & self::NOT_FIRST)) {
                    continue;
                }
                // Don't allow VOWEL followed a Vowel/Dipthong pair
                if (
                    ($prev & self::VOWEL) && ($flags & self::VOWEL)
                    &&
                    ($flags & self::DIPHTHONG)
                ) {
                    continue;
                }
                // Don't allow us to overflow the buffer
                if ($len > $this->pw_length-$c) {
                    continue;
                }

                // Handle the AMBIGUOUS flag
                if ($this->pwgen_flags & self::PW_AMBIGUOUS) {
                    if (strpbrk($str, self::$pw_ambiguous) !== false) {
                        continue;
                    }
                }

                /*
                 * OK, we found an element which matches our criteria,
                 * let's do it!
                 */
                for ($j = 0; $j < $len; $j++) {
                    $this->password[$c+$j] = $str[$j];
                }

                // Handle PW_UPPERS
                if ($this->pwgen_flags & self::PW_UPPERS) {
                    if (($first || $flags & self::CONSONANT) && (self::myRand(0, 9) < 2)) {
                        $this->password[$c] = strtoupper($this->password[$c]);
                        $feature_flags &= ~self::PW_UPPERS;
                    }
                }

                $c +=  $len;

                // Time to stop?
                if ($c >=  $this->pw_length) {
                    break;
                }

                // Handle PW_DIGITS
                if ($this->pwgen_flags & self::PW_DIGITS) {
                    if (!$first && (self::myRand(0, 9) < 3)) {
                        do {
                            $ch = strval(self::myRand(0, 9));
                        } while (($this->pwgen_flags & self::PW_AMBIGUOUS) &&
                            strpos(self::$pw_ambiguous, $ch) !== false);
                        $this->password[$c++] = $ch;
                        $feature_flags &= ~self::PW_DIGITS;

                        $first = 1;
                        $prev = 0;
                        $should_be = self::myRand(0, 1) ? self::VOWEL : self::CONSONANT;
                        continue;
                    }
                }

                // Handle PW_SYMBOLS
                if ($this->pwgen_flags & self::PW_SYMBOLS) {
                    if (!$first && (self::myRand(0, 9) < 2)) {
                        do {
                            $ch = self::$pw_symbols[self::myRand(0, strlen(self::$pw_symbols)-1)];
                        } while (($this->pwgen_flags & self::PW_AMBIGUOUS) &&
                            strpos(self::$pw_ambiguous, $ch) !== false);
                        $this->password[$c++] = $ch;
                        $feature_flags &= ~self::PW_SYMBOLS;
                    }
                }

                // OK, figure out what the next element should be
                if ($should_be ==  self::CONSONANT) {
                    $should_be = self::VOWEL;
                } else { // should_be = =  VOWEL
                    if (($prev & self::VOWEL) || ($flags & self::DIPHTHONG) || (self::myRand(0, 9) > 3)
                    ) {
                        $should_be = self::CONSONANT;
                    } else {
                        $should_be = self::VOWEL;
                    }
                }
                $prev = $flags;
                $first = 0;
            }
        } while ($feature_flags & (self::PW_UPPERS | self::PW_DIGITS | self::PW_SYMBOLS));

        $this->password = implode('', $this->password);
    }

    private function pwRand()
    {
        $this->password = array();

        $chars = '';
        if ($this->pwgen_flags & self::PW_DIGITS) {
            $chars .= self::$pw_digits;
        }
        if ($this->pwgen_flags & self::PW_UPPERS) {
            $chars .= self::$pw_uppers;
        }
        $chars .= self::$pw_lowers;
        if ($this->pwgen_flags & self::PW_SYMBOLS) {
            $chars .= self::$pw_symbols;
        }

        do {
            $len = strlen($chars);
            $feature_flags = $this->pwgen_flags;
            $i = 0;

            while ($i < $this->pw_length) {
                $ch = $chars[self::myRand(0, $len-1)];
                if (($this->pwgen_flags & self::PW_AMBIGUOUS) &&
                    strpos(self::$pw_ambiguous, $ch) !== false) {
                    continue;
                }
                if (($this->pwgen_flags & self::NO_VOWELS) &&
                    strpos(self::$pw_vowels, $ch) !== false) {
                    continue;
                }
                $this->password[$i++] = $ch;
                if (strpos(self::$pw_digits, $ch) !== false) {
                    $feature_flags &= ~self::PW_DIGITS;
                }
                if (strpos(self::$pw_uppers, $ch) !== false) {
                    $feature_flags &= ~self::PW_UPPERS;
                }
                if (strchr(self::$pw_symbols, $ch) !== false) {
                    $feature_flags &= ~self::PW_SYMBOLS;
                }
            }
        } while ($feature_flags & (self::PW_UPPERS | self::PW_DIGITS | self::PW_SYMBOLS));

        $this->password = implode('', $this->password);
    }

    /**
     * Generate a random number n, where $min < =  n < $max
     * Mersenne Twister is used as an algorithm
     */
    public static function myRand($min = 0, $max = 0)
    {
        return mt_rand($min, $max);
    }

    /**
     * This method initializes all static vars which contain complex datatypes.
     * It acts somewhat like a static block in Java. Since PHP does not support this principle, the method
     * is called from the constructor. Because of that you can not access the static vars unless there
     * exists at least one object of the class.
     */
    private static function initializeStaticVars()
    {
        if (!self::$initialized) {
            self::$initialized = true;
            self::$elements = array(
                new PWElement('a', self::VOWEL),
                new PWElement('ae', self::VOWEL | self::DIPHTHONG),
                new PWElement('ah', self::VOWEL | self::DIPHTHONG),
                new PWElement('ai', self::VOWEL | self::DIPHTHONG),
                new PWElement('b', self::CONSONANT),
                new PWElement('c', self::CONSONANT),
                new PWElement('ch', self::CONSONANT | self::DIPHTHONG),
                new PWElement('d', self::CONSONANT),
                new PWElement('e', self::VOWEL),
                new PWElement('ee', self::VOWEL | self::DIPHTHONG),
                new PWElement('ei', self::VOWEL | self::DIPHTHONG),
                new PWElement('f', self::CONSONANT),
                new PWElement('g', self::CONSONANT),
                new PWElement('gh', self::CONSONANT | self::DIPHTHONG | self::NOT_FIRST),
                new PWElement('h', self::CONSONANT),
                new PWElement('i', self::VOWEL),
                new PWElement('ie', self::VOWEL | self::DIPHTHONG),
                new PWElement('j', self::CONSONANT),
                new PWElement('k', self::CONSONANT),
                new PWElement('l', self::CONSONANT),
                new PWElement('m', self::CONSONANT),
                new PWElement('n', self::CONSONANT),
                new PWElement('ng', self::CONSONANT | self::DIPHTHONG | self::NOT_FIRST),
                new PWElement('o', self::VOWEL),
                new PWElement('oh', self::VOWEL | self::DIPHTHONG),
                new PWElement('oo', self::VOWEL | self::DIPHTHONG),
                new PWElement('p', self::CONSONANT),
                new PWElement('ph', self::CONSONANT | self::DIPHTHONG),
                new PWElement('qu', self::CONSONANT | self::DIPHTHONG),
                new PWElement('r', self::CONSONANT),
                new PWElement('s', self::CONSONANT),
                new PWElement('sh', self::CONSONANT | self::DIPHTHONG),
                new PWElement('t', self::CONSONANT),
                new PWElement('th', self::CONSONANT | self::DIPHTHONG),
                new PWElement('u', self::VOWEL),
                new PWElement('v', self::CONSONANT),
                new PWElement('w', self::CONSONANT),
                new PWElement('x', self::CONSONANT),
                new PWElement('y', self::CONSONANT),
                new PWElement('z', self::CONSONANT)
            );
            self::$pw_ambiguous = 'B8G6I1l0OQDS5Z2';
            self::$pw_symbols = "!\"#$%&'()*+,-./:;< = >?@[\\]^_`{|}~";
            self::$pw_digits = '0123456789';
            self::$pw_uppers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            self::$pw_lowers = 'abcdefghijklmnopqrstuvwxyz';
            self::$pw_vowels = '01aeiouyAEIOUY';
        }
    }

    /**
     * Returns the last generated password. If there is none, a new one will be generated.
     */
    public function __toString()
    {
        return (empty($this->password) ? $this->generate() : $this->password);
    }
}

class PWElement
{
    public $str;
    public $flags;

    public function __construct($str, $flags)
    {
        $this->str = $str;
        $this->flags = $flags;
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  DConnectSQLiteOpenHelper.h
//  SQLiteLibrary
//
//  Copyright (c) 2014 NTT DOCOMO,INC.
//  Released under the MIT license
//  http://opensource.org/licenses/mit-license.php
//

#import "DConnectSQLiteDatabase.h"

@class DConnectSQLiteOpenHelper;

typedef void (^DConnectQueryBlock)(DConnectSQLiteDatabase *database);

@protocol DConnectSQLiteOpenHelperDelegate <NSObject>
@optional

- (void) openHelper:(DConnectSQLiteOpenHelper *)helper didDowngradeDatabase:(DConnectSQLiteDatabase *)database
         oldVersion:(int)oldVersion
         newVersion:(int)newVersion;

@required

- (void) openHelper:(DConnectSQLiteOpenHelper *)helper didCreateDatabase:(DConnectSQLiteDatabase *)database;

- (void) openHelper:(DConnectSQLiteOpenHelper *)helper didUpgradeDatabase:(DConnectSQLiteDatabase *)database
         oldVersion:(int)oldVersion
         newVersion:(int)newVersion;

@end

@interface DConnectSQLiteOpenHelper : NSObject

@property (nonatomic, weak) id<DConnectSQLiteOpenHelperDelegate> delegate;

- (id) initWithDBName:(NSString *)dbName version:(int)version;

/*!
 データベースを作成、または開く。
 このメソッドで得たデータベースに対して必ずcloseを呼ぶ必要がある。
 */
- (DConnectSQLiteDatabase *) database;

/*!
 処理をキューイングし、直列的に実行していく。
 非同期で実装する場合にはこれをつかうこと。
 このメソッドの処理自体は同期的に処理される。
 実行後、ブロックの引数のdbはクローズされる。
 */
- (void) execQueryInQueue:(DConnectQueryBlock)block;

+ (DConnectSQLiteOpenHelper *) helperWithDBName:(NSString *)dbName version:(int)version;

@end


text:
<!DOCTYPE html>

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

    <title>
    	@section('title')
        | Welcome to Josh Frontend
        @show
    </title>

    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/bootstrap.min.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ asset('assets/css/frontend/custom.css') }}">

    @yield('header_styles')

                                info@joshadmin.com

                                (703) 717-4200

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapse">

                </button>

 Home

 Features

Typography

Advanced Features

Grid System

 Pages

About Us

Timeline

Price

404 Error

500 Error

FAQ

Blank

 Shop

Products

Single Product

Compare Products

Categories

 Portfolio

Portfolio

Portfolio Item

 News

News

News Item

 Blog

Blog

Blog Item

Contact

    @yield('top')

    @yield('content')

About Us

                    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

Follow Us

Contact Us

35,Lorem Lis Street, Park Ave

Lis Street, India.

Phone:9140 123 4588

 Fax:400 423 1456

 Email:
                        info@joshadmin.com

 Skype:
                        Joshadmin

News letter

subscribe to our newsletter and stay up to date with the latest news and deals

                        <input type="text" class="form-control" placeholder="yourmail@mail.com" aria-describedby="basic-addon2">
                        Subscribe

Recent Posts

Lorem Ipsum is simply dummy text of the printing and type setting industry dummy.

John Doe

Lorem Ipsum is simply dummy text of the printing and type setting industry dummy.

John Doe

Lorem Ipsum is simply dummy text of the printing and type setting industry dummy.

John Doe

Lorem Ipsum is simply dummy text of the printing and type setting industry dummy.

John Doe

Copyright © Josh Admin Template, 2015

    @yield('footer_scripts')


text:
class AddHtmlDescriptionToActivities < ActiveRecord::Migration
  def change
    add_column :activities, :html_description, :text
  end
end


text:
using System.Net;

namespace Tamir.SharpSsh.java.net
{
    public class InetAddress
    {
        internal IPAddress addr;

        public InetAddress(IPAddress addr)
        {
            this.addr = addr != null ? addr
                : IPAddress.None; // not null
                // "127.0.0.1";
        }

        public bool isAnyLocalAddress()
        {
            return IPAddress.IsLoopback(addr);
        }

        public override int GetHashCode()
        {
            return addr.ToString().GetHashCode();
        }

        public bool equals(InetAddress addr)
        {
            return addr.ToString().Equals(addr.ToString());
        }

        public bool equals(string addr)
        {
            return addr.ToString().Equals(addr.ToString());
        }

        public override string ToString()
        {
            return addr.ToString();
        }

        public override bool Equals(object obj)
        {
            return equals(obj.ToString());
        }

        public string getHostAddress()
        {
            return ToString();
        }
    }
}


text:
layout: post
status: publish
published: true
title: Skyfire introduz Silverlight no Windows Mobile!
wordpress_id: 1153
wordpress_url: http://www.pedrolamas.com/?p=1153
categories:
- Mobilidade
tags:
- Mobilidade
- Silverlight
- Windows Mobile
- Silverlight 2.0
- Flash
---
[![Skyfire with Silverlight](wp-content/uploads/2009/12/Skyfire-with-Silverlight-Thumb.jpg)](wp-content/uploads/2009/12/Skyfire-with-Silverlight.jpg "Skyfire with Silverlight")Antecipando-se à própria Microsoft, a nova versão do explorador de internet para equipamentos móveis [Skyfire](http://www.skyfire.com/) aparece como que um presente antecipado de Natal!

Este torna-se assim um dos poucos browsers móveis a suportar por completo [Flash](http://www.adobe.com/products/flash/) 10 e Ajax, e o primeiro (e até ver, o único!) a permitir visualizar conteúdos [Silverlight](http://silverlight.net/) 2.0 em Windows Mobile.


text:
namespace NArchive {
namespace NTar {

IMP_CreateArcIn
IMP_CreateArcOut

static CArcInfo g_ArcInfo =
  { "tar", "tar", 0, 0xEE,
  5, { 'u', 's', 't', 'a', 'r' },
  NFileHeader::kUstarMagic_Offset,
  NArcInfoFlags::kStartOpen |
  NArcInfoFlags::kSymLinks |
  NArcInfoFlags::kHardLinks,
  REF_CreateArc_Pair, IsArc_Tar };

REGISTER_ARC(Tar)

}}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Modèle de page unique</title>
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0-beta.1/jquery.mobile-1.3.0-beta.1.min.css" />

Page unique

C'est un modèle passe-partout d'une page unique que vous pouvez copier pour construire votre première page jQuery Mobile. Chaque lien ou formulaire, à partir d'ici, tirera une nouvelle page via Ajax pour supporter les transitions de page animée.

Affichez la source et copiez le code pour démarrer. Toutes les CSS et les JS sont liés aux versions CDN de jQuery donc c'est super facile à mettre en place. N'oubliez pas d'inclure une balise META viewport dans le head pour régler le niveau du zoom.

Ce modèle est un document HTML standard  avec un unique conteneur "page" à l'intérieur, contrairement à un modèle multi-page qui a plusieurs pages à l'intérieur. Nous recommandons fortement la construction de votre site ou de votre application comme une série de pages séparées parce que c'est plus propre, plus léger et fonctionne mieux sans JavaScript.

Contenu de pied de page


text:
<!DOCTYPE html>

    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no, maximum-scale=1,user-scalable=0">
    <title>Uniform</title>

    <link href="/assets/main-a1f215b33ebfa8a598cc6b125086b0eaad58c1fe408b67d9111889ee91f6cfd8.css" rel="stylesheet" />

    <link rel="apple-touch-icon-precomposed" sizes="57x57" href="/static-assets/favicons/apple-touch-icon-57x57.png" />
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/static-assets/favicons/apple-touch-icon-114x114.png" />
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/static-assets/favicons/apple-touch-icon-72x72.png" />
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/static-assets/favicons/apple-touch-icon-144x144.png" />
    <link rel="apple-touch-icon-precomposed" sizes="60x60" href="/static-assets/favicons/apple-touch-icon-60x60.png" />
    <link rel="apple-touch-icon-precomposed" sizes="120x120" href="/static-assets/favicons/apple-touch-icon-120x120.png" />
    <link rel="apple-touch-icon-precomposed" sizes="76x76" href="/static-assets/favicons/apple-touch-icon-76x76.png" />
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="/static-assets/favicons/apple-touch-icon-152x152.png" />
    <link rel="icon" type="image/png" href="/static-assets/favicons/favicon-196x196.png" sizes="196x196" />
    <link rel="icon" type="image/png" href="/static-assets/favicons/favicon-96x96.png" sizes="96x96" />
    <link rel="icon" type="image/png" href="/static-assets/favicons/favicon-32x32.png" sizes="32x32" />
    <link rel="icon" type="image/png" href="/static-assets/favicons/favicon-16x16.png" sizes="16x16" />
    <link rel="icon" type="image/png" href="/static-assets/favicons/favicon-128.png" sizes="128x128" />
    <meta name="application-name" content="Uniform"/>
    <meta name="msapplication-TileColor" content="#FFFFFF" />
    <meta name="msapplication-TileImage" content="/static-assets/favicons/mstile-144x144.png" />
    <meta name="msapplication-square70x70logo" content="/static-assets/favicons/mstile-70x70.png" />
    <meta name="msapplication-square150x150logo" content="/static-assets/favicons/mstile-150x150.png" />
    <meta name="msapplication-wide310x150logo" content="/static-assets/favicons/mstile-310x150.png" />
    <meta name="msapplication-square310x310logo" content="/static-assets/favicons/mstile-310x310.png" />

                Introduction

                Utilities

                        Scopes

                        Colors

                        Text

                        Borders

                        SVGs

                        Spacing

                        Background

                        Sizing

                        Position

                        Flex

                        Grid

                        Effects

                  Components

                        Button

                        Table

                        Thumb

                        Loader

                        Nav

                        Label

                        Input

                        Checkbox

                                JS

                        Floating Label Input

                                JS

                        Popover

                                JS

                        Tooltip

                                JS

                        Dropdown

                                JS

                        Select

                                JS

                        Modal

                                JS

                        Dropzone

                                JS

                        Resizer

                                JS

                        Table Grid

                                JS

                        Bound Input

                                JS

                        Spreadsheet

                                JS

      © 2021 Ben Ehmke

        Select
        JS

        Render an element that mimics a select box but is more full featured in design abilities,
        while maintaining the html simplicity of a basic select element.

import {Select} from 'uniform';
const select = new Select({
    name: 'account_type',
    options: [
        "Employee",
        "Manager",
        "General Manager"
    ]
})
document.append(select.el)
select.render()

Options

                Option
                Type
                Description
                Default

                    options

                    Array

                    Options for selection. Each item in array can be string, array, or object

["Employee", "Manager", "General Manager"]
// - or -
[
  ["Employee", "employee", false],
  ["Manager", "manager", false],
  ["General Manager", "general_manager", true],
]
// - or -
[
  {value: "employee", text: 'Employee', selected: false},
  {value: "manager", text: 'Manager', selected: false},
  {value: "general_manager", text: 'General Manager', selected: true}
]

                    false

                    multiple

                    Boolean

                    Make the select a multiple select

                    false

                    limit

                    Integer, Boolean

                    Limit number of visilbe options. Set to false to not limit.

                    8

                class, name, id, value
                String
                Accepts any html attribute that is then rendered on the select element and rendered element.

                    <select id="example-4">
                        <option>Employee</option>
                        <option>Manager</option>
                        <option selected="selected">Boss Man</option>
                    </select>

                el
                Element

                    Optionally, can pass a select element to extract options and attributes from. In this case a select will not be generated


text:
var paths = {
  dest: './public/dist'
}

var defaultConfig = {
  formats: ['es6', 'umd'],
  outputFolder: paths.dest,
  moduleNameJS: 'SiftEDiscovery',
  mapsDest: '.',
  externalMappings: {},
  useNormalizeCSS: true
}

var viewConfig = {
  mainJS: {
    name: 'view',
    indexFile: './src/scripts/view.js'
  },
  styles: [{
    name: 'style',
    indexFile: './src/styles/style.styl'
  }]
};

var controllerConfig = {
  mainJS: {
    name: 'controller',
    indexFile: './src/scripts/controller.js'
  }
};

var emailClientControllerConfig = {
  mainJS: {
    name: 'email-client-controller',
    indexFile: './src/scripts/email-client-controller.js'
  }
};

var bundles = [
  merge(defaultConfig, viewConfig),
  merge(defaultConfig, controllerConfig),
  merge(defaultConfig, emailClientControllerConfig)
];

module.exports = bundles;

function merge(obj1, obj2) {
  var newObj = JSON.parse(JSON.stringify(obj1));
  Object.keys(obj1).forEach(function(key) { newObj[key] = obj1[key]; });
  Object.keys(obj2).forEach(function(key) { newObj[key] = obj2[key]; });
  return newObj;
}


text:
@interface StampSelectViewCell : UITableViewCell {
    IBOutlet UILabel *stampName;
    IBOutlet UIImageView *thumbnailView;
}
@property (nonatomic, retain) IBOutlet UILabel *stampName;
@property (nonatomic, retain) IBOutlet UIImageView *thumbnailView;
@end


text:
gst::BasicPass::BasicPass(std::shared_ptr<Program> program)
    : Pass(program),
      uniforms(std::make_shared<UniformMapImpl>(std::unique_ptr<AnnotationFormatter>(new AnnotationFree()))),
      model_view("model_view"),
      projection("projection")
{
}

void gst::BasicPass::apply(ModelState & state)
{
    uniforms->get_uniform(model_view) = state.model_view;
    uniforms->get_uniform(projection) = state.projection;
    program->merge_uniforms(*uniforms);
}

void gst::BasicPass::set_model_view_annotation(std::string const & model_view)
{
    this->model_view = model_view;
}

void gst::BasicPass::set_projection_annotation(std::string const & projection)
{
    this->projection = projection;
}


text:
package com.marklogic.client.document;

import javax.xml.namespace.QName;

import com.marklogic.client.MarkLogicIOException;
import com.marklogic.client.io.DocumentMetadataHandle;
import com.marklogic.client.io.marker.DocumentPatchHandle;
import com.marklogic.client.util.IterableNamespaceContext;

/**
 * A DocumentMetadataPatchBuilder specifies changes to the metadata
 * of a database document.  When using the newPatchBuilder() factory
 * method of the DocumentManager to create the builder, you identify
 * whether paths are specified with JSONPath or XPath.
 */
public interface DocumentMetadataPatchBuilder {
  /**
   * The Cardinality enumeration indicates the number of times
   * that a path can match without error (which defaults to
   * ZERO_OR_MORE, meaning any number of matches).
   */
  public enum Cardinality {
    /**
     * Allows at most one match.
     */
    ZERO_OR_ONE,
    /**
     * Requires exactly one match.
     */
    ONE,
    /**
     * Allows any number of matches.
     */
    ZERO_OR_MORE,
    /**
     * Requires at least one match.
     */
    ONE_OR_MORE;
    /**
     * Returns the standard abbreviation for the cardinality value.
     * @return	the abbreviation
     */
    public String abbreviate() {
      switch(this) {
      case ZERO_OR_ONE:
        return "?";
      case ONE:
        return ".";
      case ZERO_OR_MORE:
        return "*";
      case ONE_OR_MORE:
        return "+";
      default:
        throw new InternalError("Unknown Cardinality: "+toString());
      }
    }
  }

  /**
   * A Call specifies how to apply a built-in or library function
   * when replacing an existing fragment.  You must construct a call
   * using the CallBuilder.
   */
  interface Call {
  }

  /**
   * A CallBuilder constructs a Call to a built-in or library function
   * to produce the replacement for an existing fragment.  You must
   * construct the CallBuilder using the factory method of the
   * DocumentPatchBuilder.
   */
  interface CallBuilder {
    /**
     * Calls the built-in method to add to an existing value.
     * @param number	the added number
     * @return	the specification of the add call
     */
    Call add(Number number);
    /**
     * Calls the built-in method to subtract from an existing value.
     * @param number	the subtracted number
     * @return	the specification of the subtract call
     */
    Call subtract(Number number);
    /**
     * Calls the built-in method to multiply an existing value.
     * @param number	the multiplier
     * @return	the specification of the multiply call
     */
    Call multiply(Number number);
    /**
     * Calls the built-in method to divide an existing value
     * by the supplied number.
     * @param number	the divisor
     * @return	the specification of the divide call
     */
    Call divideBy(Number number);

    /**
     * Calls the built-in method to append an existing string
     * to the supplied string.
     * @param prefix	the string that appears first
     * @return	the specification of the concatenation call
     */
    Call concatenateAfter(String prefix);
    /**
     * Calls the built-in method to concatenate an existing string
     * between the supplied strings.
     * @param prefix	the string that appears first
     * @param suffix	the string that appears last
     * @return	the specification of the concatenation call
     */
    Call concatenateBetween(String prefix, String suffix);
    /**
     * Calls the built-in method to concatenate an existing string
     * before the supplied string.
     * @param suffix	the string that appears last
     * @return	the specification of the concatenation call
     */
    Call concatenateBefore(String suffix);
    /**
     * Calls the built-in method to reduce an existing string
     * to a trailing substring.
     * @param prefix	the initial part of the string
     * @return	the specification of the substring call
     */
    Call substringAfter(String prefix);
    /**
     * Calls the built-in method to reduce an existing string
     * to a leading substring.
     * @param suffix	the final part of the string
     * @return	the specification of the substring call
     */
    Call substringBefore(String suffix);
    /**
     * Calls the built-in method to modify an existing string
     * with a regular expression
     * @param pattern	the matching regular expression
     * @param replacement	the replacement for the match
     * @return	the specification of the regex call
     */
    Call replaceRegex(String pattern, String replacement);
    /**
     * Calls the built-in method to modify an existing string
     * with a regular expression
     * @param pattern	the matching regular expression
     * @param replacement	the replacement for the match
     * @param flags	the regex flags
     * @return	the specification of the regex call
     */
    Call replaceRegex(
      String pattern, String replacement, String flags
      );

    /**
     * Calls a function with no arguments other than the existing
     * fragment.  The function must be provided by the library specified
     * using the DocumentPatchBuilder.
     * @param function	the name of the function
     * @return	the specification of the function call
     */
    Call applyLibrary(String function);
    /**
     * Calls a function with the existing fragment and one or more
     * values.  The function must be provided by the library specified
     * using the DocumentPatchBuilder.
     * @param function	the name of the function
     * @param args	the literal values
     * @return	the specification of the function call
     */
    Call applyLibraryValues(String function, Object... args);
    /**
     * Calls a function with the existing fragment and one or more
     * specified fragments.  The function must be provided by the
     * library specified using the DocumentPatchBuilder.
     * @param function	the name of the function
     * @param args	the fragments
     * @return	the specification of the function call
     */
    Call applyLibraryFragments(String function, Object... args);
  }

  /**
   * A PatchHandle produced by the builder can produce a string
   * representation of the patch for saving, logging, or other uses.
   */
  interface PatchHandle extends DocumentPatchHandle {
    /**
     * Returns a JSON or XML representation of the patch as a string.
     * @return	the patch
     */
    @Override
    String toString();
  }

  /**
   * Returns the namespaces available for the paths
   * of a patch against XML documents.
   * @return	the declared namespaces
   */
  IterableNamespaceContext getNamespaces();
  /**
   * Declares the namespaces available for the paths
   * of a patch against XML documents.  You can use the
   * {@link com.marklogic.client.util.EditableNamespaceContext}
   * class to edit a set of namespaces.  Note that the
   * following prefixes are predefined for internal use:
   * rapi, prop, xsi, and xs
   * @param namespaces	the declared namespaces
   */
  void setNamespaces(IterableNamespaceContext namespaces);

  /**
   * Specifies an XQuery library installed on the server
   * that supplies functions for modifying existing fragments.
   * @param ns	the XQuery library namespace
   * @param at	the XQuery library path on the server
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder library(String ns, String at);

  /**
   * Adds the specified collections.
   * @param collections	the collection identifiers
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder addCollection(String... collections);
  /**
   * Deletes the specified collections.
   * @param collections	the collection identifiers
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder deleteCollection(String... collections);
  /**
   * Replaces the specified collection.
   * @param oldCollection	the identifier for the existing collection
   * @param newCollection	the identifier for the new collection
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replaceCollection(String oldCollection, String newCollection);

  /**
   * Adds a role with the specified capabilities
   * @param role	the name of the role
   * @param capabilities	the set of capabilities
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder addPermission(
    String role, DocumentMetadataHandle.Capability... capabilities
    );
  /**
   * Deletes the specified roles.
   * @param roles	the names of the roles
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder deletePermission(String... roles);
  /**
   * Replaces the existing capabilities of a role.
   * @param role	the name of the role
   * @param newCapabilities	the replacing set of capabilities
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replacePermission(
    String role, DocumentMetadataHandle.Capability... newCapabilities
    );
  /**
   * Replaces an existing role with a new role.
   * @param oldRole	the name of the replaced role
   * @param newRole	the name of the replacing role
   * @param newCapabilities	the capabilities of the replacing role
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replacePermission(
    String oldRole, String newRole, DocumentMetadataHandle.Capability... newCapabilities
    );

  /**
   * Adds a new metadata-value
   * @param key	the key of the metadata-value
   * @param value	the value of the metadata-value
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder addMetadataValue(String key, String value);
  /**
   * Deletes the specified metadata-value with the given key.
   * @param key	the key of the metadata-value
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder deleteMetadataValue(String key);
  /**
   * Replaces the existing metadata-value
   * @param key	the key of the existing metadata-value
   * @param newValue	the new value to be assigned to the key
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replaceMetadataValue(String key, String newValue);
  /**
   * Specifies a replacement operation by applying a function
   * to the metadata-value. You must use
   * CallBuilder to build a specification of the call.
   * @param key	the key of the existing metadata-value
   * @param call	the specification of the function call
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replaceMetadataValueApply(String key, Call call);

  /**
   * Adds a new metadata property with a simple name.
   * @param name	the name of the new property
   * @param value	the value of the new property
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder addPropertyValue(String name, Object value);
  /**
   * Adds a new metadata property with a namespaced name.
   * @param name	the namespaced name of the new property
   * @param value	the value of the new property
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder addPropertyValue(QName name, Object value);
  /**
   * Deletes the specified metadata properties with simple names.
   * @param names	the property names
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder deleteProperty(String... names);
  /**
   * Deletes the specified metadata properties with namespaced names.
   * @param names	the namespaced property names
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder deleteProperty(QName... names);
  /**
   * Replaces the existing value of a metadata property having a simple name.
   * @param name	the name of the existing property
   * @param newValue the new value of the property
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replacePropertyValue(String name, Object newValue);
  /**
   * Replaces the existing value of a metadata property having a namespaced name.
   * @param name	the namespaced name of the existing property
   * @param newValue the new value of the property
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replacePropertyValue(QName name, Object newValue);
  /**
   * Replaces an existing metadata property with a new property having a simple name.
   * @param oldName	the name of the existing property
   * @param newName	the name of the replacing property
   * @param newValue the value of the property
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replacePropertyValue(
    String oldName, String newName, Object newValue
    );
  /**
   * Replaces an existing metadata property with a new property having a namespaced name.
   * @param oldName	the namespaced name of the existing property
   * @param newName	the namespaced name of the replacing property
   * @param newValue the value of the property
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replacePropertyValue(
    QName oldName, QName newName, Object newValue
    );

  /**
   * A factory method for building calls to modify an existing node
   * by applying built-in functions or functions from a library.
   * @return	the builder for function calls
   */
  CallBuilder call();

  /**
   * Specifies a replacement operation by applying a function
   * to a metadata property having a simple name. You must use
   * CallBuilder to build a specification of the call.
   * @param name	the name of the existing property
   * @param call	the specification of the function call
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replacePropertyApply(
    String name, Call call
    );

  /**
   * Specifies a replacement operation by applying a function
   * to a metadata property having a namespaced name. You must
   * use CallBuilder to build a specification of the call.
   * @param name	the name of the existing property
   * @param call	the specification of the function call
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder replacePropertyApply(
    QName name, Call call
    );

  /**
   * Sets the search quality of the document.
   * @param quality	the new value for search quality
   * @return	the patch builder (for convenient chaining)
   */
  DocumentMetadataPatchBuilder setQuality(int quality);

  /**
   * Builds the patch that modifies the metadata or content of the
   * database document and provides a handle for sending the patch
   * to the server using the patch() method of the DocumentManager.
   * Once the patch is built, specifying additional operation with
   * the patch builder do not alter the patch built previously.
   * @return	the handle on the built patch
   */
  PatchHandle build() throws MarkLogicIOException;
}


text:
package gov.nih.nci.cabig.caaers.api;

import gov.nih.nci.cabig.caaers.CaaersDbNoSecurityTestCase;
import gov.nih.nci.cabig.caaers.api.impl.DefaultResearchStaffMigratorService;
import gov.nih.nci.cabig.caaers.dao.query.ResearchStaffQuery;
import gov.nih.nci.cabig.caaers.domain.Identifier;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.ResearchStaff;
import gov.nih.nci.cabig.caaers.domain.SiteResearchStaff;
import gov.nih.nci.cabig.caaers.domain.repository.ResearchStaffRepository;
import gov.nih.nci.cabig.caaers.integration.schema.researchstaff.ResearchStaffType;
import gov.nih.nci.cabig.caaers.integration.schema.researchstaff.SiteResearchStaffRoleType;
import gov.nih.nci.cabig.caaers.integration.schema.researchstaff.SiteResearchStaffType;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

public class ResearchStaffMigratorServiceTest extends CaaersDbNoSecurityTestCase {

    private DefaultResearchStaffMigratorService svc = null;
	private JAXBContext jaxbContext = null;
	private Unmarshaller unmarshaller = null;
	private gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff staff = null;
	private File xmlFile = null;

	private ResearchStaffRepository researchStaffRepository= null;
	Identifier identifier = null;
	Organization organization = null;
	ResearchStaff updatedResearchStaff = null;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		jaxbContext = JAXBContext.newInstance("gov.nih.nci.cabig.caaers.integration.schema.researchstaff");
		unmarshaller = jaxbContext.createUnmarshaller();
		svc = (DefaultResearchStaffMigratorService)getDeployedApplicationContext().getBean("researchStaffMigratorService");
		researchStaffRepository = (ResearchStaffRepository)getDeployedApplicationContext().getBean("researchStaffRepository");
	}

    @Test
	public void skipTestFetchReseachStaffByLoginId() throws Exception{
		try {
			//Create or update , whatever it is new data will be populated ..
			xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/api/testdata/CreateResearchStaffTest.xml")[0].getFile();
			staff = (gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff)unmarshaller.unmarshal(xmlFile);
			modifyDates(staff);
			svc.saveResearchStaff(staff);
			interruptSession();

			//update with modified data ..
			xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/api/testdata/UpdateResearchStaffTest.xml")[0].getFile();
			staff = (gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff)unmarshaller.unmarshal(xmlFile);
			modifyDates(staff);
			svc.saveResearchStaff(staff);

			interruptSession();

			updatedResearchStaff = fetchResearchStaff("jchapman");

			assertNotNull("The updated reseach staff should not be null.", updatedResearchStaff);

			assertEquals("111-345-0983", updatedResearchStaff.getFaxNumber());
			assertEquals("111-678-0098", updatedResearchStaff.getPhoneNumber());
			assertEquals("caaers.app2@gmail.com",updatedResearchStaff.getEmailAddress());
			assertNotNull("Research Staff should have an address.", updatedResearchStaff.getAddress());
			assertEquals("13921 Park Center Road", updatedResearchStaff.getAddress().getStreet());
			assertEquals("Herndon", updatedResearchStaff.getAddress().getCity());
			assertNotNull(updatedResearchStaff.getSiteResearchStaffs());
			assertEquals(1,updatedResearchStaff.getSiteResearchStaffs().size());

		} catch (IOException e) {
			e.printStackTrace();
			fail("Error running test: " + e.getMessage());
		} catch (JAXBException e) {
			e.printStackTrace();
			fail("Error running test: " + e.getMessage());
		}
	}

	@Test
	public void skipTestResearchStaffByEmailSave() throws Exception{
		try {
			//Create or update , whatever it is new data will be populated ..
			xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/api/testdata/CreateResearchStaffTest2.xml")[0].getFile();
			staff = (gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff)unmarshaller.unmarshal(xmlFile);
			modifyDates(staff);
			svc.saveResearchStaff(staff);

			//update with modified data ..
			xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/api/testdata/UpdateResearchStaffTest2.xml")[0].getFile();
			staff = (gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff)unmarshaller.unmarshal(xmlFile);
			modifyDates(staff);
			svc.saveResearchStaff(staff);

			interruptSession();

			updatedResearchStaff = fetchResearchStaff("caaers.rock@gmail.com");

			assertNotNull("The updated reseach staff should not be null.", updatedResearchStaff);

			assertEquals("980-090-0983", updatedResearchStaff.getFaxNumber());
			assertEquals("657-093-0098", updatedResearchStaff.getPhoneNumber());

		} catch (IOException e) {
			e.printStackTrace();
			fail("Error running test: " + e.getMessage());
		} catch (JAXBException e) {
			e.printStackTrace();
			fail("Error running test: " + e.getMessage());
		}
	}

	@Test
	public void skipTestSiteRsAdd() throws Exception{

		try {
			//Create or update , whatever it is new data will be populated ..
			xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/api/testdata/CreateResearchStaffTest.xml")[0].getFile();
			staff = (gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff)unmarshaller.unmarshal(xmlFile);
			modifyDates(staff);
			svc.saveResearchStaff(staff);

			interruptSession();

			//update with modified data ..
			xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/api/testdata/UpdateResearchStaffSiteRsAdd.xml")[0].getFile();
			staff = (gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff)unmarshaller.unmarshal(xmlFile);
			modifyDates(staff);
			svc.saveResearchStaff(staff);

			interruptSession();

			updatedResearchStaff = fetchResearchStaff("jchapman");

			assertNotNull("The updated reseach staff should not be null.", updatedResearchStaff);

			assertNotNull(updatedResearchStaff.getSiteResearchStaffs());
//			assertEquals(1,updatedResearchStaff.getSiteResearchStaffs().size());    //for some reason this fails in oracle.

		} catch (IOException e) {
			e.printStackTrace();
			fail("Error running test: " + e.getMessage());
		} catch (JAXBException e) {
			e.printStackTrace();
			fail("Error running test: " + e.getMessage());
		}

	}

	public void _BROKEN_testSiteRsRemove() throws Exception{

		try {
			//Create or update , whatever it is new data will be populated ..
			xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/api/testdata/CreateResearchStaffWithTwoSiteRs.xml")[0].getFile();
			staff = (gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff)unmarshaller.unmarshal(xmlFile);
			modifyDates(staff);
			svc.saveResearchStaff(staff);

			//update with modified data ..
			xmlFile = getResources("classpath*:gov/nih/nci/cabig/caaers/api/testdata/UpdateResearchStaffRemoveSiteRs.xml")[0].getFile();
			staff = (gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff)unmarshaller.unmarshal(xmlFile);
			modifyDates(staff);
			svc.saveResearchStaff(staff);

			updatedResearchStaff = fetchResearchStaff("jchapman");

			assertNotNull("The updated staff should not be null.", updatedResearchStaff);

			assertNotNull("The site research staff should not be null.", updatedResearchStaff.getSiteResearchStaffs());
			assertEquals("There should be two site research staff.", 2,updatedResearchStaff.getSiteResearchStaffs().size());
			for(SiteResearchStaff siteResearchStaff : updatedResearchStaff.getSiteResearchStaffs()){
				assertNotNull("Site Research Staff should have a role.", siteResearchStaff.getSiteResearchStaffRoles());
				assertEquals("Site Research staff should have 2 roles.", 2, siteResearchStaff.getSiteResearchStaffRoles().size());
			}

		} catch (IOException e) {
			e.printStackTrace();
			fail("Error running test: " + e.getMessage());
		} catch (JAXBException e) {
			e.printStackTrace();
			fail("Error running test: " + e.getMessage());
		}

	}

	/**
     * Fetches the research staff from the DB
     * @return
     */
    private ResearchStaff fetchResearchStaff(String loginId) {//String nciIdentifier) {
    	ResearchStaffQuery rsQuery = new ResearchStaffQuery();
        if (StringUtils.isNotEmpty(loginId)) {
        	//rsQuery.filterByNciIdentifier(nciIdentifier);
        	rsQuery.filterByExactLoginId(loginId);
        }
        List<ResearchStaff> rsList = researchStaffRepository.searchResearchStaff(rsQuery);

        if (rsList == null || rsList.isEmpty()) {
            return null;
        }
        return rsList.get(0);
    }

	private static Resource[] getResources(String pattern) throws IOException {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(pattern);
        return resources;
    }

	private void modifyDates(gov.nih.nci.cabig.caaers.integration.schema.researchstaff.Staff staff) throws Exception{

		DatatypeFactory df = DatatypeFactory.newInstance();
		Calendar gcNow = GregorianCalendar.getInstance();
		int year = gcNow.get(Calendar.YEAR);
		int month = gcNow.get(Calendar.MONTH)+1;
		int day = gcNow.get(Calendar.DAY_OF_MONTH);
		int tz = DatatypeConstants.FIELD_UNDEFINED;

		XMLGregorianCalendar currXmlCal = df.newXMLGregorianCalendarDate(year, month, day, tz);
		XMLGregorianCalendar furXmlCal = df.newXMLGregorianCalendarDate(year+1, month, day, tz);

		List<ResearchStaffType> researchStaffList = staff.getResearchStaff();
		List<SiteResearchStaffType> siteRsTypeList;
		List<SiteResearchStaffRoleType> siteRsRoleTypeList;
		for (ResearchStaffType researchStaffType:researchStaffList) {
			siteRsTypeList = researchStaffType.getSiteResearchStaffs().getSiteResearchStaff();
			for(SiteResearchStaffType sRsType : siteRsTypeList){
				siteRsRoleTypeList = sRsType.getSiteResearchStaffRoles().getSiteResearchStaffRole();
				for(SiteResearchStaffRoleType sRsRoleType : siteRsRoleTypeList){
					sRsRoleType.setStartDate(currXmlCal);
					sRsRoleType.setEndDate(furXmlCal);
				}
			}
		}
	}

	//TODO:fix the test cases and remove this
	public void test(){

	}

}


text:
Show status info: maps table name to number of rows in that table

## Supported request methods
* GET

##Supported formats
* json

##Arguments

Requesting http://some.host.ru/db/api/status/ :
```json
{"code": 0, "response": {"user": 100000, "thread": 1000, "forum": 100, "post": 1000000}}
```


text:
mmooc-docker-dev
================

Build scripts for the Matematikk-MOOC Canvas development Docker image.

See
[http://matematikk-mooc.github.io](http://matematikk-mooc.github.io)
for more information.


text:
FOUNDATION_EXPORT double HMWKWebViewHandlerVersionNumber;
FOUNDATION_EXPORT const unsigned char HMWKWebViewHandlerVersionString[];


text:
package com.codeabovelab.dm.cluman.cluster.registry;

import com.codeabovelab.dm.cluman.cluster.registry.data.ImageCatalog;
import com.codeabovelab.dm.cluman.cluster.registry.data.SearchResult;
import com.codeabovelab.dm.cluman.cluster.registry.data.Tags;
import com.codeabovelab.dm.cluman.cluster.registry.model.RegistryCredentials;
import com.codeabovelab.dm.cluman.cluster.registry.model.RegistryConfig;
import com.codeabovelab.dm.cluman.model.ImageDescriptor;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

import static org.springframework.util.StringUtils.hasText;

/**
 * Docker registry read-only API
 */
@Slf4j
@Builder
class DockerHubRegistryServiceWrapper implements RegistryService, DockerHubRegistry {

    private final DockerHubRegistry dockerHubRegistry;
    private final String registryName;

    public ImageCatalog getCatalog() {
        return dockerHubRegistry.getCatalog();
    }

    public Tags getTags(String imageName) {
        return dockerHubRegistry.getTags(merge(registryName, imageName));
    }

    public ImageDescriptor getImage(String name, String reference) {
        return dockerHubRegistry.getImage(merge(registryName, name), reference);
    }

    @Override
    public ImageDescriptor getImage(String fullImageName) {
        return dockerHubRegistry.getImage(fullImageName);
    }

    @Override
    public void deleteTag(String name, String reference) {
        dockerHubRegistry.deleteTag(merge(registryName, name), reference);
    }

    @Override
    public RegistryConfig getConfig() {
        return dockerHubRegistry.getConfig();
    }

    @Override
    public RegistryCredentials getCredentials() {
        return dockerHubRegistry.getCredentials();
    }

    @Override
    public boolean checkHealth() {
        return dockerHubRegistry.checkHealth();
    }

    @Override
    public SearchResult search(String searchTerm, int page, int count) {
        return dockerHubRegistry.search(searchTerm, page, count);
    }

    private static String merge(String registryName, String name) {
        if (name.contains("/")) {
            return name;
        }
        return (hasText(registryName) ? registryName : "library") + "/" + name;
    }

    @Override
    public String toRelative(String name) {
        return name;
    }
}


text:
package com.timgroup.karg.functions;

import com.timgroup.karg.keywords.KeywordArgument;

public interface VarArgFunction<T> {

    T apply(KeywordArgument...parameters);

}


text:
/**
 * Loops over each item of a sequence.
 *
 *

 *

 *  {% for user in users %}
 *
{{ user.username|e }}

 *  {% endfor %}
 *

 *

 */
import {TwingTokenParser} from "../token-parser";
import {TwingErrorSyntax} from "../error/syntax";
import {TwingNodeSet} from "../node/set";
import {Token, TokenType} from "twig-lexer";

export class TwingTokenParserSet extends TwingTokenParser {
    parse(token: Token) {
        let lineno = token.line;
        let columnno = token.column;
        let stream = this.parser.getStream();
        let names = this.parser.parseAssignmentExpression();

        let capture = false;
        let values;

        if (stream.nextIf(TokenType.OPERATOR, '=')) {
            values = this.parser.parseMultitargetExpression();

            stream.expect(TokenType.TAG_END);

            if (names.getNodes().size !== values.getNodes().size) {
                throw new TwingErrorSyntax('When using set, you must have the same number of variables and assignments.', stream.getCurrent().line, stream.getSourceContext());
            }
        }
        else {
            capture = true;

            if (names.getNodes().size > 1) {
                throw new TwingErrorSyntax('When using set with a block, you cannot have a multi-target.', stream.getCurrent().line, stream.getSourceContext());
            }

            stream.expect(TokenType.TAG_END);

            values = this.parser.subparse([this, this.decideBlockEnd], true);

            stream.expect(TokenType.TAG_END);
        }

        return new TwingNodeSet(capture, names, values, lineno, columnno, this.getTag());
    }

    decideBlockEnd(token: Token) {
        return token.test(TokenType.NAME, 'endset');
    }

    getTag() {
        return 'set';
    }
}


text:
(function(){
  'use strict'

  angular
    .module('legislately')
    .config(function ($stateProvider, $urlRouterProvider) {
      $stateProvider
        .state('home', {
          url: '/',
          templateUrl: 'views/home.html',
          controller: 'HomeController as home'
        })
        .state('login', {
          url: '/login',
          templateUrl: 'views/login.html',
          controller: 'AuthController as auth',
          onEnter: function(Auth, $state) {
            Auth.currentUser().then(function() {
              $state.go('newsfeed');
            })
          }
        })
        .state('register', {
          url: '/register',
          templateUrl: 'views/register.html',
          controller: 'AuthController as auth',
          onEnter: function(Auth, $state) {
            Auth.currentUser().then(function() {
              $state.go('newsfeed')
            })
          }
        })
        .state('newsfeed', {
          url: '/feed',
          templateUrl: 'views/newsfeed.html',
          controller: 'NewsfeedController as feed',
          resolve: {
            following: function(UserFactory) {
              return UserFactory.following();
            }
          }
        })
        .state('show', {
          url: '/legislators/:id',
          templateUrl: 'views/show.html',
          controller: 'ShowController as show',
          resolve: {
            info: function(LegislatorFactory, $stateParams) {
              return LegislatorFactory.info($stateParams.id);
            },
            votes: function(LegislatorFactory, $stateParams) {
              return LegislatorFactory.votes($stateParams.id);
            },
            following: function(UserFactory, $rootScope) {
              if ($rootScope.user) {
                return UserFactory.following();
              }
            }
          }
        })
        .state('show.info', {
          url: '/info',
          templateUrl: 'views/show.info.html'
        })
        .state('show.activity', {
          url: '/activity',
          templateUrl: 'views/show.activity.html'
        })
        .state('coming-soon', {
          url: '/coming-soon',
          templateUrl: 'views/coming-soon.html',
          controller: 'ComingSoonController as soon',
          resolve: {
            comingSoon: function(SCAPIFactory) {
              return SCAPIFactory.getComingSoon();
            }
          }
        })
        .state('about', {
          url: '/about',
          templateUrl: 'views/about.html'
        });
      $urlRouterProvider.otherwise('/');
    })

}());


text:
import { createSocket } from 'dgram';
import NotificationDispatcher from './notification-dispatcher';

jest.mock('dgram');

describe('The notification dispatcher', () => {
  let dispatcher: NotificationDispatcher;
  let mockSocket;

  beforeEach(() => {
    dispatcher = new NotificationDispatcher();
    dispatcher.setPort(12345);
    dispatcher.start();
    mockSocket = createSocket.lastInstance;
  });

  afterEach(() => {
    createSocket.mockClear();
    Object.keys(mockSocket).forEach((key) => {
      if (mockSocket[key] && jest.isMockFunction(mockSocket[key])) {
        mockSocket[key].mockClear();
      }
    });
  });

  it('creates and binds an UDP4 socket on the specified port', () => {
    expect(createSocket).toHaveBeenCalledWith('udp4');
    expect(mockSocket.bind).toHaveBeenCalledWith(12345);
  });

  it('closes the socket on error and emits an error event', () => {
    const error = new Error('something went wrong');
    const spy = jest.fn();
    dispatcher.on('error', spy);
    mockSocket.emit('error', error);
    expect(mockSocket.close).toHaveBeenCalled();
    expect(spy).toHaveBeenCalledWith(error);
  });

  it('prevents the socket from keeping the node process running', () => {
    mockSocket.emit('listening');
    expect(mockSocket.unref).toHaveBeenCalled();
  });

  const TEST_CASES: Array<{ event: Object, zone?: mixed[], system?: mixed[], netusb?: mixed[] }> = [
    { event: { main: { power: 'standby' } }, zone: ['main', { power: 'standby' }] },
    {
      event: { main: { power: 'standby' }, netusb: { play_time: 30 } },
      zone: ['main', { power: 'standby' }],
      netusb: [{ play_time: 30 }],
    },
    {
      event: { netusb: { play_time: 30 }, system: { func_status_updated: true } },
      netusb: [{ play_time: 30 }],
      system: [{ func_status_updated: true }],
    },
  ];
  TEST_CASES.forEach(({ event, zone, system, netusb }, i) => {
    it(`dispatches events when receiving a message [${i}]`, () => {
      const zoneSpy = jest.fn();
      const systemSpy = jest.fn();
      const netusbSpy = jest.fn();
      dispatcher.on('change:zone', zoneSpy)
        .on('change:netusb', netusbSpy)
        .on('change:system', systemSpy);
      mockSocket.emit('message', Buffer.from(JSON.stringify(event)));
      if (zone) {
        expect(zoneSpy).toHaveBeenCalledWith(...zone);
      }
      if (system) {
        expect(systemSpy).toHaveBeenCalledWith(...system);
      }
      if (netusb) {
        expect(netusbSpy).toHaveBeenCalledWith(...netusb);
      }
    });
  });
});


text:
package co.cdev.agave.web;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

/**
 * Represents the destination of a handler method.
 * This class serves as a unifying facade for redirecting and forwarding in the Servlet API
 * and working with request parameters.
 *
 * @author Damian Carrillo
 *
 * @see Destinations.forward()
 * @see Destinations.redirect()
 */
public interface Destination {

    /**
     * Adds a parameter to the {@code Destination}.  Multi-valued parameters are supported
     * and will be serialized into a query string with the same parameter name and multiple
     * values, eg: {@code /somePath?dogs=woof&dogs=bark&cats=meow&cats=purr}
     * @param name the name of the parameter
     * @param value the value of the parameter
     */
    public abstract void addParameter(String name, String value);

    public abstract String getPath();

    public abstract void setPath(String path);

    public abstract Map<String, List<String>> getParams();

    public abstract void setParams(Map<String, List<String>> parameters);

    public abstract Boolean getRedirect();

    public abstract void setRedirect(Boolean redirect);

    /**
     * Encodes the {@code Destination} path and available parameters.
     *
     * @param context the handler context that this destination is running under
     * @return the encoded destination path and query string
     */
    public abstract String encode(ServletContext context);
}


text:
// ==========================================================================
//  JsonExternalSerializerTests.cs
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex Group
//  All rights reserved.
// ==========================================================================

using System;
using System.Collections.Generic;
using System.IO;
using FakeItEasy;
using Orleans.Serialization;
using Xunit;

namespace Squidex.Infrastructure.Orleans
{
    public class JsonExternalSerializerTests
    {
        [Fact]
        public void Should_not_copy_null()
        {
            var v = (string)null;
            var c = J<int>.Copy(v, null);

            Assert.Null(c);
        }

        [Fact]
        public void Should_copy_null_json()
        {
            var v = new J<List<int>>(null);
            var c = (J<List<int>>)J<object>.Copy(v, null);

            Assert.Null(c.Value);
        }

        [Fact]
        public void Should_not_copy_immutable_values()
        {
            var v = new List<int> { 1, 2, 3 }.AsJ();
            var c = (J<List<int>>)J<object>.Copy(v, null);

            Assert.Same(v.Value, c.Value);
        }

        [Fact]
        public void Should_serialize_and_deserialize_value()
        {
            SerializeAndDeserialize(ArrayOfLength(100), Assert.Equal);
        }

        [Fact]
        public void Should_serialize_and_deserialize_large_value()
        {
            SerializeAndDeserialize(ArrayOfLength(8000), Assert.Equal);
        }

        private static void SerializeAndDeserialize<T>(T value, Action<T, T> equals) where T : class
        {
            var buffer = new MemoryStream();

            J<object>.Serialize(J.Of(value), CreateWriter(buffer), typeof(T));

            buffer.Position = 0;

            var copy = (J<T>)J<object>.Deserialize(typeof(J<T>), CreateReader(buffer));

            equals(copy.Value, value);

            Assert.NotSame(value, copy.Value);
        }

        private static DeserializationContext CreateReader(MemoryStream buffer)
        {
            var reader = A.Fake<IBinaryTokenStreamReader>();

            A.CallTo(() => reader.ReadByteArray(A<byte[]>.Ignored, A<int>.Ignored, A<int>.Ignored))
                .Invokes(new Action<byte[], int, int>((b, o, l) => buffer.Read(b, o, l)));
            A.CallTo(() => reader.CurrentPosition)
                .ReturnsLazily(x => (int)buffer.Position);
            A.CallTo(() => reader.Length)
                .ReturnsLazily(x => (int)buffer.Length);

            return new DeserializationContext(null) { StreamReader = reader };
        }

        private static SerializationContext CreateWriter(MemoryStream buffer)
        {
            var writer = A.Fake<IBinaryTokenStreamWriter>();

            A.CallTo(() => writer.Write(A<byte[]>.Ignored, A<int>.Ignored, A<int>.Ignored))
                .Invokes(new Action<byte[], int, int>(buffer.Write));
            A.CallTo(() => writer.CurrentOffset)
                .ReturnsLazily(x => (int)buffer.Position);

            return new SerializationContext(null) { StreamWriter = writer };
        }

        private static List<int> ArrayOfLength(int length)
        {
            var result = new List<int>();

            for (var i = 0; i < length; i++)
            {
                result.Add(i);
            }

            return result;
        }
    }
}


text:
namespace options {

OptionsSyncSetupHandler::OptionsSyncSetupHandler(
    ProfileManager* profile_manager) : SyncSetupHandler(profile_manager) {
}

OptionsSyncSetupHandler::~OptionsSyncSetupHandler() {
}

void OptionsSyncSetupHandler::ShowSetupUI() {
  // Show the Sync Setup page.
  scoped_ptr<Value> page(Value::CreateStringValue("syncSetup"));
  web_ui()->CallJavascriptFunction("OptionsPage.navigateToPage", *page);
}

}  // namespace options


text:
package com.czs.gtd.api;
public interface ChangeListener
{
}


text:
title: "KnockoutJS Mapping plugin to the rescue"
date: 2014-09-29 20:47
author: saguiitay
categories: [Development]
tags: [JavaScript, KnockoutJS]
redirect_from:
 - /2014-09-29-knockoutjs-mapping-plugin-to-the-rescue/
 - /development/knockoutjs-mapping-plugin-to-the-rescue/
---
I've been using [KnockoutJS](http://knockoutjs.com/) for a long time now, but only recently found the magic that is the [Knockout-Mapping plugin](http://knockoutjs.com/documentation/plugins-mapping.html).

A few days ago, I spent some time refining some old code, and encountered something along the following lines:

{% highlight javascript %}
function report(reportData) {
    var self = reportData;
    self.StartedText = friendlyPastMoment(reportData.Started);
    if (reportData.Ended == "0001-01-01T00:00:00") {
        self.EndedText = 'Still running...';
    }
    else {
        self.EndedText = friendlyPastMoment(reportData.Ended);
    }

    return self;
}
{% endhighlight %}

(the `friendlyPastMoment()` method is just a small wrapper method around [MomentJS](http://momentjs.com), for handling edge cases)

We had a couple more properties handled similarly. Now, this worked just fine when the information displayed to the end-user was static - we just
added a few text binding to a couple of span nodes, and the `StartedText` and `EndedText` were displayed beautifully.

But we've decided that we want to updated the information displayed to the user automatically, which meant that I now had to replace
those simple `StartedText` and `EndedText` properties into Knockout computed properties. But for that to work, I had to change the
implementation - the `Started` and `Ended` properties of the report need to be [observable properties](http://knockoutjs.com/documentation/observables.html).

I've started with a naive implementation:

{% highlight javascript %}
function report(reportData) {
    var self = reportData;
    self.Started = ko.observable(reportData.Started);
    self.Ended = ko.observable(reportData.Ended);

    self.StartedText = ko.computed(function() { return friendlyPastMoment(self.Started()) });
    self.EndedText = ko.computed(function() {
        if (self.Ended() == "0001-01-01T00:00:00") {
            return 'Still running...';
        }
        else {
            return friendlyPastMoment(self.Ended());
        }});

    return self;
}
{% endhighlight %}

But since we had several properties in `reportData` that needed to implement this behavior, this started to become a code-smell. I was certain
that there must be a better way for handling these kind of scenarios.

The [Knockout-Mapping plugin](http://knockoutjs.com/documentation/plugins-mapping.html) was created exactly for such cases - it convert a simple
POCO object into its Knockout equivalent, with all properties implemented as observable properties, with arrays and all:

{% highlight javascript %}
function report(reportData) {
    ko.mapping.fromJS(reportData, {}, this);

    var self = this;

    self.StartedText = ko.computed(function() { return friendlyPastMoment(self.Started()) });
    self.EndedText = ko.computed(function() {
        if (self.Ended() == "0001-01-01T00:00:00") {
            return 'Still running...';
        }
        else {
            return friendlyPastMoment(self.Ended());
        }});

    return self;
}
{% endhighlight %}

As you can see, the first line calls the `fromJS` method, which takes a regular JavaScript object, an options object (empty `{}` in the line above),
and the destination object. The result will be that this object will have the same properties as `reportData`, implemented as Knockout observable properties.

Now, it is very easy to add a refresh function to report, which will retrieve the most current information from the server, and update the report:
{% highlight javascript %}
self.refresh = function() {
	$.getJSON("api/report?id=" + self.Id(), function (data) {
		ko.mapping.fromJS(data, self);
	});
};
{% endhighlight %}

As you can see, we're making a `getJSON` call to the server, and once we get the data back, we just call the `fromJS` method again, this time passing
the data retrieved from the server, and our current report instance.


text:
package io.github.resilience4j.timelimiter.internal;

import io.github.resilience4j.core.EventConsumer;
import io.github.resilience4j.core.EventProcessor;
import io.github.resilience4j.timelimiter.TimeLimiter;
import io.github.resilience4j.timelimiter.event.TimeLimiterEvent;
import io.github.resilience4j.timelimiter.event.TimeLimiterOnErrorEvent;
import io.github.resilience4j.timelimiter.event.TimeLimiterOnSuccessEvent;
import io.github.resilience4j.timelimiter.event.TimeLimiterOnTimeoutEvent;

public class TimeLimiterEventProcessor extends EventProcessor<TimeLimiterEvent> implements
    EventConsumer<TimeLimiterEvent>, TimeLimiter.EventPublisher {

    @Override
    public void consumeEvent(TimeLimiterEvent event) {
        super.processEvent(event);
    }

    @Override
    public TimeLimiter.EventPublisher onSuccess(
        EventConsumer<TimeLimiterOnSuccessEvent> onSuccessEventConsumer) {
        registerConsumer(TimeLimiterOnSuccessEvent.class.getName(), onSuccessEventConsumer);
        return this;
    }

    @Override
    public TimeLimiter.EventPublisher onError(
        EventConsumer<TimeLimiterOnErrorEvent> onOnFailureEventConsumer) {
        registerConsumer(TimeLimiterOnErrorEvent.class.getName(), onOnFailureEventConsumer);
        return this;
    }

    @Override
    public TimeLimiter.EventPublisher onTimeout(
        EventConsumer<TimeLimiterOnTimeoutEvent> onOnFailureEventConsumer) {
        registerConsumer(TimeLimiterOnTimeoutEvent.class.getName(), onOnFailureEventConsumer);
        return this;
    }
}