text:
package kafka.api

import java.lang.{Integer, IllegalArgumentException}

import org.apache.kafka.clients.producer._
import org.scalatest.junit.JUnit3Suite
import org.junit.Test
import org.junit.Assert._

import kafka.server.KafkaConfig
import kafka.utils.{TestZKUtils, TestUtils}
import kafka.consumer.SimpleConsumer
import kafka.message.Message
import kafka.integration.KafkaServerTestHarness
import org.apache.kafka.common.errors.SerializationException
import java.util.Properties
import org.apache.kafka.common.config.ConfigException
import org.apache.kafka.common.serialization.ByteArraySerializer

class ProducerSendTest extends JUnit3Suite with KafkaServerTestHarness {
  val numServers = 2

  val overridingProps = new Properties()
  overridingProps.put(KafkaConfig.ZkConnectProp, TestZKUtils.zookeeperConnect)
  overridingProps.put(KafkaConfig.NumPartitionsProp, 4.toString)

  val configs =
    for (props <- TestUtils.createBrokerConfigs(numServers, false))
    yield KafkaConfig.fromProps(props, overridingProps)

  private var consumer1: SimpleConsumer = null
  private var consumer2: SimpleConsumer = null

  private val topic = "topic"
  private val numRecords = 100

  override def setUp() {
    super.setUp()

    // TODO: we need to migrate to new consumers when 0.9 is final
    consumer1 = new SimpleConsumer("localhost", configs(0).port, 100, 1024*1024, "")
    consumer2 = new SimpleConsumer("localhost", configs(1).port, 100, 1024*1024, "")
  }

  override def tearDown() {
    consumer1.close()
    consumer2.close()

    super.tearDown()
  }

  /**
   * testSendOffset checks the basic send API behavior
   *
   * 1. Send with null key/value/partition-id should be accepted; send with null topic should be rejected.
   * 2. Last message of the non-blocking send should return the correct offset metadata
   */
  @Test
  def testSendOffset() {
    var producer = TestUtils.createNewProducer(brokerList)
    val partition = new Integer(0)

    object callback extends Callback {
      var offset = 0L
      def onCompletion(metadata: RecordMetadata, exception: Exception) {
        if (exception == null) {
          assertEquals(offset, metadata.offset())
          assertEquals(topic, metadata.topic())
          assertEquals(partition, metadata.partition())
          offset += 1
        } else {
          fail("Send callback returns the following exception", exception)
        }
      }
    }

    try {
      // create topic
      TestUtils.createTopic(zkClient, topic, 1, 2, servers, acl=null)

      // send a normal record
      val record0 = new ProducerRecord[Array[Byte],Array[Byte]](topic, partition, "key".getBytes, "value".getBytes)
      assertEquals("Should have offset 0", 0L, producer.send(record0, callback).get.offset)

      // send a record with null value should be ok
      val record1 = new ProducerRecord[Array[Byte],Array[Byte]](topic, partition, "key".getBytes, null)
      assertEquals("Should have offset 1", 1L, producer.send(record1, callback).get.offset)

      // send a record with null key should be ok
      val record2 = new ProducerRecord[Array[Byte],Array[Byte]](topic, partition, null, "value".getBytes)
      assertEquals("Should have offset 2", 2L, producer.send(record2, callback).get.offset)

      // send a record with null part id should be ok
      val record3 = new ProducerRecord[Array[Byte],Array[Byte]](topic, null, "key".getBytes, "value".getBytes)
      assertEquals("Should have offset 3", 3L, producer.send(record3, callback).get.offset)

      // send a record with null topic should fail
      try {
        val record4 = new ProducerRecord[Array[Byte],Array[Byte]](null, partition, "key".getBytes, "value".getBytes)
        producer.send(record4, callback)
        fail("Should not allow sending a record without topic")
      } catch {
        case iae: IllegalArgumentException => // this is ok
        case e: Throwable => fail("Only expecting IllegalArgumentException", e)
      }

      // non-blocking send a list of records
      for (i <- 1 to numRecords)
        producer.send(record0, callback)

      // check that all messages have been acked via offset
      assertEquals("Should have offset " + (numRecords + 4), numRecords + 4L, producer.send(record0, callback).get.offset)

    } finally {
      if (producer != null) {
        producer.close()
        producer = null
      }
    }
  }

  @Test
  def testSerializer() {
    // send a record with a wrong type should receive a serialization exception
    try {
      val producer = createNewProducerWithWrongSerializer(brokerList)
      val record5 = new ProducerRecord[Array[Byte],Array[Byte]](topic, new Integer(0), "key".getBytes, "value".getBytes)
      producer.send(record5)
      fail("Should have gotten a SerializationException")
    } catch {
      case se: SerializationException => // this is ok
    }

    try {
      createNewProducerWithNoSerializer(brokerList)
      fail("Instantiating a producer without specifying a serializer should cause a ConfigException")
    } catch {
      case ce : ConfigException => // this is ok
    }

    // create a producer with explicit serializers should succeed
    createNewProducerWithExplicitSerializer(brokerList)
  }

  private def createNewProducerWithWrongSerializer(brokerList: String) : KafkaProducer[Array[Byte],Array[Byte]] = {
    import org.apache.kafka.clients.producer.ProducerConfig

    val producerProps = new Properties()
    producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList)
    producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    return new KafkaProducer[Array[Byte],Array[Byte]](producerProps)
  }

  private def createNewProducerWithNoSerializer(brokerList: String) : KafkaProducer[Array[Byte],Array[Byte]] = {
    import org.apache.kafka.clients.producer.ProducerConfig

    val producerProps = new Properties()
    producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList)
    return new KafkaProducer[Array[Byte],Array[Byte]](producerProps)
  }

  private def createNewProducerWithExplicitSerializer(brokerList: String) : KafkaProducer[Array[Byte],Array[Byte]] = {
    import org.apache.kafka.clients.producer.ProducerConfig

    val producerProps = new Properties()
    producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList)
    return new KafkaProducer[Array[Byte],Array[Byte]](producerProps, new ByteArraySerializer, new ByteArraySerializer)
  }

  /**
   * testClose checks the closing behavior
   *
   * After close() returns, all messages should be sent with correct returned offset metadata
   */
  @Test
  def testClose() {
    var producer = TestUtils.createNewProducer(brokerList)

    try {
      // create topic
      TestUtils.createTopic(zkClient, topic, 1, 2, servers, acl=null)

      // non-blocking send a list of records
      val record0 = new ProducerRecord[Array[Byte],Array[Byte]](topic, null, "key".getBytes, "value".getBytes)
      for (i <- 1 to numRecords)
        producer.send(record0)
      val response0 = producer.send(record0)

      // close the producer
      producer.close()
      producer = null

      // check that all messages have been acked via offset,
      // this also checks that messages with same key go to the same partition
      assertTrue("The last message should be acked before producer is shutdown", response0.isDone)
      assertEquals("Should have offset " + numRecords, numRecords.toLong, response0.get.offset)

    } finally {
      if (producer != null) {
        producer.close()
        producer = null
      }
    }
  }

  /**
   * testSendToPartition checks the partitioning behavior
   *
   * The specified partition-id should be respected
   */
  @Test
  def testSendToPartition() {
    var producer = TestUtils.createNewProducer(brokerList)

    try {
      // create topic
      val leaders = TestUtils.createTopic(zkClient, topic, 2, 2, servers, acl=null)
      val partition = 1

      // make sure leaders exist
      val leader1 = leaders(partition)
      assertTrue("Leader for topic \"topic\" partition 1 should exist", leader1.isDefined)

      val responses =
        for (i <- 1 to numRecords)
          yield producer.send(new ProducerRecord[Array[Byte],Array[Byte]](topic, partition, null, ("value" + i).getBytes))
      val futures = responses.toList
      futures.map(_.get)
      for (future <- futures)
        assertTrue("Request should have completed", future.isDone)

      // make sure all of them end up in the same partition with increasing offset values
      for ((future, offset) <- futures zip (0 until numRecords)) {
        assertEquals(offset.toLong, future.get.offset)
        assertEquals(topic, future.get.topic)
        assertEquals(partition, future.get.partition)
      }

      // make sure the fetched messages also respect the partitioning and ordering
      val fetchResponse1 = if(leader1.get == configs(0).brokerId) {
        consumer1.fetch(new FetchRequestBuilder().addFetch(topic, partition, 0, Int.MaxValue).build())
      } else {
        consumer2.fetch(new FetchRequestBuilder().addFetch(topic, partition, 0, Int.MaxValue).build())
      }
      val messageSet1 = fetchResponse1.messageSet(topic, partition).iterator.toBuffer
      assertEquals("Should have fetched " + numRecords + " messages", numRecords, messageSet1.size)

      // TODO: also check topic and partition after they are added in the return messageSet
      for (i <- 0 to numRecords - 1) {
        assertEquals(new Message(bytes = ("value" + (i + 1)).getBytes), messageSet1(i).message)
        assertEquals(i.toLong, messageSet1(i).offset)
      }
    } finally {
      if (producer != null) {
        producer.close()
        producer = null
      }
    }
  }

  /**
   * testAutoCreateTopic
   *
   * The topic should be created upon sending the first message
   */
  @Test
  def testAutoCreateTopic() {
    var producer = TestUtils.createNewProducer(brokerList, retries = 5)

    try {
      // Send a message to auto-create the topic
      val record = new ProducerRecord[Array[Byte],Array[Byte]](topic, null, "key".getBytes, "value".getBytes)
      assertEquals("Should have offset 0", 0L, producer.send(record).get.offset)

      // double check that the topic is created with leader elected
      TestUtils.waitUntilLeaderIsElectedOrChanged(zkClient, topic, 0)

    } finally {
      if (producer != null) {
        producer.close()
        producer = null
      }
    }
  }

  /**
   * Test that flush immediately sends all accumulated requests.
   */
  @Test
  def testFlush() {
    var producer = TestUtils.createNewProducer(brokerList, lingerMs = Long.MaxValue)
    try {
      TestUtils.createTopic(zkClient, topic, 2, 2, servers, acl=null)
      val record = new ProducerRecord[Array[Byte], Array[Byte]](topic, "value".getBytes)
      for(i <- 0 until 50) {
        val responses = (0 until numRecords) map (i => producer.send(record))
        assertTrue("No request is complete.", responses.forall(!_.isDone()))
        producer.flush()
        assertTrue("All requests are complete.", responses.forall(_.isDone()))
      }
    } finally {
      if (producer != null)
        producer.close()
    }
  }

}


