text:
/*
 * This file is part of jNAT-PMPlib.
 *
 * jNAT-PMPlib is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * jNAT-PMPlib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with jNAT-PMPlib.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.tomp2p.natpmp;

import java.net.InetAddress;

/**
 * This class manages a NAT-PMP device. This class is thread-safe.
 *
 * This manages communication with a NAT-PMP device on the network. There are
 * two types of messages that can be sent to the device.
 * {@link ExternalAddressRequestMessage} can be sent to get the external IP of
 * the gateway. {@link MapRequestMessage} can be sent to map a port for a
 * certain amount of time. These two messages can be put into the message queue
 * through the {@link #enqueueMessage(Message)} method.
 *
 * As this class manages a message queue to the NAT-PMP device, it is important
 * to shut it down correctly. Any mapped ports that are no longer desired should
 * be unmapped before shutdown occurs. Refer to {@link #NatPmpDevice(boolean)}
 * for details about the shutdown mechanism.
 *
 * @author flszen
 */
public class NatPmpDevice {
	// Shutdown control instance fields.
	private boolean isShutdown = false;
	private final Object shutdownLock = new Object();

	private MessageQueue messageQueue;

	/**
	 * Constructs a new NatPmpDevice.
	 *
	 * @param shutdownHookEnabled
	 *            Shutting down existing port mappings is a desired behavior;
	 *            therefore, this value is required! Refer to
	 *            {@link #setShutdownHookEnabled(boolean)} for details about what
	 *            value should be provided here and how it alters the object's
	 *            behavior.
	 *
	 * @throws NatPmpException
	 *             A NatPmpException may be thrown if the local network is not using
	 *             addresses defined in RFC1918. A NatPmpException may also be
	 *             thrown if the the network gateway cannot be determined, which may
	 *             rarely be due to the network not using IPv4. NAT-PMP should only
	 *             be used on RFC1918 networks using IPv4.
	 *
	 * @see #setShutdownHookEnabled(boolean)
	 * @see #shutdown()
	 */
	public NatPmpDevice(InetAddress gateway) throws NatPmpException {
		// Reject if the gateway is null.
		// This indicates either no gateway or the network is not IPv4.
		// It could also be that the netstat response is not supported.
		if (gateway == null) {
			throw new NatPmpException("The network gateway cannot be located.");
		}

		// Reject if it is not RFC1918.
		if (!gateway.isSiteLocalAddress()) {
			throw new NatPmpException("The network gateway address is not RFC1918 compliant.");
		}

		// Set up messaging queue.
		messageQueue = MessageQueue.createMessageQueue(gateway);
	}

	/**
	 * Enqueues a message for sending.
	 *
	 * @param message
	 *            The {@link Message} to send.
	 * @see #clearQueue()
	 */
	public void enqueueMessage(Message message) {
		messageQueue.enqueueMessage(message);
	}

	/**
	 * Clears the queue of messages to send. If a message is currently sending, it
	 * is not interrupted.
	 *
	 * @see #enqueueMessage(Message)
	 */
	public void clearQueue() {
		messageQueue.clearQueue();
	}

	/**
	 * Synchronously waits until the queue is empty before returning.
	 */
	public void waitUntilQueueEmpty() {
		messageQueue.waitUntilQueueEmpty();
	}

	/**
	 * Shuts down this NatPmpDevice. If the shutdown hook is disabled, this method
	 * should be called manually at the time port mappings through the NAT-PMP
	 * gateway are no longer needed. If the shutdown hook is enabled, this method is
	 * called automatically during Java VM shutdown.
	 *
	 * When this method is called, if the shutdown hook is enabled, it is
	 * automatically disabled.
	 *
	 * It should be noted that when this method is called manually, it blocks until
	 * it completes. If it is desired to shutdown asynchronously, the
	 * {@link #shutdownAsync(boolean)} method should be called.
	 *
	 * @see #isShutdown()
	 * @see #setShutdownHookEnabled(boolean)
	 * @see #shutdownAsync(boolean)
	 */
	public void shutdown() {
		synchronized (shutdownLock) {
			// Do the shutdown stuff.
			messageQueue.shutdown();

			// Set the isShutdown flag.
			isShutdown = true;
		}
	}

	/**
	 * Flag indicates if this NatPmpDevice is shutdown. This method will block if a
	 * shutdown is in progress. If you desire to wait for an asynchronous shutdown
	 * to complete, please monitor the returned {@link Thread} instead.
	 *
	 * @return True if this NatPmpDeviceTest is shutdown, false if it is not.
	 * @see #shutdown()
	 */
	public boolean isShutdown() {
		synchronized (shutdownLock) {
			return isShutdown;
		}
	}
}


text:
package bootstrap.liftweb

import net.liftweb._
import util._
import Helpers._

import common._
import http._
import sitemap._
import Loc._
import mapper._

import code.model._
import code.api._
import code.view._

import code.lib.{MessageIndex,MailServerManager}

import java.lang.{Integer => JInteger}

/**
 * A class that's instantiated early and run.  It allows the application
 * to modify lift's environment
 */
class Boot {
  def boot {
    if (!DB.jndiJdbcConnAvailable_?) {
      val vendor =
	new StandardDBVendor(Props.get("db.driver") openOr "org.h2.Driver",
                             Props.get("db.url") openOr
                             "jdbc:h2:fermata.db;AUTO_SERVER=TRUE",
                             Props.get("db.user"), Props.get("db.password"))

      LiftRules.unloadHooks.append(vendor.closeAllConnections_! _)

      DB.defineConnectionManager(DefaultConnectionIdentifier, vendor)
    }

    LiftRules.unloadHooks.append(mailShutdown _)
    // Use Lift's Mapper ORM to populate the database
    // you don't need to use Mapper to use Lift... use
    // any ORM you want
    Schemifier.schemify(true, Schemifier.infoF _, User, Message, Recipient,
                        MessageRecipient)

    // Start a default mail server
    MailServerManager.startServer("default",
                                  JInteger.getInteger("fermataSmtpPort", 2500).intValue())
    // Ping the indexer, so that it starts up immediately
    MessageIndex ! None
    // Shutdown mail server at Lift unload
    def mailShutdown = {
      MailServerManager.stopServer("default")
      ()
    }

    // where to search snippet
    LiftRules.addToPackages("code")

    LiftRules.dispatch.prepend(RestAPI.dispatch)

    // Send attachments directly
    LiftRules.dispatch.append {
      case Req(List("msg",msgId,"attachments",attId),_,_) =>
        () => Attachment.view(msgId,attId)
    }

    // Rewrites for messages
    LiftRules.statelessRewrite.append {
      // Send requests for /msg/<id> to messages template
      case RewriteRequest (
        ParsePath(List("msg",msgId),_,_,_),_,_) => {
          RewriteResponse("message_detail" :: Nil, Map("msgId" -> msgId))
        }
    }

    // Rewrites for recipients
    LiftRules.statelessRewrite.append {
      // Send requests for /recipient/<id> to messages template
      case RewriteRequest (
        ParsePath(List("recipient",rcptId),_,_,_),_,_) => {
          RewriteResponse("recipient_detail" :: Nil, Map("rcptId" -> rcptId))
        }
    }

    // Build TopLevel SiteMap
    val entries = List(
      Menu.i("Home") / "index", // the simple way to declare a menu
      Menu(Loc("Messages", List("messages"), "Messages")),
      Menu(Loc("Msg", List("message_detail") -> true, "Message Detail", Hidden)),
      Menu.i("Recipients") / "recipients",
      Menu(Loc("Search", List("search"), "Search")),
      Menu(Loc("Rcpts", List("recipient_detail") -> true, "Recipient Detail", Hidden))
      //Menu.i("Addresses") / "addresses",
      //Menu.i("Configuration") / "config",
    )

    // set the sitemap.  Note if you don't want access control for
    // each page, just comment this line out.
    LiftRules.setSiteMap(SiteMap(entries:_*))

    //Show the spinny image when an Ajax call starts
    LiftRules.ajaxStart =
      Full(() => LiftRules.jsArtifacts.show("ajax-loader").cmd)

    // Make the spinny image go away when it ends
    LiftRules.ajaxEnd =
      Full(() => LiftRules.jsArtifacts.hide("ajax-loader").cmd)

    // Force the request to be UTF-8
    LiftRules.early.append(_.setCharacterEncoding("UTF-8"))

    // What is the function to test if a user is logged in?
    LiftRules.loggedInTest = Full(() => User.loggedIn_?)

    // Make a transaction span the whole HTTP request
    S.addAround(DB.buildLoanWrapper)
  }
}

redpajama_set_name: RedPajamaGithub


text:
NSString *const kSampleResourceManagerUpdatedNotification = @"com.appgratis.unlock.Sample.ResourceManager.updated";

@implementation ResourceManager

- (NSInteger)quantityForResourceNamed:(NSString*)name
{
    return [[self numberForResourceName:name] integerValue];
}

- (void)addQuantity:(NSInteger)quantity forResource:(NSString*)resource
{
    // Yes, this may overflow
    [self saveQuantity:([self quantityForResourceNamed:resource]+1) forResourceNamed:resource];
}

- (void)saveQuantity:(NSInteger)quantity forResourceNamed:(NSString*)name
{
    [self saveNumber:@(quantity) forResourceName:name];
    [[NSNotificationCenter defaultCenter] postNotificationName:kSampleResourceManagerUpdatedNotification object:nil];
}

#pragma mark Storage

- (void)saveNumber:(NSNumber*)number forResourceName:(NSString*)name
{
    number = number ? number : @(0);
    [[NSUserDefaults standardUserDefaults] setObject:number forKey:[self keyForResourceName:name]];
}

- (NSNumber*)numberForResourceName:(NSString*)name
{
    NSNumber *retVal = [[NSUserDefaults standardUserDefaults] objectForKey:[self keyForResourceName:name]];
    return retVal ? retVal : @(0);
}

- (NSString*)keyForResourceName:(NSString*)name
{
    return [@"resource_" stringByAppendingString:name];
}

@end


text:
             {{session.dateParsed |  date:'mediumDate'}}

             {{session.starttime | removeString:' AM' | removeString:' PM'}} » {{session.endtime | removeString:' AM' | removeString:' PM'}}

             {{session.room}}

             {{session.starttime | removeString:' AM' | removeString:' PM'}}

{{session.title.split('\\').join('')}}

             {{session.room}}

{{session.track.split('\\').join('')}}

{{session.details.split('\\').join('') | truncate:120:'... » '}}

    <button id="btn01_{{session.id}}" class="swiper hide" ng-click="toggleFavoriteFlag(session.id,session)"></button>


text:
package com.rtg.util.bytecompression;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;

import com.rtg.util.array.CommonIndex;
import com.rtg.util.array.ExtensibleIndex;
import com.rtg.util.array.longindex.LongCreate;
import com.rtg.util.integrity.Exam;
import com.rtg.util.integrity.Integrity;

