text:
/*
 * RemoteSwitch library v2.3.0 (20121229) made by Randy Simons http://randysimons.nl/
 *
 * License: GPLv3. See license.txt
 */

#ifndef RemoteTransmitter_h
#define RemoteTransmitter_h

#include <Arduino.h>

/**
* RemoteTransmitter provides a generic class for simulation of common RF remote controls, like the 'Klik aan Klik uit'-system
* (http://www.klikaanklikuit.nl/), used to remotely switch lights etc.
*
* Many of these remotes seem to use a 433MHz SAW resonator and one of these chips: LP801B,  HX2262, PT2262, M3E.
* Datasheet for the HX2262/PT2262 ICs:
* http://www.princeton.com.tw/downloadprocess/downloadfile.asp?mydownload=PT2262_1.pdf
*
* Hardware required for this library: a 433MHz/434MHz SAW oscillator transmitter, e.g.
* http://www.sparkfun.com/products/10534
* http://www.conrad.nl/goto/?product=130428
*
* Notes:
* - Since these chips use (and send!) tri-state inputs (low, high and floating) I use 'trits' instead of 'bits',
*   when appropriate.
* - I measured the period lengths with a scope.  Thus: they work for my remotes, but may fail for yours...
*   A better way would be to calculate the 'target'-timings using the datasheets and the resistor-values on the remotes.
*/
class RemoteTransmitter {
	public:
		/**
		* Constructor.
		*
		* To obtain the correct period length, an oscilloscope is convenient, but you can also read the
		* datasheet of the transmitter, measure the resistor for the oscillator and calculate the frequency.
		*
		* @param pin		output pin on Arduino to which the transmitter is connected
		* @param periodusec	[0..511] Duration of one period, in microseconds. A trit is 6 periods.
		* @param repeats	[0..7] The 2log-Number of times the signal is repeated. The actual number of repeats will be 2^repeats. 2 would be bare minimum, 4 seems robust.
		*/
		RemoteTransmitter(byte pin, unsigned int periodusec, byte repeats);

		/**
		* Encodes the data base on the current object and the given trits. The data can be reused, e.g.
		* for use with the static version of sendTelegram, so you won't need to instantiate costly objects!
		*
		* @return The data suited for use with RemoteTransmitter::sendTelegram.
		*/
		unsigned long encodeTelegram(byte trits[]);

		/**
		* Send a telegram, including synchronization-part.
		*
		* @param trits	Array of size 12. "trits" should be either 0, 1 or 2, where 2 indicates "float"
		*/
		void sendTelegram(byte trits[]);

		/**
		* Send a telegram, including synchronization-part. The data-param encodes the period duration, number of repeats and the actual data.
		* Note: static method, which allows for use in low-mem situations.
		*
		* Format data:
		* pppppppp|prrrdddd|dddddddd|dddddddd (32 bit)
		* p = period (9 bit unsigned integer)
		* r = repeats as 2log. Thus, if r = 3, then signal is sent 2^3=8 times
		* d = data
		*
		* @param data data, period and repeats.
		* @param pin Pin number of the transmitter.
		*/
		static void sendTelegram(unsigned long data, byte pin);

		/**
		* The complement of RemoteReceiver.	Send a telegram with specified code as data.
		*
		* Note: static method, which allows for use in low-mem situations.
		*
		* @param pin		output pin on Arduino to which the transmitter is connected
		* @param periodusec	[0..511] Duration of one period, in microseconds. A trit is 6 periods.
		* @param repeats	[0..7] The 2log-Number of times the signal is repeated. The actual number of repeats will be 2^repeats. 2 would be bare minimum, 4 seems robust.
		* @param code		The code to transmit. Note: only the first 20 bits are used, the rest is ignored. Also see sendTelegram.
		*/
		static void sendCode(byte pin, unsigned long code, unsigned int periodusec, byte repeats);

		/**
		* Compares the data received with RemoteReceive with the data obtained by one of the getTelegram-functions.
		* Period duration and repetitions are ignored by this function; only the data-payload is compared.
		*
		* @return true, if the codes are identical (the 20 least significant bits match)
		*/
		static boolean isSameCode(unsigned long encodedTelegram, unsigned long receivedData);

	protected:
		byte _pin;		// Transmitter output pin
		unsigned int _periodusec;	// Oscillator period in microseconds
		byte _repeats;	// Number over repetitions of one telegram
};

/**
* ActionTransmitter simulates a remote, as sold in the Dutch 'Action' stores. But there are many similar systems on the market.
* If your remote has setting for 5 address bits, and can control 5 devices on or off, then you can try to use the ActionTransmitter.
* Otherwise you may have luck with the ElroTransmitter, which is similar.
*/
class ActionTransmitter: RemoteTransmitter {
	public:
		/**
		* Constructor
		*
		* @param pin		output pin on Arduino to which the transmitter is connected
		* @param periodsec	Duration of one period, in microseconds. Default is 190usec
		* @param repeats	[0..7] The 2log-Number of times the signal is repeated.
		* @see RemoteTransmitter
		*/
		ActionTransmitter(byte pin, unsigned int periodusec=190, byte repeats=4);

		/**
		* Send a on or off signal to a device.
		*
		* @param systemCode	5-bit address (dip switches in remote). Range [0..31]
		* @param device	Device to switch. Range: [A..E] (case sensitive!)
		* @param on	True, to switch on. False to switch off,
		*/
		void sendSignal(byte systemCode, char device, boolean on);

		/**
		* Generates the telegram (data) which can be used for RemoteTransmitter::sendTelegram.
		* See sendSignal for details on the parameters
		*
		* @return Encoded data, including repeats and period duration.
		*/
		unsigned long getTelegram(byte systemCode, char device, boolean on);
};

/**
* BlokkerTransmitter simulates a remote, as sold in the Dutch 'Blokker' stores. But there are many similar systems on the market.
* These remotes have 4 on, 4 off buttons and a switch to switch between device 1-4 and 5-8. No further configuration
* possible.
*/
class BlokkerTransmitter: RemoteTransmitter {
	public:
		/**
		* Constructor
		*
		* @param pin		output pin on Arduino to which the transmitter is connected
		* @param periodsec	Duration of one period, in microseconds. Default is 307usec
		* @param repeats	[0..7] The 2log-Number of times the signal is repeated.
		* @see RemoteTransmitter
		*/
		BlokkerTransmitter(byte pin, unsigned int periodusec=230, byte repeats=4);

		/**
		* Send a on or off signal to a device.
		*
		* @param device	Device to switch. Range: [1..8]
		* @param on	True, to switch on. False to switch off,
		*/
		void sendSignal(byte device, boolean on);

		/**
		* @see RemoteTransmitter::getTelegram
		*/
		unsigned long getTelegram(byte device, boolean on);
};

/**
* KaKuTransmitter simulates a KlikAanKlikUit-remote, but there are many clones.
* If your transmitter has a address dial with the characters A till P, you can try this class.
*/
class KaKuTransmitter: RemoteTransmitter {
	public:
		/**
		* Constructor
		*
		* @param pin		output pin on Arduino to which the transmitter is connected
		* @param periodsec	Duration of one period, in microseconds. Default is 375usec
		* @param repeats	[0..7] The 2log-Number of times the signal is repeated.
		* @see RemoteTransmitter
		*/
		KaKuTransmitter(byte pin, unsigned int periodusec=375, byte repeats=4);

		/**
		* Send a on or off signal to a device.
		*
		* @param address	address (dial switches in remote). Range [A..P] (case sensitive!)
		* @param group	Group to switch. Range: [1..4]
		* @param device	Device to switch. Range: [1..4]
		* @param on	True, to switch on. False to switch off,
		*/
		void sendSignal(char address, byte group, byte device, boolean on);

		/**
		* Send a on or off signal to a device.
		*
		* @param address	address (dip switches in remote). Range [A..P] (case sensitive!)
		* @param device	device (dial switches in remote). Range [1..16]
		* @param on	True, to switch on. False to switch off,
		*/
		void sendSignal(char address, byte device, boolean on);

		/**
		* @see RemoteTransmitter::getTelegram
		*/
		unsigned long getTelegram(char address, byte group, byte device, boolean on);

		/**
		* @see RemoteTransmitter::getTelegram
		*/
		unsigned long getTelegram(char address, byte device, boolean on);
};

/**
* ElroTransmitter simulates remotes of the Elro "Home Control" series
* see http://www.elro.eu/en/m/products/category/home_automation/home_control
* There are are many similar systems on the market. If your remote has setting for 5 address bits, and can control
* 4 devices on or off, then you can try to use the ElroTransmitter. Otherwise you may have luck with the
* ActionTransmitter, which is similar.
*/
class ElroTransmitter: RemoteTransmitter {
	public:
		/**
		* Constructor
		*
		* @param pin		output pin on Arduino to which the transmitter is connected
		* @param periodsec	Duration of one period, in microseconds. Default is 320usec
		* @param repeats	[0..7] The 2log-Number of times the signal is repeated.
		* @see RemoteSwitch
		*/
		ElroTransmitter(byte pin, unsigned int periodusec=320, byte repeats=4);

		/**
		* Send a on or off signal to a device.
		*
		* @param systemCode	5-bit address (dip switches in remote). Range [0..31]
		* @param device	Device to switch. Range: [A..D] (case sensitive!)
		* @param on	True, to switch on. False to switch off,
		*/
		void sendSignal(byte systemCode, char device, boolean on);

		/**
		* Generates the telegram (data) which can be used for RemoteSwitch::sendTelegram.
		* See sendSignal for details on the parameters
		*
		* @return Encoded data, including repeats and period duration.
		*/
		unsigned long getTelegram(byte systemCode, char device, boolean on);
};

#endif


text:
package com.invariantproperties.projecteuler.figurate;

import org.junit.Assert;
import org.junit.Test;

import com.invariantproperties.projecteuler.figurate.OctagonalNumber;

import java.util.Arrays;

public class OctagonalNumberTest extends AbstractFigurateTest<Long> {
    /**
     * Constructor.
     */
    public OctagonalNumberTest() throws NoSuchMethodException {
        super(OctagonalNumber.class);
    }

    /**
     * Verify the definition is properly implemented.
     *
     * @return
     */
    @Test
    @Override
    public void verifyDefinition() {
        for (int n = 0; n < getMaxTests(); n++) {
            long x = (long) (n * ((3 * n) - 2));
            Assert.assertEquals(x, seq.get(n).longValue());
        }
    }