text:
package com.waincent.fleet.core;

import android.app.Application;
import android.support.compat.BuildConfig;

import com.squareup.leakcanary.LeakCanary;
import com.waincent.fleet.presentation.dagger.components.ApplicationComponent;
import com.waincent.fleet.presentation.dagger.components.DaggerApplicationComponent;
import com.waincent.fleet.presentation.dagger.modules.ApplicationModule;

/**
 * Android Main Application
 */
public class AndroidApplication extends Application {

    private ApplicationComponent applicationComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        this.initializeInjector();
        this.initializeLeakDetection();
    }

    private void initializeInjector() {
        this.applicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .build();
    }

    public ApplicationComponent getApplicationComponent() {
        return this.applicationComponent;
    }

    private void initializeLeakDetection() {
        if (BuildConfig.DEBUG) {
            LeakCanary.install(this);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
+++
type = "index"
title = "Settle"
description = ""
date = "2016-11-04T17:28:19-07:00"
+++
# Settle

*Decentralized trust graph for value exchange without a blockchain.*

While cryptocurrencies are maintained by distributed ledgers with no central
authority, their trust graph is still fully centralized: everyone has to trust
the currency that powers the blockchain (**BTC**, **ETH**, **XLM**...).

Settle's goal is to explore a new financial trust primitive, and doing so,
construct a decentralized trust graph enabling (totally) free exchange of value
without relying on a blockchain, making it particularly adapted to
machine-to-machine transactions.

The Settle transaction protocol allows users to safely transfer value along
pre-expressed trust paths (see [Mint documentation](/documentation)). Similarly
to email, users register on a "mint": a server of their choice (possibly their
own) that manage the assets they issue as well as the trust they express
towards assets in the network.

Settle distributes a command line utility, `settle`, to interact with mints. It
lets you register on a publicly available mint (or login on a mint of your
choice), create assets, express trust between your assets and others', and
transact using these trust paths.

Settle also maintains a publicly available mint **m.settle.network** on which
you can register freely.

Additional resources:

- [Settle introductory blog post](posts/intro)
- [Mint documentation](documentation)
- [Source code](https://github.com/spolu/settle)

## Installation

Install `settle` locally (under `~/.settle`):
```
curl -L https://settle.network/install | sh && export PATH=$PATH:~/.settle
```
## Getting started

Read the command-line help:
```
settle help
```

Register on a mint:
```
settle register
```

Mint (activate) your first asset (**USD** with a scale of 2, i.e expressed in cents):
```
settle mint USD.2
```
(Assets are expressed as `{CODE}.{SCALE}` where the code is an alphanumeric
string of your choice and the scale, or decimal length, is an integer
representing the factor by which the asset native amount is scaled down when
represented as a signed integer).

Trust someone for **$10**:
```
settle trust kurt@princetown.edu USD.2 1000
```

Trust at a specific price:
```
settle trust supercharger@tesla.com KWH.2 10000 with USD.2 at 20/100
```
(Prices are expressed as `base_asset/quote_asset` where the base asset is your
own asset (here **you@yourdomain.com[USD.2]**) and the quote asset is the asset
you trust (here **supercharger@tesla.com[KWH.2]**).

Pay someone **1€** (assuming a trust path exists):
```
settle pay alan@npl.co EUR.2 100
```


text:
package org.lmdbjava;

import static java.util.Objects.requireNonNull;
import jnr.ffi.Pointer;
import jnr.ffi.byref.NativeLongByReference;
import static org.lmdbjava.Dbi.KeyExistsException.MDB_KEYEXIST;
import static org.lmdbjava.Dbi.KeyNotFoundException.MDB_NOTFOUND;
import static org.lmdbjava.Env.SHOULD_CHECK;
import static org.lmdbjava.Library.LIB;
import static org.lmdbjava.MaskedFlag.isSet;
import static org.lmdbjava.MaskedFlag.mask;
import static org.lmdbjava.PutFlags.MDB_NODUPDATA;
import static org.lmdbjava.PutFlags.MDB_NOOVERWRITE;
import static org.lmdbjava.PutFlags.MDB_RESERVE;
import static org.lmdbjava.ResultCodeMapper.checkRc;
import static org.lmdbjava.SeekOp.MDB_FIRST;
import static org.lmdbjava.SeekOp.MDB_LAST;
import static org.lmdbjava.SeekOp.MDB_NEXT;
import static org.lmdbjava.SeekOp.MDB_PREV;

/**
 * A cursor handle.
 *
 * @param <T> buffer type
 */
public final class Cursor<T> implements AutoCloseable {

  private boolean closed;
  private final KeyVal<T> kv;
  private final Pointer ptrCursor;
  private Txn<T> txn;

  Cursor(final Pointer ptr, final Txn<T> txn) {
    requireNonNull(ptr);
    requireNonNull(txn);
    this.ptrCursor = ptr;
    this.txn = txn;
    this.kv = txn.newKeyVal();
  }

  /**
   * Close a cursor handle.
   *
   *

   * The cursor handle will be freed and must not be used again after this call.
   * Its transaction must still be live if it is a write-transaction.
   */
  @Override
  public void close() {
    if (closed) {
      return;
    }
    if (SHOULD_CHECK && !txn.isReadOnly()) {
      txn.checkReady();
    }
    LIB.mdb_cursor_close(ptrCursor);
    kv.close();
    closed = true;
  }

  /**
   * Return count of duplicates for current key.
   *
   *

   * This call is only valid on databases that support sorted duplicate data
   * items {@link DbiFlags#MDB_DUPSORT}.
   *
   * @return count of duplicates for current key
   */
  public long count() {
    if (SHOULD_CHECK) {
      checkNotClosed();
      txn.checkReady();
    }
    final NativeLongByReference longByReference = new NativeLongByReference();
    checkRc(LIB.mdb_cursor_count(ptrCursor, longByReference));
    return longByReference.longValue();
  }

  /**
   * Delete current key/data pair.
   *
   *

   * This function deletes the key/data pair to which the cursor refers.
   *
   * @param f flags (either null or {@link PutFlags#MDB_NODUPDATA}
   */
  public void delete(final PutFlags... f) {
    if (SHOULD_CHECK) {
      checkNotClosed();
      txn.checkReady();
      txn.checkWritesAllowed();
    }
    final int flags = mask(f);
    checkRc(LIB.mdb_cursor_del(ptrCursor, flags));
  }

  /**
   * Position at first key/data item.
   *
   * @return false if requested position not found
   */
  public boolean first() {
    return seek(MDB_FIRST);
  }

  /**
   * Reposition the key/value buffers based on the passed key and operation.
   *
   * @param key to search for
   * @param op  options for this operation
   * @return false if key not found
   */
  public boolean get(final T key, final GetOp op) {
    if (SHOULD_CHECK) {
      requireNonNull(key);
      requireNonNull(op);
      checkNotClosed();
      txn.checkReady();
    }
    kv.keyIn(key);

    final int rc = LIB.mdb_cursor_get(ptrCursor, kv.pointerKey(), kv
                                      .pointerVal(), op.getCode());

    if (rc == MDB_NOTFOUND) {
      return false;
    }

    checkRc(rc);
    kv.keyOut();
    kv.valOut();
    return true;
  }

  /**
   * @return the key that the cursor is located at.
   */
  public T key() {
    return kv.key();
  }

  /**
   * Position at last key/data item.
   *
   * @return false if requested position not found
   */
  public boolean last() {
    return seek(MDB_LAST);
  }

  /**
   * Position at next data item.
   *
   * @return false if requested position not found
   */
  public boolean next() {
    return seek(MDB_NEXT);
  }

  /**
   * Position at previous data item.
   *
   * @return false if requested position not found
   */
  public boolean prev() {
    return seek(MDB_PREV);
  }

  /**
   * Store by cursor.
   *
   *

   * This function stores key/data pairs into the database.
   *
   * @param key key to store
   * @param val data to store
   * @param op  options for this operation
   * @return true if the value was put, false if MDB_NOOVERWRITE or
   *         MDB_NODUPDATA were set and the key/value existed already.
   */
  public boolean put(final T key, final T val, final PutFlags... op) {
    if (SHOULD_CHECK) {
      requireNonNull(key);
      requireNonNull(val);
      checkNotClosed();
      txn.checkReady();
      txn.checkWritesAllowed();
    }
    kv.keyIn(key);
    kv.valIn(val);
    final int mask = mask(op);
    final int rc = LIB.mdb_cursor_put(ptrCursor, kv.pointerKey(),
                                      kv.pointerVal(), mask);
    if (rc == MDB_KEYEXIST) {
      if (isSet(mask, MDB_NOOVERWRITE)) {
        kv.valOut(); // marked as in,out in LMDB C docs
      } else if (!isSet(mask, MDB_NODUPDATA)) {
        checkRc(rc);
      }
      return false;
    }
    checkRc(rc);
    return true;
  }

  /**
   * Renew a cursor handle.
   *
   *

   * A cursor is associated with a specific transaction and database. Cursors
   * that are only used in read-only transactions may be re-used, to avoid
   * unnecessary malloc/free overhead. The cursor may be associated with a new
   * read-only transaction, and referencing the same database handle as it was
   * created with. This may be done whether the previous transaction is live or
   * dead.
   *
   * @param newTxn transaction handle
   */
  public void renew(final Txn<T> newTxn) {
    if (SHOULD_CHECK) {
      requireNonNull(newTxn);
      checkNotClosed();
      this.txn.checkReadOnly(); // existing
      newTxn.checkReadOnly();
      newTxn.checkReady();
    }
    checkRc(LIB.mdb_cursor_renew(newTxn.pointer(), ptrCursor));
    this.txn = newTxn;
  }

  /**
   * Reserve space for data of the given size, but don't copy the given val.
   * Instead, return a pointer to the reserved space, which the caller can fill
   * in later - before the next update operation or the transaction ends. This
   * saves an extra memcpy if the data is being generated later. LMDB does
   * nothing else with this memory, the caller is expected to modify all of the
   * space requested.
   *
   *

   * This flag must not be specified if the database was opened with MDB_DUPSORT
   *
   * @param key  key to store in the database (not null)
   * @param size size of the value to be stored in the database (not null)
   * @param op   options for this operation
   * @return a buffer that can be used to modify the value
   */
  public T reserve(final T key, final int size, final PutFlags... op) {
    if (SHOULD_CHECK) {
      requireNonNull(key);
      checkNotClosed();
      txn.checkReady();
      txn.checkWritesAllowed();
    }
    kv.keyIn(key);
    kv.valIn(size);
    final int flags = mask(op) | MDB_RESERVE.getMask();
    checkRc(LIB.mdb_cursor_put(ptrCursor, kv.pointerKey(), kv.pointerVal(),
                               flags));
    kv.valOut();
    return val();
  }

  /**
   * Reposition the key/value buffers based on the passed operation.
   *
   * @param op options for this operation
   * @return false if requested position not found
   */
  public boolean seek(final SeekOp op) {
    if (SHOULD_CHECK) {
      requireNonNull(op);
      checkNotClosed();
      txn.checkReady();
    }

    final int rc = LIB.mdb_cursor_get(ptrCursor, kv.pointerKey(), kv
                                      .pointerVal(), op.getCode());

    if (rc == MDB_NOTFOUND) {
      return false;
    }

    checkRc(rc);
    kv.keyOut();
    kv.valOut();
    return true;
  }

  /**
   * @return the value that the cursor is located at.
   */
  public T val() {
    return kv.val();
  }

  private void checkNotClosed() throws ClosedException {
    if (closed) {
      throw new ClosedException();
    }
  }

  /**
   * Cursor has already been closed.
   */
  public static final class ClosedException extends LmdbException {

    private static final long serialVersionUID = 1L;

    /**
     * Creates a new instance.
     */
    public ClosedException() {
      super("Cursor has already been closed");
    }
  }

  /**
   * Cursor stack too deep - internal error.
   */
  public static final class FullException extends LmdbNativeException {

    static final int MDB_CURSOR_FULL = -30_787;
    private static final long serialVersionUID = 1L;

    FullException() {
      super(MDB_CURSOR_FULL, "Cursor stack too deep - internal error");
    }
  }

}


text:
// Copyright 2005-2019 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.

#ifndef MUMBLE_MUMBLE_WASAPINOTIFICATIONCLIENT_H_
#define MUMBLE_MUMBLE_WASAPINOTIFICATIONCLIENT_H_

#include <QtCore/QObject>
#include <QtCore/QMutex>
#include <mmdeviceapi.h>

/**
 * @brief Singleton for acting on WASAPINotification events for given devices.
 */
class WASAPINotificationClient : public QObject, public IMMNotificationClient {
	Q_OBJECT
public:
	/* IMMNotificationClient interface */
	HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDevice);
	HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key);
	HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR pwstrDeviceId);
	HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR pwstrDeviceId);
	HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState);
	HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface);
	ULONG STDMETHODCALLTYPE AddRef();
	ULONG STDMETHODCALLTYPE Release();

	/* Enlist/Unlist functionality */
	void enlistDefaultDeviceAsUsed(LPCWSTR pwstrDefaultDevice);

	void enlistDeviceAsUsed(LPCWSTR pwstrDevice);
	void enlistDeviceAsUsed(const QString& device);

	void unlistDevice(LPCWSTR pwstrDevice);

	void clearUsedDefaultDeviceList();
	void clearUsedDeviceLists();

	/**
	 * @return Singleton instance reference.
	 */
	static WASAPINotificationClient& get();