/**
 * A compressed array of small integer values.
 * This is typically used for storing lots of nucleotides (0..4) or
 * protein residues (0..22), or quality values (0..63).
 * Internally it uses an array of longs, packing as many values as possible into each long.
 *
 * As an additional sanity check, callers are required to set each byte value
 * at most once (in increasing offset positions), so the single byte set
 * method is not supported.
 *
 * WARNING: this implementation clips values set if they fall above the given range.
 * i.e. if range is 22 and 30 is added it will be stored as 21.
 *
 */
public final class CompressedByteArray extends ByteArray implements Integrity {

  /** The total number of values stored. */
  private long mSize;

  private final boolean mGrow;

  /** All the data is packed into these longs. */
  private final CommonIndex mData;

  /** How many values we compress into each bit-field (via multiplication). */
  private final int mPerBitfield;

  /** How many bit-fields we can squash into each long (via bit shifting). */
  private final int mNumBitfields;

  /** The number of values packed into each long. */
  private final int mPerLong;

  /** Each bit-field of this width contains mPerByte values. */
  private final int mBits;

  /** Equals Math.pow(2, mBits) - 1 */
  private final int mMask;

  /** The allowable values are 0 .. mRange-1. */
  private final int mRange;

  /** Powers of mRange. */
  private final int[] mRangePowers;

  /** Just for checking that set calls are done in the right order. */
  private long mValuesSet = 0L;

  /** first externally visible value */
  private long mOffset;

  /**
   * A lookup table: given a bit-field with value val,
   * mValue[i][v] is the value of the i'th field in that bit-field.
   */
  private final byte[][] mValue;

  /**
   * Create a compressed array of bytes.
   *
   * @param size is the number of values that can be stored.
   * @param range means that integer values 0 .. range-1 can be stored.  Allowable values are 2..128.
   * @param pack is how many values to pack into each bit-field.
   * @param bits is the width of each bit-field (maximum 12).
   * @param grow set to true to grow array as necessary
   */
  public CompressedByteArray(long size, int range, int pack, int bits, boolean grow) {
    assert 0 <= size;
    assert 1 < range && range <= 128;
    assert 1 <= pack;
    assert 1 <= bits && bits <= 12; // so the lookup tables are not too big
    assert Math.pow(range, pack) <= Math.pow(2, bits);
    mRange = range;
    mPerBitfield = pack;
    mBits = bits;
    mMask = (int) Math.pow(2, mBits) - 1;
    mNumBitfields = 64 / mBits;
    mPerLong = mPerBitfield * mNumBitfields;
    mGrow = grow;
    if (grow) {
      mSize = 0;
      mData = LongCreate.createExtensibleIndex();
    } else {
      mSize = size;
      mData = LongCreate.createIndex(size / mPerLong + 1);
    }

    // precalculate our lookup tables
    mValue = new byte[mPerBitfield][];
    mRangePowers = new int[mPerBitfield];
    for (int withinBitfield = 0; withinBitfield < mPerBitfield; ++withinBitfield) {
      mRangePowers[withinBitfield] = (int) Math.pow(mRange, withinBitfield);
      mValue[withinBitfield] = new byte[mMask + 1];
      final int divisor = (int) Math.pow(mRange, withinBitfield);
      for (int i = 0; i <= mMask; ++i) {
        mValue[withinBitfield][i] = (byte) (i / divisor % mRange);
      }
    }
  }

  /**
   * Creates a compressed array with good compression for DNA or protein.
   *
   * @param size is the number of values that can be stored.
   * @param range means that integer values 0 .. range-1 can be stored.  At most 128.
   * @param grow set to true to grow array as necessary
   */
  public CompressedByteArray(long size, int range, boolean grow) {
    this(size, range,
        range == 5 ? 3 : range == 22 ? 2 : 1,
            range == 5 ? 7 : range == 22 ? 9 : minBits(range), grow);
  }

  /**
   * Calculate the number of bits required to store 0 .. range-1.
   * @param range a positive integer.
   * @return the number of bits, between 1 and 32.
   */
  public static int minBits(int range) {
    int max = 2;
    int bits = 1;
    while (max > 0) {
      if (range <= max) {
        return bits;
      }
      max = max << 1;
      ++bits;
    }
    return 31;
  }

  @Override
  public boolean integrity() {
    assert mMask == (int) Math.pow(2, mBits) - 1;
    Exam.assertEquals(mPerBitfield, mValue.length);
    for (int i = 0; i < mPerBitfield; ++i) {
      Exam.assertEquals(mRange, mValue[i].length);
    }
    return true;
  }

  @Override
  public boolean globalIntegrity() {
    return integrity();
  }

  /** @return the range of values that can be stored in each location. */
  public int getRange() {
    return mRange;
  }

  @Override
  public byte get(long offset) {
    assert offset <= mValuesSet;  // only read values that have been set
    final long adjOffset = mOffset + offset;
    final long whichLong = adjOffset / mPerLong;
    long longValue = mData.get(whichLong);
    final int whichBitfield = (int) (adjOffset % mPerLong) / mPerBitfield;
    longValue = longValue >>> (whichBitfield * mBits);
    final int bitField = (int) (longValue & mMask);
    final int withinBitfield = (int) (adjOffset % mPerLong) % mPerBitfield;
    return mValue[withinBitfield][bitField];
  }

  @Override
  public void get(byte[] dest, long offset, int count) {
    get(dest, offset, 0, count);
  }

  /**
   * like get but with ability to choose destination offset
   * @param dest destination array
   * @param srcOffset offset within source data
   * @param destOffset offset within destination array
   * @param length number of values to read
   */
  public void get(byte[] dest, long srcOffset, int destOffset, int length) {
    assert srcOffset <= mValuesSet;  // only read values that have been set
    final long adjOffset = mOffset + srcOffset;
    long whichLong = adjOffset / mPerLong;
    long longValue = mData.get(whichLong);
    int whichBitfield = (int) (adjOffset % mPerLong) / mPerBitfield;
    longValue = longValue >>> (whichBitfield * mBits);
    int bitField = (int) (longValue & mMask);
    int withinBitfield = (int) (adjOffset % mPerLong) % mPerBitfield;
    for (int i = destOffset; i < destOffset + length; ++i) {
      // this line is a faster version of the following two, using a lookup table.
      dest[i] = mValue[withinBitfield][bitField];
      // the slow version...
      //final int divisor = (int) Math.pow(mRange, withinBitfield);
      //dest[i] = (byte) (bitField / divisor % mRange);
      ++withinBitfield;
      if (withinBitfield == mPerBitfield) {
        // move along to next bitfield
        withinBitfield = 0;
        ++whichBitfield;
        longValue = longValue >>> mBits;
        bitField = (int) (longValue & mMask);
        if (whichBitfield == mNumBitfields) {
          whichBitfield = 0;
          ++whichLong;
          longValue = mData.get(whichLong);
          bitField = (int) (longValue & mMask);
        }
      }
    }
  }

  /**
   * Not supported.
   */
  @Override
  public void set(long offset, byte value) {
    throw new RuntimeException("not supported");
  }

  @Override
  public void set(long offset, byte[] buffer, int count) {
    set(offset, buffer, 0, count);
  }

  /**
   * Packs data[0 .. length - 1] into this byte array.
   * WARNING: Calls to set should be done with increasing offset
   * values, and a given location should never be set twice.
   *
   * @param offset the logical start position to start storing.
   * @param data the source values
   * @param bOffset position in data to start copying from
   * @param length how many values to copy.
   */
  @Override
  public void set(long offset, byte[] data, int bOffset, int length) {
    if (offset < mValuesSet) {
      // each value should be set only once.
      throw new RuntimeException("CompressedByteArray.set called out of order");
    }
    if (mGrow) {
      final long lLength = (offset + length) / mPerLong + 1;
      if (lLength > mData.length()) {
        ((ExtensibleIndex) mData).extendTo(lLength);
      }
      mSize += length;
    }
    // we must read the first long, in case it is already partially filled.
    long whichLong = offset / mPerLong;
    long longValue = mData.get(whichLong);
    int whichBitfield = (int) (offset % mPerLong) / mPerBitfield;
    int withinBitfield = (int) (offset % mPerLong) % mPerBitfield;
    for (int i = bOffset; i < bOffset + length; ++i) {
      final int mult = mRangePowers[withinBitfield];
      // final int mult = (int) Math.pow(mRange, withinBitfield);
      final byte val = data[i];
      assert 0 <= val && val < mRange : "value: " + val + " i: " + i;
      longValue += (long) (val * mult) << (whichBitfield * mBits);
      ++withinBitfield;
      if (withinBitfield == mPerBitfield) {
        withinBitfield = 0;
        ++whichBitfield;
        if (whichBitfield == mNumBitfields) {
          mData.set(whichLong, longValue);
          whichBitfield = 0;
          ++whichLong;
          longValue = 0L;
        }
      }
    }
    // store the last partial long.
    if (longValue != 0) {
      mData.set(whichLong, longValue);
    }
    mValuesSet = offset + length; // these values have now been set
  }

  @Override
  public long length() {
    return mSize;
  }

  @Override
  public long bytes() {
    return mData.bytes();
  }

  /**
   * read compressed data directly from disk
   * @param file file containing compressed byte array
   * @param startVal first value to read (inclusive)
   * @param endVal last value to read (exclusive)
   * @param range number of unique values possible in data
   * @return the array
   * @throws IOException if an IO error occurs
   */
  public static CompressedByteArray loadCompressed(File file, long startVal, long endVal, int range) throws IOException {
    final int perLong = new CompressedByteArray(0, range, true).mPerLong;
    final long adjStartVal = startVal / perLong * perLong;
    final long adjEndVal = endVal % perLong == 0 ? endVal : (endVal / perLong + 1) * perLong;
    final CompressedByteArray ret = new CompressedByteArray(adjEndVal - adjStartVal, range, false);
    ret.mOffset = startVal - adjStartVal;
    ret.mSize = endVal - startVal;
    ret.mValuesSet = adjEndVal - adjStartVal;
    final ByteBuffer buf = ByteBuffer.allocate(64 * 1024).order(ByteOrder.BIG_ENDIAN);
    final long startSeekPos = adjStartVal / perLong * 8;
    final long endSeekPos = adjEndVal / perLong * 8;
    final long totLongs = ret.mData.length();
    long startLong = 0;
    try (FileInputStream stream = new FileInputStream(file)) {
      try (FileChannel channel = stream.getChannel()) {
        if (startSeekPos > 0) {
          channel.position(startSeekPos);
        }
        long dataLoadPosition = startSeekPos;
        while (dataLoadPosition < endSeekPos && channel.read(buf) != -1) {
          buf.flip();
          final int size = buf.limit();
          final int numLongs = size / 8;

          for (int i = 0; i < numLongs && startLong + i < totLongs; ++i) {
            ret.mData.set(startLong + i, buf.getLong());
          }
          startLong += numLongs;
          final int dataAdvance = numLongs * 8;
          dataLoadPosition += dataAdvance;
          buf.compact();
        }
      }
    }
    return ret;
  }

