text:
package com.kinpa200296.android.labs.musicservicelibrary;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.TextView;

public class MusicServiceBroadcastReceiver extends BroadcastReceiver {

    public static final String BROADCAST_ACTION = "com.kinpa200296.android.labs.musicservicebroadcast";

    public static final String ARG_STATUS = "status";
    public static final String ARG_PASSED_LENGTH = "passedLength";
    public static final String ARG_TOTAL_LENGTH = "totalLength";

    private TextView textView;

    public MusicServiceBroadcastReceiver(TextView textView){
        this.textView = textView;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String status = intent.getStringExtra(ARG_STATUS);
        String passedLength = intent.getStringExtra(ARG_PASSED_LENGTH);
        String totalLength = intent.getStringExtra(ARG_TOTAL_LENGTH);

        textView.setText(String.format("%s: %s / %s", status, passedLength, totalLength));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.anba.es6draft.ast;

/**
 *
12 ECMAScript Language: Expressions

 *
12.3 Left-Hand-Side Expressions

 *

 *
12.3.5 The super Keyword
 *

 */
public final class SuperElementAccessor extends LeftHandSideExpression {
    private final Expression element;

    public SuperElementAccessor(long beginPosition, long endPosition, Expression element) {
        super(beginPosition, endPosition);
        this.element = element;
    }

    /**
     * Returns the element expression.
     *
     * @return the element expression
     */
    public Expression getElement() {
        return element;
    }

    @Override
    public <R, V> R accept(NodeVisitor<R, V> visitor, V value) {
        return visitor.visit(this, value);
    }

    @Override
    public <V> int accept(IntNodeVisitor<V> visitor, V value) {
        return visitor.visit(this, value);
    }

    @Override
    public <V> void accept(VoidNodeVisitor<V> visitor, V value) {
        visitor.visit(this, value);
    }
}


text:
class Player :
	public AnimatedObject,
	public SGD::Listener
{
public:
	Player();
	virtual ~Player();

	//*******************************************************************
	// Listener Interface:
	virtual void Update( float elapsedTime ) override;
	virtual void Render( void ) override;
	virtual int GetType( void ) const { return OBJ_PLAYER; }
	virtual SGD::Rectangle GetRect( void ) const override;
	virtual void HandleCollision( const iObject* pOther ) override;

	void TakeInput();

	void SetCheckPoint( SGD::Point _point ) { m_ptCheckpoint = _point; }
	void SetMoving( bool _move ) { m_bMoving = _move; }
	void SetSliding( bool _slide ) { m_bSliding = _slide; }
	void SetVelocity( SGD::Vector _vel ) { velocity = _vel; }
	void SetDirection( int _direction ) { m_nDirection = _direction; }
	void SetCombat( bool _combat = false ) { m_bCombat = _combat; }
	void SetPotions( int _potion ) { m_nPotions = _potion; }
	void SetHealth( float _health ) { m_nHealth = _health; }
	virtual float GetHealth() const { return m_nHealth; }
	float GetMaxHealth() const { return m_nMaxHealth; }

	bool GetMoving() const { return m_bMoving; }
	SGD::Point GetCheckpoint() { return m_ptCheckpoint; }
	int GetDirection() const { return m_nDirection; }
	bool GetCombat() const { return m_bCombat; }
	bool GetInTrap() const {return m_PrintDMG;}
	void CurrentTurn( int * _CurrentTurn ) { m_CurrentTurn = _CurrentTurn; }
	int GetNumPotions() const { return m_nPotions; }
	int m_nPotions = 0;

	void RunQuickTime( int length );
	void StopQuickTime();
	QuickTime* GetQuickTime( void ){ return currentQT; }

	int GetPrevDirection() const { return m_nPrevDirection; }
	bool GetBoulderCollision() const { return m_bCollision; }

	void ResetAnimation();
	void StartCombat();
	void StopCombat();

	void RenderDialog();
	void UpdateDialog();
	void PreventDialogFromRestarting( float elapsedTime );
	QuickTime* GetQT() const { return currentQT; }
	bool m_bDoQt = false;

	int GetSpell1Cool() const { return m_bSpell1; }
	int GetSpell2Cool() const { return m_bSpell2; }
	int GetSpell3Cool() const { return m_bSpell3; }

	void SetSpell1Cool(int _Cool) { m_bSpell1 = _Cool; }
	void SetSpell2Cool(int _Cool) { m_bSpell2 = _Cool; }
	void SetSpell3Cool(int _Cool) { m_bSpell3 = _Cool; }

	void SetRect( SGD::Rectangle pRect1 ) { playerRect = pRect1; }

	bool GetMapSwitch() const { return m_bMapSwitch; }
	void SetMapSwitch( bool MS ){ m_bMapSwitch = MS; }

	int CombatEnemyID = -1; //It says enemy, I know.

	float GetDeathAnimationTimer( void ){ return m_fDeathAnimationTimer; }
	void SetDeathAnimationTimer( float seconds = 3.0f ){ m_fDeathAnimationTimer = seconds; }

private:

	SGD::Rectangle playerRect = { 225, 200, 289, 264 };

	bool m_bMapSwitch = true;
	int m_nDirection;
	int m_nPrevDirection;
	bool m_bSliding = false;
	bool m_bMoving = false;
	bool m_bCollision = false;
	SGD::Vector velocity = SGD::Vector();
	SGD::Point m_ptCheckpoint;

	float m_nHealth = 100;
	float m_nMaxHealth = 100;

	bool m_bCombat = false;

	int m_bSpell1 = -1;
	int m_bSpell2 = -1;
	int m_bSpell3 = -1;

	int ActionSelected = 0;

	int m_nCursor = 0;
	int counter = 0;

	int * m_CurrentTurn;
	AnimationManager* m_pAnimator = nullptr;

	QuickTime* currentQT = nullptr;

	bool m_bLowHealthWarning = false;
	float m_fHealthFlash = 0.0f;
	bool m_bUpdateAnimation = true;

	SGD::HTexture m_hPortrait = SGD::INVALID_HANDLE;
	SGD::HTexture m_hDialogImg = SGD::INVALID_HANDLE;
	SGD::HTexture m_hDialogImg2 = SGD::INVALID_HANDLE;

	bool m_bPlayCombatAnimation = false;

	string m_szLastAnimation;

	bool m_bRunDialog = false;
	bool m_bPreventDialog = false;
	float m_fDialogTimer = 5.0f;
	int m_nLineCounter = 1;
	float m_fDeathAnimationTimer = 3.0f;

	float p1, p2, v1;
	bool m_PrintDMG = false;

	float		m_fScroll = 0;
	float	m_fSecond = 0;

	int m_ptTrapDmg;
};


text:
<?
  Include("Includes/global.inc.php");
  Include("Includes/reportFunctions.inc.php");
  checkPermissions(2, 1800);

  $nicmac1 = $progText423." 1";
  $nicmac2 = $progText423." 2";

  $numAttributes       = getOrPost('numAttributes');
  $aryPassedShow       = getOrPost('aryPassedShow');
  $aryPassedAttribute  = getOrPost('aryPassedAttribute');
  $btnSort             = getOrPost('btnSort');
  $btnUp               = getOrPost('btnUp');
  $btnDown             = getOrPost('btnDown');
  $btnShow             = getOrPost('btnShow');

  $systemList = $_COOKIE['systemList'];

  $exportMethod = getOrPost('exportMethod');

  // If no submit button is pressed or first visit then
  // predefine arrays and set defaults
  if (getOrPost('bolSubmit') != "TRUE") {

      if ($extraSystemField == "")
        $numAttributes = 21;  # number of possible output details
      else
        $numAttributes = 22;
      $btnSort = 1;        # default sort position

      // Default values upon user's entry to the page -- set as appropriate
      // Check whether the output details are stored in cookie
      if (!$systemList[1]) {
          $aryAttribute[1] = $progText743; $aryShow[1] = 1;
          $aryAttribute[2] = $progText722; $aryShow[2] = 0;
          $aryAttribute[3] = $progText33;  $aryShow[3] = 1;
          $aryAttribute[4] = $progText44;  $aryShow[4] = 1;
          $aryAttribute[5] = $progText45;  $aryShow[5] = 0;
          $aryAttribute[6] = $progText740; $aryShow[6] = 1;
          $aryAttribute[7] = $progText222; $aryShow[7] = 0;
          $aryAttribute[8] = $progText420; $aryShow[8] = 1;
          $aryAttribute[9] = $progText34;  $aryShow[9] = 1;
          $aryAttribute[10] = $progText35;  $aryShow[10] = 1;
          $aryAttribute[11] = $progText421; $aryShow[11] = 0;
          $aryAttribute[12] = $progText422; $aryShow[12] = 0;
          $aryAttribute[13] = $progText424; $aryShow[13] = 0;
          $aryAttribute[14] = $progText50; $aryShow[14] = 0;
          $aryAttribute[15] = $nicmac1; $aryShow[15] = 0;
          $aryAttribute[16] = $nicmac2; $aryShow[16] = 0;
          $aryAttribute[17] = $progText1226; $aryShow[17] = 0;
          $aryAttribute[18] = $progText761; $aryShow[18] = 0;
          $aryAttribute[19] = $progText762; $aryShow[19] = 0;
          $aryAttribute[20] = $progText763; $aryShow[20] = 0;
          $aryAttribute[21] = $progText46; $aryShow[21] = 0;
          if ($extraSystemField != "")
          {
             $aryAttribute[22] = $extraSystemField;
             $aryShow[22] = 0;
          }
      } else {
          # explode returns an array starting from subscript 0. So a blank value is inserted
          # at the beginning so that $aryAttribute[0] and $aryShow[0] are blank.
          $systemList[1] = ",".$systemList[1];
          $systemList[2] = ",".$systemList[2];
          $aryAttribute = explode(",",$systemList[1]);
          $aryShow = explode(",",$systemList[2]);
          $btnSort = $systemList[3];
      }

  } else {  # decode incoming arrays and check submit buttons

      $aryShow = unserialize(urldecode($aryPassedShow));
      $aryAttribute = unserialize(urldecode($aryPassedAttribute));
      $btnSortPosition = $btnSort;

      // Process incoming checkbox values for show/sort and adjust array

      updateCheckboxArray($numAttributes, $btnShow, $aryShow);

      // Check for an up/down button submitted from form

      upDownSubmitHandler($numAttributes, $btnUp, $btnDown, $btnSort, $aryShow, $aryAttribute);

      $cboVendorID         = getOrPost('cboVendorID');
      $cboSystemOwnership  = getOrPost('cboSystemOwnership');
      $cboSystemType       = getOrPost('cboSystemType');
      if ($_SESSION['stuckAtLocation']) {
          $cboLocationID = array($_SESSION['locationStatus']);
      } else {
          $cboLocationID       = getOrPost('cboLocationID');
      }
      $strPurchaseDate     = validateDate($progText421, getOrPost('txtPurchaseDate'), 1900, (date("Y")+1), FALSE);
	  $cboPurchaseDate     = cleanComparatorInput(getOrPost('cboPurchaseDate'));
	  $strWarrantyDate     = validateDate($progText422, getOrPost('txtWarrantyDate'), 1900, (date("Y")+90), FALSE);
      $cboWarrantyDate     = cleanComparatorInput(getOrPost('cboWarrantyDate'));
	  $strAgentDate        = validateDate($progText50, getOrPost('txtAgentDate'), 1900, (date("Y")+90), FALSE);
      $cboAgentDate        = cleanComparatorInput(getOrPost('cboAgentDate'));
	  $strPurchasePrice    = validateExactNumber($progText424, getOrPost('txtPurchasePrice'), 0, 99999999, FALSE, 2);
	  $cboPurchasePrice    = cleanComparatorInput(getOrPost('cboPurchasePrice'));
      $strSoftwareType     = validateText($progText380, getOrPost('txtSoftwareType'), 2, 70, FALSE, FALSE);
      $strPeripheralType   = validateText($progText382, getOrPost('txtPeripheralType'), 2, 70, FALSE, FALSE);
  }
  $btnShow = $aryShow;

  // If an export button pressed -- process the report ELSE
  // regenerate the form with the updated values

  if (($exportMethod != "") AND (!$strError)) {
       if (getOrPost('includeGraph')== "1")
       {
			//force display
			$aryShow[2] = 1;
			$aryShow[7] = 1;
		}

      // Validate the sort selection

      $strError = validateSort($numAttributes, $btnSort, $aryShow);

      // Compress incoming arrays based on what attributes are shown

      if (!$strError) {
          $strError = compressAttributeArray($numAttributes, $numToShow, $btnSort, $aryShow, $aryAttribute, $aryCompAttribute);
      }

      // Preload DB items with recursive (having to reference more than one SQL
      // table) lookups into arrays and construct a "lookup" array for retrieval of IDs

      if (!$strError) {

          for ($i=1; $i<=$numToShow; $i++) {

              switch ($aryCompAttribute[$i]) {

                case "$progText743":  # User Name
                    loadLookupTable($i, $progText743, TRUE, 'h.userID', $aryLookupTable);
                    $strSQL = "SELECT id, firstName, middleInit, lastName FROM tblSecurity WHERE hidden='0' AND accountID=" . $_SESSION['accountID'];
                    $result = dbquery($strSQL);
                    while ($row = mysql_fetch_array($result)) {
                        $strUserName = buildName($row['firstName'], $row['middleInit'], $row['lastName'], 0);
                        $aryLookupTable[$i]['values'][$row['id']] = $strUserName;
                    }
                break;

                case "$progText722":  # System Ownership
                    loadLookupTable($i, $progText722, TRUE, 'h.sparePart', $aryLookupTable);
                    $aryLookupTable[$i]['values']['0'] = $progText725;
                    $aryLookupTable[$i]['values']['1'] = $progText377;
                    $aryLookupTable[$i]['values']['2'] = $progText472;
                    $aryLookupTable[$i]['values']['3'] = ucfirst($adminDefinedCategory);
                break;

                case "$progText33":  # System Type
                    loadLookupTable($i, $progText33, TRUE, 'h.hardwareTypeID', $aryLookupTable);
                    $strSQL = "SELECT hardwareTypeID, visDescription, visManufacturer FROM hardware_types where accountID=" . $_SESSION['accountID'];
                    $result = dbquery($strSQL);
                    while ($row = mysql_fetch_array($result)) {
                        $aryLookupTable[$i]['values'][$row['hardwareTypeID']] = writePrettySystemName($row['visDescription'], $row['visManufacturer']);
                    }

                break;

                case "$progText44":  # Serial
                    loadLookupTable($i, $progText44, FALSE, 'h.serial', $aryLookupTable);
                break;

                case "$progText45":  # IP Address
                    loadLookupTable($i, $progText45, FALSE, 'h.ipAddress', $aryLookupTable);
                break;

                case "$progText740":  # Hostname
                    loadLookupTable($i, $progText740, FALSE, 'h.hostname', $aryLookupTable);
                break;

                case "$progText222":  # Status
                    loadLookupTable($i, $progText222, TRUE, 'h.hardwareStatus', $aryLookupTable);
                    $aryLookupTable[$i]['values']['n'] = $progText414;
                    $aryLookupTable[$i]['values']['i'] = $progText415;
                    $aryLookupTable[$i]['values']['w'] = $progText413;
                break;

                case "$progText420":  # Asset Tag
                    loadLookupTable($i, $progText420, FALSE, 'h.assetTag', $aryLookupTable);
                break;

                case "$progText34":  # Location
                    loadLookupTable($i, $progText34, TRUE, 'h.locationID', $aryLookupTable);
                    $strSQL = "SELECT locationID, locationName FROM locations where accountID=" . $_SESSION['accountID'] . "";
                    $result = dbquery($strSQL);
                    while ($row = mysql_fetch_array($result)) {
                        $aryLookupTable[$i]['values'][$row['locationID']] = $row['locationName'];
                    }
                break;

                case "$progText35":  # Room Name
                    loadLookupTable($i, $progText35, FALSE, 'h.roomName', $aryLookupTable);
                break;

                case "$progText421": # Purchase Date
                    loadLookupTable($i, $progText421, FALSE, 'h.purchaseDate', $aryLookupTable);
                    $aryLookupTable[$i]['date'] = TRUE;
                break;

                case "$progText422": # Warrantied Until
                    loadLookupTable($i, $progText422, FALSE, 'h.warrantyEndDate', $aryLookupTable);
                    $aryLookupTable[$i]['date'] = TRUE;
                break;

                case "$progText424": # Purchase Price
                    loadLookupTable($i, $progText424, FALSE, 'h.purchasePrice', $aryLookupTable);
                break;

                case "$progText50": # Last Agent Update
                    loadLookupTable($i, $progText50, FALSE, 'h.lastAgentUpdate', $aryLookupTable);
                    $aryLookupTable[$i]['date'] = TRUE;
                break;

                case "$nicmac1": # Nic Mac 1
                    loadLookupTable($i, $nicmac1, FALSE, 'h.nicMac1', $aryLookupTable);
                break;

                case "$nicmac2": # Nic Mac 2
                    loadLookupTable($i, $nicmac2, FALSE, 'h.nicMac2', $aryLookupTable);
                break;

                case "$progText1226":  # Vendor
                    loadLookupTable($i, $progText1226, TRUE, 'h.vendorID', $aryLookupTable);
                    $strSQL = "SELECT vendorID, vendorName FROM vendors where accountID=" . $_SESSION['accountID'] . "";
                    $result = dbquery($strSQL);
                    while ($row = mysql_fetch_array($result)) {
                        $aryLookupTable[$i]['values'][$row['vendorID']] = $row['vendorName'];
                    }
                break;

                case "$progText761": # Total RAM
                    loadLookupTable($i, $progText761, TRUE, 'h.hardwareID', $aryLookupTable);
                    $strSQL = "SELECT visDescription, hardwareID FROM peripherals LEFT JOIN peripheral_traits ON peripherals.peripheralTraitID=peripheral_traits.peripheralTraitID WHERE peripheral_traits.visTypeClass='RAM'";
                    $result = dbquery($strSQL);
                    while ($row = mysql_fetch_array($result)) {
                        $ramAry = split(" ", $row['visDescription']);
                        // Factor out, perhaps?
                        if ($ramAry[1] != "MB" || !is_numeric($ramAry[0])) {
                            //die("Unexpected RAM description");
                            continue;
                        }
                        if ($aryLookupTable[$i]['values'][$row['hardwareID']] != "") {
                            $existing = split(" ", $aryLookupTable[$i]['values'][$row['hardwareID']]);
                            $currentAmount = $existing[0];
                        } else {
                            $currentAmount = 0;
                        }
                        $aryLookupTable[$i]['values'][$row['hardwareID']] = ($currentAmount + $ramAry[0]) . " MB";
                    }
                break;

                case "$progText762": # Total Disk Space
                    loadLookupTable($i, $progText762, TRUE, 'h.hardwareID', $aryLookupTable);
                    $strSQL = "SELECT size, hardwareID FROM logicaldisks";
                    $result = dbquery($strSQL);
                    while ($row = mysql_fetch_array($result)) {
                        $sizeAry = split(" ", $row['size']);
                        // Factor out, perhaps?
                        if ($sizeAry[1] != "MB" || !is_numeric($sizeAry[0])) {
                            //die("Unexpected size description");
                            continue;
                        }
                        if ($aryLookupTable[$i]['values'][$row['hardwareID']] != "") {
                            $existing = split(" ", $aryLookupTable[$i]['values'][$row['hardwareID']]);
                            $currentAmount = $existing[0];
                        } else {
                            $currentAmount = 0;
                        }
                        $aryLookupTable[$i]['values'][$row['hardwareID']] = ($currentAmount + $sizeAry[0]) . " MB";
                    }
                break;

                case "$progText763": # Total Disk Free Space
                    loadLookupTable($i, $progText763, TRUE, 'h.hardwareID', $aryLookupTable);
                    $strSQL = "SELECT freeSpace, hardwareID FROM logicaldisks";
                    $result = dbquery($strSQL);
                    while ($row = mysql_fetch_array($result)) {
                        $freeAry = split(" ", $row['freeSpace']);
                        // Factor out, perhaps?
                        if ($freeAry[1] != "MB" || !is_numeric($freeAry[0])) {
                            //die("Unexpected size description");
                            continue;
                        }
                        if ($aryLookupTable[$i]['values'][$row['hardwareID']] != "") {
                            $existing = split(" ", $aryLookupTable[$i]['values'][$row['hardwareID']]);
                            $currentAmount = $existing[0];
                        } else {
                            $currentAmount = 0;
                        }
                        $aryLookupTable[$i]['values'][$row['hardwareID']] = ($currentAmount + $freeAry[0]) . " MB";
                    }
                break;

                case "$progText46": # Primary OS
                    loadLookupTable($i, $progText46, TRUE, 'h.hardwareID', $aryLookupTable);
                    $strSQL = "SELECT visName, visMaker, visVersion, hardwareID FROM software LEFT JOIN software_traits ON software.softwareTraitID=software_traits.softwareTraitID WHERE software_traits.operatingSystem='1'";
                    $result = dbquery($strSQL);
                    while ($row = mysql_fetch_array($result)) {
                        $aryLookupTable[$i]['values'][$row['hardwareID']] = writePrettySoftwareName($row['visName'], $row['visVersion'], $row['visMaker']);
                    }
                break;

                case "$extraSystemField": # user-defined field ("other" by default)
                    loadLookupTable($i, $extraSystemField, FALSE, 'h.other1', $aryLookupTable);
                break;
              }
          }

          // Form an SQL query based on lookup array
          $strSQL = "SELECT DISTINCT ";
          for ($i=1; $i<=$numToShow; $i++) {
              $strSQL .= $aryLookupTable[$i]['sqlColumn'];
              if ($i != $numToShow) {
                  $strSQL .= ", ";
              }
          }
          if ($strSoftwareType) {
              $strFrom1 = ", software AS s, software_traits AS st";
          }
          if ($strPeripheralType) {
               $strFrom2 = ", peripherals AS p, peripheral_traits AS pt";
          }

          $strSQL .= " FROM hardware AS h $strFrom1 $strFrom2 ";

          // Process the WHERE clause from the drop downs
          $strWhereClause = " WHERE ";

          if ($cboSystemOwnership != "") {
              $strWhereClause .= "h.sparePart='$cboSystemOwnership' AND ";
          }
          if ($cboSystemType != "") {
              $strWhereClause .= listToOrString($cboSystemType, "h.hardwareTypeID");
          }
          if ($cboLocationID != "") {
              $strWhereClause .= listToOrString($cboLocationID, "h.locationID");
          }
          if ($strPurchaseDate AND $cboPurchaseDate) {
              $strWhereClause .= " h.purchaseDate IS NOT NULL AND h.purchaseDate " . convertSign($cboPurchaseDate) . " " . dbDate($strPurchaseDate) . " AND " ;
          }
          if ($strPurchasePrice AND $cboPurchasePrice) {
              $strWhereClause .= " h.purchasePrice IS NOT NULL AND h.purchasePrice " . convertSign($cboPurchasePrice) . " " . $strPurchasePrice . " AND " ;
          }
          if ($strWarrantyDate AND $cboWarrantyDate) {
              $strWhereClause .= " h.warrantyEndDate IS NOT NULL AND h.warrantyEndDate  " . convertSign($cboWarrantyDate) . " " . dbDate($strWarrantyDate) . " AND " ;
          }
          if ($strAgentDate AND $cboAgentDate) {
              $strWhereClause .= " h.lastAgentUpdate  IS NOT NULL AND h.lastAgentUpdate   " . convertSign($cboAgentDate) . " " . dbDate($strAgentDate) . " AND " ;
          }
          if ($strSoftwareType) {
               $strWhereClause .= " s.hardwareID = h.hardwareID AND st.softwareTraitID=s.softwareTraitID AND s.hidden = '0' AND (st.visName LIKE '%$strSoftwareType%' OR st.visMaker LIKE '%$strSoftwareType%' OR st.visVersion LIKE '%$strSoftwareType%') AND ";
          }
          if ($strPeripheralType) {
               $strWhereClause .= " p.hardwareID = h.hardwareID AND pt.peripheralTraitID=p.peripheralTraitID AND p.hidden = '0' AND (pt.visManufacturer LIKE '%$strPeripheralType%' OR pt.visModel LIKE '%$strPeripheralType%' OR pt.visDescription LIKE '%$strPeripheralType%') AND ";
          }
          if ($cboVendorID != "") {
              $strWhereClause .= listToOrString($cboVendorID, "h.vendorID");
          }
          $strWhereClause .= "h.accountID=" . $_SESSION['accountID'] . "";
          $strSQL .= $strWhereClause;

          // Load up the array containing the results from the SQL and sort

          $result = dbquery($strSQL);
          $i=1;
          $numResults = mysql_num_rows($result);
          if ($numResults == 0) {
              $strError = $progText756; # Handle the empty set
          } else {
              while ($row = mysql_fetch_array($result)) {
                  for ($j=1; $j<=$numToShow; $j++) {
                      if ($aryLookupTable[$j]['fromArray'] == FALSE) {
                          $aryResult[$i][$j] = $row[($j-1)];  # Get value from SQL
                      } else {  # Get value from lookup array
                          $aryResult[$i][$j] = $aryLookupTable[$j]['values'][$row[($j-1)]];
                      }
                  }
                  $i++;
              }
          }
      }

      // Sort the multi dimensional result array by secondary index

      if (!$strError) {
          $arySortedResult = sortBySecondIndex($aryResult, $btnSort);
      }
  }
  // Date massage
  for ($i = 0; $i < count($arySortedResult); $i++) {
      for ($j = 1; $j <= $numToShow; $j++) {
          if ($aryLookupTable[$j]['date'] == TRUE) {
              $arySortedResult[$i][$j] = displayDate($arySortedResult[$i][$j]);
          }
      }
  }

  if (($exportMethod != "") AND (!$strError)) {
      $attributeList = "";
      $showList = "";
      if (1 <= $numAttributes) {
          $attributeList = $aryAttribute[1];
          $showList = $aryShow[1];
      }
      for ($i=2; $i <= $numAttributes; $i++) {
          $attributeList .= ",".$aryAttribute[$i];
          $showList.=",".$aryShow[$i];
      }

      // systemList[1] contains the list in aryAttribute seperated by comma.
      // systemList[2] contains the list in aryShow seperated by comma.
      // systemList[3] contains the sort position.

      setcookie("systemList[1]", $attributeList, (time()+18000000)); # 5000 hour expiration
      setcookie("systemList[2]", $showList, (time()+18000000)); # 5000 hour expiration
      setcookie("systemList[3]", $btnSortPosition, (time()+18000000)); # 5000 hour expiration

      switch ($exportMethod) {
         case "$progText750": # Preview in HTML
?>
<HTML>
<HEAD>
<TITLE><? echo $progText720; ?></TITLE>
<LINK REL=StyleSheet HREF="styles.css" TYPE="text/css">
</HEAD><BODY bgcolor="#FFFFFF" vlink='blue' alink='blue'>
<table border='0' cellpadding='0' cellspacing='0' width='<?=$windowWidth;?>'>
<tr><td><a href='reportSystems.php' class='larger'><b><?=$progText757;?></b></a><p>
<?
             declareError(TRUE);
             generateHTMLTable($arySortedResult, $aryLookupTable, $numToShow, $numResults);

             if (getOrPost('includeGraph') == "1") {
				if ($cboLocationID == ""){
					 $xLabel = $progText33;
					 $zLabel = $progText34;
					?>
					<table border=0 width=300>
						<tr>
							<td>
					<?
					createGraph($numToShow,$aryLookupTable,$arySortedResult,$xLabel, $zLabel, $numToShow, $numResults);
					?>
							</td>
						</tr>
					</table>
					<br>
					<?
				}
             	if ($cboSystemType == ""){
					 $xLabel = $progText33;
					 $zLabel = $progText222;
					?>
					<table border=0 width=300>
						<tr>
							<td>
					<?
					createGraph($numToShow,$aryLookupTable,$arySortedResult,$xLabel, $zLabel, $numToShow, $numResults);
					?>
							</td>
						</tr>
					</table>
					<br>
					<?
				}
				if ($cboSystemOwnership == ""){
					 $xLabel = $progText33;
					 $zLabel = $progText722;
					?>
					<table border=0 width=300>
						<tr>
							<td>
					<?
					createGraph($numToShow,$aryLookupTable,$arySortedResult,$xLabel, $zLabel, $numToShow, $numResults);
					?>
							</td>
						</tr>
					</table>
					<br>
					<?
				}

             }
             die("</td></tr></table></BODY></HTML>");
             break;

         case "$progText751": # Export to Excel
             generateExcelFile($arySortedResult, $aryLookupTable, $numToShow);
             break;

         case "$progText752": # Export to Text File
             $delimiter = ":";
             generateTxtFile($arySortedResult, $aryLookupTable, $numToShow, $delimiter);
             break;
      }

  } else {

  writeHeader($progText720);
  declareError(TRUE);

?>
  <form name="ReportForm" method="post" action="<? echo $_SERVER['PHP_SELF']?>">
  <table border = '0' width='100%' cellpadding='4' cellspacing='0'>
   <tr>
    <td width='150'><b><?=$progText721;?></b>:</td>
   </tr>
   <tr>
    <td width='150'><?=$progText722;?>:</td>
    <td>
     <select size="1" name="cboSystemOwnership">
       <option value=''> </option>
       <option value='0' <? echo writeSelected($cboSystemOwnership, "0"); ?>><?=$progText725;?></option>
       <option value='1' <? echo writeSelected($cboSystemOwnership, "1"); ?>><?=$progText377;?></option>
       <option value='2' <? echo writeSelected($cboSystemOwnership, "2"); ?>><?=$progText472;?></option>
       <? if ($adminDefinedCategory) { ?>
         <option value='3'<? echo writeSelected($cboSystemOwnership, "3"); ?>><?=ucfirst($adminDefinedCategory);?></option>
       <? } ?>
     </select>
    </td>
   </tr>
   <tr>
    <td width='150' valign='top'><?=$progText33;?>:</td>
    <td valign="top">
     <font class="soft_instructions"><?= $progText777;?></font>
     <br>
     <select multiple size="3" name="cboSystemType[]">
       <?
       // Get all hardware types for the drop down menu
       $strSQLx = "SELECT hardwareTypeID, visDescription, visManufacturer FROM hardware_types WHERE
         accountID=" . $_SESSION['accountID'] ." ORDER BY visDescription ASC";
       $resultx = dbquery($strSQLx);
       while ($rowx = mysql_fetch_array($resultx)) {
         echo "   <option value=\"".$rowx['hardwareTypeID']."\"";
         echo writeSelected($cboSystemType, $rowx['hardwareTypeID']);
         echo ">".writePrettySystemName($rowx['visDescription'], $rowx['visManufacturer'])."</option>\n";
       }
       ?>
     </select>
    </td>
   </tr>
   <? if (!$_SESSION['stuckAtLocation']) { ?>
   <tr>
    <td width='150' valign='top'><?=$progText34;?>:</td>
    <td>
      <?  buildLocationSelect($cboLocationID, FALSE, FALSE, FALSE, FALSE, 3);  ?>
    </td>
   </tr>
   <? } ?>
   <tr>
    <td width='150' valign='top'><?=$progText1226;?>:</td>
    <td>
      <?  buildVendorSelect($cboVendorID, FALSE, FALSE, FALSE, FALSE, 3);  ?>
    </td>
   </tr>
   <tr>
   <tr>
    <td width='150'><?=$progText421;?>:</td>
    <td>
        <select name='cboPurchaseDate'>
            <option value="lt" <?=writeSelected($cboPurchaseDate, "lt");?>><</OPTION>
            <option value="gt" <?=writeSelected($cboPurchaseDate, "gt");?>>></OPTION>
            <option value="eq" <?=writeSelected($cboPurchaseDate, "eq");?>>=</OPTION>
        </select>
        <? buildDate('txtPurchaseDate', $strPurchaseDate) ?>
    </td>
   </tr>
   <tr>
      <td width='150'><?=$progText422;?>:</td>
      <td>
        <select name='cboWarrantyDate'>
            <option value="lt" <?=writeSelected($cboWarrantyDate, "lt");?>><</option>
            <option value="gt" <?=writeSelected($cboWarrantyDate, "gt");?>>></option>
            <option value="eq" <?=writeSelected($cboWarrantyDate, "eq");?>>=</option>
        </select>
        <? buildDate('txtWarrantyDate', $strWarrantyDate) ?>
      </td>
   </tr>
   <tr>
      <td width='150'><?=$progText50;?>:</td>
      <td>
        <select name='cboAgentDate'>
            <option value="lt" <?=writeSelected($cboAgentDate, "lt");?>><</option>
            <option value="gt" <?=writeSelected($cboAgentDate, "gt");?>>></option>
            <option value="eq" <?=writeSelected($cboAgentDate, "eq");?>>=</option>
        </select>
        <? buildDate('txtAgentDate', $strAgentDate) ?>
      </td>
   </tr>
   <tr>
      <td width='150'><?=$progText424;?>:</td>
      <td>
        <select name='cboPurchasePrice'>
            <option value="lt" <?=writeSelected($cboPurchasePrice, "lt");?>><</OPTION>
            <option value="gt" <?=writeSelected($cboPurchasePrice, "gt");?>>></OPTION>
            <option value="eq" <?=writeSelected($cboPurchasePrice, "eq");?>>=</OPTION>
        </select>
       <INPUT SIZE="10" MAXLENGTH="11" TYPE="Text" name="txtPurchasePrice" VALUE="<? echo antiSlash($strPurchasePrice); ?>">
     </td>
   </tr>
   <tr>
      <TD width='150'><?=$progText380;?>:</TD>
      <TD><INPUT SIZE="40" MAXLENGTH="70" TYPE="Text" NAME="txtSoftwareType" VALUE="<? echo antiSlash($strSoftwareType); ?>"></TD>
   </tr>
   <tr>
      <TD width='150'><?=$progText382;?>:</TD>
      <TD><INPUT SIZE="40" MAXLENGTH="70" TYPE="Text" NAME="txtPeripheralType" VALUE="<? echo antiSlash($strPeripheralType); ?>"></TD>
   </tr>
  </table><br>
  <table border='0' cellpadding='4' cellspacing='0'>
   <tr>
    <td colspan='4'><b><?=$progText728;?></b>:</td>
   </tr>
   <tr class='title'>
    <td width='50'><b><?=$progText734;?></b>  </td>
    <td width='190'><b><?=$progText735;?></b>  </td>
    <td><b><?=$progText736;?></b>  </td>
    <td><b><?=$progText737;?></b></td>
   </tr>
<?
      for ($i=1; $i<=$numAttributes; $i++) {
          // Figure and display appropriate on/off button
          echo "<tr><td><input type=\"checkbox\" name=\"btnShow[".$i."]\" value=\"1\" ".writeChecked($aryShow[$i],1)."></td>\n";

          // Display the attribute for the individual row
          echo "<td>".$aryAttribute[$i]."  </td>\n";

          // Display the up/down buttons for the individual row
          echo "<td>";
          displayUpDownButton($i, $numAttributes);
          echo "  </td>\n";

          // Display the sort buttons
          echo "<td><input type=\"radio\" name=\"btnSort\" value=\"".$i."\" ".writeChecked($i, $btnSort)."></td>\n";
          echo "</tr>\n";
      }
      echo "</table>\n";

    createExportButtons(TRUE);
?>
  <input type="hidden" name="numAttributes" value="<? echo $numAttributes; ?>">
  <input type="hidden" name="aryPassedShow" value="<? echo urlencode(serialize($aryShow));?>">
  <input type="hidden" name="aryPassedAttribute" value="<? echo urlencode(serialize($aryAttribute));?>">
  <input type="hidden" name="bolSubmit" value="TRUE">
  </form>
<?
  writeFooter();
  }
?>


text:
- `GET /`
  - Loads React web app
  - Splash page if not logged in

### Users

- `GET /users/new`
- `POST /users`
- `PATCH /users`

### Session

- `GET /session/new`
- `POST /session`
- `DELETE /session`

## JSON API

### Teams
- `GET /api/teams/:id/projects`
  - Index of all projects & tasks for team
- `POST /api/teams`
- `GET /api/teams/:id`
  - View team admin details, if I get to that
- `PATCH /api/teams/:id`
  - Edit team admin details, if I get to that
- `DELETE /api/teams/:id`
  - Delete team, if I get to that

### Memberships
- `GET /api/memberships`
  - Includes query param for typeahead suggestions, if I get to that
- `POST /api/teams/:team_id/memberships`:
  - Add member to team by id
  - If member doesn't exist, they will be invited to create account
- `DELETE /api/teams/:team_id/memberships/:member_id`:
  - Remove member from team by id

### Projects
- `GET /api/projects/:id`
  - Index of all tasks for project
- `POST /api/projects`
- `PATCH /api/projects/:id`
- `DELETE /api/projects/:id`

### Tasks
- `GET /api/tasks`
  - For searching tasks available to user
- `POST /api/tasks`
- `GET /api/tasks/:id`
- `PATCH /api/tasks/:id`
- `DELETE /api/tasks/:id`

### Comments
- A tasks's comments are shown on the task show template
- `POST /api/tasks/:task_id/comments`:
  - Add comment to task
- `DELETE /api/comments/:comment_id`:
  - Remove comment from task

### Uploads
- Uploads (attached files) are shown on task show template
- `POST /api/tasks/:task_id/uploads`:
  - Add upload to task
- `DELETE /api/uploads/:upload_id
  - Remove upload from task

### Followers
- Task Followers are shown on task show template
- `GET /api/followers`
  - includes query param for typeahead suggestions, if I get to that
- `POST /api/tasks/:task_id/followers`:
  - Add follower to task by id
  - If follower doesn't exist, they will be invited to create account, if I get to that
- `DELETE /api/tasks/:task_id/follower/:follower_id`:
  - Remove follower from task by id


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="creditmemo_items">
            <block class="Magento\Downloadable\Block\Adminhtml\Sales\Items\Column\Downloadable\Name" name="column_name_downloadable" template="sales/items/column/downloadable/creditmemo/name.phtml" group="column"/>
        </referenceBlock>
    </body>
</page>


text:
layout: post
title:  "On Using a SBT Plugins with Heroku"
categories: blog resonance
---

One quick pro-tip for those who are using a sbt plugin as a [project dependency][projdep] on [Heroku][heroku] and run into a problem like this:

```text
Initialized empty Git repository in /tmp/build_fa31e5a8-c0d8-4f29-b45a-c1ea4dbf3e0f/.sbt_home/.sbt/0.13/staging/e8a2b2d1a8bd62bf8e10/sbt-jasmine-plugin/.git/
fatal: Not a git repository: '.'
[error] Nonzero exit code (128): git checkout -q 0.7
[error] Use 'last' for the full log.
Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore?  !     Failed to build app with sbt
! Push rejected, failed to compile Scala app
```

You might have noticed that buried in the first line of the output is a reference to the fact that I am using the [sbt-jasmine-plugin][sbtjas]. The documentation suggests using the plugin via a project dependency like:

```scala
lazy val plugins = Project("plugins", file("."))
  .dependsOn(uri("git://github.com/guardian/sbt-jasmine-plugin.git#1.0"))
```

Locally, sbt resolves the project fine, but using the git-based workflow of Heroku (which is pretty sweet in general), this doesn't seem to work. Rather than rock the boat and try something extra-clever (like hooking fancy [``before_deploy`` scripting][scripting] into my Travis CI build), I sought out a solution that better fit into the Heroku workflow.

I found [this tumblr post][post] that described a similar situation with a library dependency. (That post goes through a lot more detail than I do here, and do read it for a more step-by-step walkthrough of the problem.)

The summary is to use [git submodules][submod] and let Heroku resolve the external git repo for you. In the case of a plugin, you are adding a submodule in the ``project/lib`` directory. At that point, the line in the [``project/project/Plugins.scala`` file][pluginfile], looks like:

```scala
lazy val plugins = Project("root", file("."))
    .dependsOn(file("lib/sbt-jasmine-plugin"))
```

Push it all to Heroku, and then you should be all set!

[projdep]: http://www.scala-sbt.org/release/docs/Extending/Plugins.html#d-project-dependency
[heroku]: https://www.heroku.com/
[sbtjas]: https://github.com/guardian/sbt-jasmine-plugin
[scripting]: http://about.travis-ci.org/docs/user/deployment/heroku/#Running-commands-before-and-after-deploy
[post]: http://asoftsea.tumblr.com/post/14157451282/i-think-we-can-manage
[submod]: https://devcenter.heroku.com/articles/git-submodules
[pluginfile]: https://github.com/jasonklarsen/resonance/blob/0.0.2/project/project/Plugins.scala


text:
import * as Express from 'express';
import { Builder } from './EndpointModel';

export default class Endpoint {

    /**
     * Returns the API Root response body
     */
    public GetApiRootBody(): string {
        return this.apiRootBody;
    }

    /**
     * Returns the $metadata response body
     */
    public GetMetadataBody(): string {
        return JSON.stringify(this.ModelBuilder.GetModel());
    }

    // todo: from modelbuilder
    private apiRootBody: string = 'ApiRootBody';

    private router: Express.Router = Express.Router();

    private registerExpressRoute(expressAppRef: Express.Application) {
        this.router.get('/', (req, resp) => {
            resp
                // .set("Content-Type", "text/xml")
                .status(200)
                .send(this.GetApiRootBody());
        });

        this.router.get('/([\$])metadata', (req, resp) => {
            resp
                // .set("Content-Type", "text/xml")
                .status(200)
                .send(this.GetMetadataBody());
        });

        expressAppRef.use(`/${this.ModelBuilder.NameSpaceRoot}`, this.router);

    }

    /**
     * Constructs an OData endpoint from the specified models
     * and registers it to an Express application to a specific route
     * @param expressAppRef The Express application reference to register the OData Endpoint
     * @param route The root for the OData endpoint (e.g. 'odata.svc')
     * @param ModelBuilder The OData modelbuilder which defines what entities will be registered into the endpoint
     */
    constructor(expressAppRef: Express.Application, private ModelBuilder: Builder) {
        this.registerExpressRoute(expressAppRef);
    }
}


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

internal static partial class Interop
{
    internal static partial class Sys
    {
        internal const int IPv4AddressBytes = 4;
        internal const int IPv6AddressBytes = 16;

        internal const int MAX_IP_ADDRESS_BYTES = 16;

        internal const int INET_ADDRSTRLEN = 22;
        internal const int INET6_ADDRSTRLEN = 65;

        // NOTE: `_isIPv6` cannot be of type `bool` because `bool` is not a blittable type and this struct is
        //       embedded in other structs for interop purposes.
        [StructLayout(LayoutKind.Sequential)]
        internal unsafe struct IPAddress : IEquatable<IPAddress>
        {
            public bool IsIPv6
            {
                get { return _isIPv6 != 0; }
                set { _isIPv6 = value ? 1u : 0u; }
            }

            internal fixed byte Address[MAX_IP_ADDRESS_BYTES]; // Buffer to fit an IPv4 or IPv6 address
            private  uint _isIPv6;                             // Non-zero if this is an IPv6 address; zero for IPv4.
            internal uint ScopeId;                             // Scope ID (IPv6 only)

            public bool Equals(IPAddress other)
            {
                int addressByteCount;
                if (IsIPv6)
                {
                    if (!other.IsIPv6)
                    {
                        return false;
                    }
                    if (ScopeId != other.ScopeId)
                    {
                        return false;
                    }

                    addressByteCount = IPv6AddressBytes;
                }
                else
                {
                    if (other.IsIPv6)
                    {
                        return false;
                    }

                    addressByteCount = IPv4AddressBytes;
                }

                fixed (byte* thisAddress = Address)
                {
                    for (int i = 0; i < addressByteCount; i++)
                    {
                        if (thisAddress[i] != other.Address[i])
                        {
                            return false;
                        }
                    }
                }

                return true;
            }
        }
    }
}


text:
#ifndef __MD5_H__
#define __MD5_H__

/*
===============================================================================

	Calculates a checksum for a block of data
	using the MD5 message-digest algorithm.

===============================================================================
*/
struct MD5_CTX {
	unsigned int	state[4];
	unsigned int	bits[2];
	unsigned char	in[64];
};

void MD5_Init( MD5_CTX *ctx );
void MD5_Update( MD5_CTX *context, unsigned char const *input, size_t inputLen );
void MD5_Final( MD5_CTX *context, unsigned char digest[16] );

unsigned int MD5_BlockChecksum( const void *data, size_t length );

#endif /* !__MD5_H__ */


text:
package com.thoughtworks.go.config;

import com.thoughtworks.go.config.elastic.ElasticConfig;
import com.thoughtworks.go.config.elastic.ElasticProfile;
import com.thoughtworks.go.config.elastic.ElasticProfiles;
import com.thoughtworks.go.config.materials.MaterialConfigs;
import com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.domain.packagerepository.*;
import com.thoughtworks.go.domain.scm.SCMMother;
import com.thoughtworks.go.domain.scm.SCMs;
import com.thoughtworks.go.helper.GoConfigMother;
import com.thoughtworks.go.helper.MaterialConfigsMother;
import com.thoughtworks.go.util.Node;
import org.hamcrest.MatcherAssert;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;

public class PipelineConfigSaveValidationContextTest {

    private PipelineConfig pipelineConfig;
    private PipelineConfigSaveValidationContext pipelineContext;

    @Before
    public void setUp() throws Exception {
        pipelineConfig = mock(PipelineConfig.class);
        pipelineContext = PipelineConfigSaveValidationContext.forChain(true, "group", pipelineConfig);
    }

    @Test
    public void shouldCreatePipelineValidationContext() {
        assertThat(pipelineContext.getPipeline(), is(pipelineConfig));
        assertThat(pipelineContext.getStage(), is(nullValue()));
        assertThat(pipelineContext.getJob(), is(nullValue()));
    }

    @Test
    public void shouldCreateStageValidationContextBasedOnParent() {
        StageConfig stageConfig = mock(StageConfig.class);
        PipelineConfigSaveValidationContext stageContext = PipelineConfigSaveValidationContext.forChain(true, "group", pipelineConfig, stageConfig);

        assertThat(stageContext.getPipeline(), is(pipelineConfig));
        assertThat(stageContext.getStage(), is(stageConfig));
        assertThat(stageContext.getJob(), is(nullValue()));
    }

    @Test
    public void shouldCreateJobValidationContextBasedOnParent() {
        StageConfig stageConfig = mock(StageConfig.class);
        JobConfig jobConfig = mock(JobConfig.class);
        PipelineConfigSaveValidationContext jobContext = PipelineConfigSaveValidationContext.forChain(true, "group", pipelineConfig, stageConfig, jobConfig);
        assertThat(jobContext.getPipeline(), is(pipelineConfig));
        assertThat(jobContext.getStage(), is(stageConfig));
        assertThat(jobContext.getJob(), is(jobConfig));
    }

    @Test
    public void shouldGetAllMaterialsByFingerPrint() throws Exception {
        CruiseConfig cruiseConfig = new GoConfigMother().cruiseConfigWithPipelineUsingTwoMaterials();
        MaterialConfig expectedMaterial = MaterialConfigsMother.multipleMaterialConfigs().get(1);
        PipelineConfigSaveValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig);
        MaterialConfigs allMaterialsByFingerPrint = context.getAllMaterialsByFingerPrint(expectedMaterial.getFingerprint());
        assertThat(allMaterialsByFingerPrint.size(), is(1));
        assertThat(allMaterialsByFingerPrint.first(), is(expectedMaterial));
    }
    @Test
    public void shouldReturnNullIfMatchingMaterialConfigIsNotFound() throws Exception {
        CruiseConfig cruiseConfig = new GoConfigMother().cruiseConfigWithPipelineUsingTwoMaterials();
        PipelineConfigSaveValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig);
        assertThat(context.getAllMaterialsByFingerPrint("does_not_exist"), is(nullValue()));
    }

    @Test
    public void shouldGetDependencyMaterialsForPipelines(){
        BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("p1", "p2", "p3");
        PipelineConfig p2 = cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("p2"));
        p2.addMaterialConfig(new DependencyMaterialConfig(new CaseInsensitiveString("p1"),new CaseInsensitiveString("stage") ));
        PipelineConfig p3 = cruiseConfig.getPipelineConfigByName(new CaseInsensitiveString("p3"));
        p3.addMaterialConfig(new DependencyMaterialConfig(new CaseInsensitiveString("p2"),new CaseInsensitiveString("stage") ));
        PipelineConfigSaveValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig);

        assertThat(context.getDependencyMaterialsFor(new CaseInsensitiveString("p1")).getDependencies().isEmpty(), is(true));
        assertThat(context.getDependencyMaterialsFor(new CaseInsensitiveString("p2")).getDependencies(), contains(new Node.DependencyNode(new CaseInsensitiveString("p1"),new CaseInsensitiveString("stage"))));
        assertThat(context.getDependencyMaterialsFor(new CaseInsensitiveString("p3")).getDependencies(), contains(new Node.DependencyNode(new CaseInsensitiveString("p2"),new CaseInsensitiveString("stage"))));
        assertThat(context.getDependencyMaterialsFor(new CaseInsensitiveString("junk")).getDependencies().isEmpty(), is(true));
    }

    @Test
    public void shouldGetParentDisplayName(){
        assertThat(PipelineConfigSaveValidationContext.forChain(true, "group", new PipelineConfig()).getParentDisplayName(), is("pipeline"));
        assertThat(PipelineConfigSaveValidationContext.forChain(true, "group", new PipelineConfig(), new StageConfig()).getParentDisplayName(), is("stage"));
        assertThat(PipelineConfigSaveValidationContext.forChain(true, "group", new PipelineConfig(), new StageConfig(), new JobConfig()).getParentDisplayName(), is("job"));
    }

    @Test
    public void shouldFindPipelineByName(){
        BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("p1");
        PipelineConfigSaveValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig, new PipelineConfig(new CaseInsensitiveString("p2"), new MaterialConfigs()));
        assertThat(context.getPipelineConfigByName(new CaseInsensitiveString("p1")), is(cruiseConfig.allPipelines().get(0)));
    }

    @Test
    public void shouldReturnNullWhenNoMatchingPipelineIsFound() throws Exception {
        BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("p1");
        PipelineConfigSaveValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig, new PipelineConfig(new CaseInsensitiveString("p2"), new MaterialConfigs()));
        assertThat(context.getPipelineConfigByName(new CaseInsensitiveString("does_not_exist")), is(nullValue()));
    }

    @Test
    public void shouldGetPipelineGroupForPipelineInContext(){
        String pipelineName = "p1";
        BasicCruiseConfig cruiseConfig = GoConfigMother.configWithPipelines(pipelineName);
        PipelineConfig p1 = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString(pipelineName));
        PipelineConfigSaveValidationContext context = PipelineConfigSaveValidationContext.forChain(true, PipelineConfigs.DEFAULT_GROUP, cruiseConfig, p1);
        assertThat(context.getPipelineGroup(), is(cruiseConfig.findGroup(PipelineConfigs.DEFAULT_GROUP)));
    }

    @Test
    public void shouldGetServerSecurityContext() {
        BasicCruiseConfig cruiseConfig = new BasicCruiseConfig();
        SecurityConfig securityConfig = new SecurityConfig();
        securityConfig.addRole(new RoleConfig(new CaseInsensitiveString("admin")));
        securityConfig.adminsConfig().add(new AdminUser(new CaseInsensitiveString("super-admin")));
        cruiseConfig.server().useSecurity(securityConfig);
        PipelineConfigSaveValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig);
        Assert.assertThat(context.getServerSecurityConfig(), is(securityConfig));
    }

    @Test
    public void shouldReturnIfTheContextBelongsToPipeline(){
        ValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", new PipelineConfig());
        Assert.assertThat(context.isWithinPipelines(), is(true));
        Assert.assertThat(context.isWithinTemplates(), is(false));
    }

    @Test
    public void shouldCheckForExistenceOfTemplate(){
        BasicCruiseConfig cruiseConfig = new BasicCruiseConfig();
        cruiseConfig.addTemplate(new PipelineTemplateConfig(new CaseInsensitiveString("t1")));
        PipelineConfigSaveValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig, new PipelineConfig());

        assertThat(context.doesTemplateExist(new CaseInsensitiveString("t1")), is(true));
        assertThat(context.doesTemplateExist(new CaseInsensitiveString("t2")), is(false));
    }

    @Test
    public void shouldCheckForExistenceOfSCM() throws Exception {
        BasicCruiseConfig cruiseConfig = new BasicCruiseConfig();
        cruiseConfig.setSCMs(new SCMs(SCMMother.create("scm-id")));
        ValidationContext context = ConfigSaveValidationContext.forChain(cruiseConfig);

        MatcherAssert.assertThat(context.findScmById("scm-id").getId(), is("scm-id"));

    }

    @Test
    public void shouldCheckForExistenceOfPackage() throws Exception {
        BasicCruiseConfig cruiseConfig = new BasicCruiseConfig();
        cruiseConfig.setPackageRepositories(new PackageRepositories(PackageRepositoryMother.create("repo-id")));
        cruiseConfig.getPackageRepositories().find("repo-id").setPackages(new Packages(PackageDefinitionMother.create("package-id")));
        ValidationContext context = ConfigSaveValidationContext.forChain(cruiseConfig);

        MatcherAssert.assertThat(context.findPackageById("package-id").getId(), is("repo-id"));
    }

    @Test
    public void isValidProfileIdShouldBeValidInPresenceOfElasticProfile() {
        BasicCruiseConfig cruiseConfig = new BasicCruiseConfig();
        ElasticConfig elasticConfig = new ElasticConfig();
        elasticConfig.setProfiles(new ElasticProfiles(new ElasticProfile("docker.unit-test", "prod-cluster")));
        cruiseConfig.setElasticConfig(elasticConfig);
        ValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig, new PipelineConfig());

        assertTrue(context.isValidProfileId("docker.unit-test"));
    }

    @Test
    public void isValidProfileIdShouldBeInValidInAbsenceOfElasticProfileForTheGivenId() {
        BasicCruiseConfig cruiseConfig = new BasicCruiseConfig();
        ElasticConfig elasticConfig = new ElasticConfig();
        elasticConfig.setProfiles(new ElasticProfiles(new ElasticProfile("docker.unit-test", "prod-cluster")));
        cruiseConfig.setElasticConfig(elasticConfig);
        ValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig, new PipelineConfig());

        assertFalse(context.isValidProfileId("invalid.profile-id"));
    }

    @Test
    public void isValidProfileIdShouldBeInValidInAbsenceOfElasticProfiles() {
        BasicCruiseConfig cruiseConfig = new BasicCruiseConfig();
        ValidationContext context = PipelineConfigSaveValidationContext.forChain(true, "group", cruiseConfig, new PipelineConfig());

        assertFalse(context.isValidProfileId("docker.unit-test"));
    }
}


text:
/*

jquery.aggregate.js by Greg Brown 2011. See
http://gregbrown.co.nz/code/jquery-aggregate/ for details.

License information: http://gregbrown.co.nz/code/license/

*/

/*

Find the aggregate of a certain property across a jquery element
collection. Eg to find the maximum height of a group of elements:

$('.elements').aggregate('height', 'max');

to find the first non-zero height from a group of elements:

$('.elements').aggregate('height', function() {
    for (var i = 0; i < arguments.length; i++) {
        if (arguments[i]) {
            return arguments[i];
        }
    }
});

property: any callable jquery element property, eg. 'height',
      'outerWidth', 'scrollTop' etc, or a callable taking the element
      as its sole argument, or an array where the first item is the callable
      and subsequent items are the arguments to be passed, i.e.
      `['outerHeight', true]`.
type: 'max', 'min', 'sum', or a callable taking a variable number of arguments
      to be aggregated

*/

$.fn.aggregate = (function(property, type){
    if (typeof property === 'function') {
        var values = this.map(function () {
            return property($(this));
        });
    }
    else {
        if (typeof property === 'string') {
            property = [property];
        }
        var values = this.map(function () {
            return $(this)[property[0]].apply($(this), property.slice(1));
        });
    }
    if (type === 'sum') {
        var sum = 0;
        for (var i = 0; i < values.length; i++) {
            sum += values[i];
        }
        return sum;
    }
    else if (typeof type === 'function') {
        return type.apply(null, values.get());
    }
    else {
        return Math[type].apply(null, values.get());
    }
});

/*

Normalize a certain property across a jquery element collection, with
optional grouping into rows.
Eg to make a group of elements all the same height as the highest, in
rows of 4 elements each:

$('.elements').normalize({
    property: 'height',
    type: 'max',
    per_row: $('.elements').parent().width() + 'px',
    callback: function(el, val) {
        el.css('paddingTop', val - el.height() + 'px');
    }
});

property: any callable jquery element property (default 'height') or
      callable taking the element as its sole argument.
type: 'max', 'min', or a callable taking a variable number of
      arguments to be aggregated (default 'max')
per_row: number of elements in a row as an int, or a width in pixels,
         e.g. '300px'. (default is to normalize all elements as one)
callback: used to apply the aggregate to each element. (default
          is to use the same method specified in the property option.

*/

$.fn.normalize = (function(options){
    if (this.length) {
        var els, agg,
            // assume all have the same box-sizing & padding
            border_box = (this.css('box-sizing') === 'border-box'),
            options = $.extend({
                property: 'height',
                type: 'max',
                per_row: this.length,
                callback: function(el, val) {
                    if (options.property === 'height') {
                        var prop = 'minHeight',
                            padding = parseInt(el.css('paddingTop')) +
                                      parseInt(el.css('paddingBottom'));
                    }
                    else {
                        var prop = options.property;

                        if (prop === 'width') {
                            var padding = parseInt(el.css('paddingLeft')) +
                                          parseInt(el.css('paddingRight'));
                        }
                    }
                    el.css(prop, val + (border_box ? padding : 0) + 'px');
                }
            }, options);

        function row_item_count(items) {
            /* Get the number of items in the row - either the static per_row
               value, or the number of items that can be fitted within the
               per_row width. */
            if (typeof options.per_row === 'string' &&
                options.per_row.slice(-2) === 'px') {
                var j = 0,
                    width = items.eq(0).outerWidth(true);

                while (width <= parseInt(options.per_row) && j < items.length) {
                    if (j + 1 < items.length) {
                        width += items.eq(j + 1).outerWidth(true);
                    }
                    j++;
                }

                // at least one item per row, regardless of its length
                return Math.max(j, 1);
            }
            else {
                return options.per_row;
            }
        };

        var i = 0,
            items_per_row;
        while (i < this.length) {
            items_per_row = row_item_count(this.slice(i));

            els = this.slice(i, i + items_per_row);
            agg = els.aggregate(options.property, options.type);
            els.each(function() {
                options.callback($(this), agg);
            });
            i += items_per_row;
        }
    }
    return this;
});


text:
require 'spec_helper'

describe MatrixSpiralizer do
  describe '#read' do
    it 'throws an exception if the input is invalid' do
      input = [%w(A b), %w(D C)] # contains lowercase character

      expect { MatrixSpiralizer.new(input).read }.to raise_error(MatrixSpiralizer::InvalidInputError)
    end

    it 'returns a downcased string' do
      input = [%w(A B), %w(D C)]

      result = MatrixSpiralizer.new(input).read

      expect(result.downcase).to eq(result)
    end

    it 'returns a string' do
      input = [
        %w(A B C D),
        %w(J K L E),
        %w(I H G F)
      ]

      result = MatrixSpiralizer.new(input).read

      expect(result).to eq('a b c d e f g h i j k l')
    end
  end

  describe '#validate_matrix' do
    subject { spiralizer.validate_matrix }

    context 'given an input with varying inner-array lengths' do
      let(:spiralizer) do
        MatrixSpiralizer.new([
          %w(A B C),
          %w(D E F G),
          %w(H I J)
        ])
      end

      it 'raises an exception' do
        expect { subject }.to raise_error(MatrixSpiralizer::InconsistentLengthError)
      end
    end

    context 'given an input that contains lowercase characters' do
      let(:spiralizer) { MatrixSpiralizer.new([%w(A B), %w(D c)]) }

      it 'raises an exception' do
        expect { subject }.to raise_error(MatrixSpiralizer::InvalidInputError)
      end
    end

    context 'given an input that contains numeric characters' do
      let(:spiralizer) { MatrixSpiralizer.new([['A', 'B'], ['C', 4]]) }

      it 'raises an exception' do
        expect { subject }.to raise_error(MatrixSpiralizer::InvalidInputError)
      end
    end

    context 'given an input that contains special characters' do
      let(:spiralizer) { MatrixSpiralizer.new([['!', 'B'], ['C', 'D']]) }

      it 'raises an exception' do
        expect { subject }.to raise_error(MatrixSpiralizer::InvalidInputError)
      end
    end
  end
end


text:
A Simple Library for [GuerrillaMail](http://www.guerrillamail.com).

[![Build Status](https://travis-ci.org/taion809/GuerrillaMail.svg?branch=master)](https://travis-ci.org/taion809/GuerrillaMail)

## Requirements

* PHP 5.3+, however, [PHP 5.5](http://php.net) is recommended.
* PHP's curl extension is required if using the CurlConnection class.

## Installation
This library uses composer, you can install it like so

```json

{
    "require": {
        "johnsn/guerrillamail": "version"
    }
}

```

Replace version with the desired version or branch.
You can find additional installation details on this project's [packagist page](https://packagist.org/packages/johnsn/guerrillamail)

## Example Usage

```php

<?php
require_once __DIR__.'/vendor/autoload.php';

use GuerrillaMail\GuerrillaConnect\CurlConnection;
use GuerrillaMail\GuerrillaMail;

//The first parameter is the client's IP.
//The second parameter is the client's Browser Agent.
//There is an optional third parameter to set the api endpoint
//There's an optional fourth parameter to set the site domain
//There's an optional fifth parameter to set the API key (only needed if site access is set private)
$connection = new CurlConnection("127.0.0.1", "GuerrillaMail_Library");

//The second parameter is the client's sid (optional)
$gm = new GuerrillaMail($connection);

//Obtain an email address
$response = $gm->get_email_address();

//Fetch user's latest emails.
$emails = $gm->check_email();
```
## TODO:
I haven't given this library the TLC it deserves for awhile due to having a busy schedule so here are the couple of things that I will be taking care of in the next month or two

In no particular order:
  - [ ] Decouple transport from client, currently relies on CurlClient which is not right.
  - [ ] Move to the latest guzzle http client
  - [ ] Use a middleware for authentication
  - [ ] Better documentation and examples

## External links
[GuerrillaMail](http://www.guerrillamail.com) - Guerrilla Mail API doc

https://grr.la/ryo/guerrillamail.com/login/ - Register / login for an API key. (API key is only needed for custom domains.)

## License

This project is licensed under the MIT License.


text:
<html>
<head>
 <base href="/">
 <title>Angular 2 Tutorial</title>
 <meta charset="UTSF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
 <link rel="stylesheet" href="styles.css">

 <!-- Polyfill(s) for older browsers -->
 <script src="node_modules/es6-shim/es6-shim.min.js"></script>

 <script src="node_modules/zone.js/dist/zone.js"></script>
 <script src="node_modules/reflect-metadata/Reflect.js"></script>
 <script src="node_modules/systemjs/dist/system.src.js"></script>

 <script src="systemjs.config.js"></script>
 <script>
  System.import('app').catch(function(err){ console.error(err); });
</script>
</head>

<body>
  <my-app>Loading...</my-app>
</body>
</html>


text:
INSERT INTO users VALUES (1, 'ali', 'ali@hazelcast.com');
INSERT INTO users VALUES (2, 'can', 'can@hazelcast.com');
INSERT INTO users VALUES (3, 'marko', 'marko@hazelcast.com');
INSERT INTO users VALUES (4, 'vilo', 'vilo@hazelcast.com');


text:
/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#include <seastar/core/thread.hh>
#include <seastar/core/do_with.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/condition-variable.hh>
#include <seastar/core/do_with.hh>
#include <seastar/core/loop.hh>
#include <seastar/core/map_reduce.hh>
#include <seastar/core/sleep.hh>
#include <seastar/core/shared_mutex.hh>
#include <seastar/core/when_all.hh>
#include <seastar/core/when_any.hh>
#include <seastar/core/with_timeout.hh>
#include <boost/range/irange.hpp>

using namespace seastar;
using namespace std::chrono_literals;
using steady_clock = std::chrono::steady_clock;

SEASTAR_THREAD_TEST_CASE(test_condition_variable_signal_consume) {
    condition_variable cv;

    cv.signal();
    auto f = cv.wait();

    BOOST_REQUIRE_EQUAL(f.available(), true);
    f.get();

    auto f2 = cv.wait();

    BOOST_REQUIRE_EQUAL(f2.available(), false);

    cv.signal();

    with_timeout(steady_clock::now() + 10ms, std::move(f2)).get();

    std::vector<future<>> waiters;
    waiters.emplace_back(cv.wait());
    waiters.emplace_back(cv.wait());
    waiters.emplace_back(cv.wait());

    BOOST_REQUIRE_EQUAL(std::count_if(waiters.begin(), waiters.end(), std::mem_fn(&future<>::available)), 0u);

    cv.signal();

    BOOST_REQUIRE_EQUAL(std::count_if(waiters.begin(), waiters.end(), std::mem_fn(&future<>::available)), 1u);
    // FIFO
    BOOST_REQUIRE_EQUAL(waiters.front().available(), true);

    cv.broadcast();

    BOOST_REQUIRE_EQUAL(std::count_if(waiters.begin(), waiters.end(), std::mem_fn(&future<>::available)), 3u);
}

SEASTAR_THREAD_TEST_CASE(test_condition_variable_pred) {
    condition_variable cv;
    bool ready = false;

    try {
        cv.wait(100ms, [&] { return ready; }).get();
        BOOST_FAIL("should not reach");
    } catch (condition_variable_timed_out&) {
        // ok
    } catch (...) {
        BOOST_FAIL("should not reach");
    }
    // should not affect outcome.
    cv.signal();

    try {
        cv.wait(100ms, [&] { return ready; }).get();
        BOOST_FAIL("should not reach");
    } catch (condition_variable_timed_out&) {
        // ok
    } catch (...) {
        BOOST_FAIL("should not reach");
    }

}

SEASTAR_THREAD_TEST_CASE(test_condition_variable_signal_break) {
    condition_variable cv;

    std::vector<future<>> waiters;
    waiters.emplace_back(cv.wait());
    waiters.emplace_back(cv.wait());
    waiters.emplace_back(cv.wait());

    BOOST_REQUIRE_EQUAL(std::count_if(waiters.begin(), waiters.end(), std::mem_fn(&future<>::available)), 0u);

    cv.broken();

    for (auto& f : waiters) {
        try {
            f.get();
        } catch (broken_condition_variable&) {
            // ok
            continue;
        }
        BOOST_FAIL("should not reach");
    }

    try {
        auto f = cv.wait();
        f.get();
        BOOST_FAIL("should not reach");
    } catch (broken_condition_variable&) {
        // ok
    } catch (...) {
        BOOST_FAIL("should not reach");
    }
}

SEASTAR_THREAD_TEST_CASE(test_condition_variable_timeout) {
    condition_variable cv;

    auto f = cv.wait(100ms);
    BOOST_REQUIRE_EQUAL(f.available(), false);

    sleep(200ms).get();
    BOOST_REQUIRE_EQUAL(f.available(), true);

    try {
        f.get();
        BOOST_FAIL("should not reach");
    } catch (condition_variable_timed_out&) {
        // ok
    } catch (...) {
        BOOST_FAIL("should not reach");
    }
}

SEASTAR_THREAD_TEST_CASE(test_condition_variable_pred_wait) {
    condition_variable cv;

    bool ready = false;

    timer<> t;
    t.set_callback([&] { ready = true; cv.signal(); });
    t.arm(100ms);

    cv.wait([&] { return ready; }).get();

    ready = false;

    try {
        cv.wait(10ms, [&] { return ready; }).get();
        BOOST_FAIL("should not reach");
    } catch (timed_out_error&) {
        BOOST_FAIL("should not reach");
    } catch (condition_variable_timed_out&) {
        // ok
    } catch (...) {
        BOOST_FAIL("should not reach");
    }

    ready = true;
    cv.signal();

    cv.wait(10ms, [&] { return ready; }).get();

    for (int i = 0; i < 2; ++i) {
        ready = false;
        t.set_callback([&] { cv.broadcast();});
        t.arm_periodic(10ms);

        try {
            cv.wait(300ms, [&] { return ready; }).get();
            BOOST_FAIL("should not reach");
        } catch (timed_out_error&) {
            BOOST_FAIL("should not reach");
        } catch (condition_variable_timed_out&) {
            // ok
        } catch (...) {
            BOOST_FAIL("should not reach");
        }
        t.cancel();
        cv.signal();
    }

    ready = true;
    cv.signal();

    cv.wait([&] { return ready; }).get();
    // signal state should remain on
    cv.wait().get();
}

SEASTAR_THREAD_TEST_CASE(test_condition_variable_has_waiter) {
    condition_variable cv;

    BOOST_REQUIRE_EQUAL(cv.has_waiters(), false);

    auto f = cv.wait();
    BOOST_REQUIRE_EQUAL(cv.has_waiters(), true);

    cv.signal();
    f.get();
    BOOST_REQUIRE_EQUAL(cv.has_waiters(), false);
}

#ifdef SEASTAR_COROUTINES_ENABLED

SEASTAR_TEST_CASE(test_condition_variable_signal_consume_coroutine) {
    condition_variable cv;

    cv.signal();
    co_await with_timeout(steady_clock::now() + 10ms, [&]() -> future<> {
        co_await cv.when();
    }());

    try {
        co_await with_timeout(steady_clock::now() + 10ms, [&]() -> future<> {
            co_await cv.when();
        }());
        BOOST_FAIL("should not reach");
    } catch (condition_variable_timed_out&) {
        BOOST_FAIL("should not reach");
    } catch (timed_out_error&) {
        // ok
    } catch (...) {
        BOOST_FAIL("should not reach");
    }

    try {
        co_await with_timeout(steady_clock::now() + 10s, [&]() -> future<> {
            co_await cv.when(100ms);
        }());
        BOOST_FAIL("should not reach");
    } catch (timed_out_error&) {
        BOOST_FAIL("should not reach");
    } catch (condition_variable_timed_out&) {
        // ok
    } catch (...) {
        BOOST_FAIL("should not reach");
    }

}

SEASTAR_TEST_CASE(test_condition_variable_pred_when) {
    condition_variable cv;

    bool ready = false;

    timer<> t;
    t.set_callback([&] { ready = true; cv.signal(); });
    t.arm(100ms);

    co_await cv.when([&] { return ready; });

    ready = false;

    try {
        co_await cv.when(10ms, [&] { return ready; });
        BOOST_FAIL("should not reach");
    } catch (timed_out_error&) {
        BOOST_FAIL("should not reach");
    } catch (condition_variable_timed_out&) {
        // ok
    } catch (...) {
        BOOST_FAIL("should not reach");
    }

    ready = true;
    cv.signal();

    co_await cv.when(10ms, [&] { return ready; });

    for (int i = 0; i < 2; ++i) {
        ready = false;
        t.set_callback([&] { cv.broadcast();});
        t.arm_periodic(10ms);

        try {
            co_await cv.when(300ms, [&] { return ready; });
            BOOST_FAIL("should not reach");
        } catch (timed_out_error&) {
            BOOST_FAIL("should not reach");
        } catch (condition_variable_timed_out&) {
            // ok
        } catch (...) {
            BOOST_FAIL("should not reach");
        }
        t.cancel();
        cv.signal();
    }

    ready = true;
    cv.signal();

    co_await cv.when([&] { return ready; });
    // signal state should remain on
    co_await cv.when();
}

SEASTAR_TEST_CASE(test_condition_variable_when_signal) {
    condition_variable cv;

    bool ready = false;

    timer<> t;
    t.set_callback([&] { cv.signal(); ready = true; });
    t.arm(100ms);

    co_await cv.when();
    // ensure we did not resume before timer ran fully
    BOOST_REQUIRE_EQUAL(ready, true);
}

SEASTAR_TEST_CASE(test_condition_variable_when_timeout) {
    condition_variable cv;

    bool ready = false;

    // create "background" fiber
    auto f = [&]() -> future<> {
        try {
            co_await cv.when(100ms, [&] { return ready; });
        } catch (timed_out_error&) {
            BOOST_FAIL("should not reach");
        } catch (condition_variable_timed_out&) {
            BOOST_FAIL("should not reach");
        } catch (...) {
            BOOST_FAIL("should not reach");
        }
    }();

    // ensure we wake up waiter before timeuot
    ready = true;
    cv.signal();

    // now busy-spin until the timer should be expired
    while (cv.has_waiters()) {
    }

    // he should not have run yet...
    BOOST_REQUIRE_EQUAL(f.available(), false);
    // now, if the code is broken, the timer will run once we switch out,
    // and cause the wait to time out, even though it did not. -> assert

    co_await std::move(f);
}

#endif


text:
var expect    = require('chai').expect
var annotate  = require('../lib/tupperware').annotate

describe('tupperware#annotate', function () {

  it('throws an error for a bad fn argument', function () {
    var testCall = function () {
      annotate('notafunction')
    }

    expect( testCall ).to.throw('Bad argument: fn')
  })

  it('returns an empty array if the function has no arguments', function () {
    var result = annotate( function () {} )

    expect( result ).to.be.an('array')
    expect( result.length ).to.equal(0)
  })

  it('returns an array of the function\'s argument names', function () {
    var result = annotate( function (a, b) {} )

    expect( result ).to.be.an('array')
    expect( result.length ).to.equal(2)
    expect( result[0] ).to.equal('a')
    expect( result[1] ).to.equal('b')
  })

})