private:
	WASAPINotificationClient();
	~WASAPINotificationClient() Q_DECL_OVERRIDE;

	WASAPINotificationClient(const WASAPINotificationClient&);
	WASAPINotificationClient& operator=(const WASAPINotificationClient&);

	static WASAPINotificationClient& doGet();
	static void doGetOnce();

	void restartAudio();

	/* _fu = Non locking versions */
	void _clearUsedDeviceLists();
	void _enlistDeviceAsUsed(const QString& device);

	QStringList usedDefaultDevices;
	QStringList usedDevices;
	IMMDeviceEnumerator *pEnumerator;
	LONG _cRef;
	QMutex listsMutex;

signals:
	void doResetAudio();
};

#endif // WASAPINOTIFICATIONCLIENT_H_


text: Copyright ©2014 by Matt Van Der Westhuizen


text:
import org.antlr.v4.runtime.*;

abstract class Python3LexerBase extends Lexer {
    protected Python3LexerBase(CharStream input) {
        super(input);
    }
    // A queue where extra tokens are pushed on (see the NEWLINE lexer rule).
    private java.util.LinkedList<Token> tokens = new java.util.LinkedList<>();
    // The stack that keeps track of the indentation level.
    private java.util.Stack<Integer> indents = new java.util.Stack<>();
    // The amount of opened braces, brackets and parenthesis.
    private int opened = 0;
    // The most recently produced token.
    private Token lastToken = null;
    @Override
    public void emit(Token t) {
        super.setToken(t);
        tokens.offer(t);
    }

    @Override
    public Token nextToken() {
        // Check if the end-of-file is ahead and there are still some DEDENTS expected.
        if (_input.LA(1) == EOF && !this.indents.isEmpty()) {
            // Remove any trailing EOF tokens from our buffer.
            for (int i = tokens.size() - 1; i >= 0; i--) {
                if (tokens.get(i).getType() == EOF) {
                    tokens.remove(i);
                }
            }

            // First emit an extra line break that serves as the end of the statement.
            this.emit(commonToken(Python3Lexer.NEWLINE, "\n"));

            // Now emit as much DEDENT tokens as needed.
            while (!indents.isEmpty()) {
                this.emit(createDedent());
                indents.pop();
            }

            // Put the EOF back on the token stream.
            this.emit(commonToken(Python3Lexer.EOF, "<EOF>"));
        }

        Token next = super.nextToken();

        if (next.getChannel() == Token.DEFAULT_CHANNEL) {
            // Keep track of the last token on the default channel.
            this.lastToken = next;
        }

        return tokens.isEmpty() ? next : tokens.poll();
    }

    private Token createDedent() {
        CommonToken dedent = commonToken(Python3Lexer.DEDENT, "");
        dedent.setLine(this.lastToken.getLine());
        return dedent;
    }

    private CommonToken commonToken(int type, String text) {
        int stop = this.getCharIndex() - 1;
        int start = text.isEmpty() ? stop : stop - text.length() + 1;
        return new CommonToken(this._tokenFactorySourcePair, type, DEFAULT_TOKEN_CHANNEL, start, stop);
    }

    // Calculates the indentation of the provided spaces, taking the
    // following rules into account:
    //
    // "Tabs are replaced (from left to right) by one to eight spaces
    //  such that the total number of characters up to and including
    //  the replacement is a multiple of eight [...]"
    //
    //  -- https://docs.python.org/3.1/reference/lexical_analysis.html#indentation
    static int getIndentationCount(String spaces) {
        int count = 0;
        for (char ch : spaces.toCharArray()) {
            switch (ch) {
                case '\t':
                    count += 8 - (count % 8);
                    break;
                default:
                    // A normal space char.
                    count++;
            }
        }

        return count;
    }

    boolean atStartOfInput() {
        return super.getCharPositionInLine() == 0 && super.getLine() == 1;
    }

    void openBrace(){
        this.opened++;
    }

    void closeBrace(){
        this.opened--;
    }

    void onNewLine(){
        String newLine = getText().replaceAll("[^\r\n\f]+", "");
        String spaces = getText().replaceAll("[\r\n\f]+", "");

        // Strip newlines inside open clauses except if we are near EOF. We keep NEWLINEs near EOF to
        // satisfy the final newline needed by the single_put rule used by the REPL.
        int next = _input.LA(1);
        int nextnext = _input.LA(2);
        if (opened > 0 || (nextnext != -1 && (next == '\r' || next == '\n' || next == '\f' || next == '#'))) {
            // If we're inside a list or on a blank line, ignore all indents,
            // dedents and line breaks.
            skip();
        }
        else {
            emit(commonToken(Python3Lexer.NEWLINE, newLine));
            int indent = getIndentationCount(spaces);
            int previous = indents.isEmpty() ? 0 : indents.peek();
            if (indent == previous) {
                // skip indents of the same size as the present indent-size
                skip();
            }
            else if (indent > previous) {
                indents.push(indent);
                emit(commonToken(Python3Lexer.INDENT, spaces));
            }
            else {
                // Possibly emit more than 1 DEDENT token.
                while(!indents.isEmpty() && indents.peek() > indent) {
                    this.emit(createDedent());
                    indents.pop();
                }
            }
        }
    }
}


text:
function dataread_split_2(data){
	// Fonction de lecture de deux données contenues dans une export_data_chaine de 8 chiffres ; bbbbaaaa
	// Les valeures réelles ont été encapsulé dans DCS export avec +5000
	// pour gestion zero et négatif, on enlève donc 5000
	//
	// Appel de la fonction sous la forme :
	// Valeur = dataread_split_2(data)
	// Nombre a = Valeur[0]
	// Nombre b = Valeur[1]

	var a = (data % 10000) - 5000
	var b = (Math.floor (data / 10000)) - 5000

	//console.log("a= ",a)
	//console.log("b= ",b)

	return [a,b];

}

function dataread_posit(data,position){
	// Fonction de lecture d'une valeur 0-9, contenue dans une export_data_chaine de 8 chiffres
	// Les valeures réelles ont été encapsulé dans DCS export avec +5
	// pour gestion zero et négatif, on enlève donc 5
	// Appel de la fonction sous la forme :
	// Chiffre = dataread_posit(data,x)  où x est le xieme chiffre en partant de la droite (1 pour unité, 2 pour dizaine ...)

	var c = Math.floor (data % Math.pow(10,position) / Math.pow(10,position-1)) - 5

	//console.log("c= ",c)

	return c;

}


text:
<?php

/**
 * @package     Propel
 * @subpackage  Import
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author      Paul Cooper <pgc@ucecom.com>
 * @author      Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
 * @version     $Revision: 7490 $
 * @link        www.propel-project.org
 * @since       1.0
 */
class Propel_Import_Pgsql extends Propel_Import
{