  /**
   * This method dumps the contents for testing purposes
   * @param dos output stream
   * @param values I do not know.
   * @throws IOException if the data could not be dumped
   */
  public void dumpCompressedValues(DataOutputStream dos, long values) throws IOException {
    final long whichLong = values / mPerLong + 1;
    for (long i = 0; i < whichLong; ++i) {
      dos.writeLong(mData.get(i));
    }
  }

}


text:
<?php

namespace GetOpt;

/**
 * Class Command
 *
 * @package GetOpt
 * @author  Thomas Flori <thflori@gmail.com>
 */
class Command implements CommandInterface
{
    use WithOptions, WithOperands, WithMagicGetter;

    /** @var string */
    protected $name;

    /** @var string */
    protected $shortDescription;

    /** @var string */
    protected $longDescription;

    /** @var mixed */
    protected $handler;

    /**
     * Command constructor.
     *
     * @param string $name
     * @param mixed  $handler
     * @param mixed  $options
     */
    public function __construct($name, $handler, $options = null)
    {
        $this->setName($name);
        $this->handler = $handler;

        if ($options !== null) {
            $this->addOptions($options);
        }
    }

    /**
     * Fluent interface for constructor so commands can be added during construction
     *
     * @param string $name
     * @param mixed  $handler
     * @param mixed  $options
     * @return static
     */
    public static function create($name, $handler, $options = null)
    {
        return new static($name, $handler, $options);
    }

    /**
     * @param string $name
     * @return $this
     */
    public function setName($name)
    {
        if (empty($name) || preg_match('/(^| )-/', $name)) {
            throw new \InvalidArgumentException(sprintf(
                'Command name has to be an alphanumeric string not starting with dash, found \'%s\'',
                $name
            ));
        }
        $this->name = $name;
        return $this;
    }

    /**
     * @param mixed $handler
     * @return $this
     * @codeCoverageIgnore trivial
     */
    public function setHandler($handler)
    {
        $this->handler = $handler;
        return $this;
    }

    /**
     * @param string $longDescription
     * @return $this
     */
    public function setDescription($longDescription)
    {
        $this->longDescription = $longDescription;
        if ($this->shortDescription === null) {
            $this->shortDescription = $longDescription;
        }
        return $this;
    }

    /**
     * @param string $shortDescription
     * @return $this
     */
    public function setShortDescription($shortDescription)
    {
        $this->shortDescription = $shortDescription;
        if ($this->longDescription === null) {
            $this->longDescription = $shortDescription;
        }
        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return mixed
     */
    public function getHandler()
    {
        return $this->handler;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->longDescription;
    }

    /**
     * @return string
     */
    public function getShortDescription()
    {
        return $this->shortDescription;
    }
}


text:
#include "tensorflow/lite/kernels/internal/reference/conv.h"

#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/reference/integer_ops/conv.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/padding.h"
#include "tensorflow/lite/micro/kernels/kernel_util.h"

namespace tflite {
namespace {

constexpr int kInputTensor = 0;
constexpr int kFilterTensor = 1;
constexpr int kBiasTensor = 2;
constexpr int kOutputTensor = 0;

// Conv is quantized along dimension 0:
// https://www.tensorflow.org/lite/performance/quantization_spec
constexpr int kConvQuantizedDimension = 0;

// This file has 2 implementation of Conv.

struct OpData {
  TfLitePaddingValues padding;

  // Cached tensor zero point values for quantized operations.
  int32_t input_zero_point;
  int32_t filter_zero_point;
  int32_t output_zero_point;

  // The scaling factor from input to output (aka the 'real multiplier') can
  // be represented as a fixed point multiplier plus a left shift.
  int32_t output_multiplier;
  int output_shift;

  // Per channel output multiplier and shift.
  int32_t* per_channel_output_multiplier;
  int32_t* per_channel_output_shift;

  // The range of the fused activation layer. For example for kNone and
  // uint8_t these would be 0 and 255.
  int32_t output_activation_min;
  int32_t output_activation_max;
};

inline PaddingType RuntimePaddingType(TfLitePadding padding) {
  switch (padding) {
    case TfLitePadding::kTfLitePaddingSame:
      return PaddingType::kSame;
    case TfLitePadding::kTfLitePaddingValid:
      return PaddingType::kValid;
    case TfLitePadding::kTfLitePaddingUnknown:
    default:
      return PaddingType::kNone;
  }
}

TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node,
                             const TfLiteConvParams* params, int width,
                             int height, int filter_width, int filter_height,
                             int out_width, int out_height,
                             const TfLiteType data_type, OpData* data) {
  bool has_bias = node->inputs->size == 3;
  // Check number of inputs/outputs
  TF_LITE_ENSURE(context, has_bias || node->inputs->size == 2);
  TF_LITE_ENSURE_EQ(context, node->outputs->size, 1);

  // Matching GetWindowedOutputSize in TensorFlow.
  auto padding = params->padding;
  data->padding = ComputePaddingHeightWidth(
      params->stride_height, params->stride_width,
      params->dilation_height_factor, params->dilation_width_factor, height,
      width, filter_height, filter_width, padding, &out_height, &out_width);

  // Note that quantized inference requires that all tensors have their
  // parameters set. This is usually done during quantized training.
  if (data_type != kTfLiteFloat32) {
    const TfLiteTensor* input = GetInput(context, node, kInputTensor);
    TF_LITE_ENSURE(context, input != nullptr);
    const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);
    TF_LITE_ENSURE(context, filter != nullptr);
    const TfLiteTensor* bias =
        GetOptionalInputTensor(context, node, kBiasTensor);
    TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
    TF_LITE_ENSURE(context, output != nullptr);
    int output_channels = filter->dims->data[kConvQuantizedDimension];

    TF_LITE_ENSURE_STATUS(tflite::PopulateConvolutionQuantizationParams(
        context, input, filter, bias, output, params->activation,
        &data->output_multiplier, &data->output_shift,
        &data->output_activation_min, &data->output_activation_max,
        data->per_channel_output_multiplier,
        reinterpret_cast<int*>(data->per_channel_output_shift),
        output_channels));
  }
  return kTfLiteOk;
}

void* Init(TfLiteContext* context, const char* buffer, size_t length) {
  TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
  return context->AllocatePersistentBuffer(context, sizeof(OpData));
}

TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  TFLITE_DCHECK(node->user_data != nullptr);
  TFLITE_DCHECK(node->builtin_data != nullptr);

  OpData* data = static_cast<OpData*>(node->user_data);
  const auto params = static_cast<const TfLiteConvParams*>(node->builtin_data);

  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
  TF_LITE_ENSURE(context, output != nullptr);
  const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  TF_LITE_ENSURE(context, input != nullptr);
  const TfLiteTensor* filter = GetInput(context, node, kFilterTensor);
  TF_LITE_ENSURE(context, filter != nullptr);

  int input_width = input->dims->data[2];
  int input_height = input->dims->data[1];
  int filter_width = filter->dims->data[2];
  int filter_height = filter->dims->data[1];
  int output_width = output->dims->data[2];
  int output_height = output->dims->data[1];

  // Dynimically allocate per-channel quantization parameters.
  const int num_channels = filter->dims->data[kConvQuantizedDimension];
  data->per_channel_output_multiplier =
      static_cast<int32_t*>(context->AllocatePersistentBuffer(
          context, num_channels * sizeof(int32_t)));
  data->per_channel_output_shift =
      static_cast<int32_t*>(context->AllocatePersistentBuffer(
          context, num_channels * sizeof(int32_t)));

  // All per-channel quantized tensors need valid zero point and scale arrays.
  if (input->type == kTfLiteInt8) {
    TF_LITE_ENSURE_EQ(context, filter->quantization.type,
                      kTfLiteAffineQuantization);

    const auto* affine_quantization =
        static_cast<TfLiteAffineQuantization*>(filter->quantization.params);
    TF_LITE_ENSURE(context, affine_quantization);
    TF_LITE_ENSURE(context, affine_quantization->scale);
    TF_LITE_ENSURE(context, affine_quantization->zero_point);

    TF_LITE_ENSURE(context,
                   affine_quantization->scale->size == 1 ||
                       affine_quantization->scale->size ==
                           filter->dims->data[kConvQuantizedDimension]);
    TF_LITE_ENSURE_EQ(context, affine_quantization->scale->size,
                      affine_quantization->zero_point->size);
  }

  TF_LITE_ENSURE_STATUS(CalculateOpData(
      context, node, params, input_width, input_height, filter_width,
      filter_height, output_width, output_height, input->type, data));

  data->input_zero_point = input->params.zero_point;
  data->filter_zero_point = filter->params.zero_point;
  data->output_zero_point = output->params.zero_point;

  return kTfLiteOk;
}  // namespace conv

void EvalQuantized(TfLiteContext* context, TfLiteNode* node,
                   TfLiteConvParams* params, const OpData& data,
                   const TfLiteEvalTensor* input,
                   const TfLiteEvalTensor* filter, const TfLiteEvalTensor* bias,
                   TfLiteEvalTensor* im2col, TfLiteEvalTensor* hwcn_weights,
                   TfLiteEvalTensor* output) {
  const int32_t input_offset = -data.input_zero_point;
  const int32_t filter_offset = -data.filter_zero_point;
  const int32_t output_offset = data.output_zero_point;

  // TODO(b/154032858): Investigate removing extra copies.
  ConvParams op_params;
  op_params.padding_type = RuntimePaddingType(params->padding);
  op_params.padding_values.width = data.padding.width;
  op_params.padding_values.height = data.padding.height;
  op_params.stride_width = params->stride_width;
  op_params.stride_height = params->stride_height;
  op_params.dilation_width_factor = params->dilation_width_factor;
  op_params.dilation_height_factor = params->dilation_height_factor;
  op_params.input_offset = input_offset;
  op_params.weights_offset = filter_offset;
  op_params.output_offset = output_offset;
  op_params.output_multiplier = data.output_multiplier;
  op_params.output_shift = -data.output_shift;
  op_params.quantized_activation_min = data.output_activation_min;
  op_params.quantized_activation_max = data.output_activation_max;
  reference_ops::Conv(op_params, tflite::micro::GetTensorShape(input),
                      tflite::micro::GetTensorData<uint8_t>(input),
                      tflite::micro::GetTensorShape(filter),
                      tflite::micro::GetTensorData<uint8_t>(filter),
                      tflite::micro::GetTensorShape(bias),
                      tflite::micro::GetTensorData<int32_t>(bias),
                      tflite::micro::GetTensorShape(output),
                      tflite::micro::GetTensorData<uint8_t>(output),
                      tflite::micro::GetTensorShape(im2col),
                      tflite::micro::GetTensorData<uint8_t>(im2col), nullptr);
}