    /**
     * Verify initial terms.
     */
    @Test
    @Override
    public void verifyInitialTerms() {
        verifyInitialTerms(Arrays.asList(0L, 1L, 8L, 21L, 40L, 65L, 96L, 133L,
                176L, 225L, 280L, 341L));
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const awsCommon = require('../../lib/aws-common');

/**
 * Amazon CloudHSM version 2014-05-30
 *
 * --- TODO REMOVE WHEN IMPLEMENTED ---
 * AUTOGENERATED BY build-api.py
 */

// Setup input and output to use AWS protocol json
require('../../lib/aws-common/shape_http')('json', module.exports, null);
// -----------------------------------
module.exports.AddTagsToResource = function AddTagsToResource(aws) {
  var resourceArn = aws.params.ResourceArn;
  var tagList = aws.params.TagList;
  if (!resourceArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter ResourceArn'];
  }
  if (!tagList) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter TagList'];
  }

  // TODO implement code

  var ret = {
    Status: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.CreateHapg = function CreateHapg(aws) {
  var label = aws.params.Label;
  if (!label) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter Label'];
  }

  // TODO implement code

  var ret = {
    HapgArn: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.CreateHsm = function CreateHsm(aws) {
  var clientToken = aws.params.ClientToken;
  var eniIp = aws.params.EniIp;
  var externalId = aws.params.ExternalId;
  var iamRoleArn = aws.params.IamRoleArn;
  var sshKey = aws.params.SshKey;
  var subnetId = aws.params.SubnetId;
  var subscriptionType = aws.params.SubscriptionType;
  var syslogIp = aws.params.SyslogIp;
  if (!iamRoleArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter IamRoleArn'];
  }
  if (!sshKey) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter SshKey'];
  }
  if (!subnetId) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter SubnetId'];
  }
  if (!subscriptionType) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter SubscriptionType'];
  }

  // TODO implement code

  var ret = {
    HsmArn: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.CreateLunaClient = function CreateLunaClient(aws) {
  var certificate = aws.params.Certificate;
  var label = aws.params.Label;
  if (!certificate) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter Certificate'];
  }

  // TODO implement code

  var ret = {
    ClientArn: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.DeleteHapg = function DeleteHapg(aws) {
  var hapgArn = aws.params.HapgArn;
  if (!hapgArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter HapgArn'];
  }

  // TODO implement code

  var ret = {
    Status: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.DeleteHsm = function DeleteHsm(aws) {
  var hsmArn = aws.params.HsmArn;
  if (!hsmArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter HsmArn'];
  }

  // TODO implement code

  var ret = {
    Status: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.DeleteLunaClient = function DeleteLunaClient(aws) {
  var clientArn = aws.params.ClientArn;
  if (!clientArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter ClientArn'];
  }

  // TODO implement code

  var ret = {
    Status: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.DescribeHapg = function DescribeHapg(aws) {
  var hapgArn = aws.params.HapgArn;
  if (!hapgArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter HapgArn'];
  }

  // TODO implement code

  var ret = {
    HapgArn: '',
    HapgSerial: '',
    HsmsLastActionFailed: /*Sz*/[ '', /* ...*/ ],
    HsmsPendingDeletion: /*Sz*/[ '', /* ...*/ ],
    HsmsPendingRegistration: /*Sz*/[ '', /* ...*/ ],
    Label: '',
    LastModifiedTimestamp: '',
    PartitionSerialList: /*S11*/[ '', /* ...*/ ],
    State: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.DescribeHsm = function DescribeHsm(aws) {
  var hsmArn = aws.params.HsmArn;
  var hsmSerialNumber = aws.params.HsmSerialNumber;

  // TODO implement code

  var ret = {
    AvailabilityZone: '',
    EniId: '',
    EniIp: '',
    HsmArn: '',
    HsmType: '',
    IamRoleArn: '',
    Partitions: [ '', /* ...*/ ],
    SerialNumber: '',
    ServerCertLastUpdated: '',
    ServerCertUri: '',
    SoftwareVersion: '',
    SshKeyLastUpdated: '',
    SshPublicKey: '',
    Status: '',
    StatusDetails: '',
    SubnetId: '',
    SubscriptionEndDate: '',
    SubscriptionStartDate: '',
    SubscriptionType: '',
    VendorName: '',
    VpcId: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.DescribeLunaClient = function DescribeLunaClient(aws) {
  var certificateFingerprint = aws.params.CertificateFingerprint;
  var clientArn = aws.params.ClientArn;

  // TODO implement code

  var ret = {
    Certificate: '',
    CertificateFingerprint: '',
    ClientArn: '',
    Label: '',
    LastModifiedTimestamp: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.GetConfig = function GetConfig(aws) {
  var clientArn = aws.params.ClientArn;
  var clientVersion = aws.params.ClientVersion;
  var hapgList = aws.params.HapgList;
  if (!clientArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter ClientArn'];
  }
  if (!clientVersion) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter ClientVersion'];
  }
  if (!hapgList) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter HapgList'];
  }

  // TODO implement code

  var ret = {
    ConfigCred: '',
    ConfigFile: '',
    ConfigType: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.ListAvailableZones = function ListAvailableZones(aws) {

  // TODO implement code

  var ret = {
    AZList: [ '', /* ...*/ ],
  };
  return [200, ret];
};
// -----------------------------------
module.exports.ListHapgs = function ListHapgs(aws) {
  var nextToken = aws.params.NextToken;

  // TODO implement code

  var ret = {
    HapgList: /*S1i*/[ '', /* ...*/ ],
    NextToken: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.ListHsms = function ListHsms(aws) {
  var nextToken = aws.params.NextToken;

  // TODO implement code

  var ret = {
    HsmList: /*Sz*/[ '', /* ...*/ ],
    NextToken: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.ListLunaClients = function ListLunaClients(aws) {
  var nextToken = aws.params.NextToken;

  // TODO implement code

  var ret = {
    ClientList: [ '', /* ...*/ ],
    NextToken: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.ListTagsForResource = function ListTagsForResource(aws) {
  var resourceArn = aws.params.ResourceArn;
  if (!resourceArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter ResourceArn'];
  }

  // TODO implement code

  var ret = {
    TagList: /*S3*/[ {
      Key: '',
      Value: '',
    }, /* ...*/ ],
  };
  return [200, ret];
};
// -----------------------------------
module.exports.ModifyHapg = function ModifyHapg(aws) {
  var hapgArn = aws.params.HapgArn;
  var label = aws.params.Label;
  var partitionSerialList = aws.params.PartitionSerialList;
  if (!hapgArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter HapgArn'];
  }

  // TODO implement code

  var ret = {
    HapgArn: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.ModifyHsm = function ModifyHsm(aws) {
  var eniIp = aws.params.EniIp;
  var externalId = aws.params.ExternalId;
  var hsmArn = aws.params.HsmArn;
  var iamRoleArn = aws.params.IamRoleArn;
  var subnetId = aws.params.SubnetId;
  var syslogIp = aws.params.SyslogIp;
  if (!hsmArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter HsmArn'];
  }

  // TODO implement code

  var ret = {
    HsmArn: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.ModifyLunaClient = function ModifyLunaClient(aws) {
  var certificate = aws.params.Certificate;
  var clientArn = aws.params.ClientArn;
  if (!certificate) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter Certificate'];
  }
  if (!clientArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter ClientArn'];
  }

  // TODO implement code

  var ret = {
    ClientArn: '',
  };
  return [200, ret];
};
// -----------------------------------
module.exports.RemoveTagsFromResource = function RemoveTagsFromResource(aws) {
  var resourceArn = aws.params.ResourceArn;
  var tagKeyList = aws.params.TagKeyList /* Type list */;
  if (!resourceArn) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter ResourceArn'];
  }
  if (!tagKeyList) {
    return [400, 'Sender', 'MissingParameter', 'Did not specify parameter TagKeyList'];
  }

  // TODO implement code

  var ret = {
    Status: '',
  };
  return [200, ret];
};


text:
HASH

Description

No description

Children

SHA_1, SHA_256

Features

   SEQUENCE[BIT] digest(SEQUENCE[BIT] message)

      Ensures:

          digest: SEQUENCE[BIT]
            -> message: SEQUENCE[BIT]
            ensure
              Result.count = size
            end

   Show specs
   Show source

   STRING print(SEQUENCE[BIT] digest)

          print: STRING
            -> digest: SEQUENCE[BIT]

   Show source

   NATURAL size

          size: NATURAL

   Show source

   NATURAL security

          security: NATURAL

   Show source

 Show all specs
 Show all source


text:
<?xml version='1.0' encoding='ISO-8859-1'?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN"
                     "http://java.sun.com/products/javahelp/helpset_2_0.dtd"">

<helpset version="2.0">

   <title>NbGzip Help</title>

   <maps>
     <homeID>nbgzip</homeID>
     <mapref location="nbgzip-map.jhm"/>
   </maps>

   <view mergetype="javax.help.AppendMerge">
     <name>TOC</name>
     Table of Contents
     <type>javax.help.TOCView</type>
     <data>nbgzip-toc.xml</data>
   </view>

   <view mergetype="javax.help.AppendMerge">
      <name>Index</name>
      Index
      <type>javax.help.IndexView</type>
      <data>nbgzip-idx.xml</data>
   </view>

   <view>
      <name>Search</name>
      Search
      <type>javax.help.SearchView</type>
      <data engine="com.sun.java.help.search.DefaultSearchEngine">JavaHelpSearch</data>
   </view>

</helpset>


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using dexih.functions;
using System.Threading;
using dexih.functions.Query;
using dexih.transforms.Transforms;
using Dexih.Utils.CopyProperties;
using Dexih.Utils.DataType;

namespace dexih.transforms
{

    /// <summary>
    /// The join table is loaded into memory and then joined to the primary table.
    /// </summary>
    [Transform(
        Name = "Concatenate",
        Description = "Concatenate (union) the two data streams together.",
        TransformType = ETransformType.Concatenate
        )]
    public class TransformConcatenate : Transform
    {
        private Task<bool> _primaryReadTask;
        private Task<bool> _referenceReadTask;

        private bool _primaryMoreRecords;
        private bool _referenceMoreRecords;
        private List<int> _primarySortOrdinals;
        private List<int> _referenceSortOrdinals;

        private bool _sortedMerge = false;

        private readonly List<int> _primaryMappings = new List<int>();
        private readonly List<int> _referenceMappings = new List<int>();

        public TransformConcatenate() { }

        public TransformConcatenate(Transform primaryTransform, Transform concatenateTransform)
        {
            SetInTransform(primaryTransform, concatenateTransform);
        }

        private bool _firstRead;

      public override bool RequiresSort => false;

      public override string TransformName { get; } = "Concatenate Rows";

      public override Dictionary<string, object> TransformProperties()
      {
          return null;
      }

        public override async Task<bool> Open(long auditKey, SelectQuery requestQuery = null, CancellationToken cancellationToken = default)
        {
            AuditKey = auditKey;
            IsOpen = true;

            if (requestQuery == null)
            {
                requestQuery = new SelectQuery();
            }
            else
            {
                requestQuery = requestQuery.CloneProperties(true);
            }

            var primarySorts = new Sorts();
            var referenceSorts = new Sorts();

            //we need to translate filters and sorts to source column names before passing them through.
            if (requestQuery?.Sorts != null)
            {
                foreach (var sort in requestQuery.Sorts)
                {
                    if (sort.Column != null)
                    {
                        var column = PrimaryTransform.CacheTable[sort.Column.Name];
                        if (column != null)
                        {
                            primarySorts.Add(new Sort(column, sort.Direction));
                        }

                        column = ReferenceTransform.CacheTable[sort.Column.Name];
                        if (column != null)
                        {
                            referenceSorts.Add(new Sort(column, sort.Direction));
                        }
                    }
                }
            }

            SelectQuery = requestQuery;

            var primaryQuery = new SelectQuery() {Sorts = primarySorts};
            var referenceQuery = new SelectQuery() {Sorts = referenceSorts};

            var returnValue = await PrimaryTransform.Open(auditKey, primaryQuery, cancellationToken);
            if (!returnValue)
                return false;

            returnValue = await ReferenceTransform.Open(auditKey, referenceQuery, cancellationToken);

            if (ReferenceTransform == null)
                throw new Exception("There must a concatenate transform specified.");

            CacheTable = new Table("Concatenated");

            var pos = 0;
            foreach (var column in PrimaryTransform.CacheTable.Columns)
            {
                CacheTable.Columns.Add(column.Copy());
                _primaryMappings.Add(pos);
                pos++;
            }

            foreach (var column in ReferenceTransform.CacheTable.Columns)
            {
                var ordinal = CacheTable.GetOrdinal(column.Name);
                if (ordinal < 0)
                {
                    CacheTable.Columns.Add(column.Copy());
                    ordinal = pos;
                    pos++;
                }
                _referenceMappings.Add(ordinal);
            }

            _firstRead = true;

            //if the primary & reference transforms are sorted, we will merge sort the items.
            if (PrimaryTransform.SortFields != null && ReferenceTransform.SortFields != null)
            {
                var newSortFields = new Sorts();
                _primarySortOrdinals = new List<int>();
                _referenceSortOrdinals = new List<int>();

                var index = 0;
                var referenceSortFields = ReferenceTransform.SortFields;

                foreach (var sortField in PrimaryTransform.SortFields)
                {
                    if (referenceSortFields.Count <= index)
                    {
                        break;
                    }

                    var referenceSortField = referenceSortFields[index];
                    if (sortField.Column.Name == referenceSortField.Column.Name &&
                        sortField.Direction == referenceSortField.Direction)
                    {
                        newSortFields.Add(sortField);

                        _primarySortOrdinals.Add(PrimaryTransform.CacheTable.GetOrdinal(sortField.Column.Name));
                        _referenceSortOrdinals.Add(ReferenceTransform.CacheTable.GetOrdinal(sortField.Column.Name));
                    }
                    else
                    {
                        break;
                    }

                    index++;
                }

                if (newSortFields.Count > 0)
                {
                    _sortedMerge = true;
                    CacheTable.OutputSortFields = newSortFields;
                }

                GeneratedQuery = new SelectQuery()
                {
                    Sorts = newSortFields
                };
            }

            return returnValue;
        }

        protected override async Task<object[]> ReadRecord(CancellationToken cancellationToken = default)
        {
            // sorted merge will concatenate 2 sorted incoming datasets, and maintain the sort order.
            if (_sortedMerge)
            {
                if (_firstRead)
                {
                    // read one row for each reader.
                    var primaryReadTask = PrimaryTransform.ReadAsync(cancellationToken);
                    var referenceReadTask = ReferenceTransform.ReadAsync(cancellationToken);
                    var results = await Task.WhenAll(primaryReadTask, referenceReadTask);

                    if (primaryReadTask.IsFaulted)
                    {
                        throw primaryReadTask.Exception ?? new Exception("Unknown error in concatenate transform reading the primary reader.");
                    }

                    if (referenceReadTask.IsFaulted)
                    {
                        throw referenceReadTask.Exception ?? new Exception("Unknown error in concatenate transform reading the reference reader.");
                    }

                    _primaryMoreRecords = results[0];
                    _referenceMoreRecords = results[1];

                    _firstRead = false;
                }

                if (_primaryReadTask != null)
                {
                    _primaryMoreRecords = await _primaryReadTask;
                }

                if (_referenceReadTask != null)
                {
                    _referenceMoreRecords = await _referenceReadTask;
                }

                if (!_primaryMoreRecords && !_referenceMoreRecords)
                {
                    return null;
                }

                var newRow = new object[FieldCount];

                // no more primary records, then just read from the reference
                if (!_primaryMoreRecords)
                {
                    var returnValue = CreateRecord(ReferenceTransform, _referenceMappings);
                    _primaryReadTask = null;
                    _referenceReadTask = ReferenceTransform.ReadAsync(cancellationToken);
                    return returnValue;
                }
                // no more reference record ,just read from the primary.
                else if (!_referenceMoreRecords)
                {
                    var returnValue = CreateRecord(PrimaryTransform, _primaryMappings);
                    PrimaryTransform.GetValues(newRow);
                    _referenceReadTask = null;
                    _primaryReadTask = ReferenceTransform.ReadAsync(cancellationToken);
                    return returnValue;
                }
                else
                {
                    //more records in both, then compare the rows and take the next in sort order.

                    var usePrimary = true;

                    for (var i = 0; i < _primarySortOrdinals.Count; i++)
                    {
                        var compareResult = Operations.Compare(
                            PrimaryTransform.CacheTable.Columns[_primarySortOrdinals[i]].DataType,
                            PrimaryTransform[_primarySortOrdinals[i]], ReferenceTransform[_referenceSortOrdinals[i]]);

                        if (compareResult > 0 &&
                            SortFields[i].Direction == ESortDirection.Ascending ||
                            compareResult < 0 &&
                            SortFields[i].Direction == ESortDirection.Descending)
                        {
                            usePrimary = false;
                            break;
                        }
                    }

                    if (usePrimary)
                    {
                        var returnValue = CreateRecord(PrimaryTransform, _primaryMappings);
                        _primaryReadTask = PrimaryTransform.ReadAsync(cancellationToken);
                        return returnValue;
                    }
                    else
                    {
                        var returnValue = CreateRecord(ReferenceTransform, _referenceMappings);
                        _referenceReadTask = ReferenceTransform.ReadAsync(cancellationToken);
                        return returnValue;
                    }
                }

            } else
            {
                // if no sorting specified, concatenate will be in any order as the records arrive.
                if (_firstRead)
                {
                    _primaryReadTask = PrimaryTransform.ReadAsync(cancellationToken);
                    _referenceReadTask = ReferenceTransform.ReadAsync(cancellationToken);
                    _firstRead = false;
                }

                if (_primaryReadTask != null && _referenceReadTask != null)
                {
                    await Task.WhenAny(_primaryReadTask, _referenceReadTask);

                    if (_primaryReadTask.IsCanceled || _referenceReadTask.IsCanceled ||
                        cancellationToken.IsCancellationRequested)
                    {
                        throw new OperationCanceledException("The read record task was cancelled");
                    }

                    if (_primaryReadTask.IsFaulted)
                    {
                        throw _primaryReadTask.Exception;
                    }

                    if (_referenceReadTask.IsFaulted)
                    {
                        throw _referenceReadTask.Exception;
                    }

                    if (_primaryReadTask.IsCompleted)
                    {
                        var result = await _primaryReadTask;
                        if (result)
                        {
                            var returnValue = CreateRecord(PrimaryTransform, _primaryMappings);
                            _primaryReadTask = PrimaryTransform.ReadAsync(cancellationToken);
                            return returnValue;
                        }
                        _primaryReadTask = null;
                    }

                    if (_referenceReadTask.IsCompleted)
                    {
                        var result = await _referenceReadTask;
                        if (result)
                        {
                            var returnValue = CreateRecord(ReferenceTransform, _referenceMappings);
                            _referenceReadTask = ReferenceTransform.ReadAsync(cancellationToken);
                            return returnValue;
                        }
                        _primaryReadTask = null;
                    }
                }

                if (_primaryReadTask != null)
                {
                    var result = await _primaryReadTask;
                    if (result)
                    {
                        var returnValue = CreateRecord(PrimaryTransform, _primaryMappings);
                        _primaryReadTask = PrimaryTransform.ReadAsync(cancellationToken);
                        return returnValue;
                    }
                    _primaryReadTask = null;
                }

                if (_referenceReadTask != null)
                {
                    var result = await _referenceReadTask;
                    if (result)
                    {
                        var returnValue = CreateRecord(ReferenceTransform, _referenceMappings);
                        _referenceReadTask = ReferenceTransform.ReadAsync(cancellationToken);
                        return returnValue;
                    }
                    _referenceReadTask = null;
                }
            }

            return null;
        }

        private object[] CreateRecord(Transform transform, List<int> mappings)
        {
            var newRow = new object[CacheTable.Columns.Count];

            for(var i = 0; i< mappings.Count; i++)
            {
                newRow[mappings[i]] = transform[i];
            }

            return newRow;
        }

        public override bool ResetTransform()
        {
            return true;
        }

    }

}


text:
.class final Lcom/android/server/hdmi/SystemAudioStatusAction;
.super Lcom/android/server/hdmi/HdmiCecFeatureAction;
.source "SystemAudioStatusAction.java"

# static fields
.field private static final STATE_WAIT_FOR_REPORT_AUDIO_STATUS:I = 0x1

.field private static final TAG:Ljava/lang/String; = "SystemAudioStatusAction"

# instance fields
.field private final mAvrAddress:I

.field private final mCallback:Landroid/hardware/hdmi/IHdmiControlCallback;

# direct methods
.method static synthetic -wrap0(Lcom/android/server/hdmi/SystemAudioStatusAction;)V
    .locals 0

    invoke-direct {p0}, Lcom/android/server/hdmi/SystemAudioStatusAction;->handleSendGiveAudioStatusFailure()V

    return-void
.end method

.method constructor <init>(Lcom/android/server/hdmi/HdmiCecLocalDevice;ILandroid/hardware/hdmi/IHdmiControlCallback;)V
    .locals 0

    invoke-direct {p0, p1}, Lcom/android/server/hdmi/HdmiCecFeatureAction;-><init>(Lcom/android/server/hdmi/HdmiCecLocalDevice;)V

    iput p2, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mAvrAddress:I

    iput-object p3, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mCallback:Landroid/hardware/hdmi/IHdmiControlCallback;

    return-void
.end method

.method private finishWithCallback(I)V
    .locals 3

    iget-object v1, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mCallback:Landroid/hardware/hdmi/IHdmiControlCallback;

    if-eqz v1, :cond_0

    :try_start_0
    iget-object v1, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mCallback:Landroid/hardware/hdmi/IHdmiControlCallback;

    invoke-interface {v1, p1}, Landroid/hardware/hdmi/IHdmiControlCallback;->onComplete(I)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    :cond_0
    :goto_0
    invoke-virtual {p0}, Lcom/android/server/hdmi/SystemAudioStatusAction;->finish()V

    return-void

    :catch_0
    move-exception v0

    const-string/jumbo v1, "SystemAudioStatusAction"

    const-string/jumbo v2, "Failed to invoke callback."

    invoke-static {v1, v2, v0}, Landroid/util/Slog;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0
.end method

.method private handleReportAudioStatus(Lcom/android/server/hdmi/HdmiCecMessage;)V
    .locals 6

    const/4 v5, 0x0

    invoke-virtual {p1}, Lcom/android/server/hdmi/HdmiCecMessage;->getParams()[B

    move-result-object v1

    aget-byte v3, v1, v5

    and-int/lit16 v3, v3, 0x80

    const/16 v4, 0x80

    if-ne v3, v4, :cond_1

    const/4 v0, 0x1

    :goto_0
    aget-byte v3, v1, v5

    and-int/lit8 v2, v3, 0x7f

    invoke-virtual {p0}, Lcom/android/server/hdmi/SystemAudioStatusAction;->tv()Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;

    move-result-object v3

    invoke-virtual {v3, v0, v2}, Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;->setAudioStatus(ZI)V

    invoke-virtual {p0}, Lcom/android/server/hdmi/SystemAudioStatusAction;->tv()Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;

    move-result-object v3

    invoke-virtual {v3}, Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;->isSystemAudioActivated()Z

    move-result v3

    xor-int/2addr v3, v0

    if-nez v3, :cond_0

    iget v3, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mAvrAddress:I

    const/16 v4, 0x43

    invoke-virtual {p0, v3, v4}, Lcom/android/server/hdmi/SystemAudioStatusAction;->sendUserControlPressedAndReleased(II)V

    :cond_0
    invoke-direct {p0, v5}, Lcom/android/server/hdmi/SystemAudioStatusAction;->finishWithCallback(I)V

    return-void

    :cond_1
    const/4 v0, 0x0

    goto :goto_0
.end method

.method private handleSendGiveAudioStatusFailure()V
    .locals 3

    const/4 v2, 0x0

    invoke-virtual {p0}, Lcom/android/server/hdmi/SystemAudioStatusAction;->tv()Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;

    move-result-object v0

    const/4 v1, -0x1

    invoke-virtual {v0, v2, v1}, Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;->setAudioStatus(ZI)V

    iget v0, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mAvrAddress:I

    invoke-virtual {p0}, Lcom/android/server/hdmi/SystemAudioStatusAction;->tv()Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;

    move-result-object v1

    invoke-virtual {v1}, Lcom/android/server/hdmi/HdmiCecLocalDeviceTv;->isSystemAudioActivated()Z

    move-result v1

    xor-int/lit8 v1, v1, 0x1

    invoke-static {v1}, Lcom/android/server/hdmi/HdmiCecKeycode;->getMuteKey(Z)I

    move-result v1

    invoke-virtual {p0, v0, v1}, Lcom/android/server/hdmi/SystemAudioStatusAction;->sendUserControlPressedAndReleased(II)V

    invoke-direct {p0, v2}, Lcom/android/server/hdmi/SystemAudioStatusAction;->finishWithCallback(I)V

    return-void
.end method

.method private sendGiveAudioStatus()V
    .locals 2

    invoke-virtual {p0}, Lcom/android/server/hdmi/SystemAudioStatusAction;->getSourceAddress()I

    move-result v0

    iget v1, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mAvrAddress:I

    invoke-static {v0, v1}, Lcom/android/server/hdmi/HdmiCecMessageBuilder;->buildGiveAudioStatus(II)Lcom/android/server/hdmi/HdmiCecMessage;

    move-result-object v0

    new-instance v1, Lcom/android/server/hdmi/SystemAudioStatusAction$1;

    invoke-direct {v1, p0}, Lcom/android/server/hdmi/SystemAudioStatusAction$1;-><init>(Lcom/android/server/hdmi/SystemAudioStatusAction;)V

    invoke-virtual {p0, v0, v1}, Lcom/android/server/hdmi/SystemAudioStatusAction;->sendCommand(Lcom/android/server/hdmi/HdmiCecMessage;Lcom/android/server/hdmi/HdmiControlService$SendMessageCallback;)V

    return-void
.end method

# virtual methods
.method handleTimerEvent(I)V
    .locals 1

    iget v0, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mState:I

    if-eq v0, p1, :cond_0

    return-void

    :cond_0
    invoke-direct {p0}, Lcom/android/server/hdmi/SystemAudioStatusAction;->handleSendGiveAudioStatusFailure()V

    return-void
.end method

.method processCommand(Lcom/android/server/hdmi/HdmiCecMessage;)Z
    .locals 4

    const/4 v3, 0x1

    const/4 v2, 0x0

    iget v0, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mState:I

    if-ne v0, v3, :cond_0

    iget v0, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mAvrAddress:I

    invoke-virtual {p1}, Lcom/android/server/hdmi/HdmiCecMessage;->getSource()I

    move-result v1

    if-eq v0, v1, :cond_1

    :cond_0
    return v2

    :cond_1
    invoke-virtual {p1}, Lcom/android/server/hdmi/HdmiCecMessage;->getOpcode()I

    move-result v0

    packed-switch v0, :pswitch_data_0

    return v2

    :pswitch_0
    invoke-direct {p0, p1}, Lcom/android/server/hdmi/SystemAudioStatusAction;->handleReportAudioStatus(Lcom/android/server/hdmi/HdmiCecMessage;)V

    return v3

    nop

    :pswitch_data_0
    .packed-switch 0x7a
        :pswitch_0
    .end packed-switch
.end method

.method start()Z
    .locals 3

    const/4 v2, 0x1

    iput v2, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mState:I

    iget v0, p0, Lcom/android/server/hdmi/SystemAudioStatusAction;->mState:I

    const/16 v1, 0x7d0

    invoke-virtual {p0, v0, v1}, Lcom/android/server/hdmi/SystemAudioStatusAction;->addTimer(II)V

    invoke-direct {p0}, Lcom/android/server/hdmi/SystemAudioStatusAction;->sendGiveAudioStatus()V

    return v2
.end method


text:
const char* RequiredInstanceExtensionNames[] =
{
    "VK_EXT_debug_report",
    "VK_KHR_surface",
    "VK_KHR_win32_surface"
};
const uint32_t RequiredInstanceExtensionCount = sizeof(RequiredInstanceExtensionNames) / sizeof(RequiredInstanceExtensionNames[0]);

const char* RequiredDeviceExtensionNames[] =
{
    "VK_KHR_swapchain",
};
const uint32_t RequiredDeviceExtensionCount = sizeof(RequiredDeviceExtensionNames) / sizeof(RequiredDeviceExtensionNames[0]);

const char* RequiredLayerNames[] =
{
    "VK_LAYER_LUNARG_core_validation",
    "VK_LAYER_LUNARG_object_tracker",
    "VK_LAYER_LUNARG_standard_validation",
};
const uint32_t RequiredLayerCount = sizeof(RequiredLayerNames) / sizeof(RequiredLayerNames[0]);

const AppInfo appInfo =
{
    "VkTessTri",
    "NullEngine",
    VK_API_VERSION_1_1,

    RequiredInstanceExtensionNames,
    RequiredInstanceExtensionCount,
    RequiredLayerNames,
    RequiredLayerCount,

    RequiredDeviceExtensionNames,
    RequiredDeviceExtensionCount,

    GetSimpleAllocator()
};

///@todo decouple descriptor layout from push constant layout
///      build one descriptor set up front, use it for everything
///      push constants tied to programs, so pipeline layout + program is a uint
void createPipelineLayout(
    VkDevice vkDevice,
    VkDescriptorSetLayoutBinding* pBindings,
    uint32_t                      bindingCount,
    VkPushConstantRange*          pPushConstantRanges,
    uint32_t                      pushConstantRangeCount,
    VkDescriptorSetLayout*        pDescriptorSetLayout,
    VkPipelineLayout*             pPipelineLayout)
{
    VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo = {};
    descriptorSetLayoutCreateInfo.sType        = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
    descriptorSetLayoutCreateInfo.pBindings    = pBindings;
    descriptorSetLayoutCreateInfo.bindingCount = bindingCount;

    VK_CHECK(vkCreateDescriptorSetLayout(vkDevice, &descriptorSetLayoutCreateInfo, GetSimpleAllocator(), pDescriptorSetLayout));

    VkPipelineLayoutCreateInfo layoutCreateInfo =
    {
        VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
        NULL,
        0,
        1,
        pDescriptorSetLayout,
        0,
        NULL
    };

    layoutCreateInfo.pPushConstantRanges    = pPushConstantRanges;
    layoutCreateInfo.pushConstantRangeCount = pushConstantRangeCount;

    VK_CHECK(vkCreatePipelineLayout(vkDevice, &layoutCreateInfo, GetSimpleAllocator(), pPipelineLayout));
}

///@todo create shader to wrap SPV loading & module creation, create program to group them?
void createGraphicsPipeline(
    VkDevice device,
    VkPipelineLayout layout,
    VkRenderPass renderPass,
    uint32_t     subpassIndex,
    VkPipeline* pPipeline)
{
    std::ifstream vsFile = std::ifstream("vert.spv", std::ios::ate | std::ios::binary);

    size_t shader_size = static_cast<size_t>(vsFile.tellg());
    std::vector<char> vert_shader(shader_size);
    vsFile.seekg(0);
    vsFile.read(vert_shader.data(), shader_size);
    vsFile.close();

    std::ifstream tescFile = std::ifstream("tesc.spv", std::ios::ate | std::ios::binary);

    shader_size = static_cast<size_t>(tescFile.tellg());
    std::vector<char> tesc_shader(shader_size);
    tescFile.seekg(0);
    tescFile.read(tesc_shader.data(), shader_size);
    tescFile.close();

    std::ifstream teseFile = std::ifstream("tese.spv", std::ios::ate | std::ios::binary);

    shader_size = static_cast<size_t>(teseFile.tellg());
    std::vector<char> tese_shader(shader_size);
    teseFile.seekg(0);
    teseFile.read(tese_shader.data(), shader_size);
    teseFile.close();

    std::ifstream fsFile = std::ifstream("frag.spv", std::ios::ate | std::ios::binary);

    shader_size = static_cast<size_t>(fsFile.tellg());
    std::vector<char> frag_shader(shader_size);
    fsFile.seekg(0);
    fsFile.read(frag_shader.data(), shader_size);
    fsFile.close();

    VkShaderModule vsModule  = 0;
    VkShaderModule tcsModule = 0;
    VkShaderModule tesModule = 0;
    VkShaderModule fsModule  = 0;

    VkShaderModuleCreateInfo shaderModuleCreateInfo = {};

    shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;

    shaderModuleCreateInfo.codeSize = vert_shader.size();
    shaderModuleCreateInfo.pCode = (uint32_t*)vert_shader.data();
    VK_CHECK(vkCreateShaderModule(device, &shaderModuleCreateInfo, GetSimpleAllocator(), &vsModule));

    shaderModuleCreateInfo.codeSize = tesc_shader.size();
    shaderModuleCreateInfo.pCode = (uint32_t*)tesc_shader.data();
    VK_CHECK(vkCreateShaderModule(device, &shaderModuleCreateInfo, GetSimpleAllocator(), &tcsModule));

    shaderModuleCreateInfo.codeSize = tese_shader.size();
    shaderModuleCreateInfo.pCode = (uint32_t*)tese_shader.data();
    VK_CHECK(vkCreateShaderModule(device, &shaderModuleCreateInfo, GetSimpleAllocator(), &tesModule));

    shaderModuleCreateInfo.codeSize = frag_shader.size();
    shaderModuleCreateInfo.pCode = (uint32_t*)frag_shader.data();
    VK_CHECK(vkCreateShaderModule(device, &shaderModuleCreateInfo, GetSimpleAllocator(), &fsModule));

    VkPipelineBuilder* pBuilder = VkPipelineBuilder::Create(device, GetSimpleAllocator());

    pBuilder->SetViewportState(256, 256);
    pBuilder->SetShaderState(vsModule, tcsModule, tesModule, fsModule);
    pBuilder->SetVertexState(false);

    pBuilder->SetTessellationState(3);

    *pPipeline = pBuilder->GetPipeline(layout, renderPass, subpassIndex);

    pBuilder->Destroy();

    // Free shader modules no longer needed
    vkDestroyShaderModule(device, vsModule,  GetSimpleAllocator());
    vkDestroyShaderModule(device, tcsModule, GetSimpleAllocator());
    vkDestroyShaderModule(device, tesModule, GetSimpleAllocator());
    vkDestroyShaderModule(device, fsModule,  GetSimpleAllocator());
}

int main()
{
    Ivy::IvyWindow* pWindow = Ivy::IvyWindow::Create(256, 256);
    pWindow->SetWindowName(appInfo.pAppName);

    // Init Vulkan

    VkCoreInfo vulkanInfo = {};
    if (createVulkan(&appInfo, &vulkanInfo) == false)
    {
        return -1;
    }

    VkSwapchainInfo swapchainInfo = {};
    createSwapchain(&vulkanInfo, GetModuleHandle(NULL), pWindow->GetHwnd(), GetSimpleAllocator(), &swapchainInfo);

    VkCommandBufferAllocateInfo commandBufferAllocateInfo = {};
    commandBufferAllocateInfo.sType              = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
    commandBufferAllocateInfo.commandPool        = vulkanInfo.vkCommandPool;
    commandBufferAllocateInfo.commandBufferCount = 1;
    commandBufferAllocateInfo.level              = VK_COMMAND_BUFFER_LEVEL_PRIMARY;

    VkCommandBuffer commandBuffer = {};
    vkAllocateCommandBuffers(vulkanInfo.vkDevice, &commandBufferAllocateInfo, &commandBuffer);

    ///@todo Create Renderpass / Subpass Generator
    // Create Render Pass
    VkAttachmentDescription colorAttachmentDescription = {};
    colorAttachmentDescription.format         = VK_FORMAT_B8G8R8A8_UNORM;
    colorAttachmentDescription.samples        = VK_SAMPLE_COUNT_1_BIT;
    colorAttachmentDescription.loadOp         = VK_ATTACHMENT_LOAD_OP_CLEAR;
    colorAttachmentDescription.storeOp        = VK_ATTACHMENT_STORE_OP_STORE;
    colorAttachmentDescription.stencilLoadOp  = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
    colorAttachmentDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
    colorAttachmentDescription.initialLayout  = VK_IMAGE_LAYOUT_UNDEFINED;
    colorAttachmentDescription.finalLayout    = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;

    VkAttachmentReference colorAttachmentReference;
    colorAttachmentReference.attachment = 0;
    colorAttachmentReference.layout     = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;

    VkSubpassDescription subpassDescription = {};
    subpassDescription.pipelineBindPoint    = VK_PIPELINE_BIND_POINT_GRAPHICS;
    subpassDescription.colorAttachmentCount = 1;
    subpassDescription.pColorAttachments    = &colorAttachmentReference;

    VkRenderPassCreateInfo renderPassCreateInfo = {};
    renderPassCreateInfo.sType                  = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
    renderPassCreateInfo.attachmentCount        = 1;
    renderPassCreateInfo.pAttachments           = &colorAttachmentDescription;
    renderPassCreateInfo.subpassCount           = 1;
    renderPassCreateInfo.pSubpasses             = &subpassDescription;

    VkRenderPass renderPass;
    VK_CHECK(vkCreateRenderPass(vulkanInfo.vkDevice, &renderPassCreateInfo, GetSimpleAllocator(), &renderPass));

    // Create Framebuffers
    VkFramebuffer* framebuffers = new VkFramebuffer[swapchainInfo.swapchainImageCount];
    for (uint32_t i = 0; i < swapchainInfo.swapchainImageCount; ++i)
    {
        VkFramebufferCreateInfo framebufferCreateInfo = {};

        framebufferCreateInfo.sType           = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
        framebufferCreateInfo.width           = 256;
        framebufferCreateInfo.height          = 256;
        framebufferCreateInfo.layers          = 1;
        framebufferCreateInfo.renderPass      = renderPass;
        framebufferCreateInfo.attachmentCount = 1;
        framebufferCreateInfo.pAttachments    = &swapchainInfo.pSwapchainImageViews[i];

        VK_CHECK(vkCreateFramebuffer(vulkanInfo.vkDevice, &framebufferCreateInfo, GetSimpleAllocator(), &framebuffers[i]));
    }

    // Create Pipeline

    VkDescriptorSetLayout descriptorSetLayout;
    VkPipelineLayout      pipelineLayout;

    VkPushConstantRange pushConstantRange = {};
    pushConstantRange.size   = 16;
    pushConstantRange.offset = 0;
    pushConstantRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;

    createPipelineLayout(vulkanInfo.vkDevice, NULL, 0, &pushConstantRange, 1, &descriptorSetLayout, &pipelineLayout);

    VkPipeline graphicsPipeline;
    createGraphicsPipeline(vulkanInfo.vkDevice, pipelineLayout, renderPass, 0, &graphicsPipeline);

    pWindow->Show();

    BOOL quit = FALSE;
    while (quit == FALSE)
    {
        VkSemaphore presentCompleteSemaphore;
        VkSemaphoreCreateInfo presentCompleteSemaphoreCreateInfo;
        presentCompleteSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
        presentCompleteSemaphoreCreateInfo.pNext = NULL;
        presentCompleteSemaphoreCreateInfo.flags = 0;

        VK_CHECK(vkCreateSemaphore(vulkanInfo.vkDevice, &presentCompleteSemaphoreCreateInfo, GetSimpleAllocator(), &presentCompleteSemaphore));

        uint32_t imageIndex = 0;
        VK_CHECK(vkAcquireNextImageKHR(vulkanInfo.vkDevice, swapchainInfo.swapchain, UINT64_MAX, presentCompleteSemaphore, 0, &imageIndex));

        VkCommandBufferBeginInfo commandBufferBeginInfo = {};
        commandBufferBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
        commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;  // HW: regenerate per frame vs cache per frame

        VK_CHECK(vkResetCommandPool(vulkanInfo.vkDevice, vulkanInfo.vkCommandPool, VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT));
        VK_CHECK(vkBeginCommandBuffer(commandBuffer, &commandBufferBeginInfo));

        VkRenderPassBeginInfo renderPassBeginInfo = {};
        renderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
        renderPassBeginInfo.framebuffer = framebuffers[imageIndex];
        renderPassBeginInfo.renderPass = renderPass;

        renderPassBeginInfo.renderArea.offset.x = 0;
        renderPassBeginInfo.renderArea.offset.y = 0;
        renderPassBeginInfo.renderArea.extent.width = 256;
        renderPassBeginInfo.renderArea.extent.height = 256;

        static const VkClearValue FramebufferClearValue = { 1.0f, 1.0f, 0.0, 1.0f };
        renderPassBeginInfo.clearValueCount = 1;
        renderPassBeginInfo.pClearValues = &FramebufferClearValue;

        vkCmdBeginRenderPass(commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);

        vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);

        vkCmdDraw(commandBuffer, 3, 1, 0, 0);

        vkCmdEndRenderPass(commandBuffer);

        ///@todo Abstract out pipeline barriers
        VkImageMemoryBarrier prePresentBarrier = {};
        prePresentBarrier.sType               = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
        prePresentBarrier.pNext               = NULL;
        prePresentBarrier.srcAccessMask       = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
        prePresentBarrier.dstAccessMask       = VK_ACCESS_MEMORY_READ_BIT;
        prePresentBarrier.oldLayout           = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
        prePresentBarrier.newLayout           = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
        prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
        prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
        prePresentBarrier.subresourceRange    = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
        prePresentBarrier.image               = swapchainInfo.pSwapchainImages[imageIndex];

        VkImageMemoryBarrier *pmemory_barrier = &prePresentBarrier;
        vkCmdPipelineBarrier(commandBuffer,
                             VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
                             VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
                             0,
                             0,
                             NULL,
                             0,
                             NULL,
                             1,
                             pmemory_barrier);

        VK_CHECK(vkEndCommandBuffer(commandBuffer));

        VkSubmitInfo submitInfo       = {};
        submitInfo.sType              = VK_STRUCTURE_TYPE_SUBMIT_INFO;
        submitInfo.commandBufferCount = 1;
        submitInfo.pCommandBuffers    = &commandBuffer;
        submitInfo.pWaitSemaphores    = &presentCompleteSemaphore;
        submitInfo.waitSemaphoreCount = 1;

        VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
        submitInfo.pWaitDstStageMask          = &pipe_stage_flags;

        VK_CHECK(vkQueueSubmit(vulkanInfo.vkQueue, 1, &submitInfo, VK_NULL_HANDLE));

        VkPresentInfoKHR presentInfo = {};
        presentInfo.sType            = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
        presentInfo.pSwapchains      = &swapchainInfo.swapchain;
        presentInfo.swapchainCount   = 1;
        presentInfo.pImageIndices    = &imageIndex;

        VK_CHECK(vkQueuePresentKHR(vulkanInfo.vkQueue, &presentInfo));

        VK_CHECK(vkQueueWaitIdle(vulkanInfo.vkQueue));

        vkDestroySemaphore(vulkanInfo.vkDevice, presentCompleteSemaphore, GetSimpleAllocator());

        pWindow->ProcessMsg(&quit);
    }

    if (framebuffers != nullptr)
    {
        vkDestroyFramebuffer(vulkanInfo.vkDevice, framebuffers[0], GetSimpleAllocator());
        vkDestroyFramebuffer(vulkanInfo.vkDevice, framebuffers[1], GetSimpleAllocator());

        delete[] framebuffers;
    }

    destroySwapchain(&vulkanInfo, &swapchainInfo, GetSimpleAllocator());
    destroyVulkan(&vulkanInfo, GetSimpleAllocator());

    return 0;
}


text:
namespace content {
class WebContents;
}  // namespace content

namespace search {

// Focus or unfocus the omnibox if |focus| is true or false respectively.
void FocusOmnibox(bool focus, content::WebContents* web_contents);
// Pastes |text| (or the clipboard if |text| is empty) into the omnibox.
void PasteIntoOmnibox(const base::string16& text,
                      content::WebContents* web_contents);
// Returns whether input is in progress, i.e. if the omnibox has focus and the
// active tab is in mode SEARCH_SUGGESTIONS.
bool IsOmniboxInputInProgress(content::WebContents* web_contents);

}  // namespace search

#endif  // CHROME_BROWSER_UI_SEARCH_OMNIBOX_UTILS_H_


text:
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.

namespace PInvoke
{
    using System;
    using System.Runtime.InteropServices;

    /// <content>
    /// Contains the <see cref="SafeObjectHandle"/> nested type.
    /// </content>
    public static partial class Kernel32
    {
        /// <summary>
        /// Represents a library handle that can be closed with <see cref="FreeLibrary"/>.
        /// </summary>
        public class SafeLibraryHandle : SafeHandle
        {
            /// <summary>
            /// A handle that may be used in place of <see cref="IntPtr.Zero"/>.
            /// </summary>
            public static readonly SafeLibraryHandle Null = new SafeLibraryHandle(IntPtr.Zero);

            /// <summary>
            /// An invalid handle that may be used in place of <see cref="INVALID_HANDLE_VALUE"/>.
            /// </summary>
            public static readonly SafeLibraryHandle Invalid = new SafeLibraryHandle();

            /// <summary>
            /// Initializes a new instance of the <see cref="SafeLibraryHandle"/> class.
            /// </summary>
            public SafeLibraryHandle()
                : base(INVALID_HANDLE_VALUE, true)
            {
            }

            /// <summary>
            /// Initializes a new instance of the <see cref="SafeLibraryHandle"/> class.
            /// </summary>
            /// <param name="preexistingHandle">An object that represents the pre-existing handle to use.</param>
            /// <param name="ownsHandle">
            ///     <see langword="true" /> to have the native handle released when this safe handle is disposed or finalized;
            ///     <see langword="false" /> otherwise.
            /// </param>
            public SafeLibraryHandle(IntPtr preexistingHandle, bool ownsHandle = true)
                : base(INVALID_HANDLE_VALUE, ownsHandle)
            {
                this.SetHandle(preexistingHandle);
            }

            /// <inheritdoc />
            public override bool IsInvalid => this.handle == INVALID_HANDLE_VALUE || this.handle == IntPtr.Zero;

            /// <inheritdoc />
            protected override bool ReleaseHandle() => FreeLibrary(this.handle);
        }
    }
}


text:
using System.ComponentModel;

namespace CardBattle.Lib.ComponentModel
{
    /// <summary>
    /// データバインディング用共通基底。
    /// </summary>
    /// <remarks>
    /// System.Threading.Tasks 版もある。
    /// あっちは、[CallerMemberName] を使ってるのと、boxing 回避用オーバーロードがない。
    /// </remarks>
    public class BindableBase : INotifyPropertyChanged
    {
        /// <summary>
        /// <see cref="INotifyPropertyChanged.PropertyChanged"/>
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged { add { _PropertyChanged += value; } remove { _PropertyChanged -= value; } }

        /// <summary>
        /// 派生クラスから直接 Invoke したいことがあるので。
        /// </summary>
        protected PropertyChangedEventHandler _PropertyChanged { get; private set; }

        /// <summary>
        /// フィールドの値を書き替え&通知。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="storage"></param>
        /// <param name="value"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        protected bool SetProperty<T>(ref T storage, T value, string propertyName) => SetProperty(ref storage, value, new PropertyChangedEventArgs(propertyName));

        /// <summary>
        /// 変更通知。
        /// </summary>
        /// <param name="propertyName"></param>
        protected void OnPropertyChanged(string propertyName) => OnPropertyChanged(new PropertyChangedEventArgs(propertyName));

        /// <summary>
        /// フィールドの値を書き替え&通知。
        /// </summary>
        protected bool SetProperty<T>(ref T storage, T value, PropertyChangedEventArgs e)
        {
            if (Equals(storage, value)) return false;

            storage = value;
            OnPropertyChanged(e);
            return true;

        }

        /// <summary>
        /// 変更通知。
        /// </summary>
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) => _PropertyChanged?.Invoke(this, e);
    }
}


text:
package se.coredev.week2.recap;

public class Main {

	public static void main(String[] args) {

	}
}


text:
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import iceprod

# the dbmethod decorator and docstrings don't get along
# so turn the decorator off
def nodecorate(func):
    return func
#import iceprod.server.dbmethods
#iceprod.server.dbmethods.dbmethod = nodecorate

master_doc = "index"

project = 'IceProd'
copyright = '2016, IceCube Collaboration'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
is_master = False
try:
    with open('../.git/HEAD') as f:
        is_master = 'master' in f.read()
except:
    pass
if is_master:
    release = 'master'
    parts = list(iceprod.version_info[:3])
    parts[-1] -= 1
    version = '%d.%d.%d'%tuple(parts)
else:
    release = '%d.%d'%iceprod.version_info[:2]
    version = iceprod.__version__

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.coverage',
    'sphinx.ext.extlinks',
    'sphinx.ext.autosectionlabel',
    'sphinx.ext.intersphinx',
    'sphinx.ext.viewcode',
    'sphinx.ext.mathjax',
    'sphinx.ext.napoleon',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = True

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# -- Autodoc options -----------------------------------------------------------------

autodoc_member_order = 'bysource'
autoclass_content = 'both'
autodoc_default_flags = ['members', 'undoc-members']

# Without this line sphinx includes a copy of object.__init__'s docstring
# on any class that doesn't define __init__.
# https://bitbucket.org/birkenfeld/sphinx/issue/1337/autoclass_content-both-uses-object__init__
autodoc_docstring_signature = False

coverage_skip_undoc_in_source = True
coverage_ignore_modules = [
    'iceprod.core.tests'
    'iceprod.server.tests',
    ]
coverage_ignore_classes = [
    ]

coverage_ignore_functions = [
    # various modules
    "test",
    "main",
]

# -- Options for HTML output ---------------------------------------------------

html_theme = '_theme'
html_theme_path = ['.']

#html_favicon = None

# -- Options for LaTeX output --------------------------------------------------

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
  ('index', 'IceProd.tex', u'IceProd Documentation',
   u'David Schultz', 'manual'),
]

intersphinx_mapping = {
    'python': ('https://docs.python.org/3.6/', None),
    'tornado': ('http://tornado.readthedocs.io/en/stable/', None),
    }


text:
//
//  QJDCategory.h
//  QJD-百思不得姐
//
//  Created by 姚叶 on 2017/3/10.
//  Copyright © 2017年 qjd. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface QJDCategory : NSObject
/** 关注人数 */
@property (nonatomic, assign) NSInteger count;
/** ID */
@property (nonatomic, assign) NSInteger ID;
/** 名称 */
@property (nonatomic, strong) NSString *name;

/** 当前左边类别对应的右边数据 */
@property (nonatomic, strong) NSMutableArray *users;
/** 数据总数 */
@property (nonatomic, assign) NSInteger total;
/** 当前页码 */
@property (nonatomic, assign) NSInteger currentPage;

@end


text:
    Stability: 3 - Stable

To use this module, do `require('string_decoder')`. StringDecoder decodes a
buffer to a string. It is a simple interface to `buffer.toString()` but provides
additional support for utf8.

    var StringDecoder = require('string_decoder').StringDecoder;
    var decoder = new StringDecoder('utf8');

    var cent = new Buffer([0xC2, 0xA2]);
    console.log(decoder.write(cent));

    var euro = new Buffer([0xE2, 0x82, 0xAC]);
    console.log(decoder.write(euro));

## Class: StringDecoder

Accepts a single argument, `encoding` which defaults to `utf8`.

### StringDecoder.write(buffer)

Returns a decoded string.


text:
package org.kj.pxe.protocol.impl;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.kj.pxe.protocol.VendorSuboption;

/**
 * Represents DHCP option 43, a.k.a. vendor suboptions. Contains a list of the
 * suboptions.
 *
 * @author Kinjal
 *
 */
public class VendorOptions extends DhcpOption {

	List<VendorSuboption> suboptions = new ArrayList<VendorSuboption>();

	/**
	 * Returns the list of suboptions. Initially an empty list.
	 *
	 * @return the list of suboptions
	 */
	List<VendorSuboption> getSuboptions() {
		return suboptions;
	}

	/**
	 * Sets the suboptions to the specified value
	 *
	 * @param suboptions
	 *            the list to set to
	 */
	void setSuboptions(List<VendorSuboption> suboptions) {
		this.suboptions = suboptions;
	}

	/**
	 * Returns the length of the option. This is the sum of all the bytes of the
	 * suboptions contained.
	 *
	 * @return the length
	 */
	@Override
	short getLen() {
		short actualLen = 0;
		for (VendorSuboption suboption : suboptions) {
			if (suboption.getTag() == VendorSuboptionTag.PAD.getValue()
					|| suboption.getTag() == VendorSuboptionTag.END.getValue()) {
				actualLen++;
			} else {
				actualLen += 2; // for tag and len fields
				actualLen += suboption.getLen();
			}
		}
		return actualLen;
	}

	/**
	 * Writes itself as a series of bytes into a DataOutPutStream. Order is tag,
	 * length, then each suboption from the list, sequentially.
	 *
	 * @param outStream
	 *            the stream to write to
	 */
	@Override
	void writeToStream(DataOutputStream outStream) {
		try {
			outStream.writeByte(43);

			outStream.writeByte(getLen());

			for (VendorSuboption suboption : suboptions) {
				suboption.writeToStream(outStream);
			}
		} catch (IOException e) {
			throw new DhcpPacketConstructionException(e);
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Asterina stylospora Cooke

### Remarks
null


text:
package org.vas.commons.station;

public class LibStations {

  public final Stations<Autolib> autolibs;
  public final Stations<Velib> velibs;

  public LibStations(Stations<Autolib> autolibs, Stations<Velib> velibs) {
    super();
    this.autolibs = autolibs;
    this.velibs = velibs;
  }
}


text:
\documentclass[12pt]{article}

\usepackage{tikz}
\usepackage[ruled, vlined]{algorithm2e}
\usepackage{pst-node,pst-plot}
\usepackage{amsmath}
\usepackage{float}

\newcommand{\BigO}[1]{\ensuremath{\operatorname{\mathcal{O}}\bigl(#1\bigr)}}

\begin{document}
\title{Homework 25}
\author{Robbie McKinstry, Jack McQuown, Cyrus Ramavarapu}
\renewcommand{\today}{31 October 2016}
\renewcommand{\baselinestretch}{1.5}
\maketitle

\textbf{Please provide written or oral feedback on this and future homeworks :)}

\section*{Problem 17: }
Although a CRCW Common algorithm for finding the max of $n$ numbers
was developed earlier, it required $n^2$ processors and could be shown
to be highly inefficient.  An improvement to the parallel efficiency of
this problem can be made at the sacrifice of runtime if only $n$
processors are used.  Unlike the \BigO{1} CRCW algorithm originally
developed, this algorithm is modeled after the EREW divide and
conquer algorithm.\\\\
In the EREW algorithm, recursive calls were made to divide the
initial set of numbers into halves with each half given half
the processors.  This process continues until each processor
is assigned a single number at which point two processors
assigned neighboring numbers make a comparison to determine the
larger.  The larger value is then returned from the recursive
call.\\\\
In a similar manner, for this CRCW common algorithm recursive
calls can be made until each processor is assigned a single
number.  However, instead of each processor only comparing
with the neighboring processor, it can communicate with both
of neighbors (Note: there is only one neighbor for processors
assigned numbers at the end).  This CR done by the three
neighboring processors can be used to determine which of
the processors holds the largest number.  Since the rank
of the processor holding the largest number will be
a common value, it can be safely written to a single location
which can then be returned from the recursive call.  In the
case that two processors are assigned the same number,
an arbitrary decision can be made, since in this case,
the commonality will be the number written to the shared
location.\\\\
As the process returns from its recursive call tree, the number of
available numbers to be assigned processors decreases; however,
instead of having the processors unassigned do no work, the can be
used to further reduce the problem size by expanding the size
of the local group for which a max is found by double assigning
a number to two or more processors.\\\\
As a result of cutting the size of the problem into progressively
smaller groups as the recursive tree returns, this algorithm
will have a run time of $\log \log n$.

\section*{Problem 18: }

This was a fun problem.

First, initialize a bitarray $A$ of length $n$, will all bits zeroed. The $i$th bit from the right represents whether or not the value $i$ has been found in the input sequence $x_{1} \dots x_{n}$. Now, assign each of the $n$ processes a unique value $i$ from 1 to $n$. Have the $i$th processor look at $x_{i}$. Let that value be $k$. Flip the $k$th bit from the right in the bit array $A$. This operation occurs in constant time, since there are $n$ indexes into the sequence $x_{1} \dots x_{n}$, and each operation takes constant time. Notice that if a value occurs twice in the input sequence, then the same index in $A$ will be accessed by multiple processors at once, but they will be writing a common value.

Finally, assuming each processor is assigned a unique priority from 1 to $n$ as per the problem description, have the processor with priority $y$ look at the bit $A[n - y + 1]$, and if it's set, it will write $n - y + 1$ to the output register. (That is, assign the highest priority processor to the highest index in the bit array, and write that index to output if the value at that index is set). Because the highest priority processor takes precedence to all lower priority processes, the highest value will be written to the output register.

\section*{Problem 19: }

The beginning steps of Problem 19 are the same as problem 18. I will repeat them here for the sake of completeness, but feel free to skip to the final paragraph if you understand what I'm attempting to communicate.

First, initialize a bitarray $A$ of length $n$, will all bits zeroed. The $i$th bit from the right represents whether or not the value $i$ has been found in the input sequence $x_{1} \dots x_{n}$. Now, assign each of the $n$ processes a unique value $i$ from 1 to $n$. Have the $i$th processor look at $x_{i}$. Let that value be $k$. Flip the $k$th bit from the right in the bit array $A$. This operation occurs in constant time, since there are $n$ indexes into the sequence $x_{1} \dots x_{n}$, and each operation takes constant time. Notice that if a value occurs twice in the input sequence, then the same index in $A$ will be accessed by multiple processors at once, but they will be writing a common value.

Finally, we need to find a way in constant time to write out the highest bit in the array. This is actually fairly easy; cast the bit array as an integer (making the unrealistic assumption that we can perform computation with $2^{n}$ bits, like we have with past problems). Let that value be $B$. Write to the output register the value $\left \lfloor lg({B}) \right \rfloor $. This is, of course, constant time arithmetic.

\end{document}


text:
package com.hubspot.blazar.config;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.validation.constraints.NotNull;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.getsentry.raven.logback.SentryAppender;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import io.dropwizard.logging.AbstractAppenderFactory;
import io.dropwizard.logging.async.AsyncAppenderFactory;
import io.dropwizard.logging.filter.LevelFilterFactory;
import io.dropwizard.logging.layout.LayoutFactory;

/**
 * This class configures sentry via a Logback appender the resource
 * file META-INF/services/io.dropwizard.logging.AppenderFactory is responsible
 * for telling Dropwizard's logging mechanics to create an appender using this class
 * provided that the logging configuration of type "sentry" is available.
 *
 * <p>
 * sentryDsn: string (Data Source Name) is the secret Sentry gives you to report exceptions with.
 * sentryRelease: string the version of blazar you are deploying. Sentry will tag exceptions using this release value
 *
 * This appender is only used if you configure the logging appender in the dropwizard config for sentry as follows:
 * {@Code
 *  logging:
 *    appenders:
 *      - type: sentry
 *        sentryDsn: http://some_Sentry_provided_DSN
 *        sentryRelease: "PROD"
 * }
 *
 */
@JsonTypeName("sentry")
public class SentryAppenderFactory extends AbstractAppenderFactory<ILoggingEvent> {
  private static final String APPENDER_NAME = "sentry-appender";
  private final String sentryDsn;
  private final String blazarRelease;

  @JsonCreator
  public SentryAppenderFactory(
      @NotNull
      @JsonProperty("sentryDsn") String sentryDsn,
      @JsonProperty("blazarRelease") String blazarRelease ) {

    this.sentryDsn = sentryDsn;
    this.blazarRelease = blazarRelease;
  }

  public String getSentryDsn() {
    return sentryDsn;
  }

  public String getBlazarRelease() {
    return blazarRelease;
  }

  @Override
  public Appender<ILoggingEvent> build(LoggerContext context,
                                       String applicationName,
                                       LayoutFactory<ILoggingEvent> layoutFactory,
                                       LevelFilterFactory<ILoggingEvent> levelFilterFactory,
                                       AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory) {

    final SentryAppender appender = new SentryAppender();
    appender.setName(APPENDER_NAME);
    appender.setDsn(sentryDsn);
    appender.setRelease(blazarRelease);
    appender.setServerName(getHostNameOrTaskId());
    appender.setContext(context);
    appender.addFilter(levelFilterFactory.build(Level.ERROR));
    getFilterFactories().stream().forEach(f -> appender.addFilter(f.build()));
    appender.start();
    return wrapAsync(appender, asyncAppenderFactory, context);
  }

  private static String getHostNameOrTaskId() {
    // Try to use "TASK_HOST" provided by singularity deploy environment
    if (System.getenv().containsKey("TASK_HOST") ) {
      return System.getenv().get("TASK_HOST");
    }

    // If not deployed in singularity try to fetch the hostname out of dns
    try {
      return InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
      return "unknown-host";
    }
  }

}


text:
package org.jboss.seam.examples.seamcrm.core.navigation;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.jboss.seam.security.Identity;

@RequestScoped
@Named
public class AlreadyLoggedIn {

    @Inject
    private Identity identity;

    public String alreadyLoggedIn() {

        if (identity.isLoggedIn()) {
            return "/admin/home.xhtml";
        }
        else
        {
            return null;
        }

    }

}


text:
package org.apache.flink.formats.csv;

import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.api.common.typeinfo.BasicArrayTypeInfo;
import org.apache.flink.api.common.typeinfo.PrimitiveArrayTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.typeutils.ObjectArrayTypeInfo;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.types.Row;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.jackson.JacksonMapperFactory;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ArrayNode;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ContainerNode;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.dataformat.csv.CsvMapper;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Objects;

import static org.apache.flink.formats.common.TimeFormats.SQL_TIMESTAMP_FORMAT;
import static org.apache.flink.formats.common.TimeFormats.SQL_TIMESTAMP_WITH_LOCAL_TIMEZONE_FORMAT;

/**
 * Serialization schema that serializes an object of Flink types into a CSV bytes.
 *
 *
Serializes the input row into a {@link ObjectNode} and converts it into byte[].
 *
 *
Result byte[] messages can be deserialized using {@link
 * CsvRowDeserializationSchema}.
 *
 * @deprecated The format was developed for the Table API users and will not be maintained for
 *     DataStream API users anymore. Either use Table API or switch to Data Stream, defining your
 *     own {@link SerializationSchema}.
 */
@PublicEvolving
@Deprecated
public final class CsvRowSerializationSchema implements SerializationSchema<Row> {

    private static final long serialVersionUID = 2098447220136965L;

    /** Type information describing the input CSV data. */
    private final RowTypeInfo typeInfo;

    /** Runtime instance that performs the actual work. */
    private final RuntimeConverter runtimeConverter;

    /** CsvMapper used to write {@link JsonNode} into bytes. */
    private transient CsvMapper csvMapper;

    /** Schema describing the input CSV data. */
    private final CsvSchema csvSchema;

    /** Object writer used to write rows. It is configured by {@link CsvSchema}. */
    private transient ObjectWriter objectWriter;

    /** Reusable object node. */
    private transient ObjectNode root;

    private CsvRowSerializationSchema(RowTypeInfo typeInfo, CsvSchema csvSchema) {
        this.typeInfo = typeInfo;
        this.runtimeConverter = createRowRuntimeConverter(typeInfo, true);
        this.csvSchema = csvSchema;
    }

    @Override
    public void open(InitializationContext context) throws Exception {
        this.csvMapper = JacksonMapperFactory.createCsvMapper();
        this.objectWriter = csvMapper.writer(csvSchema);
    }

    /** A builder for creating a {@link CsvRowSerializationSchema}. */
    @PublicEvolving
    public static class Builder {

        private final RowTypeInfo typeInfo;
        private CsvSchema csvSchema;

        /**
         * Creates a {@link CsvRowSerializationSchema} expecting the given {@link TypeInformation}.
         *
         * @param typeInfo type information used to create schema.
         */
        public Builder(TypeInformation<Row> typeInfo) {
            Preconditions.checkNotNull(typeInfo, "Type information must not be null.");

            if (!(typeInfo instanceof RowTypeInfo)) {
                throw new IllegalArgumentException("Row type information expected.");
            }

            this.typeInfo = (RowTypeInfo) typeInfo;
            this.csvSchema = CsvRowSchemaConverter.convert((RowTypeInfo) typeInfo);
        }

        public Builder setFieldDelimiter(char c) {
            this.csvSchema = this.csvSchema.rebuild().setColumnSeparator(c).build();
            return this;
        }

        public Builder setLineDelimiter(String delimiter) {
            Preconditions.checkNotNull(delimiter, "Delimiter must not be null.");
            if (!delimiter.equals("\n")
                    && !delimiter.equals("\r")
                    && !delimiter.equals("\r\n")
                    && !delimiter.equals("")) {
                throw new IllegalArgumentException(
                        "Unsupported new line delimiter. Only \\n, \\r, \\r\\n, or empty string are supported.");
            }
            this.csvSchema = this.csvSchema.rebuild().setLineSeparator(delimiter).build();
            return this;
        }

        public Builder setArrayElementDelimiter(String delimiter) {
            Preconditions.checkNotNull(delimiter, "Delimiter must not be null.");
            this.csvSchema = this.csvSchema.rebuild().setArrayElementSeparator(delimiter).build();
            return this;
        }

        public Builder disableQuoteCharacter() {
            this.csvSchema = this.csvSchema.rebuild().disableQuoteChar().build();
            return this;
        }

        public Builder setQuoteCharacter(char c) {
            this.csvSchema = this.csvSchema.rebuild().setQuoteChar(c).build();
            return this;
        }

        public Builder setEscapeCharacter(char c) {
            this.csvSchema = this.csvSchema.rebuild().setEscapeChar(c).build();
            return this;
        }

        public Builder setNullLiteral(String s) {
            this.csvSchema = this.csvSchema.rebuild().setNullValue(s).build();
            return this;
        }

        public CsvRowSerializationSchema build() {
            return new CsvRowSerializationSchema(typeInfo, csvSchema);
        }
    }

    @Override
    public byte[] serialize(Row row) {
        if (root == null) {
            root = csvMapper.createObjectNode();
        }
        try {
            runtimeConverter.convert(csvMapper, root, row);
            return objectWriter.writeValueAsBytes(root);
        } catch (Throwable t) {
            throw new RuntimeException("Could not serialize row '" + row + "'.", t);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || o.getClass() != this.getClass()) {
            return false;
        }
        if (this == o) {
            return true;
        }
        final CsvRowSerializationSchema that = (CsvRowSerializationSchema) o;
        final CsvSchema otherSchema = that.csvSchema;

        return typeInfo.equals(that.typeInfo)
                && csvSchema.getColumnSeparator() == otherSchema.getColumnSeparator()
                && Arrays.equals(csvSchema.getLineSeparator(), otherSchema.getLineSeparator())
                && csvSchema
                        .getArrayElementSeparator()
                        .equals(otherSchema.getArrayElementSeparator())
                && csvSchema.getQuoteChar() == otherSchema.getQuoteChar()
                && csvSchema.getEscapeChar() == otherSchema.getEscapeChar()
                && Arrays.equals(csvSchema.getNullValue(), otherSchema.getNullValue());
    }

    @Override
    public int hashCode() {
        return Objects.hash(
                typeInfo,
                csvSchema.getColumnSeparator(),
                csvSchema.getLineSeparator(),
                csvSchema.getArrayElementSeparator(),
                csvSchema.getQuoteChar(),
                csvSchema.getEscapeChar(),
                csvSchema.getNullValue());
    }

    // --------------------------------------------------------------------------------------------

    private interface RuntimeConverter extends Serializable {
        JsonNode convert(CsvMapper csvMapper, ContainerNode<?> container, Object obj);
    }

    private static RuntimeConverter createRowRuntimeConverter(
            RowTypeInfo rowTypeInfo, boolean isTopLevel) {
        final TypeInformation[] fieldTypes = rowTypeInfo.getFieldTypes();
        final String[] fieldNames = rowTypeInfo.getFieldNames();

        final RuntimeConverter[] fieldConverters = createFieldRuntimeConverters(fieldTypes);

        return assembleRowRuntimeConverter(isTopLevel, fieldNames, fieldConverters);
    }

    private static RuntimeConverter[] createFieldRuntimeConverters(
            TypeInformation<?>[] fieldTypes) {
        final RuntimeConverter[] fieldConverters = new RuntimeConverter[fieldTypes.length];
        for (int i = 0; i < fieldTypes.length; i++) {
            fieldConverters[i] = createNullableRuntimeConverter(fieldTypes[i]);
        }
        return fieldConverters;
    }

    private static RuntimeConverter assembleRowRuntimeConverter(
            boolean isTopLevel, String[] fieldNames, RuntimeConverter[] fieldConverters) {
        final int rowArity = fieldNames.length;
        // top level reuses the object node container
        if (isTopLevel) {
            return (csvMapper, container, obj) -> {
                final Row row = (Row) obj;

                validateArity(rowArity, row.getArity());

                final ObjectNode objectNode = (ObjectNode) container;
                for (int i = 0; i < rowArity; i++) {
                    objectNode.set(
                            fieldNames[i],
                            fieldConverters[i].convert(csvMapper, container, row.getField(i)));
                }
                return objectNode;
            };
        } else {
            return (csvMapper, container, obj) -> {
                final Row row = (Row) obj;

                validateArity(rowArity, row.getArity());

                final ArrayNode arrayNode = csvMapper.createArrayNode();
                for (int i = 0; i < rowArity; i++) {
                    arrayNode.add(
                            fieldConverters[i].convert(csvMapper, arrayNode, row.getField(i)));
                }
                return arrayNode;
            };
        }
    }

    private static RuntimeConverter createNullableRuntimeConverter(TypeInformation<?> info) {
        final RuntimeConverter valueConverter = createRuntimeConverter(info);
        return (csvMapper, container, obj) -> {
            if (obj == null) {
                return container.nullNode();
            }
            return valueConverter.convert(csvMapper, container, obj);
        };
    }

    private static RuntimeConverter createRuntimeConverter(TypeInformation<?> info) {
        if (info.equals(Types.VOID)) {
            return (csvMapper, container, obj) -> container.nullNode();
        } else if (info.equals(Types.STRING)) {
            return (csvMapper, container, obj) -> container.textNode((String) obj);
        } else if (info.equals(Types.BOOLEAN)) {
            return (csvMapper, container, obj) -> container.booleanNode((Boolean) obj);
        } else if (info.equals(Types.BYTE)) {
            return (csvMapper, container, obj) -> container.numberNode((Byte) obj);
        } else if (info.equals(Types.SHORT)) {
            return (csvMapper, container, obj) -> container.numberNode((Short) obj);
        } else if (info.equals(Types.INT)) {
            return (csvMapper, container, obj) -> container.numberNode((Integer) obj);
        } else if (info.equals(Types.LONG)) {
            return (csvMapper, container, obj) -> container.numberNode((Long) obj);
        } else if (info.equals(Types.FLOAT)) {
            return (csvMapper, container, obj) -> container.numberNode((Float) obj);
        } else if (info.equals(Types.DOUBLE)) {
            return (csvMapper, container, obj) -> container.numberNode((Double) obj);
        } else if (info.equals(Types.BIG_DEC)) {
            return (csvMapper, container, obj) -> container.numberNode((BigDecimal) obj);
        } else if (info.equals(Types.BIG_INT)) {
            return (csvMapper, container, obj) -> container.numberNode((BigInteger) obj);
        } else if (info.equals(Types.SQL_DATE)) {
            return (csvMapper, container, obj) -> container.textNode(obj.toString());
        } else if (info.equals(Types.SQL_TIME)) {
            return (csvMapper, container, obj) -> container.textNode(obj.toString());
        } else if (info.equals(Types.SQL_TIMESTAMP)) {
            return (csvMapper, container, obj) -> container.textNode(obj.toString());
        } else if (info.equals(Types.LOCAL_DATE)) {
            return (csvMapper, container, obj) -> container.textNode(obj.toString());
        } else if (info.equals(Types.LOCAL_TIME)) {
            return (csvMapper, container, obj) -> container.textNode(obj.toString());
        } else if (info.equals(Types.LOCAL_DATE_TIME)) {
            return (csvMapper, container, obj) ->
                    container.textNode(SQL_TIMESTAMP_FORMAT.format((LocalDateTime) obj));
        } else if (info.equals(Types.INSTANT)) {
            return (csvMapper, container, obj) ->
                    container.textNode(
                            LocalDateTime.ofInstant((Instant) obj, ZoneId.of("UTC"))
                                    .format(SQL_TIMESTAMP_WITH_LOCAL_TIMEZONE_FORMAT));
        } else if (info instanceof RowTypeInfo) {
            return createRowRuntimeConverter((RowTypeInfo) info, false);
        } else if (info instanceof BasicArrayTypeInfo) {
            return createObjectArrayRuntimeConverter(
                    ((BasicArrayTypeInfo) info).getComponentInfo());
        } else if (info instanceof ObjectArrayTypeInfo) {
            return createObjectArrayRuntimeConverter(
                    ((ObjectArrayTypeInfo) info).getComponentInfo());
        } else if (info instanceof PrimitiveArrayTypeInfo
                && ((PrimitiveArrayTypeInfo) info).getComponentType() == Types.BYTE) {
            return createByteArrayRuntimeConverter();
        } else {
            throw new RuntimeException("Unsupported type information '" + info + "'.");
        }
    }

    private static RuntimeConverter createObjectArrayRuntimeConverter(
            TypeInformation<?> elementType) {
        final RuntimeConverter elementConverter = createNullableRuntimeConverter(elementType);
        return (csvMapper, container, obj) -> {
            final Object[] array = (Object[]) obj;
            final ArrayNode arrayNode = csvMapper.createArrayNode();
            for (Object element : array) {
                arrayNode.add(elementConverter.convert(csvMapper, arrayNode, element));
            }
            return arrayNode;
        };
    }

    private static RuntimeConverter createByteArrayRuntimeConverter() {
        return (csvMapper, container, obj) -> container.binaryNode((byte[]) obj);
    }

    private static void validateArity(int expected, int actual) {
        if (expected != actual) {
            throw new RuntimeException(
                    "Row length mismatch. "
                            + expected
                            + " fields expected but was "
                            + actual
                            + ".");
        }
    }
}