    protected $sql = array(
                        'listDatabases' => 'SELECT datname FROM pg_database',
                        'listFunctions' => "SELECT
                                                proname
                                            FROM
                                                pg_proc pr,
                                                pg_type tp
                                            WHERE
                                                tp.oid = pr.prorettype
                                                AND pr.proisagg = FALSE
                                                AND tp.typname <> 'trigger'
                                                AND pr.pronamespace IN
                                                    (SELECT oid FROM pg_namespace
                                                     WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema'",
                        'listSequences' => "SELECT
                                                regexp_replace(relname, '_seq$', '')
                                            FROM
                                                pg_class
                                            WHERE relkind = 'S' AND relnamespace IN
                                                (SELECT oid FROM pg_namespace
                                                 WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')",
                        'listTables'    => "SELECT
                                                c.relname AS table_name
                                            FROM pg_class c, pg_user u
                                            WHERE c.relowner = u.usesysid
                                                AND c.relkind = 'r'
                                                AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname)
                                                AND c.relname !~ '^(pg_|sql_)'
                                            UNION
                                            SELECT c.relname AS table_name
                                            FROM pg_class c
                                            WHERE c.relkind = 'r'
                                                AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname)
                                                AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner)
                                                AND c.relname !~ '^pg_'",
                        'listViews'     => 'SELECT viewname FROM pg_views',
                        'listUsers'     => 'SELECT usename FROM pg_user',
                        'listTableConstraints' => "SELECT
                                                        relname
                                                   FROM
                                                        pg_class
                                                   WHERE oid IN (
                                                        SELECT indexrelid
                                                        FROM pg_index, pg_class
                                                        WHERE pg_class.relname = %s
                                                            AND pg_class.oid = pg_index.indrelid
                                                            AND (indisunique = 't' OR indisprimary = 't')
                                                        )",
                        'listTableIndexes'     => "SELECT
                                                        relname
                                                   FROM
                                                        pg_class
                                                   WHERE oid IN (
                                                        SELECT indexrelid
                                                        FROM pg_index, pg_class
                                                        WHERE pg_class.relname = %s
                                                            AND pg_class.oid=pg_index.indrelid
                                                            AND indisunique != 't'
                                                            AND indisprimary != 't'
                                                        )",
                        'listTableColumns'     => "SELECT
                                                        a.attnum,
                                                        a.attname AS field,
                                                        t.typname AS type,
                                                        format_type(a.atttypid, a.atttypmod) AS complete_type,
                                                        a.attnotnull AS isnotnull,
                                                        (SELECT 't'
                                                          FROM pg_index
                                                          WHERE c.oid = pg_index.indrelid
                                                          AND a.attnum = ANY (pg_index.indkey)
                                                          AND pg_index.indisprimary = 't'
                                                        ) AS pri,
                                                        (SELECT pg_attrdef.adsrc
                                                          FROM pg_attrdef
                                                          WHERE c.oid = pg_attrdef.adrelid
                                                          AND pg_attrdef.adnum=a.attnum
                                                        ) AS default
                                                  FROM pg_attribute a, pg_class c, pg_type t
                                                  WHERE c.relname = %s
                                                        AND a.attnum > 0
                                                        AND a.attrelid = c.oid
                                                        AND a.atttypid = t.oid
                                                  ORDER BY a.attnum",
                        'listTableRelations'   => "SELECT pg_catalog.pg_get_constraintdef(oid, true) as condef
                                                          FROM pg_catalog.pg_constraint r
                                                          WHERE r.conrelid =
                                                          (
                                                              SELECT c.oid
                                                              FROM pg_catalog.pg_class c
                                                              LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                                                              WHERE c.relname ~ ? AND pg_catalog.pg_table_is_visible(c.oid)
                                                          )
                                                          AND r.contype = 'f'"
                        );

    /**
     * lists all database triggers
     *
     * @param string|null $database
     * @return array
     */
    public function listTriggers($database = null)
    {

    }

    /**
     * lists table constraints
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableConstraints($table)
    {
        $table = $this->conn->quote($table);
        $query = sprintf($this->sql['listTableConstraints'], $table);

        return $this->conn->fetchColumn($query);
    }

    /**
     * lists table constraints
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableColumns($table)
    {
        $table = $this->conn->quote($table);
        $query = sprintf($this->sql['listTableColumns'], $table);
        $result = $this->conn->fetchAssoc($query);

        $columns     = array();
        foreach ($result as $key => $val) {
            $val = array_change_key_case($val, CASE_LOWER);

            if (strtolower($val['type']) === 'character varying') {
                // get length from varchar definition
                $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $val['complete_type']);
                $val['length'] = $length;
            }

            $decl = $this->conn->dataDict->getPortableDeclaration($val);

            $description = array(
                'name'      => $val['field'],
                'ntype'     => $val['type'],
                'type'      => $decl['type'][0],
                'alltypes'  => $decl['type'],
                'length'    => $decl['length'],
                'fixed'     => (bool) $decl['fixed'],
                'unsigned'  => (bool) $decl['unsigned'],
                'notnull'   => ($val['isnotnull'] == true),
                'default'   => $val['default'],
                'primary'   => ($val['pri'] == 't'),
            );

            $matches = array();

            if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $description['default'], $matches)) {
                $description['sequence'] = $this->conn->formatter->fixSequenceName($matches[1]);
                $description['default'] = null;
            } else if (preg_match("/^'(.*)'::character varying$/", $description['default'], $matches)) {
                $description['default'] = $matches[1];
            } else if ($description['type'] == 'boolean') {
                if ($description['default'] === 'true') {
                   $description['default'] = true;
                } else if ($description['default'] === 'false') {
                   $description['default'] = false;
                }
            }

            $columns[$val['field']] = $description;
        }

        return $columns;
    }

    /**
     * list all indexes in a table
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableIndexes($table)
    {
        $table = $this->conn->quote($table);
        $query = sprintf($this->sql['listTableIndexes'], $table);

        return $this->conn->fetchColumn($query);
    }

    /**
     * lists tables
     *
     * @param string|null $database
     * @return array
     */
    public function listTables($database = null)
    {
        return $this->conn->fetchColumn($this->sql['listTables']);
    }

    /**
     * lists table triggers
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableTriggers($table)
    {
        $query = 'SELECT trg.tgname AS trigger_name
                    FROM pg_trigger trg,
                         pg_class tbl
                   WHERE trg.tgrelid = tbl.oid';
        if ($table !== null) {
            $table = $this->conn->quote(strtoupper($table), 'string');
            $query .= " AND tbl.relname = $table";
        }
        return $this->conn->fetchColumn($query);
    }

    /**
     * list the views in the database that reference a given table
     *
     * @param string $table     database table name
     * @return array
     */
    public function listTableViews($table)
    {
        return $this->conn->fetchColumn($table);
    }

    public function listTableRelations($table)
    {
        $sql = $this->sql['listTableRelations'];
        $param = array('^(' . $table . ')$');

        $relations = array();

        $results = $this->conn->fetchAssoc($sql, $param);
        foreach ($results as $result) {
            preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $result['condef'], $values);
            if ((strpos($values[1], ',') === false) && (strpos($values[3], ',') === false)) {
                $tableName = trim($values[2], '"');
                $relations[] = array('table'   => $tableName,
                                     'local'   => $values[1],
                                     'foreign' => $values[3]);
            }
        }

        return $relations;
    }
}


text:
package org.apache.hyracks.storage.am.lsm.common.impls;

public enum LSMOperationType {
    SEARCH,
    MODIFICATION,
    FORCE_MODIFICATION,
    FLUSH,
    MERGE,
    REPLICATE
}


text:
<?php

/**
 * base class
 */
require_once 'PEAR/Command/Common.php';

/**
 * PEAR commands for registry manipulation
 *
 * @category   pear
 * @package    PEAR
 * @author     Stig Bakken <ssb@php.net>
 * @author     Greg Beaver <cellog@php.net>
 * @copyright  1997-2009 The Authors
 * @license    http://opensource.org/licenses/bsd-license.php New BSD License
 * @version    Release: 1.9.5
 * @link       http://pear.php.net/package/PEAR
 * @since      Class available since Release 0.1
 */