void EvalQuantizedPerChannel(TfLiteContext* context, TfLiteNode* node,
                             TfLiteConvParams* params, const OpData& data,
                             const TfLiteEvalTensor* input,
                             const TfLiteEvalTensor* filter,
                             const TfLiteEvalTensor* bias,
                             TfLiteEvalTensor* output,
                             TfLiteEvalTensor* im2col) {
  // TODO(b/154032858): Investigate removing extra copies.
  ConvParams op_params;
  op_params.input_offset = -data.input_zero_point;
  op_params.output_offset = data.output_zero_point;
  op_params.stride_height = params->stride_height;
  op_params.stride_width = params->stride_width;
  op_params.dilation_height_factor = params->dilation_height_factor;
  op_params.dilation_width_factor = params->dilation_width_factor;
  op_params.padding_values.height = data.padding.height;
  op_params.padding_values.width = data.padding.width;
  op_params.quantized_activation_min = data.output_activation_min;
  op_params.quantized_activation_max = data.output_activation_max;

  reference_integer_ops::ConvPerChannel(
      op_params, data.per_channel_output_multiplier,
      data.per_channel_output_shift, tflite::micro::GetTensorShape(input),
      tflite::micro::GetTensorData<int8_t>(input),
      tflite::micro::GetTensorShape(filter),
      tflite::micro::GetTensorData<int8_t>(filter),
      tflite::micro::GetTensorShape(bias),
      tflite::micro::GetTensorData<int32_t>(bias),
      tflite::micro::GetTensorShape(output),
      tflite::micro::GetTensorData<int8_t>(output));
}

void EvalFloat(TfLiteContext* context, TfLiteNode* node,
               TfLiteConvParams* params, const OpData& data,
               const TfLiteEvalTensor* input, const TfLiteEvalTensor* filter,
               const TfLiteEvalTensor* bias, TfLiteEvalTensor* im2col,
               TfLiteEvalTensor* hwcn_weights, TfLiteEvalTensor* output) {
  float output_activation_min, output_activation_max;
  CalculateActivationRange(params->activation, &output_activation_min,
                           &output_activation_max);
  // TODO(b/154032858): Investigate removing extra copies.
  ConvParams op_params;
  op_params.padding_type = RuntimePaddingType(params->padding);
  op_params.padding_values.width = data.padding.width;
  op_params.padding_values.height = data.padding.height;
  op_params.stride_width = params->stride_width;
  op_params.stride_height = params->stride_height;
  op_params.dilation_width_factor = params->dilation_width_factor;
  op_params.dilation_height_factor = params->dilation_height_factor;
  op_params.float_activation_min = output_activation_min;
  op_params.float_activation_max = output_activation_max;

  reference_ops::Conv(op_params, tflite::micro::GetTensorShape(input),
                      tflite::micro::GetTensorData<float>(input),
                      tflite::micro::GetTensorShape(filter),
                      tflite::micro::GetTensorData<float>(filter),
                      tflite::micro::GetTensorShape(bias),
                      tflite::micro::GetTensorData<float>(bias),
                      tflite::micro::GetTensorShape(output),
                      tflite::micro::GetTensorData<float>(output),
                      tflite::micro::GetTensorShape(im2col),
                      tflite::micro::GetTensorData<float>(im2col));
}

TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  auto* params = reinterpret_cast<TfLiteConvParams*>(node->builtin_data);

  const TfLiteEvalTensor* input =
      tflite::micro::GetEvalInput(context, node, kInputTensor);
  const TfLiteEvalTensor* filter =
      tflite::micro::GetEvalInput(context, node, kFilterTensor);
  const TfLiteEvalTensor* bias =
      (NumInputs(node) == 3)
          ? tflite::micro::GetEvalInput(context, node, kBiasTensor)
          : nullptr;
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kOutputTensor);

  TFLITE_DCHECK(node->user_data != nullptr);
  const OpData& data = *(static_cast<const OpData*>(node->user_data));

  TF_LITE_ENSURE_EQ(context, input->type, output->type);
  TF_LITE_ENSURE_MSG(context, input->type == filter->type,
                     "Hybrid models are not supported on TFLite Micro.");

  switch (input->type) {  // Already know in/out types are same.
    case kTfLiteFloat32:
      EvalFloat(context, node, params, data, input, filter, bias, nullptr,
                nullptr, output);
      break;
    case kTfLiteInt8:
      EvalQuantizedPerChannel(context, node, params, data, input, filter, bias,
                              output, nullptr);
      break;
    case kTfLiteUInt8:
      EvalQuantized(context, node, params, data, input, filter, bias, nullptr,
                    nullptr, output);
      break;
    default:
      TF_LITE_KERNEL_LOG(context, "Type %s (%d) not supported.",
                         TfLiteTypeGetName(input->type), input->type);
      return kTfLiteError;
  }
  return kTfLiteOk;
}

}  // namespace

TfLiteRegistration Register_CONV_2D() {
  return {/*init=*/Init,
          /*free=*/nullptr,
          /*prepare=*/Prepare,
          /*invoke=*/Eval,
          /*profiling_string=*/nullptr,
          /*builtin_code=*/0,
          /*custom_name=*/nullptr,
          /*version=*/0};
}

}  // namespace tflite


text:
    <md-toolbar md-scroll-shrink id="visit_list" class="md-hue-1" ng-init="pageTitle = 'pages.visit.list.title'">

            <md-button class="md-icon-button" ng-click="isSearchOpen = !isSearchOpen">
                <md-icon md-font-set="material-icons" class="md-primary">search</md-icon>
                <md-tooltip ></md-tooltip>
            </md-button>
            <md-button class="md-icon-button" ng-if="!isModal" ui-sref="app.visit.create" ng-click="$event.stopPropagation();" >
                <md-icon md-font-set="material-icons" class="md-primary">add_circle</md-icon>
                <md-tooltip ></md-tooltip>
            </md-button>

    </md-toolbar>

    <md-content>

         <form name="visitForm" novalidate>

                        <md-input-container flex>

     <input
     	name="date"
     	aria-label="date"
     	ng-model="search.date"
     	type="text"
        bs-datepicker
        data-model-date-format="yyyy-MM-dd'T'HH:mm:ssZ"
        data-date-type='string'

      />
      </md-input-container>

                        <md-input-container flex>

                    <input
                    	name="description"
                    	aria-label="description"
                   		ng-model="search.description"
                   		type="text"
                 /> </md-input-container>

                        <md-input-container flex>

    <md-chips
            ng-init="search.pet = []"
            ng-model="search.pet"
            readonly="false"
            md-autocomplete-snap
            md-require-match
    ><md-autocomplete
            md-selected-item="selectedItem_pet"
            md-search-text="searchText_pet"
            md-items="item in appCtrl.autocompleteService.petQuery(searchText_pet, ['id','name','birthDate'], true)"
            md-item-text="item.name || item.label"
            md-min-length="0"
            placeholder="{{'pages.visit.defaultFieldName.pet' | translate}}"
        >
        {{item.name || item.label}}
    </md-autocomplete>
    <md-chip-template>
        {{$chip.name || $chip.label}}
    </md-chip-template>
    </md-chips></md-input-container>

        </form>

    <md-content layout-padding layout="column" class="list-search">

                            <md-icon md-font-set="material-icons"
                                     ng-class="{'md-primary':hovering}"
                                     ng-mouseenter="hovering = true"
                                     ng-mouseleave="hovering = false">remove_red_eye</md-icon>

                            <md-icon md-font-set="material-icons"
                                     ng-class="{'md-accent':hovering}"
                                     ng-mouseenter="hovering = true"
                                     ng-mouseleave="hovering = false">edit</md-icon>

                            <md-icon md-font-set="material-icons"
                                     ng-class="{'md-warn':hovering}"
                                     ng-mouseenter="hovering = true"
                                     ng-mouseleave="hovering = false">delete</md-icon>

                            <md-icon md-font-set="material-icons"
                                     ng-class="{'md-primary':hovering}"
                                     ng-mouseenter="hovering = true"
                                     ng-mouseleave="hovering = false">add_circle</md-icon>

                    {{::visit.id}}

{{::visit.date | date:'yyyy-MM-dd HH:mm'}}

{{::visit.description}}

{{::visit.pet.id}} {{::visit.pet.name}} {{::visit.pet.birthDate}}

    </md-content>
</md-content>


text:
#include "config.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/stack.h>
#include <openssl/evp.h>
#include <openssl/bio.h>

#include "vomsproxy.h"
#include "myproxycertinfo.h"
#include "sslutils.h"
#include "doio.h"

static char *readfromfile(char *file, int *size, int *warning);
static void setWarning(int *warning, int value);
static void setAdditional(void **additional, void *data);
static X509_EXTENSION *set_KeyUsageFlags(int flags);
static int get_KeyUsageFlags(X509 *cert);
static X509_EXTENSION *set_ExtendedKeyUsageFlags(char *flagnames);
static char *getBitName(char**string);
static int getBitValue(char *bitname);
static int convertMethod(char *bits, int *warning, void **additional);
static X509_EXTENSION *get_BasicConstraints(int ca);

struct VOMSProxyArguments *VOMS_MakeProxyArguments()
{
  return (struct VOMSProxyArguments*)calloc(1, sizeof(struct VOMSProxyArguments));
}

void VOMS_FreeProxyArguments(struct VOMSProxyArguments *args)
{
  free(args);
}

void VOMS_FreeProxy(struct VOMSProxy *proxy)
{
  if (proxy) {
    X509_free(proxy->cert);
    sk_X509_pop_free(proxy->chain, X509_free);
    EVP_PKEY_free(proxy->key);
    free(proxy);
  }
}

struct VOMSProxy *VOMS_AllocProxy()
{
  return (struct VOMSProxy*)calloc(1, sizeof(struct VOMSProxy));
}

int VOMS_WriteProxy(const char *filename, struct VOMSProxy *proxy)
{
  int ret = -1;
  int fd = -1;
  int retry = 3;
  BIO *bp = NULL;

  while (fd < 0 && retry > 0) {
    unlink(filename);
    fd  = open(filename, O_WRONLY|O_CREAT|O_EXCL|O_TRUNC, 0600);
    retry --;
  }

#ifndef WIN32
  if (fd != -1) {
    if (fchmod(fd, S_IRUSR|S_IWUSR) < 0) {
      close(fd);
      return -1;
    }
  }
#endif

  if (fd != -1) {
    if ((bp = BIO_new_fd(fd, BIO_NOCLOSE)) != NULL) {
      ret = proxy_marshal_bp(bp, proxy->cert, proxy->key, NULL, proxy->chain);
      BIO_free(bp);
    }
    close(fd);
  }

  return ret;
}

static int kpcallback(int UNUSED(p), int UNUSED(n))
{
  return 0;
}

#define SET_EXT(ex)  (!sk_X509_EXTENSION_push(extensions, (ex)) ? \
   (PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT), 0) : \
   ((ex = ((X509_EXTENSION*)NULL)), 1))

struct VOMSProxy *VOMS_MakeProxy(struct VOMSProxyArguments *args, int *warning, void **additional)
{
  char *value = NULL;