class PEAR_Command_Registry extends PEAR_Command_Common
{
    var $commands = array(
        'list' => array(
            'summary' => 'List Installed Packages In The Default Channel',
            'function' => 'doList',
            'shortcut' => 'l',
            'options' => array(
                'channel' => array(
                    'shortopt' => 'c',
                    'doc' => 'list installed packages from this channel',
                    'arg' => 'CHAN',
                    ),
                'allchannels' => array(
                    'shortopt' => 'a',
                    'doc' => 'list installed packages from all channels',
                    ),
                'channelinfo' => array(
                    'shortopt' => 'i',
                    'doc' => 'output fully channel-aware data, even on failure',
                    ),
                ),
            'doc' => '<package>
If invoked without parameters, this command lists the PEAR packages
installed in your php_dir ({config php_dir}).  With a parameter, it
lists the files in a package.
',
            ),
        'list-files' => array(
            'summary' => 'List Files In Installed Package',
            'function' => 'doFileList',
            'shortcut' => 'fl',
            'options' => array(),
            'doc' => '<package>
List the files in an installed package.
'
            ),
        'shell-test' => array(
            'summary' => 'Shell Script Test',
            'function' => 'doShellTest',
            'shortcut' => 'st',
            'options' => array(),
            'doc' => '<package> [[relation] version]
Tests if a package is installed in the system. Will exit(1) if it is not.
   <relation>   The version comparison operator. One of:
                <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
   <version>    The version to compare with
'),
        'info' => array(
            'summary'  => 'Display information about a package',
            'function' => 'doInfo',
            'shortcut' => 'in',
            'options'  => array(),
            'doc'      => '<package>
Displays information about a package. The package argument may be a
local package file, an URL to a package file, or the name of an
installed package.'
            )
        );

    /**
     * PEAR_Command_Registry constructor.
     *
     * @access public
     */
    function PEAR_Command_Registry(&$ui, &$config)
    {
        parent::PEAR_Command_Common($ui, $config);
    }

    function _sortinfo($a, $b)
    {
        $apackage = isset($a['package']) ? $a['package'] : $a['name'];
        $bpackage = isset($b['package']) ? $b['package'] : $b['name'];
        return strcmp($apackage, $bpackage);
    }

    function doList($command, $options, $params)
    {
        $reg = &$this->config->getRegistry();
        $channelinfo = isset($options['channelinfo']);
        if (isset($options['allchannels']) && !$channelinfo) {
            return $this->doListAll($command, array(), $params);
        }

        if (isset($options['allchannels']) && $channelinfo) {
            // allchannels with $channelinfo
            unset($options['allchannels']);
            $channels = $reg->getChannels();
            $errors = array();
            PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
            foreach ($channels as $channel) {
                $options['channel'] = $channel->getName();
                $ret = $this->doList($command, $options, $params);

                if (PEAR::isError($ret)) {
                    $errors[] = $ret;
                }
            }

            PEAR::staticPopErrorHandling();
            if (count($errors)) {
                // for now, only give first error
                return PEAR::raiseError($errors[0]);
            }

            return true;
        }

        if (count($params) === 1) {
            return $this->doFileList($command, $options, $params);
        }

        if (isset($options['channel'])) {
            if (!$reg->channelExists($options['channel'])) {
                return $this->raiseError('Channel "' . $options['channel'] .'" does not exist');
            }

            $channel = $reg->channelName($options['channel']);
        } else {
            $channel = $this->config->get('default_channel');
        }

        $installed = $reg->packageInfo(null, null, $channel);
        usort($installed, array(&$this, '_sortinfo'));

        $data = array(
            'caption' => 'Installed packages, channel ' .
                $channel . ':',
            'border' => true,
            'headline' => array('Package', 'Version', 'State'),
            'channel' => $channel,
            );
        if ($channelinfo) {
            $data['headline'] = array('Channel', 'Package', 'Version', 'State');
        }

        if (count($installed) && !isset($data['data'])) {
            $data['data'] = array();
        }

        foreach ($installed as $package) {
            $pobj = $reg->getPackage(isset($package['package']) ?
                                        $package['package'] : $package['name'], $channel);
            if ($channelinfo) {
                $packageinfo = array($pobj->getChannel(), $pobj->getPackage(), $pobj->getVersion(),
                                    $pobj->getState() ? $pobj->getState() : null);
            } else {
                $packageinfo = array($pobj->getPackage(), $pobj->getVersion(),
                                    $pobj->getState() ? $pobj->getState() : null);
            }
            $data['data'][] = $packageinfo;
        }

        if (count($installed) === 0) {
            if (!$channelinfo) {
                $data = '(no packages installed from channel ' . $channel . ')';
            } else {
                $data = array(
                    'caption' => 'Installed packages, channel ' .
                        $channel . ':',
                    'border' => true,
                    'channel' => $channel,
                    'data' => array(array('(no packages installed)')),
                );
            }
        }

        $this->ui->outputData($data, $command);
        return true;
    }

    function doListAll($command, $options, $params)
    {
        // This duplicate code is deprecated over
        // list --channelinfo, which gives identical
        // output for list and list --allchannels.
        $reg = &$this->config->getRegistry();
        $installed = $reg->packageInfo(null, null, null);
        foreach ($installed as $channel => $packages) {
            usort($packages, array($this, '_sortinfo'));
            $data = array(
                'caption'  => 'Installed packages, channel ' . $channel . ':',
                'border'   => true,
                'headline' => array('Package', 'Version', 'State'),
                'channel'  => $channel
            );

            foreach ($packages as $package) {
                $p = isset($package['package']) ? $package['package'] : $package['name'];
                $pobj = $reg->getPackage($p, $channel);
                $data['data'][] = array($pobj->getPackage(), $pobj->getVersion(),
                                        $pobj->getState() ? $pobj->getState() : null);
            }

            // Adds a blank line after each section
            $data['data'][] = array();

            if (count($packages) === 0) {
                $data = array(
                    'caption' => 'Installed packages, channel ' . $channel . ':',
                    'border' => true,
                    'data' => array(array('(no packages installed)'), array()),
                    'channel' => $channel
                    );
            }
            $this->ui->outputData($data, $command);
        }
        return true;
    }

    function doFileList($command, $options, $params)
    {
        if (count($params) !== 1) {
            return $this->raiseError('list-files expects 1 parameter');
        }

        $reg = &$this->config->getRegistry();
        $fp = false;
        if (!is_dir($params[0]) && (file_exists($params[0]) || $fp = @fopen($params[0], 'r'))) {
            if ($fp) {
                fclose($fp);
            }

            if (!class_exists('PEAR_PackageFile')) {
                require_once 'PEAR/PackageFile.php';
            }

            $pkg = &new PEAR_PackageFile($this->config, $this->_debug);
            PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
            $info = &$pkg->fromAnyFile($params[0], PEAR_VALIDATE_NORMAL);
            PEAR::staticPopErrorHandling();
            $headings = array('Package File', 'Install Path');
            $installed = false;
        } else {
            PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
            $parsed = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
            PEAR::staticPopErrorHandling();
            if (PEAR::isError($parsed)) {
                return $this->raiseError($parsed);
            }

            $info = &$reg->getPackage($parsed['package'], $parsed['channel']);
            $headings = array('Type', 'Install Path');
            $installed = true;
        }

        if (PEAR::isError($info)) {
            return $this->raiseError($info);
        }

        if ($info === null) {
            return $this->raiseError("`$params[0]' not installed");
        }

        $list = ($info->getPackagexmlVersion() == '1.0' || $installed) ?
            $info->getFilelist() : $info->getContents();
        if ($installed) {
            $caption = 'Installed Files For ' . $params[0];
        } else {
            $caption = 'Contents of ' . basename($params[0]);
        }

        $data = array(
            'caption' => $caption,
            'border' => true,
            'headline' => $headings);
        if ($info->getPackagexmlVersion() == '1.0' || $installed) {
            foreach ($list as $file => $att) {
                if ($installed) {
                    if (empty($att['installed_as'])) {
                        continue;
                    }
                    $data['data'][] = array($att['role'], $att['installed_as']);
                } else {
                    if (isset($att['baseinstalldir']) && !in_array($att['role'],
                          array('test', 'data', 'doc'))) {
                        $dest = $att['baseinstalldir'] . DIRECTORY_SEPARATOR .
                            $file;
                    } else {
                        $dest = $file;
                    }
                    switch ($att['role']) {
                        case 'test':
                        case 'data':
                        case 'doc':
                            $role = $att['role'];
                            if ($role == 'test') {
                                $role .= 's';
                            }
                            $dest = $this->config->get($role . '_dir') . DIRECTORY_SEPARATOR .
                                $info->getPackage() . DIRECTORY_SEPARATOR . $dest;
                            break;
                        case 'php':
                        default:
                            $dest = $this->config->get('php_dir') . DIRECTORY_SEPARATOR .
                                $dest;
                    }
                    $ds2 = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR;
                    $dest = preg_replace(array('!\\\\+!', '!/!', "!$ds2+!"),
                                                    array(DIRECTORY_SEPARATOR,
                                                          DIRECTORY_SEPARATOR,
                                                          DIRECTORY_SEPARATOR),
                                                    $dest);
                    $file = preg_replace('!/+!', '/', $file);
                    $data['data'][] = array($file, $dest);
                }
            }
        } else { // package.xml 2.0, not installed
            if (!isset($list['dir']['file'][0])) {
                $list['dir']['file'] = array($list['dir']['file']);
            }

            foreach ($list['dir']['file'] as $att) {
                $att = $att['attribs'];
                $file = $att['name'];
                $role = &PEAR_Installer_Role::factory($info, $att['role'], $this->config);
                $role->setup($this, $info, $att, $file);
                if (!$role->isInstallable()) {
                    $dest = '(not installable)';
                } else {
                    $dest = $role->processInstallation($info, $att, $file, '');
                    if (PEAR::isError($dest)) {
                        $dest = '(Unknown role "' . $att['role'] . ')';
                    } else {
                        list(,, $dest) = $dest;
                    }
                }
                $data['data'][] = array($file, $dest);
            }
        }

        $this->ui->outputData($data, $command);
        return true;
    }

    function doShellTest($command, $options, $params)
    {
        if (count($params) < 1) {
            return PEAR::raiseError('ERROR, usage: pear shell-test packagename [[relation] version]');
        }

        PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
        $reg = &$this->config->getRegistry();
        $info = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
        if (PEAR::isError($info)) {
            exit(1); // invalid package name
        }

        $package = $info['package'];
        $channel = $info['channel'];
        // "pear shell-test Foo"
        if (!$reg->packageExists($package, $channel)) {
            if ($channel == 'pecl.php.net') {
                if ($reg->packageExists($package, 'pear.php.net')) {
                    $channel = 'pear.php.net'; // magically change channels for extensions
                }
            }
        }

        if (count($params) === 1) {
            if (!$reg->packageExists($package, $channel)) {
                exit(1);
            }
            // "pear shell-test Foo 1.0"
        } elseif (count($params) === 2) {
            $v = $reg->packageInfo($package, 'version', $channel);
            if (!$v || !version_compare("$v", "{$params[1]}", "ge")) {
                exit(1);
            }
            // "pear shell-test Foo ge 1.0"
        } elseif (count($params) === 3) {
            $v = $reg->packageInfo($package, 'version', $channel);
            if (!$v || !version_compare("$v", "{$params[2]}", $params[1])) {
                exit(1);
            }
        } else {
            PEAR::staticPopErrorHandling();
            $this->raiseError("$command: expects 1 to 3 parameters");
            exit(1);
        }
    }

    function doInfo($command, $options, $params)
    {
        if (count($params) !== 1) {
            return $this->raiseError('pear info expects 1 parameter');
        }

        $info = $fp = false;
        $reg = &$this->config->getRegistry();
        if (is_file($params[0]) && !is_dir($params[0]) &&
            (file_exists($params[0]) || $fp = @fopen($params[0], 'r'))
        ) {
            if ($fp) {
                fclose($fp);
            }

            if (!class_exists('PEAR_PackageFile')) {
                require_once 'PEAR/PackageFile.php';
            }

            $pkg = &new PEAR_PackageFile($this->config, $this->_debug);
            PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
            $obj = &$pkg->fromAnyFile($params[0], PEAR_VALIDATE_NORMAL);
            PEAR::staticPopErrorHandling();
            if (PEAR::isError($obj)) {
                $uinfo = $obj->getUserInfo();
                if (is_array($uinfo)) {
                    foreach ($uinfo as $message) {
                        if (is_array($message)) {
                            $message = $message['message'];
                        }
                        $this->ui->outputData($message);
                    }
                }

                return $this->raiseError($obj);
            }

            if ($obj->getPackagexmlVersion() != '1.0') {
                return $this->_doInfo2($command, $options, $params, $obj, false);
            }

            $info = $obj->toArray();
        } else {
            $parsed = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
            if (PEAR::isError($parsed)) {
                return $this->raiseError($parsed);
            }

            $package = $parsed['package'];
            $channel = $parsed['channel'];
            $info = $reg->packageInfo($package, null, $channel);
            if (isset($info['old'])) {
                $obj = $reg->getPackage($package, $channel);
                return $this->_doInfo2($command, $options, $params, $obj, true);
            }
        }

        if (PEAR::isError($info)) {
            return $info;
        }

        if (empty($info)) {
            $this->raiseError("No information found for `$params[0]'");
            return;
        }

        unset($info['filelist']);
        unset($info['dirtree']);
        unset($info['changelog']);
        if (isset($info['xsdversion'])) {
            $info['package.xml version'] = $info['xsdversion'];
            unset($info['xsdversion']);
        }

        if (isset($info['packagerversion'])) {
            $info['packaged with PEAR version'] = $info['packagerversion'];
            unset($info['packagerversion']);
        }

        $keys = array_keys($info);
        $longtext = array('description', 'summary');
        foreach ($keys as $key) {
            if (is_array($info[$key])) {
                switch ($key) {
                    case 'maintainers': {
                        $i = 0;
                        $mstr = '';
                        foreach ($info[$key] as $m) {
                            if ($i++ > 0) {
                                $mstr .= "\n";
                            }
                            $mstr .= $m['name'] . " <";
                            if (isset($m['email'])) {
                                $mstr .= $m['email'];
                            } else {
                                $mstr .= $m['handle'] . '@php.net';
                            }
                            $mstr .= "> ($m[role])";
                        }
                        $info[$key] = $mstr;
                        break;
                    }
                    case 'release_deps': {
                        $i = 0;
                        $dstr = '';
                        foreach ($info[$key] as $d) {
                            if (isset($this->_deps_rel_trans[$d['rel']])) {
                                $rel = $this->_deps_rel_trans[$d['rel']];
                            } else {
                                $rel = $d['rel'];
                            }
                            if (isset($this->_deps_type_trans[$d['type']])) {
                                $type = ucfirst($this->_deps_type_trans[$d['type']]);
                            } else {
                                $type = $d['type'];
                            }
                            if (isset($d['name'])) {
                                $name = $d['name'] . ' ';
                            } else {
                                $name = '';
                            }
                            if (isset($d['version'])) {
                                $version = $d['version'] . ' ';
                            } else {
                                $version = '';
                            }
                            if (isset($d['optional']) && $d['optional'] == 'yes') {
                                $optional = ' (optional)';
                            } else {
                                $optional = '';
                            }
                            $dstr .= "$type $name$rel $version$optional\n";
                        }
                        $info[$key] = $dstr;
                        break;
                    }
                    case 'provides' : {
                        $debug = $this->config->get('verbose');
                        if ($debug < 2) {
                            $pstr = 'Classes: ';
                        } else {
                            $pstr = '';
                        }
                        $i = 0;
                        foreach ($info[$key] as $p) {
                            if ($debug < 2 && $p['type'] != "class") {
                                continue;
                            }
                            // Only print classes when verbosity mode is < 2
                            if ($debug < 2) {
                                if ($i++ > 0) {
                                    $pstr .= ", ";
                                }
                                $pstr .= $p['name'];
                            } else {
                                if ($i++ > 0) {
                                    $pstr .= "\n";
                                }
                                $pstr .= ucfirst($p['type']) . " " . $p['name'];
                                if (isset($p['explicit']) && $p['explicit'] == 1) {
                                    $pstr .= " (explicit)";
                                }
                            }
                        }
                        $info[$key] = $pstr;
                        break;
                    }
                    case 'configure_options' : {
                        foreach ($info[$key] as $i => $p) {
                            $info[$key][$i] = array_map(null, array_keys($p), array_values($p));
                            $info[$key][$i] = array_map(create_function('$a',
                                'return join(" = ",$a);'), $info[$key][$i]);
                            $info[$key][$i] = implode(', ', $info[$key][$i]);
                        }
                        $info[$key] = implode("\n", $info[$key]);
                        break;
                    }
                    default: {
                        $info[$key] = implode(", ", $info[$key]);
                        break;
                    }
                }
            }

            if ($key == '_lastmodified') {
                $hdate = date('Y-m-d', $info[$key]);
                unset($info[$key]);
                $info['Last Modified'] = $hdate;
            } elseif ($key == '_lastversion') {
                $info['Previous Installed Version'] = $info[$key] ? $info[$key] : '- None -';
                unset($info[$key]);
            } else {
                $info[$key] = trim($info[$key]);
                if (in_array($key, $longtext)) {
                    $info[$key] = preg_replace('/  +/', ' ', $info[$key]);
                }
            }
        }

        $caption = 'About ' . $info['package'] . '-' . $info['version'];
        $data = array(
            'caption' => $caption,
            'border' => true);
        foreach ($info as $key => $value) {
            $key = ucwords(trim(str_replace('_', ' ', $key)));
            $data['data'][] = array($key, $value);
        }
        $data['raw'] = $info;

        $this->ui->outputData($data, 'package-info');
    }

    /**
     * @access private
     */
    function _doInfo2($command, $options, $params, &$obj, $installed)
    {
        $reg = &$this->config->getRegistry();
        $caption = 'About ' . $obj->getChannel() . '/' .$obj->getPackage() . '-' .
            $obj->getVersion();
        $data = array(
            'caption' => $caption,
            'border' => true);
        switch ($obj->getPackageType()) {
            case 'php' :
                $release = 'PEAR-style PHP-based Package';
            break;
            case 'extsrc' :
                $release = 'PECL-style PHP extension (source code)';
            break;
            case 'zendextsrc' :
                $release = 'PECL-style Zend extension (source code)';
            break;
            case 'extbin' :
                $release = 'PECL-style PHP extension (binary)';
            break;
            case 'zendextbin' :
                $release = 'PECL-style Zend extension (binary)';
            break;
            case 'bundle' :
                $release = 'Package bundle (collection of packages)';
            break;
        }
        $extends = $obj->getExtends();
        $extends = $extends ?
            $obj->getPackage() . ' (extends ' . $extends . ')' : $obj->getPackage();
        if ($src = $obj->getSourcePackage()) {
            $extends .= ' (source package ' . $src['channel'] . '/' . $src['package'] . ')';
        }

        $info = array(
            'Release Type' => $release,
            'Name' => $extends,
            'Channel' => $obj->getChannel(),
            'Summary' => preg_replace('/  +/', ' ', $obj->getSummary()),
            'Description' => preg_replace('/  +/', ' ', $obj->getDescription()),
            );
        $info['Maintainers'] = '';
        foreach (array('lead', 'developer', 'contributor', 'helper') as $role) {
            $leads = $obj->{"get{$role}s"}();
            if (!$leads) {
                continue;
            }

            if (isset($leads['active'])) {
                $leads = array($leads);
            }

            foreach ($leads as $lead) {
                if (!empty($info['Maintainers'])) {
                    $info['Maintainers'] .= "\n";
                }

                $active = $lead['active'] == 'no' ? ', inactive' : '';
                $info['Maintainers'] .= $lead['name'] . ' <';
                $info['Maintainers'] .= $lead['email'] . "> ($role$active)";
            }
        }

        $info['Release Date'] = $obj->getDate();
        if ($time = $obj->getTime()) {
            $info['Release Date'] .= ' ' . $time;
        }

        $info['Release Version'] = $obj->getVersion() . ' (' . $obj->getState() . ')';
        $info['API Version'] = $obj->getVersion('api') . ' (' . $obj->getState('api') . ')';
        $info['License'] = $obj->getLicense();
        $uri = $obj->getLicenseLocation();
        if ($uri) {
            if (isset($uri['uri'])) {
                $info['License'] .= ' (' . $uri['uri'] . ')';
            } else {
                $extra = $obj->getInstalledLocation($info['filesource']);
                if ($extra) {
                    $info['License'] .= ' (' . $uri['filesource'] . ')';
                }
            }
        }

        $info['Release Notes'] = $obj->getNotes();
        if ($compat = $obj->getCompatible()) {
            if (!isset($compat[0])) {
                $compat = array($compat);
            }

            $info['Compatible with'] = '';
            foreach ($compat as $package) {
                $info['Compatible with'] .= $package['channel'] . '/' . $package['name'] .
                    "\nVersions >= " . $package['min'] . ', <= ' . $package['max'];
                if (isset($package['exclude'])) {
                    if (is_array($package['exclude'])) {
                        $package['exclude'] = implode(', ', $package['exclude']);
                    }

                    if (!isset($info['Not Compatible with'])) {
                        $info['Not Compatible with'] = '';
                    } else {
                        $info['Not Compatible with'] .= "\n";
                    }
                    $info['Not Compatible with'] .= $package['channel'] . '/' .
                        $package['name'] . "\nVersions " . $package['exclude'];
                }
            }
        }

        $usesrole = $obj->getUsesrole();
        if ($usesrole) {
            if (!isset($usesrole[0])) {
                $usesrole = array($usesrole);
            }

            foreach ($usesrole as $roledata) {
                if (isset($info['Uses Custom Roles'])) {
                    $info['Uses Custom Roles'] .= "\n";
                } else {
                    $info['Uses Custom Roles'] = '';
                }

                if (isset($roledata['package'])) {
                    $rolepackage = $reg->parsedPackageNameToString($roledata, true);
                } else {
                    $rolepackage = $roledata['uri'];
                }
                $info['Uses Custom Roles'] .= $roledata['role'] . ' (' . $rolepackage . ')';
            }
        }

        $usestask = $obj->getUsestask();
        if ($usestask) {
            if (!isset($usestask[0])) {
                $usestask = array($usestask);
            }

            foreach ($usestask as $taskdata) {
                if (isset($info['Uses Custom Tasks'])) {
                    $info['Uses Custom Tasks'] .= "\n";
                } else {
                    $info['Uses Custom Tasks'] = '';
                }

                if (isset($taskdata['package'])) {
                    $taskpackage = $reg->parsedPackageNameToString($taskdata, true);
                } else {
                    $taskpackage = $taskdata['uri'];
                }
                $info['Uses Custom Tasks'] .= $taskdata['task'] . ' (' . $taskpackage . ')';
            }
        }

        $deps = $obj->getDependencies();
        $info['Required Dependencies'] = 'PHP version ' . $deps['required']['php']['min'];
        if (isset($deps['required']['php']['max'])) {
            $info['Required Dependencies'] .= '-' . $deps['required']['php']['max'] . "\n";
        } else {
            $info['Required Dependencies'] .= "\n";
        }

        if (isset($deps['required']['php']['exclude'])) {
            if (!isset($info['Not Compatible with'])) {
                $info['Not Compatible with'] = '';
            } else {
                $info['Not Compatible with'] .= "\n";
            }

            if (is_array($deps['required']['php']['exclude'])) {
                $deps['required']['php']['exclude'] =
                    implode(', ', $deps['required']['php']['exclude']);
            }
            $info['Not Compatible with'] .= "PHP versions\n  " .
                $deps['required']['php']['exclude'];
        }

        $info['Required Dependencies'] .= 'PEAR installer version';
        if (isset($deps['required']['pearinstaller']['max'])) {
            $info['Required Dependencies'] .= 's ' .
                $deps['required']['pearinstaller']['min'] . '-' .
                $deps['required']['pearinstaller']['max'];
        } else {
            $info['Required Dependencies'] .= ' ' .
                $deps['required']['pearinstaller']['min'] . ' or newer';
        }

        if (isset($deps['required']['pearinstaller']['exclude'])) {
            if (!isset($info['Not Compatible with'])) {
                $info['Not Compatible with'] = '';
            } else {
                $info['Not Compatible with'] .= "\n";
            }

            if (is_array($deps['required']['pearinstaller']['exclude'])) {
                $deps['required']['pearinstaller']['exclude'] =
                    implode(', ', $deps['required']['pearinstaller']['exclude']);
            }
            $info['Not Compatible with'] .= "PEAR installer\n  Versions " .
                $deps['required']['pearinstaller']['exclude'];
        }

        foreach (array('Package', 'Extension') as $type) {
            $index = strtolower($type);
            if (isset($deps['required'][$index])) {
                if (isset($deps['required'][$index]['name'])) {
                    $deps['required'][$index] = array($deps['required'][$index]);
                }

                foreach ($deps['required'][$index] as $package) {
                    if (isset($package['conflicts'])) {
                        $infoindex = 'Not Compatible with';
                        if (!isset($info['Not Compatible with'])) {
                            $info['Not Compatible with'] = '';
                        } else {
                            $info['Not Compatible with'] .= "\n";
                        }
                    } else {
                        $infoindex = 'Required Dependencies';
                        $info[$infoindex] .= "\n";
                    }

                    if ($index == 'extension') {
                        $name = $package['name'];
                    } else {
                        if (isset($package['channel'])) {
                            $name = $package['channel'] . '/' . $package['name'];
                        } else {
                            $name = '__uri/' . $package['name'] . ' (static URI)';
                        }
                    }

                    $info[$infoindex] .= "$type $name";
                    if (isset($package['uri'])) {
                        $info[$infoindex] .= "\n  Download URI: $package[uri]";
                        continue;
                    }

                    if (isset($package['max']) && isset($package['min'])) {
                        $info[$infoindex] .= " \n  Versions " .
                            $package['min'] . '-' . $package['max'];
                    } elseif (isset($package['min'])) {
                        $info[$infoindex] .= " \n  Version " .
                            $package['min'] . ' or newer';
                    } elseif (isset($package['max'])) {
                        $info[$infoindex] .= " \n  Version " .
                            $package['max'] . ' or older';
                    }

                    if (isset($package['recommended'])) {
                        $info[$infoindex] .= "\n  Recommended version: $package[recommended]";
                    }

                    if (isset($package['exclude'])) {
                        if (!isset($info['Not Compatible with'])) {
                            $info['Not Compatible with'] = '';
                        } else {
                            $info['Not Compatible with'] .= "\n";
                        }

                        if (is_array($package['exclude'])) {
                            $package['exclude'] = implode(', ', $package['exclude']);
                        }

                        $package['package'] = $package['name']; // for parsedPackageNameToString
                         if (isset($package['conflicts'])) {
                            $info['Not Compatible with'] .= '=> except ';
                        }
                       $info['Not Compatible with'] .= 'Package ' .
                            $reg->parsedPackageNameToString($package, true);
                        $info['Not Compatible with'] .= "\n  Versions " . $package['exclude'];
                    }
                }
            }
        }

        if (isset($deps['required']['os'])) {
            if (isset($deps['required']['os']['name'])) {
                $dep['required']['os']['name'] = array($dep['required']['os']['name']);
            }

            foreach ($dep['required']['os'] as $os) {
                if (isset($os['conflicts']) && $os['conflicts'] == 'yes') {
                    if (!isset($info['Not Compatible with'])) {
                        $info['Not Compatible with'] = '';
                    } else {
                        $info['Not Compatible with'] .= "\n";
                    }
                    $info['Not Compatible with'] .= "$os[name] Operating System";
                } else {
                    $info['Required Dependencies'] .= "\n";
                    $info['Required Dependencies'] .= "$os[name] Operating System";
                }
            }
        }

        if (isset($deps['required']['arch'])) {
            if (isset($deps['required']['arch']['pattern'])) {
                $dep['required']['arch']['pattern'] = array($dep['required']['os']['pattern']);
            }

            foreach ($dep['required']['arch'] as $os) {
                if (isset($os['conflicts']) && $os['conflicts'] == 'yes') {
                    if (!isset($info['Not Compatible with'])) {
                        $info['Not Compatible with'] = '';
                    } else {
                        $info['Not Compatible with'] .= "\n";
                    }
                    $info['Not Compatible with'] .= "OS/Arch matching pattern '/$os[pattern]/'";
                } else {
                    $info['Required Dependencies'] .= "\n";
                    $info['Required Dependencies'] .= "OS/Arch matching pattern '/$os[pattern]/'";
                }
            }
        }

        if (isset($deps['optional'])) {
            foreach (array('Package', 'Extension') as $type) {
                $index = strtolower($type);
                if (isset($deps['optional'][$index])) {
                    if (isset($deps['optional'][$index]['name'])) {
                        $deps['optional'][$index] = array($deps['optional'][$index]);
                    }

                    foreach ($deps['optional'][$index] as $package) {
                        if (isset($package['conflicts']) && $package['conflicts'] == 'yes') {
                            $infoindex = 'Not Compatible with';
                            if (!isset($info['Not Compatible with'])) {
                                $info['Not Compatible with'] = '';
                            } else {
                                $info['Not Compatible with'] .= "\n";
                            }
                        } else {
                            $infoindex = 'Optional Dependencies';
                            if (!isset($info['Optional Dependencies'])) {
                                $info['Optional Dependencies'] = '';
                            } else {
                                $info['Optional Dependencies'] .= "\n";
                            }
                        }

                        if ($index == 'extension') {
                            $name = $package['name'];
                        } else {
                            if (isset($package['channel'])) {
                                $name = $package['channel'] . '/' . $package['name'];
                            } else {
                                $name = '__uri/' . $package['name'] . ' (static URI)';
                            }
                        }

                        $info[$infoindex] .= "$type $name";
                        if (isset($package['uri'])) {
                            $info[$infoindex] .= "\n  Download URI: $package[uri]";
                            continue;
                        }

                        if ($infoindex == 'Not Compatible with') {
                            // conflicts is only used to say that all versions conflict
                            continue;
                        }

                        if (isset($package['max']) && isset($package['min'])) {
                            $info[$infoindex] .= " \n  Versions " .
                                $package['min'] . '-' . $package['max'];
                        } elseif (isset($package['min'])) {
                            $info[$infoindex] .= " \n  Version " .
                                $package['min'] . ' or newer';
                        } elseif (isset($package['max'])) {
                            $info[$infoindex] .= " \n  Version " .
                                $package['min'] . ' or older';
                        }

                        if (isset($package['recommended'])) {
                            $info[$infoindex] .= "\n  Recommended version: $package[recommended]";
                        }

                        if (isset($package['exclude'])) {
                            if (!isset($info['Not Compatible with'])) {
                                $info['Not Compatible with'] = '';
                            } else {
                                $info['Not Compatible with'] .= "\n";
                            }

                            if (is_array($package['exclude'])) {
                                $package['exclude'] = implode(', ', $package['exclude']);
                            }

                            $info['Not Compatible with'] .= "Package $package\n  Versions " .
                                $package['exclude'];
                        }
                    }
                }
            }
        }

        if (isset($deps['group'])) {
            if (!isset($deps['group'][0])) {
                $deps['group'] = array($deps['group']);
            }

            foreach ($deps['group'] as $group) {
                $info['Dependency Group ' . $group['attribs']['name']] = $group['attribs']['hint'];
                $groupindex = $group['attribs']['name'] . ' Contents';
                $info[$groupindex] = '';
                foreach (array('Package', 'Extension') as $type) {
                    $index = strtolower($type);
                    if (isset($group[$index])) {
                        if (isset($group[$index]['name'])) {
                            $group[$index] = array($group[$index]);
                        }

                        foreach ($group[$index] as $package) {
                            if (!empty($info[$groupindex])) {
                                $info[$groupindex] .= "\n";
                            }

                            if ($index == 'extension') {
                                $name = $package['name'];
                            } else {
                                if (isset($package['channel'])) {
                                    $name = $package['channel'] . '/' . $package['name'];
                                } else {
                                    $name = '__uri/' . $package['name'] . ' (static URI)';
                                }
                            }

                            if (isset($package['uri'])) {
                                if (isset($package['conflicts']) && $package['conflicts'] == 'yes') {
                                    $info[$groupindex] .= "Not Compatible with $type $name";
                                } else {
                                    $info[$groupindex] .= "$type $name";
                                }

                                $info[$groupindex] .= "\n  Download URI: $package[uri]";
                                continue;
                            }

                            if (isset($package['conflicts']) && $package['conflicts'] == 'yes') {
                                $info[$groupindex] .= "Not Compatible with $type $name";
                                continue;
                            }

                            $info[$groupindex] .= "$type $name";
                            if (isset($package['max']) && isset($package['min'])) {
                                $info[$groupindex] .= " \n  Versions " .
                                    $package['min'] . '-' . $package['max'];
                            } elseif (isset($package['min'])) {
                                $info[$groupindex] .= " \n  Version " .
                                    $package['min'] . ' or newer';
                            } elseif (isset($package['max'])) {
                                $info[$groupindex] .= " \n  Version " .
                                    $package['min'] . ' or older';
                            }

                            if (isset($package['recommended'])) {
                                $info[$groupindex] .= "\n  Recommended version: $package[recommended]";
                            }

                            if (isset($package['exclude'])) {
                                if (!isset($info['Not Compatible with'])) {
                                    $info['Not Compatible with'] = '';
                                } else {
                                    $info[$groupindex] .= "Not Compatible with\n";
                                }

                                if (is_array($package['exclude'])) {
                                    $package['exclude'] = implode(', ', $package['exclude']);
                                }
                                $info[$groupindex] .= "  Package $package\n  Versions " .
                                    $package['exclude'];
                            }
                        }
                    }
                }
            }
        }

        if ($obj->getPackageType() == 'bundle') {
            $info['Bundled Packages'] = '';
            foreach ($obj->getBundledPackages() as $package) {
                if (!empty($info['Bundled Packages'])) {
                    $info['Bundled Packages'] .= "\n";
                }

                if (isset($package['uri'])) {
                    $info['Bundled Packages'] .= '__uri/' . $package['name'];
                    $info['Bundled Packages'] .= "\n  (URI: $package[uri]";
                } else {
                    $info['Bundled Packages'] .= $package['channel'] . '/' . $package['name'];
                }
            }
        }

        $info['package.xml version'] = '2.0';
        if ($installed) {
            if ($obj->getLastModified()) {
                $info['Last Modified'] = date('Y-m-d H:i', $obj->getLastModified());
            }

            $v = $obj->getLastInstalledVersion();
            $info['Previous Installed Version'] = $v ? $v : '- None -';
        }

        foreach ($info as $key => $value) {
            $data['data'][] = array($key, $value);
        }

        $data['raw'] = $obj->getArray(); // no validation needed
        $this->ui->outputData($data, 'package-info');
    }
}


text:
function compactness(collection, query, limit) {
    "use strict";
    Object.size = function(o) {
        var size = 0, key;
        for (key in o) { if (o.hasOwnProperty(key)) size++; }
        return size;
    };

    var count = 0,
        size=0;
    var disklocs = {}; //will store each disk loc, format: file-loc%4kb, ie file-0, file-4096, etc

    db.getCollection(collection).find(query).limit(limit).showDiskLoc().forEach(
        function(doc) {
            var file = doc.$diskLoc.file,
                offset = (doc.$diskLoc.offset),
                offsetPage = offset - offset % 4096;
            count++;
            size += Object.bsonsize(doc) - 45; //$diskloc info adds 45 bytes
            disklocs[file + "-" + offsetPage] = 1;
        }
    );
    var numpages = Object.size(disklocs);
    var numbytespages = 1024 * 4 * numpages;
    print("Size of returned data in bytes: " + size);
    print("Size of pages touched by data : " + numbytespages);
    print("Compactness: " + Math.floor(100*size/numbytespages) + "%");
}


text:
package com.dtstack.jlogstash.format.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: haisi
 * @date 2019-06-18 14:44
 */

public class PathConverterUtil {