  X509 * ncert = NULL;
  EVP_PKEY * npkey = NULL;
  X509_REQ * req = NULL;
  STACK_OF(X509_EXTENSION) * extensions = NULL;
  int ku_flags = 0;
  char *policy = NULL;

  X509_EXTENSION *ex1 = NULL, *ex2 = NULL, *ex3 = NULL,
    *ex4 = NULL, *ex5 = NULL, *ex6 = NULL, *ex7 = NULL,
    *ex8 = NULL, *ex9 = NULL, *ex10 = NULL, *ex11 = NULL,
    *ex12 = NULL, *ex13 = NULL;

  int i = 0;

  struct VOMSProxy *proxy = NULL;

  static int init = 0;

  int (*cback)();

  if (!init) {
    InitProxyCertInfoExtension(1);
    init = 1;
  }

  setWarning(warning, PROXY_NO_ERROR);

  if (args->callback)
    cback = args->callback;
  else
    cback = kpcallback;

  if (args->proxyrequest == NULL) {
    if (proxy_genreq(args->cert, &req, &npkey, args->bits,
                     args->newsubject ? args->newsubject : NULL,
                     (int (*)())cback))
      goto err;
  }
  else
    req = args->proxyrequest;

  /* initialize extensions stack */

  if ((extensions = sk_X509_EXTENSION_new_null()) == NULL) {
    PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
    goto err;
  }

  /* Add passed extensions */
  if (args->extensions) {
    int proxyindex;

    for (proxyindex = 0; proxyindex < sk_X509_EXTENSION_num(args->extensions); proxyindex++) {
      X509_EXTENSION *ext = X509_EXTENSION_dup(sk_X509_EXTENSION_value(args->extensions, i));
      if (ext) {
        if (!sk_X509_EXTENSION_push(extensions, ext)) {
          X509_EXTENSION_free(ext);
          PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
          goto err;
        }
      }
      else {
        PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
        goto err;
      }
    }
  }
  /* Add proxy extensions */

  /* voms extension */

  if (args->datalen) {
    if ((ex1 = CreateProxyExtension("voms", args->data, args->datalen, 0)) == NULL) {
      PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
      goto err;
    }

    if (!SET_EXT(ex1))
      goto err;
  }

  /* include extension */

  if (args->filename) {

    int filesize;
    char *filedata = readfromfile(args->filename, &filesize, warning);

    if (filedata) {
      if ((ex3 = CreateProxyExtension("incfile", filedata, filesize, 0)) == NULL) {
        PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
        free(filedata);
        goto err;
      }

      free(filedata);
      if (!SET_EXT(ex3))
        goto err;
    }
    else {
      setAdditional(additional, args->filename);
      goto err;
    }
  }

  /* AC extension  */

  if (args->aclist) {

    if ((ex5 = X509V3_EXT_conf_nid(NULL, NULL, OBJ_txt2nid("acseq"), (char *)args->aclist)) == NULL) {
      PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
      goto err;
    }

    if (!SET_EXT(ex5))
      goto err;
  }

  /* keyUsage extension */

  if (args->keyusage) {
    ku_flags = convertMethod(args->keyusage, warning, additional);
    if (ku_flags == -1) {
      PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
      goto err;
    }
  }
  else if (args->selfsigned) {
    ku_flags = X509v3_KU_DIGITAL_SIGNATURE | X509v3_KU_KEY_CERT_SIGN |
      X509v3_KU_CRL_SIGN;
  }
  else {
    ku_flags = get_KeyUsageFlags(args->cert);

    if (ku_flags != 0) {
      ku_flags &= ~X509v3_KU_KEY_CERT_SIGN;
      ku_flags &= ~X509v3_KU_NON_REPUDIATION;
    }
  }

  if (ku_flags != 0) {
    if ((ex8 = set_KeyUsageFlags(ku_flags)) == NULL) {
      PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
      goto err;
    }

    X509_EXTENSION_set_critical(ex8, 1);

    if (!SET_EXT(ex8))
      goto err;
  }

  /* netscapeCert extension */
  if (args->netscape) {

    if ((ex9 = X509V3_EXT_conf_nid(NULL, NULL, NID_netscape_cert_type, args->netscape)) == NULL) {
      /*      PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT); */
      goto err;
    }

    if (!SET_EXT(ex9))
      goto err;
  }

  /* extended key usage */

  if (args->exkusage) {
    if ((ex10 = set_ExtendedKeyUsageFlags(args->exkusage)) == NULL) {
      PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
      setWarning(warning, PROXY_ERROR_UNKNOWN_EXTENDED_BIT);
      setAdditional(additional,args->exkusage);
      goto err;
    }

    if (!SET_EXT(ex10))
      goto err;
  }

  /* Basic Constraints */

  if ((ex12 = get_BasicConstraints(args->selfsigned ? 1 : 0)) == NULL) {
      PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
      goto err;
    }

  X509_EXTENSION_set_critical(ex12, 1);

  if (!SET_EXT(ex12))
    goto err;

  /* vo extension */

  if (strlen(args->voID)) {
    if ((ex4 = CreateProxyExtension("vo", args->voID, strlen(args->voID), 0)) == NULL) {
      PRXYerr(PRXYERR_F_PROXY_SIGN,PRXYERR_R_CLASS_ADD_EXT);
      goto err;
    }

    if (!SET_EXT(ex4))
      goto err;
  }

  /* authority key identifier and subject key identifier extension */

  {
    X509V3_CTX ctx;

    X509V3_set_ctx(&ctx, (args->selfsigned ? NULL : args->cert), NULL, req, NULL, 0);

    if (args->selfsigned) {
      X509 *tmpcert = NULL;
      ex13 = X509V3_EXT_conf_nid(NULL, &ctx, NID_subject_key_identifier, "hash");

      if (!ex13) {
        PRXYerr(PRXYERR_F_PROXY_SIGN,PRXYERR_R_CLASS_ADD_EXT);
        goto err;
      }

      if (!SET_EXT(ex13))
        goto err;

      tmpcert = X509_new();
      if (tmpcert) {
        EVP_PKEY *key = X509_REQ_get_pubkey(req);
        X509_set_pubkey(tmpcert, key);
        X509_add_ext(tmpcert, ex13, -1);
        X509V3_set_ctx(&ctx, tmpcert, tmpcert, req, NULL, 0);
        ex11 = X509V3_EXT_conf_nid(NULL, &ctx, NID_authority_key_identifier, "keyid");
        X509_free(tmpcert);
        EVP_PKEY_free(key);
      }
      else
        ex11 = NULL;
    }
    else {
      ex11 = X509V3_EXT_conf_nid(NULL, &ctx, NID_authority_key_identifier, "keyid");
    }

    if (!ex11) {
      PRXYerr(PRXYERR_F_PROXY_SIGN,PRXYERR_R_CLASS_ADD_EXT);
      goto err;
    }

    if (!SET_EXT(ex11))
      goto err;
  }

  /* class_add extension */

#ifdef CLASS_ADD

  if (class_add_buf && class_add_buf_len > 0) {
    if ((ex2 = proxy_extension_class_add_create((void *)args->class_add_buf, args->class_add_buf_len)) == NULL) {
      PRXYerr(PRXYERR_F_PROXY_SIGN,PRXYERR_R_CLASS_ADD_EXT);
      goto err;
    }

    if (!SET_EXT(ex2))
      goto err;
  }

#endif

  /* PCI extension */

  if (args->proxyversion>=3) {
    myPROXYPOLICY *                     proxypolicy;
    myPROXYCERTINFO *                   proxycertinfo = NULL;
    ASN1_OBJECT *                       policy_language;

    /* getting contents of policy file */

    int policysize = 0;
    char *policylang = args->policylang;

    if (args->policyfile) {
      policy = readfromfile(args->policyfile, &policysize, warning);

      if (!policy) {
        setAdditional(additional, args->policyfile);
        goto err;
      }
    }

    /* setting policy language field */

    if (!policylang) {
      if (!args->policyfile) {
        policylang = IMPERSONATION_PROXY_OID;
        setWarning(warning, PROXY_WARNING_GSI_ASSUMED);
      }
      else {
        policylang = GLOBUS_GSI_PROXY_GENERIC_POLICY_OID;
        setWarning(warning, PROXY_WARNING_GENERIC_LANGUAGE_ASSUMED);
      }
    }

    /* predefined policy language can be specified with simple name string */

    else if (strcmp(policylang, IMPERSONATION_PROXY_SN) == 0)
      policylang = IMPERSONATION_PROXY_OID;
    else if (strcmp(policylang, INDEPENDENT_PROXY_SN) == 0)
      policylang = INDEPENDENT_PROXY_OID;

    /* does limited prevail on others? don't know what does grid-proxy_init since if pl is given with
       limited options it crash */
    if (args->limited)
      policylang = LIMITED_PROXY_OID;

    OBJ_create(policylang, policylang, policylang);

    if (!(policy_language = OBJ_nid2obj(OBJ_sn2nid(policylang)))) {
      PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_OID);
      goto err;
    }

    int nativeopenssl = proxynative();

    if (args->proxyversion == 3 || (args->proxyversion == 4 && !nativeopenssl)) {
      /* proxypolicy */

      proxypolicy = myPROXYPOLICY_new();

      if (policy) {
        myPROXYPOLICY_set_policy(proxypolicy, (unsigned char*)policy, policysize);
        free(policy);
        policy = NULL;
      }
      else if (args->policytext)
        myPROXYPOLICY_set_policy(proxypolicy,
                                 (unsigned char*)args->policytext,
                                 strlen(args->policytext));

      myPROXYPOLICY_set_policy_language(proxypolicy, policy_language);

      /* proxycertinfo */

      proxycertinfo = myPROXYCERTINFO_new();
      myPROXYCERTINFO_set_version(proxycertinfo, args->proxyversion);
      myPROXYCERTINFO_set_proxypolicy(proxycertinfo, proxypolicy);

      myPROXYPOLICY_free(proxypolicy);

      if (args->pathlength>=0)
        myPROXYCERTINFO_set_path_length(proxycertinfo, args->pathlength);

      value = (char *)proxycertinfo;
    }
    else {
      if (args->pathlength != -1) {
        char *buffer = snprintf_wrap("%d", args->pathlength);

        if (policy) {
          value = snprintf_wrap("language:%s,pathlen:%s,policy:text:%s", policylang, buffer, policy);
          free(policy);
          policy = NULL;
        }
        else if (args->policytext)
          value = snprintf_wrap("language:%s,pathlen:%s,policy:text:%s", policylang, buffer, args->policytext);
        else
          value = snprintf_wrap("language:%s,pathlen:%s", policylang, buffer);
        free(buffer);
      }
      else {
        if (policy)
          value = snprintf_wrap("language:%s,policy:text:%s", policylang, policy);
        else if (args->policytext)
          value = snprintf_wrap("language:%s,policy:text:%s", policylang, args->policytext);
        else
          value = snprintf_wrap("language:%s", policylang);
      }
    }

    if (args->proxyversion == 3) {
      ex7 = X509V3_EXT_conf_nid(NULL, NULL, my_txt2nid(PROXYCERTINFO_V3), (char*)proxycertinfo);
      value = NULL;
    } else {
      if (nativeopenssl) {
        X509V3_CTX ctx;
        X509V3_set_ctx(&ctx, NULL, NULL, NULL, NULL, 0L);
        ctx.db = (void*)&ctx;
        X509V3_CONF_METHOD method = { NULL, NULL, NULL, NULL };
        ctx.db_meth = &method;
        ex7 = X509V3_EXT_conf_nid(NULL, &ctx, my_txt2nid(PROXYCERTINFO_V4), (char*)value);
        free(value);
        value = NULL;
      }
      else
        ex7 = X509V3_EXT_conf_nid(NULL, NULL, my_txt2nid(PROXYCERTINFO_V4), (char*)value);
      value = NULL;
    }

    if (policy) {
      free(policy);
      policy = NULL;
    }

    if (ex7 == NULL) {
      PRXYerr(PRXYERR_F_PROXY_SIGN, PRXYERR_R_CLASS_ADD_EXT);
      goto err;
    }

    if (args->proxyversion >= 3) {
      X509_EXTENSION_set_critical(ex7, 1);
    }

    if (!SET_EXT(ex7))
      goto err;
  }

  if (!args->selfsigned)  {
    if (proxy_sign(args->cert,
                   args->key,
                   req,
                   &ncert,
                   args->hours*60*60 + args->minutes*60,
                   extensions,
                   args->limited,
                   args->proxyversion,
                   args->newsubject,
                   args->newissuer,
                   args->pastproxy,
                   args->newserial,
                   args->selfsigned)) {
      goto err;
    }
  }
  else  {
    if (proxy_sign(NULL,
                   npkey,
                   req,
                   &ncert,
                   args->hours*60*60 + args->minutes*60,
                   extensions,
                   args->limited,
                   0,
                   args->newsubject,
                   args->newsubject,
                   args->pastproxy,
                   NULL,
                   args->selfsigned)) {
      goto err;
    }
  }

  proxy = (struct VOMSProxy*)malloc(sizeof(struct VOMSProxy));

  if (proxy) {
    proxy->cert = ncert;
    proxy->key = npkey;
    proxy->chain = sk_X509_new_null();

    if (args->cert)
      sk_X509_push(proxy->chain, X509_dup(args->cert));

    for (i = 0; i < sk_X509_num(args->chain); i++)
      sk_X509_push(proxy->chain, X509_dup(sk_X509_value(args->chain, i)));
  }

 err:

  if (!proxy) {
    X509_free(ncert);
    EVP_PKEY_free(npkey);
  }

  if (extensions) {
    sk_X509_EXTENSION_pop_free(extensions, X509_EXTENSION_free);
  }
  if (!args->proxyrequest)
    X509_REQ_free(req);

  X509_EXTENSION_free(ex13);
  X509_EXTENSION_free(ex12);
  X509_EXTENSION_free(ex11);
  X509_EXTENSION_free(ex10);
  X509_EXTENSION_free(ex9);
  X509_EXTENSION_free(ex8);
  X509_EXTENSION_free(ex6);
  X509_EXTENSION_free(ex7);
  X509_EXTENSION_free(ex5);
  X509_EXTENSION_free(ex2);
  X509_EXTENSION_free(ex3);
  X509_EXTENSION_free(ex4);
  X509_EXTENSION_free(ex1);
  free(policy);
  free(value);
  return proxy;
}

X509_EXTENSION *CreateProxyExtension(char * name, char *data, int datalen, int crit)
{

  X509_EXTENSION *                    ex = NULL;
  ASN1_OBJECT *                       ex_obj = NULL;
  ASN1_OCTET_STRING *                 ex_oct = NULL;

  int nid = OBJ_txt2nid(name);

  if (nid != 0)
    ex_obj = OBJ_nid2obj(nid);
  else
    ex_obj = OBJ_txt2obj(name, 0);

  if (!ex_obj) {
    PRXYerr(PRXYERR_F_PROXY_SIGN,PRXYERR_R_CLASS_ADD_OID);
    goto err;
  }

  if (!(ex_oct = ASN1_OCTET_STRING_new())) {
    PRXYerr(PRXYERR_F_PROXY_SIGN,PRXYERR_R_CLASS_ADD_EXT);
    goto err;
  }

  ex_oct->data   = (unsigned char*)data;
  ex_oct->length = datalen;

  if (!(ex = X509_EXTENSION_create_by_OBJ(NULL, ex_obj, crit, ex_oct))) {
    PRXYerr(PRXYERR_F_PROXY_SIGN,PRXYERR_R_CLASS_ADD_EXT);
  }

 err:

  if (ex_oct) {
    /* avoid spurious free of the contents. */
    ex_oct->length = 0;
    ex_oct->data = NULL;
    ASN1_OCTET_STRING_free(ex_oct);
  }

  ASN1_OBJECT_free(ex_obj);

  return ex;

}

static char *readfromfile(char *file, int *size, int *warning)
{
  int fd = open(file,O_RDONLY);
  char *buffer = NULL;

  if (fd != -1) {
    struct stat filestats;

    if (!fstat(fd, &filestats)) {
      *size = filestats.st_size;

      buffer = (char *)malloc(*size);

      if (buffer) {
        int offset = 0;
        int ret = 0;

        do {
          ret = read(fd, buffer+offset, *size - offset);
          offset += ret;
        } while ( ret > 0);

        if (ret < 0) {
          free(buffer);
          buffer = NULL;
          setWarning(warning, PROXY_ERROR_FILE_READ);
        }
      }
      else
        setWarning(warning, PROXY_ERROR_OUT_OF_MEMORY);
    }
    else
      setWarning(warning, PROXY_ERROR_STAT_FILE);
    close(fd);
  }
  else
    setWarning(warning, PROXY_ERROR_OPEN_FILE);

  return buffer;
}

static void setWarning(int *warning, int value)
{
  if (warning)
    *warning = value;
}

static void setAdditional(void **additional, void *data)
{
  if (additional)
    *additional = data;
}

static X509_EXTENSION *set_KeyUsageFlags(int flags)
{
  unsigned char data[2];

  X509_EXTENSION  *ext = NULL;
  ASN1_BIT_STRING *str = ASN1_BIT_STRING_new();

  if (str) {
    int len =0;

    data[0] =  flags & 0x00ff;
    data[1] = (flags & 0xff00) >> 8;

    len = (data[1] ? 2 : 1);

    ASN1_BIT_STRING_set(str, data, len);

    ext = X509V3_EXT_i2d(NID_key_usage, 1, str);
    ASN1_BIT_STRING_free(str);

    return ext;
  }

  return NULL;
}

static X509_EXTENSION *set_ExtendedKeyUsageFlags(char *flagnames)
{
  if (!flagnames)
    return NULL;

  return X509V3_EXT_conf_nid(NULL, NULL, NID_ext_key_usage, flagnames);
}

static X509_EXTENSION *get_BasicConstraints(int ca)
{
  return X509V3_EXT_conf_nid(NULL, NULL, NID_basic_constraints, (ca ? "CA:true" : "CA:false"));
}

static int get_KeyUsageFlags(X509 *cert)
{
  int keyusage = 0;

  ASN1_BIT_STRING *usage = X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL);

  if (usage) {
    if (usage->length > 0)
      keyusage = usage->data[0];
    if (usage->length > 1)
      keyusage |= usage->data[1] << 8;

    ASN1_BIT_STRING_free(usage);
  }

  return keyusage;
}

static char *getBitName(char**string)
{
  char *div = NULL;
  char *temp = NULL;

  if (!string || !(*string) || (*(*string) == '\0'))
    return NULL;

  div = strchr(*string, ',');

  if (div) {
    temp = *string;
    *div++ = '\0';
    *string = div;
  }
  else {
    temp = *string;
    *string = *string + strlen(*string);
  }

  return temp;
}

static int getBitValue(char *bitname)
{
  if (!strcmp(bitname, "digitalSignature"))
    return KU_DIGITAL_SIGNATURE;
  else if (!strcmp(bitname, "nonRepudiation"))
    return KU_NON_REPUDIATION;
  else if (!strcmp(bitname, "keyEncipherment"))
    return KU_KEY_ENCIPHERMENT;
  else if (!strcmp(bitname, "dataEncipherment"))
    return KU_DATA_ENCIPHERMENT;
  else if (!strcmp(bitname, "keyAgreement"))
    return KU_KEY_AGREEMENT;
  else if (!strcmp(bitname, "keyCertSign"))
    return KU_KEY_CERT_SIGN;
  else if (!strcmp(bitname, "cRLSign"))
    return KU_CRL_SIGN;
  else if (!strcmp(bitname, "encipherOnly"))
    return KU_ENCIPHER_ONLY;
  else if (!strcmp(bitname, "decipherOnly"))
    return KU_DECIPHER_ONLY;

  return 0;
}

static int convertMethod(char *bits, int *warning, void **additional)
{
  char *bitname = NULL;
  int value = 0;
  int total = 0;

  while ((bitname = getBitName(&bits))) {
    value = getBitValue(bitname);
    if (value == 0) {
      setWarning(warning, PROXY_ERROR_UNKNOWN_BIT);
      setAdditional(additional, bitname);
      return -1;
    }
    total |= value;
  }

  return total;
}

char *ProxyCreationError(int error, void *additional)
{
  switch (error) {
  case PROXY_NO_ERROR:
    return NULL;
    break;

  case PROXY_ERROR_OPEN_FILE:
    return snprintf_wrap("Error: cannot open file: %s\n%s\n", additional, strerror(errno));
    break;

  case PROXY_ERROR_FILE_READ:
    return snprintf_wrap("Error: cannot read from file: %s\n%s\n", additional, strerror(errno));
    break;

  case PROXY_ERROR_STAT_FILE:
    return snprintf_wrap("Error: cannot stat file: %s\n%s\n", additional, strerror(errno));
    break;

  case PROXY_ERROR_OUT_OF_MEMORY:
    return snprintf_wrap("Error: out of memory");
    break;

  case PROXY_ERROR_UNKNOWN_BIT:
    return snprintf_wrap("KeyUsage bit: %s unknown\n", additional);
    break;

  case PROXY_ERROR_UNKNOWN_EXTENDED_BIT:
    return snprintf_wrap("ExtKeyUsage bit value: %s invalid.  One or more of the bits are unknown\n", additional);
    break;

  case PROXY_WARNING_GSI_ASSUMED:
    return snprintf_wrap("\nNo policy language specified, Gsi impersonation proxy assumed.");
    break;

  case PROXY_WARNING_GENERIC_LANGUAGE_ASSUMED:
    return snprintf_wrap("\nNo policy language specified with policy file, assuming generic.");
    break;

  default:
    return snprintf_wrap("Unknown error");
    break;
  }
}


text:
<?php

/*
 * Split shipments checkout example
 *
 * This demonstrates a merchant use case where the order needs to be
 * furfilled in multiple shipments, or where a single item is shipped
 * in multiple shipments over time.
 *
 * See SplitShipmentsCheckoutExample.php for more information
 */