    private static Logger logger = LoggerFactory.getLogger(PathConverterUtil.class);

    private static Pattern pat1 = Pattern.compile("\\$\\{.*?\\}");

    private static String KEY_TABLE = "table";

    /**
     * @param path
     * @return
     */
    public static String regaxByRules(Map output, String path, Map<String, String> distributeTableMapping) {
        try {
            Matcher mat1 = pat1.matcher(path);
            while (mat1.find()) {
                String pkey = mat1.group();
                String key = pkey.substring(2, pkey.length() - 1);
                Object value = output.get(key);
                if (value == null) {
                    value = "";
                }
                String ruleValue = value.toString();
                if (KEY_TABLE.equals(key)) {
                    ruleValue = distributeTableMapping.getOrDefault(ruleValue, ruleValue);
                }
                //.在sql中会视为db.table的分隔符,需要单独过滤特殊字符 '.'
                path = path.replace(pkey, ruleValue).replace(".", "_");
            }
        } catch (Exception e) {
            logger.error("parser path rules is fail", e);
        }
        return path;
    }

}


text:
<!doctype html>
<title>fur</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">

    {% with messages = get_flashed_messages() %}
        {% if messages %}

                {% for message in messages %}

{{ message }}

                {% endfor %}

        {% endif %}
    {% endwith %}