require_once realpath(dirname(__FILE__)) . '/.config.inc.php';
require_once realpath(dirname(__FILE__)) . '/SetOrderReferenceDetailsSample.php';
require_once realpath(dirname(__FILE__)) . '/ConfirmOrderReferenceSample.php';
require_once realpath(dirname(__FILE__)) . '/AuthorizeSample.php';
require_once realpath(dirname(__FILE__)) . '/GetAuthorizationDetailsSample.php';
require_once realpath(dirname(__FILE__)) . '/CaptureSample.php';
require_once realpath(dirname(__FILE__)) . '/CloseOrderReferenceSample.php';
require_once realpath(dirname(__FILE__)) . '/CLIExample.php';
require_once realpath(dirname(__FILE__)) . '/SplitShipmentsCheckoutExample.php';
require_once realpath(dirname(__FILE__)) . '/GetCaptureDetailsSample.php';

/*
 * SplitShipmentsCheckoutExampleCLI class captures input from stdin and prints to stdout,
 * and drives the split shipment checkout example
 *
 */
class SplitShipmentsCheckoutExampleCLI extends CLIExample
{
    /**
     * Create a new instance of the cli example and
     * validate command line arguments
     *
     * @param array $argv arguments to the application passed to the command line
     */
    public function __construct($argv)
    {
        if (count($argv) < 1) {
            print "Missing mandatory argument: " .
               "please provide an amazonOrderReferenceId";
            exit(0);
        }

        /*
         * Instantiate Implementation of OffAmazonPaymentsService client
         *
         * Merchant ids and access keys are defined in the constants
         * are defined in the OffAmazonPaymentsService.config.inc.php file in
         * the parent directory of this server
         */
        $this->exampleClass
            = new SplitShipmentsCheckoutExample(
                new OffAmazonPaymentsService_Client(),
                $argv[1]
            );
    }

    /**
     * Run all the steps for the sample in sequence
     *
     */
    public function runSample()
    {
        $shipments = $this->_getNumberOfShipmentsInOrder();
        $this->_addShipmentsToOrder($shipments);
        $this->_addOrderAmountToOrderReference();
        $this->_confirmOrderReference();
        $this->_performAuthAndCaptureForOrderShipments($shipments);
        $this->_closeOrderReference();
        print "Split shipments checkout example completed" . PHP_EOL;
    }

    /**
     * Capture the number of shipments for this run of the scenario
     *
     * @return int number of shipments in this order
     */
    private function _getNumberOfShipmentsInOrder()
    {
        print "Enter the number of shipments that you want to perform for this order: ";

        do {
            $shipments = trim(fgets(STDIN));
        } while (!is_numeric($shipments));

        print PHP_EOL;
        return $shipments;
    }

    /**
     * Fill in the details for each shipment in this order
     *
     * @param int $shipments number of shipments to fill
     *
     */
    private function _addShipmentsToOrder($shipments)
    {
        for ($i = 0; $i < $shipments; $i++) {
            $this->_addShipmentToOrder($i);
        }
    }

    /**
     * Fill in the details for a single shipment in the order
     *
     * @param int $shipmentNumber nth shipment for the order
     */
    private function _addShipmentToOrder($shipmentNumber)
    {
        print "Select an item to add to shipment #" . ($shipmentNumber + 1) . ":" . PHP_EOL;
        $items = $this->exampleClass->getItemNames();
        for ($i = 0; $i < count($items); $i++) {
            print " " . $i . " - " . $items[$i] . PHP_EOL;
        }

        do {
            print "Select the number of the item to add to this shipment:";
            $itemToAdd = trim(fgets(STDIN));
        } while (!is_numeric($itemToAdd));

        print PHP_EOL;

        $this->exampleClass->addShipmentToOrder($itemToAdd);
    }

    /**
     * Add the total price of all items in the order and update the payment contract
     *
     */
    private function _addOrderAmountToOrderReference()
    {
        $response = $this->callStepAndCheckForException('addOrderAmountToOrderReference');
        printSetOrderReferenceDetailsResponse($response);
    }

    /**
     * Confirm the order reference information, allowing for
     * authorizations and captures to be created
     *
     * @return OffAmazonPaymentsService_Model_ConfirmOrderReferenceResponse service response
     */
    private function _confirmOrderReference()
    {
        $response = $this->callStepAndCheckForException('confirmOrderReference');
        printConfirmOrderReferenceResponse($response);
    }

    /**
     * Perform the authorize and captures for all shipments in this
     * order
     *
     * @param int $shipments total number of shipments in this order
     */
    private function _performAuthAndCaptureForOrderShipments($shipments)
    {
        for ($i = 0; $i < $shipments; $i++) {
             $this->_performAuthAndCaptureForOrderShipment($i);
        }
    }

    /**
     * Perform the authorize and capture for a single shipment in the order
     *
     * @param int $shipmentNumber the shipment to perform transactions on
     */
    private function _performAuthAndCaptureForOrderShipment($shipmentNumber)
    {
        $response = $amazonAuthorizationId = $this->_performAuthorizationForShipment($shipmentNumber);
        $this->_waitUntilAuthorizationProcessingIsCompleted($amazonAuthorizationId);
        $this->_performCaptureForShipment($shipmentNumber, $amazonAuthorizationId);
    }

    /**
     * Perform the authorization for the shipment at the given index
     *
     * @param int $shipmentNumber order item index to authorize
     *
     * @return string amazonAuthorizationId for the single auth call
     */
    private function _performAuthorizationForShipment($shipmentNumber)
    {
        $response = $this->callStepAndCheckForException('performAuthorizationForShipment', array($shipmentNumber));
        printAuthorizeResponse($response);
        return $response->getAuthorizeResult()->getAuthorizationDetails()->getAmazonAuthorizationId();
    }

    /**
     * Poll the API for the status of the Authorization Request, and continue
     * once the status has been updated
     * WARNING: This is not the way to integrate for production systems,
     * instead merchants should use IPN to receive a callback once the
     * processing has been completed.
     * Note that Amazon reserves the right to throttle requests that
     * ignore this advice and poll for a response
     *
     * @param string $amazonAuthorizationReferenceId authorization transaction to query
     */
    private function _waitUntilAuthorizationProcessingIsCompleted($amazonAuthorizationId)
    {
        $response = $this->callStepAndCheckForException(
            'waitUntilAuthorizationProcessingIsCompleted',
            array($amazonAuthorizationId)
        );
        printGetAuthorizationDetailsResponse($response);
        validateThatAuthorizationIsOpen($response);
    }

    /**
     * Perform the capture for a single shipment
     *
     * @param int    $shipmentNumber        order item index to capture
     * @param string $amazonAuthorizationId authorization to capture
     *
     */
    private function _performCaptureForShipment($shipmentNumber, $amazonAuthorizationId)
    {
        $response = $this->callStepAndCheckForException(
            'performCaptureForShipment',
            array($shipmentNumber, $amazonAuthorizationId)
        );
        validateThatCaptureIsCompleted($response->getCaptureResult());
        printCaptureResponse($response);
    }

    /**
     * Close this order reference to indicate that the order is complete, and
     * no further authorizations and captures will be performed on this order
     *
     */
    private function _closeOrderReference()
    {
        $response = $this->callStepAndCheckForException('closeOrderReference');
    }
}

$splitShipmentsCheckoutExample = new SplitShipmentsCheckoutExampleCLI($argv);
$splitShipmentsCheckoutExample->runSample();
?>


text:
#pragma once

#include <QtCore/QTimer>
#include <QtGui/QQuaternion>

#include <trikControl/gyroSensorInterface.h>
#include <trikKitInterpreterCommon/robotModel/twoD/trikTwoDRobotModel.h>
#include <kitBase/robotModel/robotParts/gyroscopeSensor.h>

namespace kitBase {
namespace robotModel {
namespace robotParts {
class GyroscopeSensor;
}
}
}

class TrikGyroscopeAdapter : public trikControl::GyroSensorInterface
{

	Q_OBJECT

public:
	TrikGyroscopeAdapter(kitBase::robotModel::robotParts::GyroscopeSensor *gyro
		, const QSharedPointer<trik::robotModel::twoD::TrikTwoDRobotModel> &model);

	virtual Status status() const override { return Status::ready; }

public slots:
	virtual QVector<int> read() const override;
	virtual void calibrate(int msec) override;
	virtual bool isCalibrated() const override;
	virtual QVector<int> readRawData() const override;
	virtual void setCalibrationValues(const QVector<int> &) override {}
	virtual QVector<int> getCalibrationValues() override { return QVector<int>(); }

private slots:
	void countTilt(const QVector<int> &oldFormat);

private:
	qreal degreeToMilidegree(qreal value);
	int convertToTrikRuntimeTime(quint64 time) const;

	bool mTimeInited = false;

	kitBase::robotModel::robotParts::GyroscopeSensor *mGyro;
	QSharedPointer<trik::robotModel::twoD::TrikTwoDRobotModel> mModel;
	QVector<int> mResult;
	QQuaternion mQuaternion;
	quint64 mStartTime;
	quint64 mLastUpdateTimeStamp;
};


text:
package batfai.samuentropy.brainboard3;

/**
 *
 * @author nbatfai
 */
public class SurfaceEvents implements android.view.SurfaceHolder.Callback {

    private NorbironSurfaceView surfaceView;
    Thread thread;

    public SurfaceEvents(NorbironSurfaceView surfaceView) {

        this.surfaceView = surfaceView;
    }

    @Override
    public void surfaceDestroyed(android.view.SurfaceHolder holder) {

        surfaceView.stop();
        thread = null;
    }

    @Override

    public void surfaceCreated(android.view.SurfaceHolder holder) {

        thread = new Thread(surfaceView);
        thread.start();
        surfaceView.repaint();

    }

    @Override
    public void surfaceChanged(android.view.SurfaceHolder holder, int format,
            int width, int height) {

        surfaceView.repaint();

    }

}


text:
package com.mygdx.pmd.utils;

import com.badlogic.gdx.Gdx;

public class KeyInput {

    public boolean pressed(int key) {
        return Gdx.input.isKeyPressed(key);
    }

    public boolean justPressed(int key) {
        return Gdx.input.isKeyJustPressed(key);
    }
}


text:
using System.Diagnostics;
using NUnit.Framework;
using Rivet.Operations;

namespace Rivet.Test.Operations
{
	[TestFixture]
	public sealed class RemoveSynonymOperationTestFixture
	{
		private const string SchemaName = "schemaName";
		private const string Name = "name";

		[Test]
		public void ShouldWriteQueryForRemoveSynonym()
		{
			var op = new RemoveSynonymOperation(SchemaName, Name);
			Trace.WriteLine(op.ToQuery());
			const string expectedQuery = "drop synonym [schemaName].[name]";
			Assert.AreEqual(expectedQuery, op.ToQuery());
			Assert.That(op.ObjectName, Is.EqualTo(string.Format("{0}.{1}", SchemaName, Name)));
		}

	}
}


text:
first: debug
install: debug-install
uninstall: debug-uninstall
MAKEFILE      = Makefile
QMAKE         = d:\Qt\4.8.6\bin\qmake.exe
DEL_FILE      = del
CHK_DIR_EXISTS= if not exist
MKDIR         = mkdir
COPY          = copy /y
COPY_FILE     = $(COPY)
COPY_DIR      = xcopy /s /q /y /i
INSTALL_FILE  = $(COPY_FILE)
INSTALL_PROGRAM = $(COPY_FILE)
INSTALL_DIR   = $(COPY_DIR)
DEL_FILE      = del
SYMLINK       =
DEL_DIR       = rmdir
MOVE          = move
CHK_DIR_EXISTS= if not exist
MKDIR         = mkdir
SUBTARGETS    =  \
		debug \
		release

debug: $(MAKEFILE).Debug FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug
debug-make_default: $(MAKEFILE).Debug FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug
debug-make_first: $(MAKEFILE).Debug FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug first
debug-all: $(MAKEFILE).Debug FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug all
debug-clean: $(MAKEFILE).Debug FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug clean
debug-distclean: $(MAKEFILE).Debug FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug distclean
debug-install: $(MAKEFILE).Debug FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug install
debug-uninstall: $(MAKEFILE).Debug FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug uninstall
release: $(MAKEFILE).Release FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release
release-make_default: $(MAKEFILE).Release FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release
release-make_first: $(MAKEFILE).Release FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release first
release-all: $(MAKEFILE).Release FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release all
release-clean: $(MAKEFILE).Release FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release clean
release-distclean: $(MAKEFILE).Release FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release distclean
release-install: $(MAKEFILE).Release FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release install
release-uninstall: $(MAKEFILE).Release FORCE
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release uninstall

Makefile: IM_QXmpp.pro  d:\Qt\4.8.6\mkspecs\win32-msvc2010\qmake.conf d:\Qt\4.8.6\mkspecs\qconfig.pri \
		d:\Qt\4.8.6\mkspecs\modules\qt_webkit_version.pri \
		d:\Qt\4.8.6\mkspecs\features\qt_functions.prf \
		d:\Qt\4.8.6\mkspecs\features\qt_config.prf \
		d:\Qt\4.8.6\mkspecs\features\exclusive_builds.prf \
		d:\Qt\4.8.6\mkspecs\features\default_pre.prf \
		d:\Qt\4.8.6\mkspecs\features\win32\default_pre.prf \
		d:\Qt\4.8.6\mkspecs\features\debug.prf \
		d:\Qt\4.8.6\mkspecs\features\debug_and_release.prf \
		d:\Qt\4.8.6\mkspecs\features\default_post.prf \
		d:\Qt\4.8.6\mkspecs\features\win32\default_post.prf \
		d:\Qt\4.8.6\mkspecs\features\win32\rtti.prf \
		d:\Qt\4.8.6\mkspecs\features\win32\exceptions.prf \
		d:\Qt\4.8.6\mkspecs\features\win32\stl.prf \
		d:\Qt\4.8.6\mkspecs\features\shared.prf \
		d:\Qt\4.8.6\mkspecs\features\win32\embed_manifest_exe.prf \
		d:\Qt\4.8.6\mkspecs\features\win32\embed_manifest_dll.prf \
		d:\Qt\4.8.6\mkspecs\features\warn_on.prf \
		d:\Qt\4.8.6\mkspecs\features\qt.prf \
		d:\Qt\4.8.6\mkspecs\features\win32\thread.prf \
		d:\Qt\4.8.6\mkspecs\features\moc.prf \
		d:\Qt\4.8.6\mkspecs\features\win32\windows.prf \
		d:\Qt\4.8.6\mkspecs\features\resources.prf \
		d:\Qt\4.8.6\mkspecs\features\uic.prf \
		d:\Qt\4.8.6\mkspecs\features\yacc.prf \
		d:\Qt\4.8.6\mkspecs\features\lex.prf \
		d:\Qt\4.8.6\mkspecs\features\include_source_dir.prf \
		d:\Qt\4.8.6\lib\qtmaind.prl
	$(QMAKE) -spec d:\Qt\4.8.6\mkspecs\win32-msvc2010 -o Makefile IM_QXmpp.pro
d:\Qt\4.8.6\mkspecs\qconfig.pri:
d:\Qt\4.8.6\mkspecs\modules\qt_webkit_version.pri:
d:\Qt\4.8.6\mkspecs\features\qt_functions.prf:
d:\Qt\4.8.6\mkspecs\features\qt_config.prf:
d:\Qt\4.8.6\mkspecs\features\exclusive_builds.prf:
d:\Qt\4.8.6\mkspecs\features\default_pre.prf:
d:\Qt\4.8.6\mkspecs\features\win32\default_pre.prf:
d:\Qt\4.8.6\mkspecs\features\debug.prf:
d:\Qt\4.8.6\mkspecs\features\debug_and_release.prf:
d:\Qt\4.8.6\mkspecs\features\default_post.prf:
d:\Qt\4.8.6\mkspecs\features\win32\default_post.prf:
d:\Qt\4.8.6\mkspecs\features\win32\rtti.prf:
d:\Qt\4.8.6\mkspecs\features\win32\exceptions.prf:
d:\Qt\4.8.6\mkspecs\features\win32\stl.prf:
d:\Qt\4.8.6\mkspecs\features\shared.prf:
d:\Qt\4.8.6\mkspecs\features\win32\embed_manifest_exe.prf:
d:\Qt\4.8.6\mkspecs\features\win32\embed_manifest_dll.prf:
d:\Qt\4.8.6\mkspecs\features\warn_on.prf:
d:\Qt\4.8.6\mkspecs\features\qt.prf:
d:\Qt\4.8.6\mkspecs\features\win32\thread.prf:
d:\Qt\4.8.6\mkspecs\features\moc.prf:
d:\Qt\4.8.6\mkspecs\features\win32\windows.prf:
d:\Qt\4.8.6\mkspecs\features\resources.prf:
d:\Qt\4.8.6\mkspecs\features\uic.prf:
d:\Qt\4.8.6\mkspecs\features\yacc.prf:
d:\Qt\4.8.6\mkspecs\features\lex.prf:
d:\Qt\4.8.6\mkspecs\features\include_source_dir.prf:
d:\Qt\4.8.6\lib\qtmaind.prl:
qmake: qmake_all FORCE
	@$(QMAKE) -spec d:\Qt\4.8.6\mkspecs\win32-msvc2010 -o Makefile IM_QXmpp.pro

qmake_all: FORCE

make_default: debug-make_default release-make_default FORCE
make_first: debug-make_first release-make_first FORCE
all: debug-all release-all FORCE
clean: debug-clean release-clean FORCE
	-$(DEL_FILE) ".\IM_QXmpp.intermediate.manifest"
	-$(DEL_FILE) IM_QXmpp.exp
	-$(DEL_FILE) IM_QXmpp.ilk
	-$(DEL_FILE) vc*.pdb
	-$(DEL_FILE) vc*.idb
distclean: debug-distclean release-distclean FORCE
	-$(DEL_FILE) Makefile
	-$(DEL_FILE) IM_QXmpp.pdb

check: first

debug-mocclean: $(MAKEFILE).Debug
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug mocclean
release-mocclean: $(MAKEFILE).Release
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release mocclean
mocclean: debug-mocclean release-mocclean

debug-mocables: $(MAKEFILE).Debug
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Debug mocables
release-mocables: $(MAKEFILE).Release
	@set MAKEFLAGS=$(MAKEFLAGS)
	$(MAKE) -f $(MAKEFILE).Release mocables
mocables: debug-mocables release-mocables
FORCE:

$(MAKEFILE).Debug: Makefile
$(MAKEFILE).Release: Makefile


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Store;
using Windows.Storage;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace SDKTemplate
{
    /// <summary>
    /// A page for third scenario.
    /// </summary>
    public sealed partial class Scenario3_ExpiringProduct : Page
    {
        // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
        // as NotifyUser()
        MainPage rootPage = MainPage.Current;

        public Scenario3_ExpiringProduct()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            CurrentAppSimulator.LicenseInformation.LicenseChanged += ExpiringProductRefreshScenario;
            await MainPage.ConfigureSimulatorAsync("expiring-product.xml");
        }

        /// <summary>
        /// Invoked when this page is about to unload
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            CurrentAppSimulator.LicenseInformation.LicenseChanged -= ExpiringProductRefreshScenario;
            base.OnNavigatingFrom(e);
        }

        private void ExpiringProductRefreshScenario()
        {
            var task = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;
                if (licenseInformation.IsActive)
                {
                    if (licenseInformation.IsTrial)
                    {
                        rootPage.NotifyUser("You don't have a full license to this app.", NotifyType.ErrorMessage);
                    }
                    else
                    {
                        var productLicense1 = licenseInformation.ProductLicenses["product1"];
                        if (productLicense1.IsActive)
                        {
                            var longdateTemplate = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longdate");
                            Product1Message.Text = "Product 1 expires on " + longdateTemplate.Format(productLicense1.ExpirationDate) + ". Days remaining: " + (productLicense1.ExpirationDate - DateTime.Now).Days;
                        }
                        else
                        {
                            rootPage.NotifyUser("Product 1 is not available.", NotifyType.ErrorMessage);
                        }
                    }
                }
                else
                {
                    rootPage.NotifyUser("You don't have active license.", NotifyType.ErrorMessage);
                }
            });
        }
    }
}


text:
using System;
using Splat;

namespace AnotarSplatSample
{
    public class Logger : ILogger
    {
        public void Write(string message, LogLevel logLevel)
        {
            LogCaptureBuilder.LastMessage = message;
        }

        public void Write(Exception exception, string message, LogLevel logLevel)
        {
            LogCaptureBuilder.LastMessage = message;
        }

        public void Write(string message, Type type, LogLevel logLevel)
        {
            LogCaptureBuilder.LastMessage = message;
        }

        public void Write(Exception exception, string message, Type type, LogLevel logLevel)
        {
            LogCaptureBuilder.LastMessage = message;
        }

        public LogLevel Level { get; set; }
    }
}


text:
module ActiveGit
  class SynchronizationError < StandardError

    def initialize(models)
      @models = models
    end

    def message
      messages = []
      @models.each do |model|
        model.errors.full_messages.each do |msg|
          attributes = {}
          model.attributes.each do |name, value|
            attributes[model.class.human_attribute_name(name)] = value
          end

          attributes = model.attributes.inject({}) do |memo, item|
            memo[model.class.human_attribute_name(item[0])] = item[1]
            memo
          end

          messages << "#{model.class.model_name.human} - #{msg}\n#{attributes}"
        end
      end
      messages.join("\n")
    end

    def to_s
      "#{self.class.name} (#{message}):\n#{backtrace.join("\n")}"
    end

  end
end