            Fedoraur |
        {% if not session.username %}
            Log in or register
        {% else %}
            upload | Logged in as {{ session.username }}, log out
        {% endif %}

        <form action="/search" method="post">
            <input type="text" name="search_box"/>
            <input type="submit" value="search"/>
        </form>

    {% block body %}{% endblock %}


text:
Modifications of WRF-Chem 3.5.1 described in Mues et al.,
"Air quality in the Kathmandu Valley: WRF and WRF-Chem simulations of meteorology and black carbon concentrations",
Geosci. Model Dev.

The following two modifications have been applied:

- added gravitational settling of aerosol particles for chem_opt=41 (RADM2/MADE/SORGAM)
- fix to prevent sea salt emissions from small in-land lakes in the Himalayas

For more information on WRF-Chem, see official website at https://ruc.noaa.gov/wrf/wrf-chem/

[![DOI](https://zenodo.org/badge/104982258.svg)](https://zenodo.org/badge/latestdoi/104982258)


text:
layout: page
title: Fuller Tech Dinner
date: 2016-05-24
author: Kelly Best
tags: weekly links, java
status: published
summary: Nulla eu vulputate erat. Donec dignissim finibus aliquet. Aliquam condimentum.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 07/04/2016
  endDate: 07/09/2016
  ctyhocn: AVPTKHX
  groupCode: FTD
published: true
---
Nulla consequat metus sodales, ultricies elit id, feugiat eros. Aenean consectetur tincidunt maximus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin ac placerat lacus. In euismod ornare odio, ut commodo nulla mattis ut. Phasellus eget blandit mi, vel molestie augue. Sed molestie nisl mi, vitae suscipit sapien consectetur ut. Vestibulum aliquam risus ultricies ipsum egestas fringilla. Fusce sed sagittis felis. Donec feugiat eros at orci dapibus, lacinia maximus tellus auctor. Vivamus ultrices odio libero, eu porta magna dapibus in. Vivamus facilisis, augue id aliquet faucibus, lorem mi molestie ante, sed malesuada velit sem eget justo.

1 Sed in nisl vestibulum, viverra velit vitae, lobortis nibh
1 Curabitur quis lectus tincidunt, pharetra velit nec, gravida nulla.

Fusce pharetra purus magna, ultricies auctor lorem commodo nec. Nulla felis tortor, condimentum ut volutpat eu, bibendum faucibus risus. Duis ante quam, consequat quis egestas eu, maximus vel nisi. Nullam a nibh mollis, sodales ligula at, consectetur diam. Integer eget diam vitae velit luctus aliquam eget quis est. Vestibulum varius lectus a urna ultricies, sit amet tincidunt leo sodales. Pellentesque sed justo at quam pellentesque convallis. Maecenas vel magna luctus, blandit purus tincidunt, rutrum justo. Donec eros nunc, dapibus at eros vel, commodo sollicitudin sapien. Maecenas vitae finibus eros. Pellentesque convallis dui non orci pellentesque sodales. Fusce viverra eget neque vitae interdum.


text:
namespace ui {

// Configures the ozone platform so it would return an error early at the stage
// of initialisation.  In such event, the browser should gracefully exit.
// See https://crbug.com/1280138.
class OzonePlatformTest : public InProcessBrowserTest {
 public:
  OzonePlatformTest() {
    OzonePlatform::SetFailInitializeUIForTest(true);
    set_expected_exit_code(1);
  }

  ~OzonePlatformTest() override {
    OzonePlatform::SetFailInitializeUIForTest(false);
  }
};

IN_PROC_BROWSER_TEST_F(OzonePlatformTest, ExitsGracefullyOnPlatormInitFailure) {
  // This should never be hit.  The browser is expected to exit before entering
  // the test body.
  ASSERT_TRUE(false);
}

}  // namespace ui


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template when<Grammar, Fun *></title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../proto/reference.html#header.boost.proto.transform.when_hpp" title="Header <boost/proto/transform/when.hpp>">
<link rel="prev" href="when.html" title="Struct template when">
<link rel="next" href="when_Gra_1_3_34_5_52_2_1_5.html" title="Struct template when<Grammar, R(A...)>">

Home
Libraries
People
FAQ
More

Struct template when<Grammar, Fun *>

boost::proto::when<Grammar, Fun *> — A specialization that treats function pointer Transforms as if they
          were function type Transforms.

Synopsis

// In header: <boost/proto/transform/when.hpp>

template<typename Grammar, typename Fun>
struct when<Grammar, Fun *> :  proto::when< Grammar, Fun > {
};

Description

            This specialization requires that Fun is actually a function type.

            This specialization is required for nested transforms such as
            proto::when<G, T0(T1(_))>. In C++, functions that are used
            as parameters to other functions automatically decay to funtion pointer types. In other words, the
            type T0(T1(_)) is indistinguishable from
            T0(T1(*)(_)). This specialization is required to handle these
            nested function pointer type transforms properly.

Copyright © 2008 Eric Niebler

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
  items:{
        html:'<a href="https://help.rallydev.com/apps/2.0rc1/doc/#!/api/Rally.ui.cardboard.CardBoard">Hint!<a>'
    },

    launch: function() {
        var cardBoardConfig = {
            xtype: 'rallycardboard',
            types: ['User Story', 'Defect'],
            attribute: "ScheduleState",
            cardConfig:{
                xtype: 'customcard'
             },
            columns: [{
                xtype: 'rallycardboardcolumn',
                value: 'Defined'
            },
            {   xtype: 'rallycardboardcolumn',
                value: 'Completed'
            }]
         };

        this.add(cardBoardConfig);
    }
});