text:
package org.apache.sandesha2.storage.beans;

import org.apache.axis2.addressing.EndpointReference;
import org.apache.sandesha2.Sandesha2Constants;
import org.apache.sandesha2.util.Range;
import org.apache.sandesha2.util.RangeString;

/**
 * This bean is used at the sending side (of both server and client)
 * There is on object of this for each sequence.
 */

public class RMSBean extends RMSequenceBean {

	private static final long serialVersionUID = 7051201094510208784L;

	/**
	 * Comment for internalSequenceID
	 * This property is a unique identifier that can be used to identify the messages of a certain sequence.
	 * This is specially used by the sending side, since sequence id is not available in the begining.
	 * For the client side, indernal sequence id is a concantination of wsa:To and SEQUENCE_KEY (SEQUENCE_KEY can be set as a property).
	 * For the server side, this is the sequenceId of the incoming sequence.
	 */
	private String internalSequenceID;

	/**
	 * Comment for createSeqMsgID
	 * This is the message ID of the create sequence message.
	 */
	private String createSeqMsgID;

	/**
	 * The key that is used to store the CreateSequence message in the Message Storage.
	 * This is stored here, so that the CreateSequence message can be used as a reference when Sandesha
	 * want the generate new messages. (e.g. MakeConnection)
	 */
	private String createSequenceMsgStoreKey;

	/**
	 * This is stored here, so that the message pointed by this can be used as a reference when Sandesha
	 * want the generate new messages. (e.g. MakeConnection). Create sequence message could not be used
	 * here since it may be subjected to things like encryption.
	 */
	private String referenceMessageStoreKey;

	/**
	 * This is the last error that was encountered when sending a message
	 */
	private Exception lastSendError = null;

	/**
	 * The highest out message relates to message id
	 * Keeps track of the highest transmitted message
	 */
	private String highestOutRelatesTo = null;

	/**
	 * For out going sequences this gives the message ranges that were sent and that were successfully
	 * acked by the other end point.
	 */
	private RangeString clientCompletedMessages = null;

	private String transportTo;

	private String offeredEndPoint = null;
	private EndpointReference offeredEndPointEPR = null;

	private String offeredSequence = null;

	private String anonymousUUID = null;

	/**
	 * This is the timestamp of when the last error occured when sending
	 */
	private long lastSendErrorTimestamp = -1;

	/**
	 * The last Out message number
	 */
	private long lastOutMessage = 0;

	/**
	 * The Highest out message number
	 * Keeps track of the highest transmitted message
	 */
	private long highestOutMessageNumber = 0;

	/**
	 * The next sequence number to apply to the message
	 */
	private long nextMessageNumber = -1;

	/**
	 * Indicates that a terminate sequence message was added.
	 */
	private boolean terminateAdded = false;

	/**
	 * Indicates that a sequence has timed out.
	 */
	private boolean timedOut = false;

	/**
	 * Indicates the client has sent a close sequence
	 */
	private boolean sequenceClosedClient = false;

	/**
	 * The number of reply messages that we expect
	 */
	private long expectedReplies = 0;

	/**
	 * When sending a RM Protocol message from SandeshaClient if there isn't
	 * a SOAP version specified in the Options, this version will be used.
	 * .NET interop requires all messages to be sent with the same SOAP version.
	 */
	private int soapVersion;

	/**
	 * In WSRM Anon URI scenario, we may not want to terminate a perticular sequence until the CreateSequence has been received
	 * for the response side, other wise PollingManager will pause the polling process in termination and we will never be able
	 * to get the CS.
	 */
	private boolean terminationPauserForCS = false;
  	/**
	 * If this is set, the current sequence is not expected to auto terminate when all the acks are received.
	 * I.e. the user explicitly have to call for termination (using SandeshaClient).
	 */
	private boolean avoidAutoTermination = false;

	/**
	 * Flags that are used to check if the primitive types on this bean
	 * have been set. If a primitive type has not been set then it will
	 * be ignored within the match method.
	 */
	private int rmsFlags = 0;

	/**
	 * Indicates the reallocation state.  The states can be either:
	 * notReallocated - The bean hasn't been reallocated
	 * reallocated - The bean is to be reallocated
	 * ReallocatedBeanComplete - The bean was created for reallocation but is no longer needed as itself has been reallocated
	 * BeanUsedForReallocation - The bean was created for reallocation
	 * ReallocationFailed - The reallocation of this bean failed
	 */
	private int reallocated = Sandesha2Constants.WSRM_COMMON.NOT_REALLOCATED;

	/**
	 * Contains the internalSeqID of the seq that has sent the reallocated msgs
	 */
	private String internalSeqIDOfSeqUsedForReallocation = null;

	public static final int LAST_SEND_ERROR_TIME_FLAG = 0x00000001;
	public static final int LAST_OUT_MSG_FLAG         = 0x00000010;
	public static final int HIGHEST_OUT_MSG_FLAG      = 0x00000100;
	public static final int NEXT_MSG_NUM_FLAG         = 0x00001000;
	public static final int TERMINATE_ADDED_FLAG      = 0x00010000;
	public static final int TIMED_OUT_FLAG            = 0x00100000;
	public static final int SEQ_CLOSED_CLIENT_FLAG    = 0x01000000;
	public static final int ACKED_MESSAGES_FLAG       = 0x10000000;
	public static final int TERM_PAUSER_FOR_CS        = 0x00000002;
	public static final int EXPECTED_REPLIES          = 0x00000020;
	public static final int SOAP_VERSION_FLAG         = 0x00000200;
	public static final int REALLOCATED               = 0x00002000;

	public RMSBean() {
	}

	/**
	 * Constructor that copies all RMSBean values from the RMSBean supplied
	 * @param beanToCopy
	 */
	public RMSBean(RMSBean beanToCopy) {
		super(beanToCopy);
		 anonymousUUID = beanToCopy.getAnonymousUUID();
		 if (beanToCopy.getClientCompletedMessages() != null)
			 clientCompletedMessages = new RangeString(beanToCopy.getClientCompletedMessages());
		 createSeqMsgID = beanToCopy.getCreateSeqMsgID();
		 createSequenceMsgStoreKey = beanToCopy.getCreateSequenceMsgStoreKey();
		 expectedReplies = beanToCopy.getExpectedReplies();
		 highestOutMessageNumber = beanToCopy.getHighestOutMessageNumber();
		 highestOutRelatesTo = beanToCopy.getHighestOutRelatesTo();
		 internalSequenceID = beanToCopy.getInternalSequenceID();
		 lastOutMessage = beanToCopy.getLastOutMessage();
		 lastSendError = beanToCopy.getLastSendError();
		 lastSendErrorTimestamp = beanToCopy.getLastSendErrorTimestamp();
		 nextMessageNumber = beanToCopy.getNextMessageNumber();
		 offeredEndPoint = beanToCopy.getOfferedEndPoint();
		 offeredEndPointEPR = beanToCopy.getOfferedEndPointEPR();
		 offeredSequence = beanToCopy.getOfferedSequence();
		 referenceMessageStoreKey = beanToCopy.getReferenceMessageStoreKey();
		 sequenceClosedClient = beanToCopy.isSequenceClosedClient();
		 soapVersion = beanToCopy.getSoapVersion();
		 terminateAdded = beanToCopy.isTerminateAdded();
		 terminationPauserForCS = beanToCopy.isTerminationPauserForCS();
		 timedOut = beanToCopy.isTimedOut();
		 transportTo = beanToCopy.getTransportTo();
		 avoidAutoTermination = beanToCopy.isAvoidAutoTermination();
		 reallocated = beanToCopy.isReallocated();
		 internalSeqIDOfSeqUsedForReallocation = beanToCopy.getInternalSeqIDOfSeqUsedForReallocation();
	}

	public String getCreateSeqMsgID() {
		return createSeqMsgID;
	}

	public void setCreateSeqMsgID(String createSeqMsgID) {
		this.createSeqMsgID = createSeqMsgID;
	}

	public String getInternalSequenceID() {
		return internalSequenceID;
	}

	public void setInternalSequenceID(String internalSequenceID) {
		this.internalSequenceID = internalSequenceID;
	}

	public String getCreateSequenceMsgStoreKey() {
		return createSequenceMsgStoreKey;
	}

	public void setCreateSequenceMsgStoreKey(String createSequenceMsgStoreKey) {
		this.createSequenceMsgStoreKey = createSequenceMsgStoreKey;
	}

	public String getReferenceMessageStoreKey() {
		return referenceMessageStoreKey;
	}

	public void setReferenceMessageStoreKey(String referenceMessageStoreKey) {
		this.referenceMessageStoreKey = referenceMessageStoreKey;
	}

	public Exception getLastSendError() {
  	return lastSendError;
  }

	public void setLastSendError(Exception lastSendError) {
  	this.lastSendError = lastSendError;
  }

	public long getLastSendErrorTimestamp() {
  	return lastSendErrorTimestamp;
  }

	public void setLastSendErrorTimestamp(long lastSendErrorTimestamp) {
  	this.lastSendErrorTimestamp = lastSendErrorTimestamp;
  	this.rmsFlags |= LAST_SEND_ERROR_TIME_FLAG;
  }

	public long getLastOutMessage() {
  	return lastOutMessage;
  }

	public void setLastOutMessage(long lastOutMessage) {
  	this.lastOutMessage = lastOutMessage;
  	this.rmsFlags |= LAST_OUT_MSG_FLAG;
  }

	public long getHighestOutMessageNumber() {
  	return highestOutMessageNumber;
  }

	public void setHighestOutMessageNumber(long highestOutMessageNumber) {
  	this.highestOutMessageNumber = highestOutMessageNumber;
  	rmsFlags |= HIGHEST_OUT_MSG_FLAG;
  }

	public String getHighestOutRelatesTo() {
  	return highestOutRelatesTo;
  }

	public void setHighestOutRelatesTo(String highestOutRelatesTo) {
  	this.highestOutRelatesTo = highestOutRelatesTo;
  }

	public long getNextMessageNumber() {
  	return nextMessageNumber;
  }

	public void setNextMessageNumber(long nextMessageNumber) {
  	this.nextMessageNumber = nextMessageNumber;
  	rmsFlags |= NEXT_MSG_NUM_FLAG;
  }

	public RangeString getClientCompletedMessages() {
  	return clientCompletedMessages;
  }

	public void setClientCompletedMessages(RangeString clientCompletedMessages) {
  	this.clientCompletedMessages = clientCompletedMessages;
  }

	public boolean isTerminateAdded() {
  	return terminateAdded;
  }

	public void setTerminateAdded(boolean terminateAdded) {
  	this.terminateAdded = terminateAdded;
  	this.rmsFlags |= TERMINATE_ADDED_FLAG;
  }

	public boolean isTimedOut() {
  	return timedOut;
  }

	public void setTimedOut(boolean timedOut) {
  	this.timedOut = timedOut;
  	this.rmsFlags |= TIMED_OUT_FLAG;
  }

	public boolean isSequenceClosedClient() {
  	return sequenceClosedClient;
  }

	public void setSequenceClosedClient(boolean sequenceClosedClient) {
  	this.sequenceClosedClient = sequenceClosedClient;
  	this.rmsFlags |= SEQ_CLOSED_CLIENT_FLAG;
  }

	public long getNumberOfMessagesAcked() {
		long numberOfMessagesAcked = 0;
		if (clientCompletedMessages != null) {
			// Process this value based on the ClientCompletedMessages
			Range ranges[] = clientCompletedMessages.getRanges();

			for (int rangeIndex=0; rangeIndex < ranges.length; rangeIndex++) {
				Range range = ranges[rangeIndex];
				numberOfMessagesAcked = range.upperValue - range.lowerValue + 1;
			}
		}
  	return numberOfMessagesAcked;
  }

	public String getTransportTo() {
  	return transportTo;
  }

	public void setTransportTo(String transportTo) {
  	this.transportTo = transportTo;
  }

	public String getOfferedEndPoint() {
  	return offeredEndPoint;
  }

	public void setOfferedEndPoint(String offeredEndPoint) {
  	this.offeredEndPoint = offeredEndPoint;
  }

	public String getOfferedSequence() {
  	return offeredSequence;
  }

	public void setOfferedSequence(String offeredSequence) {
  	this.offeredSequence = offeredSequence;
  }

	public boolean isTerminationPauserForCS() {
		return terminationPauserForCS;
	}

	public void setTerminationPauserForCS(boolean terminationPauserForCS) {
		this.terminationPauserForCS = terminationPauserForCS;
  	this.rmsFlags |= TERM_PAUSER_FOR_CS;
	}

	public long getExpectedReplies() {
		return expectedReplies;
	}

	public void setExpectedReplies(long expectedReplies) {
		this.expectedReplies = expectedReplies;
		this.rmsFlags |= EXPECTED_REPLIES;
	}

	public String getAnonymousUUID() {
		return anonymousUUID;
	}

	public void setAnonymousUUID(String anonymousUUID) {
		this.anonymousUUID = anonymousUUID;
	}

	public boolean isAvoidAutoTermination() {
		return avoidAutoTermination;
	}

	public void setAvoidAutoTermination(boolean avoidAutoTermination) {
		this.avoidAutoTermination = avoidAutoTermination;
	}

	public int getSoapVersion() {
		return soapVersion;
	}

	public void setSoapVersion(int soapVersion) {
		this.soapVersion = soapVersion;
	}

	public int getRmsFlags() {
		return rmsFlags;
	}

	public void setRmsFlags(int rmsFlags) {
		this.rmsFlags = rmsFlags;
	}

	public String toString() {
		StringBuffer result = new StringBuffer();
		result.append(this.getClass().getName());
		result.append(super.toString());
		result.append("\nInternal Seq Id  : "); result.append(internalSequenceID);
		result.append("\nCreateSeq Msg Id : "); result.append(createSeqMsgID);
		result.append("\nCreateSeq Msg Key: "); result.append(createSequenceMsgStoreKey);
		result.append("\nReference Msg Key: "); result.append(referenceMessageStoreKey);
		result.append("\nLastOutMessageNumber: "); result.append(lastOutMessage);
		result.append("\nHighestOutMessage: "); result.append(highestOutMessageNumber);
		result.append("\nHighestOutRelatesTo: ");result.append(highestOutRelatesTo);
		result.append("\nNextMessageNumber: "); result.append(nextMessageNumber);
		result.append("\nTerminateAdded   : "); result.append(terminateAdded);
		result.append("\nTerminatePauser  : "); result.append(terminationPauserForCS);
		result.append("\nTimedOut         : "); result.append(timedOut);
		result.append("\nClosedClient     : "); result.append(sequenceClosedClient);
		result.append("\nExpectedReplies  : "); result.append(expectedReplies);
		result.append("\nTransportTo      : "); result.append(transportTo);
		if(offeredEndPointEPR != null){
			result.append("\nOfferedEndPoint  : "); result.append(offeredEndPointEPR.getAddress());
		} else {
			result.append("\nOfferedEndPoint  : null");
		}
		result.append("\nOfferedSequence  : "); result.append(offeredSequence);
		if (lastSendErrorTimestamp > 0) {
			result.append("\nLastError        : "); result.append(lastSendError);
			result.append("\nLastErrorTime    : "); result.append(lastSendErrorTimestamp);
		}
		result.append("\nClientCompletedMsgs: "); result.append(clientCompletedMessages);
		result.append("\nAnonymous UUID     : "); result.append(anonymousUUID);
		result.append("\nSOAPVersion  : "); result.append(soapVersion);
		result.append("\nReallocated  : "); result.append(reallocated);
		result.append("\nInternalSeqIDOfSeqUsedForReallocation  : "); result.append(internalSeqIDOfSeqUsedForReallocation);
		return result.toString();
	}

	public boolean match(RMBean matchInfo) {
		RMSBean bean = (RMSBean) matchInfo;
		boolean match = true;

		if(!super.match(matchInfo))
			match = false;

		else if(bean.getInternalSequenceID() != null && !bean.getInternalSequenceID().equals(this.getInternalSequenceID()))
			match = false;

		else if(bean.getCreateSeqMsgID() != null && !bean.getCreateSeqMsgID().equals(this.getCreateSeqMsgID()))
			match = false;

		else if(bean.getCreateSequenceMsgStoreKey() != null && !bean.getCreateSequenceMsgStoreKey().equals(this.getCreateSequenceMsgStoreKey()))
			match = false;

		else if(bean.getReferenceMessageStoreKey() != null && !bean.getReferenceMessageStoreKey().equals(this.getReferenceMessageStoreKey()))
			match = false;

// Avoid matching on the error information
//		else if(bean.getLastSendError() != null && !bean.getLastSendError().equals(this.getLastSendError()))
//			match = false;

		else if(bean.getHighestOutRelatesTo() != null && !bean.getHighestOutRelatesTo().equals(this.getHighestOutRelatesTo()))
			match = false;

		else if(bean.getClientCompletedMessages() != null && !bean.getClientCompletedMessages().equals(this.getClientCompletedMessages()))
			match = false;

		else if(bean.getTransportTo() != null && !bean.getTransportTo().equals(this.getTransportTo()))
			match = false;

		else if(bean.getOfferedEndPointEPR() != null && !bean.getOfferedEndPointEPR().getAddress().equals(this.getOfferedEndPointEPR().getAddress()))
			match = false;

		else if(bean.getOfferedEndPoint() != null && !bean.getOfferedEndPoint().equals(this.getOfferedEndPoint()))
			match = false;

		else if(bean.getOfferedSequence() != null && !bean.getOfferedSequence().equals(this.getOfferedSequence()))
			match = false;

		else if(bean.getAnonymousUUID() != null && !bean.getAnonymousUUID().equals(this.getAnonymousUUID()))
			match = false;

		else if((bean.getInternalSeqIDOfSeqUsedForReallocation() != null && !bean.getInternalSeqIDOfSeqUsedForReallocation().equals(this.getInternalSeqIDOfSeqUsedForReallocation())))
			match = false;

		else if((bean.rmsFlags & REALLOCATED) != 0 && bean.isReallocated() != this.isReallocated())
			match = false;

// Avoid matching on the error information
//		else if((bean.rmsFlags & LAST_SEND_ERROR_TIME_FLAG) != 0 && bean.getLastSendErrorTimestamp() != this.getLastSendErrorTimestamp())
//			match = false;

		else if((bean.rmsFlags & LAST_OUT_MSG_FLAG) != 0 && bean.getLastOutMessage() != this.getLastOutMessage())
			match = false;

		else if((bean.rmsFlags & HIGHEST_OUT_MSG_FLAG) != 0 && bean.getHighestOutMessageNumber() != this.getHighestOutMessageNumber())
			match = false;

		else if((bean.rmsFlags & NEXT_MSG_NUM_FLAG) != 0 && bean.getNextMessageNumber() != this.getNextMessageNumber())
			match = false;

		else if((bean.rmsFlags & TERMINATE_ADDED_FLAG) != 0 && bean.isTerminateAdded() != this.isTerminateAdded())
			match = false;

		else if ((bean.rmsFlags & SOAP_VERSION_FLAG) != 0 && bean.getSoapVersion() != this.getSoapVersion())
			match = false;

		else if((bean.rmsFlags & TIMED_OUT_FLAG) != 0 && bean.isTimedOut() != this.isTimedOut())
			match = false;

		else if((bean.rmsFlags & SEQ_CLOSED_CLIENT_FLAG) != 0 && bean.isSequenceClosedClient() != this.isSequenceClosedClient())
			match = false;

		else if((bean.rmsFlags & ACKED_MESSAGES_FLAG) != 0 && bean.getNumberOfMessagesAcked() != this.getNumberOfMessagesAcked())
			match = false;

		else if((bean.rmsFlags & TERM_PAUSER_FOR_CS) != 0 && bean.isTerminationPauserForCS() != this.isTerminationPauserForCS())
			match = false;

		else if((bean.rmsFlags & EXPECTED_REPLIES) != 0 && bean.getExpectedReplies() != this.getExpectedReplies())
			match = false;

		return match;
	}

	public int isReallocated() {
		return reallocated;
	}

	public void setReallocated(int reallocated) {
		this.reallocated = reallocated;
		this.rmsFlags |= REALLOCATED;
	}

	public String getInternalSeqIDOfSeqUsedForReallocation() {
		return internalSeqIDOfSeqUsedForReallocation;
	}

	public void setInternalSeqIDOfSeqUsedForReallocation(String internalSeqIDOfSeqUsedForReallocation) {
		this.internalSeqIDOfSeqUsedForReallocation = internalSeqIDOfSeqUsedForReallocation;
	}

	public EndpointReference getOfferedEndPointEPR() {
		return offeredEndPointEPR;
	}

	public void setOfferedEndPointEPR(EndpointReference offeredEndPointEPR) {
		this.offeredEndPointEPR = offeredEndPointEPR;
		this.offeredEndPoint = offeredEndPointEPR.getAddress();
	}

}


text:
/*
  load csv file in serial using cpp

  g++ serial.cpp
  ./a.out

  https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c
  https://stackoverflow.com/questions/2808398/easily-measure-elapsed-time
*/

#include <iostream>
#include <fstream>
#include <cstdio>
#include <chrono>
#include <vector>
#include <string>
#include <sstream>
#include <iomanip>

void ReadFile()
{
  // std::FILE *f = std::fopen("prices-split-adjusted.csv", "r");
  // if (!f)
  // {
  //   std::perror("failed to open file");
  // }
  // std::fclose(f);
  std::ifstream f("prices-split-adjusted.csv");
  if (!f.is_open())
  {
    std::perror("failed to open file");
  }
  std::string line;
  int i = 0;
  auto begin = std::chrono::steady_clock::now();
  while (std::getline(f, line))
  {
    i++;
  }
  auto end = std::chrono::steady_clock::now();

  std::cout << i << std::endl; // 851265
  std::chrono::duration<double> elapsed_seconds = end - begin;
  std::cout << "elapsed time: " << elapsed_seconds.count() << std::endl;
  std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::seconds>(end - begin).count() << std::endl;
  std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << std::endl;
  std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() << std::endl;
  f.close();
}

void ReadHeader()
{
  std::ifstream f("prices-split-adjusted.csv");
  if (!f.is_open())
  {
    std::perror("failed to open file");
  }

  std::string line;
  // FIXED: has incomplete type and cannot be defined
  // #include <sstream>
  std::stringstream line_stream;
  std::string cell;
  std::vector<std::string> header;
  std::vector<std::string> values;

  std::getline(f, line);
  std::cout << line << std::endl;
  line_stream << line;
  while (std::getline(line_stream, cell, ','))
  {
    header.push_back(std::move(cell));
  }
  for (const auto &h : header)
  {
    std::cout << h << std::endl;
  }
  // FIXED: you can't reuse the line stream, need to call clear()
  // https://www.eecis.udel.edu/~breech/progteam/stringstream.html
  std::getline(f, line);
  std::cout << line << std::endl;
  line_stream.clear();
  line_stream << line;
  while (std::getline(line_stream, cell, ','))
  {
    values.push_back(std::move(cell));
  }
  for (const auto &v : values)
  {
    // std::cout << v << std::endl;
    std::printf("%s\n", v.c_str());
  }
  // now let's infer the schema? or let the user specify it? ...
  // well let the user specify it ....
  // FIXME: it's 2016-01-05 00:00:00, but it seems the stream stop on blank ?
  // FIXED: it's the problem of Kaggle
  // prices.csv and prices-split-adjusted.csv use different time format ....
  // 2016-01-05
  std::tm tm;
  std::stringstream value_stream;
  value_stream << values[0];
  // http://en.cppreference.com/w/cpp/io/manip/get_time
  value_stream >> std::get_time(&tm, "%Y-%m-%d");
  // value_stream >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
  if (value_stream.fail())
  {
    std::cout << "failed to parse time" << std::endl;
  }
  else
  {
    // FIXME: ? Jan  5 1611344960:21939:1375664304 2016
    // TODO: get epoch
    std::cout << std::put_time(&tm, "%c") << std::endl;
  }
  // TODO: parse float, double etc.
  // http://en.cppreference.com/w/cpp/string/basic_string/stof
}

int main()
{
  std::cout << "Hello world" << std::endl;
  // ReadHeader();
  ReadFile();
  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
class EXPCL_PANDA_PGRAPH AsyncTaskCollection {
PUBLISHED:
  AsyncTaskCollection();
  AsyncTaskCollection(const AsyncTaskCollection &copy);
  void operator = (const AsyncTaskCollection &copy);
  INLINE ~AsyncTaskCollection();

  void add_task(AsyncTask *task);
  bool remove_task(AsyncTask *task);
  void add_tasks_from(const AsyncTaskCollection &other);
  void remove_tasks_from(const AsyncTaskCollection &other);
  void remove_duplicate_tasks();
  bool has_task(AsyncTask *task) const;
  void clear();

  AsyncTask *find_task(const string &name) const;

  int get_num_tasks() const;
  AsyncTask *get_task(int index) const;
  MAKE_SEQ(get_tasks, get_num_tasks, get_task);
  void remove_task(int index);
  AsyncTask *operator [] (int index) const;
  int size() const;
  INLINE void operator += (const AsyncTaskCollection &other);
  INLINE AsyncTaskCollection operator + (const AsyncTaskCollection &other) const;

  void output(ostream &out) const;
  void write(ostream &out, int indent_level = 0) const;

private:
  typedef PTA(PT(AsyncTask)) AsyncTasks;
  AsyncTasks _tasks;
};

INLINE ostream &operator << (ostream &out, const AsyncTaskCollection &col) {
  col.output(out);
  return out;
}

#include "asyncTaskCollection.I"

#endif


text:
"""
ldifcopy - reads LDIF from stdin, retrieve values by URL and
           write resulting LDIF to stdout

Written by Michael Stroeder <michael@stroeder.com>

$Id: ldifcopy.py,v 1.2 2001/12/12 22:04:49 stroeder Exp $

This example translates the naming context of data read from
input, sanitizes some attributes, maps/removes object classes,
maps/removes attributes., etc. It's far from being complete though.

Python compability note:
Tested on Python 2.0+, should run on Python 1.5.x.
"""

import sys,ldif

infile = sys.stdin
outfile = sys.stdout

ldif_collector = ldif.LDIFCopy(
  infile,
  outfile,
  process_url_schemes=['file','ftp','http']
)
ldif_collector.parse()


text:
namespace common {

namespace pcg = openvdb::math::pcg;

template<class ScalarGridT>
void Solver<ScalarGridT>::InitializePartition(const MetaGrid &metagrid) {
  metagrid_valid_ = true;
  metagrid_ = metagrid;
}  // InitializePartition

template<class ScalarGridT>
void Solver<ScalarGridT>::ResetVariables() {
  if (b_grid_) {
    b_grid_ = nullptr;
  }
  if (marker_) {
    marker_ = nullptr;
  }
  if (x_grid_) {
    x_grid_ = nullptr;
  }
  if (A_) {
    A_ = nullptr;
  }
  if (idx_) {
    idx_ = nullptr;
  }
  if (x_) {
    x_ = nullptr;
  }
  if (r_) {
    r_ = nullptr;
  }
}  // ResetVariables

template<class ScalarGridT>
void Solver<ScalarGridT>::SetVariablesForAssembly(
  ScalarGridInt *marker, ScalarGridT *b_grid, ScalarGridT *x_grid,
  ScalarGridVIdx *idx, LaplacianMatrix *A, VectorT *b, VectorT *x,
  PreconditionerT *M) {
  marker_ = marker;
  b_grid_ = b_grid;
  x_grid_ = x_grid;
  idx_    = idx;
  A_      = A;
  b_      = b;
  x_      = x;
  M_      = M;
}  // SetVariablesForAssembly

template<class ScalarGridT>
void Solver<ScalarGridT>::SetVariablesToCopySolution(
  VectorT *x, ScalarGridVIdx *idx, ScalarGridT *x_grid) {
  x_ = x;
  idx_ = idx;
  x_grid_ = x_grid;
}  // SetVariablesToCopySolution

template<class ScalarGridT>
void Solver<ScalarGridT>::InitializeMatrixVectorsAndPreconditioner() {
  InitializeMatrixAndVectors();
  BuildPreconditioner();
}  // InitializeMatrixVectorsAndPreconditioner

template<class ScalarGridT>
void Solver<ScalarGridT>::InitializeMatrixAndVectors() {
  CHECK(metagrid_valid_);
  CoordBBox box_interior = metagrid_.bbox();
  CoordBBox box_total = box_interior.expandBy(1);
  n_rows_ = marker_->Count(box_interior, FLUID);
  n_cols_ = marker_->Count(box_total, FLUID);
  ScalarGridBool local_mask;
  local_mask.InitializePartition(metagrid_, 1.f, false);
  CreateIndexAndMaskTree(local_mask);
  b_->Resize(n_rows_);
  CreateVectorFromGrid(*b_grid_, box_interior, *b_);
  x_->Resize(n_cols_);
  CreateVectorFromGrid(*x_grid_, box_total, *x_);
  A_->Resize(n_rows_, n_cols_);
  CreateLaplacianMatrix(local_mask);
}  // InitializeMatrixAndVectors

template<class ScalarGridT>
void Solver<ScalarGridT>::CopySolution() {
  x_grid_->Clear();
  CHECK(metagrid_valid_);
  CoordBBox box_interior = metagrid_.bbox();
  CreateGridFromVector(*x_, box_interior, *x_grid_);
}  // CopySolution

template<class ScalarGridT>
void Solver<ScalarGridT>::BuildPreconditioner() {
  if (preconditioner_type_ == IC) {
    M_->Reset(typename PreconditionerT::PreconditionerT::Ptr(new pcg::
      IncompleteCholeskyPreconditioner<typename LaplacianMatrix::MatrixT>(
        *(A_->data()))));
  } else {
    M_->Reset(typename PreconditionerT::PreconditionerT::Ptr(new pcg::
      JacobiPreconditioner<typename LaplacianMatrix::MatrixT>(
        *(A_->data()))));
  }
}  // BuildPreconditioner

template<class ScalarGridT>
void Solver<ScalarGridT>::CreateIndexAndMaskTree(ScalarGridBool &local_mask) {
  CHECK(metagrid_valid_);
  // Create/initialize idx tree.
  idx_->InitializePartition(metagrid_);
  CoordBBox box_interior = metagrid_.bbox();
  CoordBBox box_total = box_interior.expandBy(1);
  const Coord start_interior = box_interior.min();
  const Coord end_interior   = box_interior.max();
  const Coord start_total = box_total.min();
  const Coord end_total   = box_total.max();
  int used_interior = 0;
  int used_exterior = n_rows_;
  for (int i = start_total[0]; i <= end_total[0]; ++i) {
    for (int j = start_total[1]; j <= end_total[1]; ++j) {
      for (int k = start_total[2]; k <= end_total[2]; ++k) {
        Coord ijk(i,j,k);
        if ( !((marker_->isOn(ijk)) && (marker_->get(ijk) == FLUID)) ) {
          continue;
        }
        if (i >= start_interior[0] && i <= end_interior[0] &&
            j >= start_interior[1] && j <= end_interior[1] &&
            k >= start_interior[2] && k <= end_interior[2]) {
          assert(used_interior < n_rows_);
          idx_->set(ijk, used_interior);
          local_mask.set(ijk, true);
          used_interior++;
        } else {
          assert(used_exterior < n_cols_);
          idx_->set(ijk, used_exterior);
          used_exterior++;
        }
      }  // for k
    }  // for j
  }  // for i
  CHECK_EQ(used_interior, n_rows_);
  CHECK_EQ(used_exterior, n_cols_);
}  // CreateIndexAndMaskTree

template<class ScalarGridT>
void Solver<ScalarGridT>::CreateVectorFromGrid(
  const ScalarGridT &grid, const CoordBBox box, VectorT &vector) {
  auto data = vector.data();
  const Coord start = box.min();
  const Coord end = box.max();
  for (int i = start[0]; i <= end[0]; ++i) {
    for (int j = start[1]; j <= end[1]; ++j) {
      for (int k = start[2]; k <= end[2]; ++k) {
        Coord ijk(i,j,k);
        if (!idx_->isOn(ijk)) {
          continue;
        }
        VIndex index = idx_->get(ijk);
        CHECK(index < data->size());
        assert(index < data->size());
        data->at(index) = grid.get(ijk);
      }  // for k
    }  // for j
  }  // for i
}  // CreateVectorFromGrid

template<class ScalarGridT>
void Solver<ScalarGridT>::CreateGridFromVector(
  const VectorT &vector, const CoordBBox box, ScalarGridT &grid) {
  const typename VectorT::VectorT::Ptr data = vector.const_data();
  const Coord start = box.min();
  const Coord end = box.max();
  for (int i = start[0]; i <= end[0]; ++i) {
    for (int j = start[1]; j <= end[1]; ++j) {
      for (int k = start[2]; k <= end[2]; ++k) {
        Coord ijk(i,j,k);
        if (!idx_->isOn(ijk)) {
          continue;
        }
        VIndex index = idx_->get(ijk);
        CHECK(index < data->size());
        assert(index < data->size());
        grid.set(ijk, data->at(index));
      }  // for k
    }  // for j
  }  // for i
}  // CreateGridFromVector

template<class ScalarGridT>
void Solver<ScalarGridT>::CreateLaplacianMatrix(
  const ScalarGridBool &local_mask) {
  auto data = A_->data();
  typedef pcg::SizeType SizeType;
  const int num_offsets = 6;
  Coord offsets[num_offsets] = { Coord(-1,0,0), Coord(1,0,0),
                                 Coord(0,-1,0), Coord(0,1,0),
                                 Coord(0,0,-1), Coord(0,0,1) };
  for (typename ScalarGridBool::GridT::ValueOnCIter iter =
       local_mask.const_data()->cbeginValueOn(); iter.test(); ++iter) {
    const Coord ijk = iter.getCoord();
    const VIndex row_id = idx_->get(ijk);
    CHECK(row_id < n_rows_);
    CHECK_EQ(marker_->get(ijk), FLUID);
    assert(row_id < n_rows_);
    assert(marker_->get(ijk) == FLUID);
    T diagonal = 0;
    typename LaplacianMatrix::MatrixT::RowEditor row =
      data->getRowEditor(row_id);
    for (int n = 0; n < num_offsets; ++n) {
      const Coord nbr = ijk + offsets[n];
      const int nbr_marker = marker_->get(nbr);
      if (nbr_marker == FLUID || nbr_marker == AIR) {
        // Add 1 to diagonal.
        diagonal += 1;
      }
      if (nbr_marker == FLUID) {
        assert(idx_->isOn(nbr));
        // Set off-diagonal to -1.
        row.setValue(idx_->get(nbr), -1);
      }
    }  // for n < num_offsets
    // Set diagonal.
    row.setValue(row_id, diagonal);
  }  // for iter
}  // CreateLaplacianMatrix

template<class ScalarGridT>
void PCGSolver<ScalarGridT>::ResetVariables() {
  Solver<ScalarGridT>::ResetVariables();
  if (p_) {
    p_ = nullptr;
  }
  if (z_) {
    z_ = nullptr;
  }
  if (Ap_) {
    Ap_ = nullptr;
  }
}  // ResetVariables

template<class ScalarGridT>
void PCGSolver<ScalarGridT>::SetVariablesToPreparePCGSolver(
  LaplacianMatrix *A, PreconditionerT *M, VectorT *b, VectorT *x,
  VectorT *r, VectorT *p, VectorT *z) {
  Base::A_ = A;
  Base::b_ = b;
  Base::x_ = x;
  Base::r_ = r;
  Base::M_ = M;
  p_ = p;
  z_ = z;
}  // SetVariablesToPreparePCGSolver

template<class ScalarGridT>
void PCGSolver<ScalarGridT>::PreparePCGSolver() {
  Base::r_->Resize(Base::n_rows_);
  z_->Resize(Base::n_rows_);
  p_->Resize(Base::n_cols_);
  auto A = Base::A_->data();
  auto x = Base::x_->data();
  auto b = Base::b_->data();
  auto M = Base::M_->data();
  auto r = Base::r_->data();
  auto z = z_->data();
  auto p = p_->data();
  // r = b - Ax
  pcg::internal::computeResidual(*A, *x, *b, *r);
  // z = M_inv r
  M->apply(*r, *z);
  // p = z (p and z have different sizes)
  for (int i = 0; i < Base::n_rows_; ++i) {
    p->at(i) = z->at(i);
  }
  // rz = r'z
  rz_ = r->dot(*z);
  // rr = r'r
  rr_ = r->dot(*r);
}  // PrepareCGSolver

template<class ScalarGridT>
void PCGSolver<ScalarGridT>::SetVariablesForComputeLocal1(
  LaplacianMatrix *A, VectorT *p, VectorT *Ap) {
  Base::A_ = A;
  p_  = p;
  Ap_ = Ap;
}  // SetVariablesForComputeLocal1

template<class ScalarGridT>
void PCGSolver<ScalarGridT>::ComputeLocal1() {
  Ap_->Resize(Base::n_rows_);
  auto A = Base::A_->data();
  auto p = p_->data();
  auto Ap = Ap_->data();
  // Ap = Ap
  A->vectorMultiply(*p, *Ap);
  pAp_ = 0;
  // pAp = p'Ap (p and AP have different sizes)
  for (int i = 0; i < Base::n_rows_; ++i) {
    pAp_ += p->at(i)*Ap->at(i);
  }
}  // ComputeLocal1

template<class ScalarGridT>
void PCGSolver<ScalarGridT>::SetVariablesForComputeLocal2(
  VectorT *x, VectorT *p, VectorT *r, VectorT *Ap,
  PreconditionerT *M, VectorT *z) {
  Base::x_ = x;
  p_ = p;
  Base::r_ = r;
  Ap_ = Ap;
  Base::M_ = M;
  z_ = z;
}  // SetVariablesForComputeLocal2

template<class ScalarGridT>
void PCGSolver<ScalarGridT>::ComputeLocal2() {
  auto &x  = *(Base::x_->data());
  auto &p  = *(p_->data());
  auto &r  = *(Base::r_->data());
  auto &Ap = *(Ap_->data());
  auto &M  = *(Base::M_->data());
  auto &z  = *(z_->data());
  // alpha = rz/pAp
  T alpha = rz_/pAp_;
  CHECK_LE(alpha, LARGE_FLOAT);
  // x = x + alpha * p
  pcg::internal::axpy(alpha, p, x, x);
  // r = r - alpha * Ap
  pcg::internal::axpy(-alpha, Ap, r, r);
  // z = M_inv * r
  M.apply(r, z);
  // rr = r r'r
  rr_ = r.dot(r);
  // rz_old = rz
  rz_old_ = rz_;
  // rznew = r'z
  rz_ = r.dot(z);
}  // ComputeLocal2

template<class ScalarGridT>
void PCGSolver<ScalarGridT>::SetVariablesForComputeLocal3(
  VectorT *p, VectorT *z) {
  p_ = p;
  z_ = z;
}  // SetVariablesForComputeLocal3

template<class ScalarGridT>
void PCGSolver<ScalarGridT>::ComputeLocal3() {
  auto &p = *(p_->data());
  auto &z = *(z_->data());
  // beta = rz/rz_old
  T beta = rz_/rz_old_;
  CHECK_LE(beta, LARGE_FLOAT);
  // p = z + beta * p (p and z have different sizes)
  for (int i = 0; i < Base::n_rows_; ++i) {
    p[i] = z[i] + beta * p[i];
  }
}  // ComputeLocal3

template class Solver< ScalarGrid<3, 3, float> >;
template class Solver< ScalarGrid<3, 3, double> >;

template class PCGSolver< ScalarGrid<3, 3, float> >;
template class PCGSolver< ScalarGrid<3, 3, double> >;

}  // namespace common


text:
/**
 * @requires window.jQuery
 *
 * @fileOverview
 * Telepix banner ad manager. Inserts Google DFP premium ad tags into the calling page.
 *
 * Auto-discovery mode by default, set selector containing ad containers, attach data- attributes, and let
 * buildSlots() find all the ad containers.  Once slots are set up, a call to showAds() will tell google to queue the ads
 * in all discovered containers.  subsequent showAds() calls will queue ads from new containers, as well as any
 * which contain the data-refresh="true" attribute
 *
 * Programmatic mode (can be combined with auto-discovery mode) allows programmatic insertion of slots as well as
 * custom global targeting and targeting for existing/new slots.  subsequent calls to showAds() are still required
 * to update any created/modified slots
 *
 * @see google's official documentation
 *
 * @usage wbads.init( '4321', 'Mysite', 'Myzone', { debug_enabled: true }, { collapse_empty_divs: true, global_targeting: { category: "kids" } });
 *          ...discovery method...
 *     <insert empty divs in body where ads go, using class="[insert selector here]">
 *          ...and/or programmatic method...
 *          wbads.addSlot()
 *          wbads.addSlotTargeting()
 *          ...after all ads defined...
 *     wbads.buildSlots();
 *     wbads.showAds();
 */
/*** BEGIN REQUIRED GOOGLE DFP PREMIUM AD CODE ***/
if( typeof googletag === "undefined" ){ // todo: check this syntax
    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
    (function() {
        var gads = document.createElement('script');
        gads.async = true;
        gads.type = 'text/javascript';
        var useSSL = 'https:' == document.location.protocol;
        gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';
        var node = document.getElementsByTagName('script')[0];
        node.parentNode.insertBefore(gads, node);
    })();
}
/*** END REQUIRED GOOGLE DFP PREMIUM AD CODE ***/

wbads = (function($, window, document, undefined) {
    'use strict';

    var _this = Object.create({});
    var settings;
    var dfp_settings;

    /** @type {string} unit_name - calculated from <tt>required_params</tt> */
    var unit_name       = "",
        required_params = {
            site_id:       "",
            site_domain:   "",
            ad_zone:       ""
        };

    var module_defaults  = {
        /** @type {boolean} enabled - if false, ads won't render */
        enabled:            true,
        debug_enabled:      false,
        device_view:        "main",
        selector:           "tpixads-container",
        data_store:         "tpixadData",
        evt_callbacks:      {
            onBeforeInit:           null,
            onAfterInit:            null,
            onBeforeEnableServices: null,
            onAfterEnableServices:  null,
            onBeforeSlotDiscovery:  null,
            onAfterSlotDiscovery:   null,
            onBeforeDefineSlot:     null,
            onAfterDefineSlot:      null,
            onBeforeDisplayAds:     null,
            onAfterDisplayAds:      null
        },
        quantcast:          {
            enabled:                true,
            qacct:                  "p-21jBY4_vbHNJQ",
            segs:                   ""
        }
    };

    /** @type {object} dfp_options - page-wide options to pass to the google ad service */
    var dfp_defaults     = {
            collapse_empty_divs:        false,
            disable_initial_load:       false,  // If webpage has an auto-play video player, set this to true
            enable_single_request:      false,
            enable_async_rendering:     true,
            enable_video_ads:           false,
            no_fetch:                   false,
            disable_publisher_console:  false,
            category_exclusion:         [],     // array of categories
            /**
             * qcs : The format should be ['####', '####', '####', 'etc']
             * category : channel from cf
             * tag : hashtags from cf
             * url : the URL of the page after .com. eg ellentv.com/photos the url value should be ['/photos']
             * adtest : if "?adtest=keyword" appended to URL then pass ['keyword'] as value
             */
            global_targeting:           {
                qcs:                    {},
                category:               "",
                channel:                "", /** duplicate of category for consistency */
                tag:                    [],
                url:                    "",
                adtest:                 ""
            } /** todo: consider removing these explicit defs but they don't hurt */
    };

    var bindableEvents = [
        "pre.init",
        "post.init",
        "pre.enable.services",
        "post.enable.services",
        "pre.slot.discovery",
        "post.slot.discovery",
        "pre.slot.define",
        "post.slot.define",
        "pre.display.ads",
        "post.display.ads"
    ];

    /** @type {Array} tpixadslots - array of created local slot objects */
    var tpixadslots     = [],
        slot_count      = 0;

    /** @type {object}
     * todo: find out if adops even has device-specific size mappings
     */
    var ad_sizes_list = {
        main: {
            leaderboard: [[728,90]],
            leaderboard_flex: [[970,250],[970,66],[1010,150],[1010,250],[728,90]],
            medium_rectangle: [[300,250]],
            medium_rectangle_flex: [[300,250],[300,600]],
            skin: [[1,1]]
        },
        /**
         * todo: make responsive via google's sizeMapping()/defineSizeMapping()/addSize() methods
         */
        smartphone: {
            leaderboard: [[320,50]],
            leaderboard_flex: [[300,250],[320,50]],
            leaderboard_all: [[1,1],[300,250],[320,50],[320,360],[320, 480]],
            medium_rectangle: [[300,250]],
            medium_rectangle_flex: [[300,250],[300,600]],
            skin: [[1,1]]
        }
    };

    /**
     * @constructor
     * locally stored slot object instance
     */
    function Slot(id,gptslot) {
//        debug("Slot :: creating AD SLOT OBJECT with id:" + id);

        this.div_id             = id;
        this.gpt_slot_object    = gptslot;   /** the googletag slot object */
        this.slot_data = {
            tile:               "",
            size_list:          "",
            size_nickname:      "",
            interstitial:       false,
            refresh:            false,
            /**
             * eg. { "interests": ["sports", "music", "movies"], "pos": ["atf"], "age": "20-30"] }
             * then eg. slot1.setTargeting( "pos", ["atf"] ).setTargeting( "age", "20-30" );
             */
            slot_targeting:     [],
            /**
             * eg.  addSize( [browser-size], [[ad-size1],..,[ad-sizeN]] )...
             *   var mapping = googletag.sizeMapping().
             *   addSize([1024, 768], [970, 250]).  // desktop
             *   addSize([980, 690], [728, 90]).    // ipad
             *   addSize([640, 480], [120, 60]).    // mobile
             *   addSize([0, 0], [88, 31]).         // Fits browsers of any size smaller than 640 x 480
             *   build();
             *   adSlot.defineSizeMapping(mapping);
             */
            responsive_size_map: {

            },
            /**
             * values for AdSense parameters on a particular ad slot.
             * These will override any values set at the service level for this key.
             * All values must be set before any display call.
             * eg. slot.set("adsense_background_color", "#FFFFFF");
             * @see {@link https://support.google.com/dfp_premium/answer/1650154?expand=pubservice_details#set} for full list
             */
            adsense_params:     {

            }
        };

//        debug("Slot :: AD SLOT OBJECT created with id:" + id);
    }

    /**
     * Stores values for targeting keys and slot parameters on a particular ad slot.
     * these will be applied when the slot is processed and added to google pubads service
     * @param key
     * @param value
     */
    Slot.prototype.setTargetingParam = function(key, value) {
//        debug("setTargetingParam :: setting param[" + key + "] = " + value + "...");

        /** todo: validate key/value before continuing */

        /** todo: change to key as index */
        /** without checking existence this.slot_data.slot_targeting[key] = value ("set" means overwrite if exists) */

        this.slot_data.slot_targeting[key] = value;
        debug("setTargetingParam :: ...slot_targeting[" + key + "] set to " + this.slot_data.slot_targeting[key]);

        return this;
    };

    /**
     * define and attach the responsive size map
     * @param browserSize
     * @param adSizeList
     */
    Slot.prototype.addSlotSizeMapping = function(browserSize, adSizeList) {

        /** todo: set responsive size mapping  */

    };

    /**
     *  todo consider supporting any helpful SLOT-specific methods such as...
     *  addService(service)
     *  Adds the ad slot to the specified Google tag service.
     *
     *  clearTargeting()
     *  Clears all slot-level targeting for a particular ad slot.
     *
     *  set(key, value)
     *  Sets values for AdSense parameters on a particular ad slot.
     *
     *  setClickUrl(url)
     *  Sets the redirect URL for a click on an ad in a particular slot. The DoubleClick servers still record a click even if the click URL is replaced, but any landing page URL associated with the creative that is served is overridden.
     *
     *  setCollapseEmptyDiv(collapse, collapseBeforeAdFetch [optional])
     *  Specifies a slot-specific override to the page-wide div collapse behavior that was specified through pubService.collapseEmptyDivs().
     *
     *  setTargeting(key, value)
     *  Sets values for targeting keys on a particular ad slot.
     */

    /*
     * sets up the config object. (to be called explicitly from the page ie wbads.init('8310','Ellen','Homepage') )
     * @param {string} site_id a code provided by AdOps representing the site / partner
     * @param {string} site_domain a code provided by AdOps representing the specific site subdomain
     * @param {string} ad_zone a code representing the current page section NOTE: 1st 3 required_params will be combined to form a unit_name
     * @param {object} options module-specific settings, default-overrides
     * @param {object} dfp_options googledfp-specific settings, default-overrides
     * eg like... init("55123377", "ellen", "home", { debug_enabled: true }, {} )
     *
     */
    function init(site_id, site_domain, ad_zone, options, dfp_options) {
        settings = $.extend({}, module_defaults, options);
        dfp_settings = $.extend({}, dfp_defaults, dfp_options);

        /** if req'd params invalid or missing, or if !settings.enabled, nothing can happen */
        /** these parameters combined form the networkId */
        /** todo: optimize combine 3 calls with && */
        settings.enabled = setRequiredParam("site_id", site_id);
        settings.enabled = setRequiredParam("site_domain", site_domain);
        settings.enabled = setRequiredParam("ad_zone", ad_zone);
        unit_name = "/" + getRequiredParam("site_id") + "/" + getRequiredParam("site_domain") + "/" + getRequiredParam("ad_zone");

        if(!settings.enabled) {
            debug("init :: TPIXADS ads disabled. no ad slots will be created or displayed");
            return;
        }

        /** bind any passed-in/default callbacks before any events can fire */
        $.each(settings.evt_callbacks, function(name, func) {
            debug("init :: binding callback defined for " + name + "...");
            defineCallback(name, func);
        });

        trigger("pre.init");
        /** note: set quantcast (qcs) prior to processing globalTargetingParams */
        if( settings.quantcast.enabled ) {
            embedQuantCastDeliveryTag();
            embedQuantCastMeasurementTag();
        }
        getGlobalTargetingParams(); /** todo: move this to callback for onBeforeInit */

        /** todo: move this to function set global options (including targting options) */
        /** pass global options to google object */
        googletag.cmd.push( function() {
            /** todo: consider moving all but enableServices to the onBeforeInit callback */
            if( dfp_settings.collapse_empty_divs ) googletag.pubads().collapseEmptyDivs();
            if( dfp_settings.disable_initial_load ) googletag.pubads().disableInitialLoad();
            if( dfp_settings.enable_single_request ) googletag.pubads().enableSingleRequest();
            /** async is the default, but it doesn't hurt to set explicitly here */
            if( dfp_settings.enable_async ) googletag.pubads().enableAsyncRendering();
            if( dfp_settings.enable_video_ads ) googletag.pubads().enableVideoAds();
            /** noFetch processes the JavaScript but does not make any HTTP calls for ad slot contents. */
            if( dfp_settings.no_fetch ) googletag.pubads().noFetch();
            /** Disables the Google Publisher Console */
            if( dfp_settings.disable_publisher_console ) googletag.pubads().disablePublisherConsole();

            /** pass valid global targeting options thru */
            $.each(dfp_settings.global_targeting, function( key, value ) {
                if( value && value != '' ) {
                    googletag.pubads().setTargeting(key, value);
                    debug("init :: setting global param[" + key + "]=" + value);
                }
            });

            /** todo: add support for category exclusion */

            trigger("pre.enable.services");
            googletag.enableServices();
            trigger("post.enable.services");
        });
        trigger("post.init");
    }

    /**
     * programmatically add callback binding
     * @param {string} eventRef - must be a predefined EVENT or CALLBACK nickname {eg pre.init or onBeforeInit}
     * @param {string} eventBinding - must be a valid function
     */
    function defineCallback( eventRef, eventBinding ) {
        var eventName = eventRef;

        if($.isFunction(eventBinding)) {
            bind(eventName, eventBinding);
        } else {
            debug("defineCallback :: " + eventBinding + " must be a valid function...ABORTING");
        }
    }

    /**
     * Sets values for DFP options that apply globally
     * IMPORTANT NOTE: these must be set prior to enableServices
     * @param {string} option - the option to turn on or off
     * @param {boolean} enabled - true or false
     * */
    function setGlobalOption( option, enabled ) {
        if (typeof dfp_settings === "undefined") {
            defineCallback("pre.init", function(){ setGlobalOption( option, enabled ); });
            return;
        }

        /** only allow from preset list at this time */
        if( typeof dfp_settings[option] !== 'undefined' ) {
            dfp_settings[option] = enabled;
            debug("setGlobalOption :: " + option + " set to: " + dfp_settings[option]);
        } else {
            debug("setGlobalOption :: No such option: " + option + " ...ABORTING! ");
        }
    }

    /**
     * Sets values for targeting keys that apply to all pubService ad slots.
     * IMPORTANT NOTE: these must be set prior to wbads.init()
     */
    function setGlobalTargetingParam( param, value ) {
        if (typeof dfp_settings === "undefined") {
            defineCallback("pre.init", function(){ setGlobalTargetingParam( param, value ); });
            return;
        }
        dfp_settings.global_targeting[param] = value;
        debug("setGlobalTargetingParam :: param " + param + " set to: " + dfp_settings.global_targeting[param]);
    }

    /**
     * use local methods to determine each optional global param
     */
    function getGlobalTargetingParams() {
        debug("getGlobalTargetingParams :: begin...");

        dfp_settings.global_targeting["url"] = getUriPaths();
        dfp_settings.global_targeting["qcs"] = getQCSegs();
        /** info: this is because adops uses a different terminology than we do, storing both doesn't hurt */
        dfp_settings.global_targeting["category"] = dfp_settings.global_targeting["channel"] = getChannel();
        getHashtags();
        dfp_settings.global_targeting["adtest"] = getParamFromUri("adtest");

        debug("getGlobalTargetingParams :: ...done");
    }

    /**
     * auto-discover all potential slots via the selector, and call defineNewAdSlot on each candidate
     * NOTE: this is not called by init, must be kicked off explicitly by calling page
     */
    function buildSlots() {
        trigger("pre.slot.discovery");

        if(!settings.enabled) {
            debug("buildSlots :: TPIXADS ads disabled. no ad slots will be created or displayed");
            return;
        }

        debug("buildSlots :: TPIXADS ad container discovery...");
        /** find all tpixads ad containers on the page */
        var dfpContainersCount =  0;
        $("."+settings.selector).each( function(ac) {
            dfpContainersCount++;
            var adDiv = $(this);
            defineNewAdSlot(adDiv, null, null, false, false);
        });
        debug("buildSlots :: ...TPIXADS ad container discovery found and created " + dfpContainersCount + " ads");
        trigger("post.slot.discovery");
    }

    /**
     * create a new slot sometime after (or in lieu of) buildSlots()
     * supports js programmatic slot building and populating
     * @param {string} divId div ID of existing ad container to convert to ad slot
     * @param {string} sizeType [optional] - nickname for preset size
     * @param {string} sizeList [optional] - explicit comma-separated WxH pairs eg. "300x250,320x50"
     * @param {boolean} interstitial [optional] - true if this is out-of-page slot
     * @param {boolean} refresh [optional] - true if this slot repopulates with each call to showAds()
     * @returns {boolean} successful add
     */
    function addSlot(divId, sizeType, sizeList, interstitial, refresh) {
        if(!settings.enabled) {
            debug("addSlot :: TPIXADS ads disabled. no ad slots will be created or displayed");
            return false;
        }

        /** find ad container on the page and extract data */
        var adDiv = $('#'+divId);
        if( null === adDiv ) {
            debug("addSlot :: no adDiv exists! ABORTING.");
            return false;
        }
        defineNewAdSlot(adDiv, sizeType, sizeList, interstitial, refresh);

        debug("addSlot :: googletag slot[" + divId + "] added");
        return true;
    }

    /**
     * Sets values for targeting keys that apply to a SPECIFIC ad slot.
     * NOTE: must be called prior to any display commands
     * @param {string} slotDivId - the DOM id of the slot to update (eg. "dfp-tpixad-1")
     * @param {string} param - the param to set
     * @param {string} value - the value to set for the given param
     * @returns {boolean} success/fail of finding slot and setting param
     */
    function setSlotTargetingParam( slotDivId, param, value ) {
        debug("setSlotTargetingParam :: setting slot[" + slotDivId + "] param " + param + " to: " + value);
        /** @type {Object} */
        var localSlot = getSlotById(slotDivId);

        if( !localSlot ) {
            debug("setSlotTargetingParam :: slot[" + slotDivId + "] does not exist...ABORTING");
            return false;
        }

        localSlot.setTargetingParam(param, value);
        debug("setSlotTargetingParam :: SUCCESS - slot[" + slotDivId + "]." + param + "=" + localSlot.slot_data.slot_targeting[param]);
        return true;
    }

    /**
     * @param {string} adDiv div ID of container
     * @param {string} sizeType [optional] - nickname for preset size
     * @param {string} sizeList [optional] - explicit comma-separated WxH pairs eg. "300x250,320x50"
     * @param {boolean} interstitial [optional] - true if this is an out-of-page slot
     * @param {boolean} refresh
     * @returns {boolean} successful create
     */
    function defineNewAdSlot(adDiv, sizeType, sizeList, interstitial, refresh) {
        if( null === adDiv ) {
            debug("defineNewAdSlot :: no adDiv exists! ABORTING.");
            return false;
        }

        /** actual slot definition is queued.
         * _required_ data is stored now {id, sizing, interstitial}
         */
        trigger("pre.slot.define");
        googletag.cmd.push(function() {
            var newAdSlot;
            var existingAdData = adDiv.data(settings.data_store);
            var divId = generateId(adDiv);
            var slotUnit = unit_name;
            if( existingAdData ) {
                debug("defineNewAdSlot :: updating existing slot with id:" + divId);
                newAdSlot = existingAdData;
            } else {
//                debug("defineNewAdSlot :: creating new slot with id:" + divId);

                /**
                 * get an index into the adsizes map
                 * but allow for adHoc override via size arg
                 */
                var adSizeType = sizeType || adDiv.data('adsize');
                var adSizeList = sizeList || adDiv.data('adsize-list');
                var isInterstitial = (interstitial ? true : adDiv.data('interstitial')) || false;
                if( adSizeType == 'skin' ) {
                    slotUnit += '/skin';
                }
                var refreshable = (refresh ? true : adDiv.data('refresh')) || false;
                debug("defineNewAdSlot :: type:" + adSizeType + ", list:" + adSizeList + ", interstitial:" + isInterstitial + ", refreshable:" + refreshable );

                /**
                 * out-of-page slots have no size
                 */
                if( !isInterstitial ) {
                    var dfpAdSizes;
                    if( adSizeList ) {
                        debug("defineNewAdSlot :: using adhoc size:" + adSizeList );
                        dfpAdSizes = getSizesFromString(adSizeList);
                    } else if( adSizeType && ad_sizes_list[settings.device_view][adSizeType]) {
                        dfpAdSizes = ad_sizes_list[settings.device_view][adSizeType];
                        debug("defineNewAdSlot :: using sizetype:" + adSizeType );
                    } else {
                        debug("defineNewAdSlot :: NO VALID SIZES FOUND. will expand to element size by default");
                    }
                    newAdSlot = googletag.defineSlot(slotUnit, dfpAdSizes, divId).addService(googletag.pubads());
                    if( dfp_settings.enable_single_request ) {
                        adDiv.data('unfilled', true);
                        defineCallback( "pre.display.ads", function() {
                            if( !adDiv.data('registered') ) {
                                googletag.cmd.push( function() {
                                    googletag.display(divId); // just register the slot in non SRA mode
                                    adDiv.data('registered', true);
                                    debug("defineNewAdSlot :: pushing " + divId + " SRA display to cmd queue");
                                });
                            }
                        });
                    }
                    debug("defineNewAdSlot :: googletag slot[" + divId + "] defined");
                } else {
                    if( adDiv.data('pos') == 'prestitial' ) {
                        slotUnit += '/prestitial';
                    } else {
                        slotUnit += '/interstitial';
                    }
                    /** note: these out-of-page slots have no size, but take up block-space if empty, so force collapse */
                    newAdSlot = googletag.defineOutOfPageSlot(slotUnit, divId).addService(googletag.pubads()).setCollapseEmptyDiv(true);
                    if( dfp_settings.enable_single_request ) {
                        adDiv.data('unfilled', true);
                        defineCallback( "pre.display.ads", function() {
                            if( !adDiv.data('registered') ) {
                                googletag.cmd.push( function() {
                                    googletag.display(divId); // just register the slot in non SRA mode
                                    adDiv.data('registered', true);
                                    debug("defineNewAdSlot :: pushing OutOfPageSlot " + divId + " SRA display to cmd queue");
                                });
                            }
                        });
                    }
                    debug("defineNewAdSlot :: googletag out-of-page slot[" + divId + "] defined");

                    /** update the DOM element data with programmatic option */
                    adDiv.data('interstitial', true);
                }

                /** update the DOM element data with programmatic option */
                if( refreshable ) {
                    adDiv.data('refresh', true);
                    debug("defineNewAdSlot :: this slot will REFRESH with each showAds()")
                }

                /** store new object using divId as indexable id where it can be further modified */
                tpixadslots[divId] = new Slot(divId, newAdSlot);
            }

            /** @type {object} get the tpixadslot in context in case of existing slot */
            var localSlot = getSlotById(divId);

            /** todo: if localSlot doesn't exist, skip further slot stuff */
            /** todo: set adSlot options on BOTH tpix and gpt objects */
            /** todo: METHOD A: DISCOVERY set directly on both tpix and gpt or consolidate */
            /** todo: METHOD B: PROGRAMMATIC (set directly on tpix and pass thru to its gpt) */

            /** local slot object: discovery */
            if( adDiv.data('pos') != null ) {
                localSlot.setTargetingParam("pos", adDiv.data('pos') );
            }
            /** todo: add all targeting params to google slot object USE EVENT */
            if( localSlot.slot_data.slot_targeting.pos ) newAdSlot.setTargeting("pos", localSlot.slot_data.slot_targeting.pos);

            /**
             * todo: set additional adSlot options (on both local slot object and actual google slot)
             * ...something like...
             *
             * $.each(slot_options, function (k, v) {
             *  googletag.pubads().setTargeting(k, v);
             * });
             *
             */

            /** Store/update slot reference */
            adDiv.data(settings.data_store, newAdSlot);
        });
        trigger("post.slot.define");

        debug("defineNewAdSlot :: adslot[" + adDiv.attr('id') + "] pushed to google cmd queue");
        return true;
    }

    /**
     * return a single slot reference for modification/custom targeting
     * NOTE: modifications must be called prior to showAds()
     * yes this function is quite trivial now. todo: skip it and handle inline
     * @param {string} id
     * @returns {object}
     */
    function getSlotById(id) {
//        debug("getting locally stored adSlot object with id: " + id );

        if(tpixadslots[id]) {
//            debug("getSlotById :: found:" + tpixadslots[id].div_id);
            return tpixadslots[id];
        }

        debug("getSlotById :: local slot[" + id + "] not found.. ABORTING");
        return null;
    }

    /**
     * display an ad in all defined slots. if refreshable, update slot with a new ad
     * called to tell Google that it's time to put ads in the slots which have already been placed on the page
     */
    function showAds() {
        trigger("pre.display.ads");

        $("."+settings.selector).each( function() {
            var adDiv = $(this);
            var adSlotData = adDiv.data(settings.data_store);
            var refreshable = adDiv.data('refresh') || false;
            var unfilled = adDiv.data('unfilled') || false;
            var filled = adDiv.data('filled') || false;

            if(dfp_settings.enable_single_request) {
                if(refreshable) {
                    googletag.cmd.push(function () { window.googletag.pubads().refresh([adSlotData]); });
                    debug("showAds :: refreshing ad " + adDiv.id )
                } else if( unfilled /* && adSlotData*/ ) {
                    googletag.cmd.push(function() { googletag.pubads().refresh([adSlotData]); });
                    debug("showAds :: filling unfilled ad " + adDiv.attr('id') );
                    adDiv.data('unfilled',false);
                }
            } else {
                if(refreshable) {
                    googletag.cmd.push(function () { window.googletag.pubads().refresh([adSlotData]); });
                    debug("showAds :: refreshing ad " + adDiv.id )
                } else if (!filled) {
                    googletag.cmd.push(function() { googletag.display(adDiv.attr('id')); });
                    debug("showAds :: displaying ad " + adDiv.attr('id') + " for the first and only time!");
                    adDiv.data('filled',true);
                } else {
                    debug("showAds :: nonrefreshing ad " + adDiv.attr('id') + " already displayed..skipping.");
                }
            }
        });
        trigger("post.display.ads");
    }

    /**
     * generates a unique id for the container element
     * that the ad will be written into.
     * @param {object} element the element to update
     * @returns {string} the element's id
     */
    function generateId(element) {
        slot_count++;

        if(element !== null && element.attr('id')) {
            debug("generateId :: using existing id : " + element.attr('id'));
            return element.attr('id');
        }

        // else generate a unique id and attach to element
        var id = "dfpAd-" + getRequiredParam("site_domain") + "-" + slot_count;
        element.attr('id', id );
//        debug("generateId :: creating unique id : " + id);

        return id;
    }

    /**
     * param name will be false if it fails
     * to clean up.
     * @param {string} param the param name to clean up
     * @returns {string} the cleaned up param
     */
    function cleanParamName(param) {
        param = trim(param.toLowerCase());
        param = param.replace(/[^a-z0-9_]/g, '');
        var param_regex = /^[a-z_][a-z0-9_]{1,20}$/;
        if (!param_regex.test(param)) {
            debug("_cleanParamName :: invalid param name: " + param);
            return "";
        }
        return param;
    }

    /**
     * sets a param.  returns true if that
     * param was set, false otherwise
     * @param {string} param the param to set
     * @param {string|object|boolean|number} val the value to assign
     * @returns {boolean} success or fail of the set
     */
    function setRequiredParam(param, val) {
        param = cleanParamName(param);
        if (!param) return false;

        required_params[param] = val || false;
        if (typeof(required_params[param]) == "string")
            required_params[param] = trim(required_params[param]);
//        debug("setRequiredParam :: param " + param + " set to: " + required_params[param]);
        return true;
    }

    /**
     * gets a param value.  note that false
     * will be returned if it's not a valid
     * param name or if the param isn't set.
     * @param {string} param
     * @returns {string|object|boolean|number} value of the passed param or false
     */
    function getRequiredParam(param) {
        param = cleanParamName(param);
        if (!param) return false;
        return (required_params[param] || false);
    }

    /**
     * override default selector class for finding ad container divs
     * NOTE: do NOT include the preceding "." so "div" not ".div"
     * @param {string} classname
     */
    function setSelector(classname) {
        if (typeof settings === "undefined") {
            defineCallback("pre.slot.discovery", function(){ setSelector(classname); });
            return;
        }
        if( null !== classname && "" != classname ) {
            // trim preceding "." if present
            // or classname = classname.replace(/^\./,"");
            if( classname.charAt(0) === '.' ) classname = classname.substr(1);
            settings.selector = classname;
        }
    }

    /**
     * enables/disables ads
     * @param {boolean} showAds
     */
    function setEnabled(showAds) {
        if (typeof settings === "undefined") {
            defineCallback("pre.init", function(){ setEnabled(showAds); });
            return;
        }
        settings.enabled = showAds || false;
        debug("setEnabled :: TPIXADS ads enabled : " + settings.enabled);
    }
    /**
     * get if enables/disables ads
     * @return {boolean}
     */
    function getEnabled() {

        return settings.enabled;
    }

    /**
     * set the device
     * @param {string} device
     */
    function setDeviceView(device) {
        if (typeof settings === "undefined") {
            defineCallback("pre.init", function(){ setDeviceView(device); });
            return;
        }
        settings.device_view = device || "main";
        debug("setDeviceView :: TPIXADS device_view set to : " + settings.device_view);
    }

    /**
     * enables/disables debugging
     * @param {boolean} enabled
     */
    function setDebug(enabled) {
        if (typeof settings === "undefined") {
            defineCallback("pre.init", function(){ setDebug(enabled); });
            return;
        }
        settings.debug_enabled = enabled || false;
    }

    /**
     * simple little debugger, writes message <tt>msg</tt>
     * to console when enabled
     * @param {string} msg The string to display in the console
     */
    function debug(msg) {
        if (typeof settings === "undefined" || !settings.debug_enabled) return;
        if (window.console && typeof console.log != "undefined")
            console.log("[TPIXADS] " + msg);
    }

    /**
     * trims the white space from the
     * start and end of a string <tt>str</tt>
     * @param {string} str The string to trim
     * @returns {string}
     */
    function trim(str) {
        return str.replace(/^\s+|\s+$/g, "");
    }

    /**
     * gets param from a uri.  format should be
     * something like url.ext?var=val;var2=val2
     * @param {string} param - the var to get from the key-value pairs
     * @returns {string} value of query string param detected from Uri
     */
    function getParamFromUri(param) {
//        debug("getParamFromUri :: checking for param " + param + " from page url...");
        var value = decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(param).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
        debug("getParamFromUri :: param " + param + (value ? " found with value: " + value : " not found"));
        return value;
    }

    /**
     * Get list of width,height pairs from string
     * @param  {string} str
     * @return {Object[]}
     */
    function getSizesFromString( str ) {
        var sizes = [];

        if( str.length ) {
            var pairs = str.split(',');
            $.each(pairs, function (key, value) {
                var currentSize = value.split('x');
                sizes.push([parseInt(currentSize[0], 10), parseInt(currentSize[1], 10)]);
                debug("getSizesFromString :: adding SIZE=[" + currentSize[0] + "," + currentSize[1] + "]");
            });
        } else {
            debug("getSizesFromString :: NO VALID SIZES FOUND. will expand to element size by default");
        }

        return sizes;
    }

    /**
     * gets the full uri after the base not including search nor hash
     * @returns {string}
     */
    function getUriPaths() {
        var paths = window.location.pathname.replace(/\/$/, '');
        debug("getUriPaths :: found paths:" + paths);

        return paths;
    }

    /**
     * enables/disables QuantCast
     */
    function setQuantcast(enabled) {
        settings.quantcast.enabled = enabled || false;
		embedQuantCastDeliveryTag();
    }

    /**
     * embeds the Quantcast delivery tag (html head)
     * if quantcast is enabled.
     */
    function embedQuantCastDeliveryTag() {
        if (!settings.quantcast.enabled) return;
        document.write('<scr' + 'ipt src="http://pixel.quantserve.com/seg/' + settings.quantcast.qacct + '.js" type="text/javascript"></scr' + 'ipt>');
    }

    /**
     * embeds the Quantcast measurement tag (footer)
     * if quantcast is enabled.
     */
    function embedQuantCastMeasurementTag() {
        if (!settings.quantcast.enabled) return;
        document.write('<scr' + 'ipt src="http://edge.quantserve.com/quant.js" type="text/javascript"></scr' + 'ipt>');
    }

    /**
     * quantcast specific functions/variables.
     */
    function _quantgc(n) {
        var c=document.cookie;if(!c)return '';
        var i=c.indexOf(n+"=");if(-1==i)return '';
        var len=i+n.length+1;
        var end=c.indexOf(";", len);
        return c.substring(len,end<0?c.length:end);
    }

    /**
     * gets the quantcast segments and returns them as array
     * @returns {string}
     */
    function getQCSegs() {
        if (!settings.quantcast.enabled) return "";
        if (settings.quantcast.segs != "")
            return settings.quantcast.segs;
        //var segs = "";
        var segs = [];
        var _qsegs = _quantgc("__qseg").split("|");
        for (var i=0; i < _qsegs.length;i++) {
            var qArr = _qsegs[i].split("_");
            //if (qArr.length > 1)
                //segs += ";qcseg=" + qArr[1];
            segs.push(qArr[1]);
        }
        settings.quantcast.segs = segs;
        debug("getQCSegs :: found segs:" + settings.quantcast.segs);

        return settings.quantcast.segs;
    }

    /**
     * gets the channel (currently passed as "category" for AdOps)
     * @returns {string}
     */
    function getChannel() {
        var channel = "";

        /** todo: get channel */
        debug("getChannel :: found channel:" + channel);

        return channel;
    }

    /**
     * gets the hashtags (currently passed as "tag" for AdOps)
     */
    function getHashtags() {
        var hashtags = [];

        /** todo: get hashtags automagically? or just allow via setGlobalTargeting/init dfp_settings */
        /*if( dfp_settings.global_targeting["tag"] != "" ) {

        } else {

        }
        */
        debug("getHashtags :: found hashtags:" + dfp_settings.global_targeting["tag"]);
    }

    /** bind general wbads events to specified trigger
     * @param {string} trigger
     * @param {object} func
     */
    function bind(trigger, func) {
        debug("bind :: binding callback " + func + " to event " + trigger + ".wbads");
        $(_this).bind(trigger + ".wbads", func);
    }

    /** announce general wbads events
     * @param {string} trigger
     */
    function trigger(trigger) {
        debug("trigger :: " + trigger + ".wbads");
        $(_this).trigger(trigger + ".wbads", _this);
    }

    /**
     * add privileged methods
     */
    _this.setDebug = setDebug;
    _this.setEnabled = setEnabled;
    _this.getEnabled = getEnabled;
    _this.setSelector = setSelector;
    _this.setGlobalOption = setGlobalOption;
    _this.setGlobalTargetingParam = setGlobalTargetingParam;
    _this.addSlot = addSlot;
    _this.getSlotById = getSlotById;
    _this.setSlotTargetingParam = setSlotTargetingParam;
    _this.defineCallback = defineCallback;
    _this.debug = debug;
    _this.showAds = showAds;
    _this.buildSlots = buildSlots;
    _this.init = init;

    return _this;
})(window.jQuery, window, document);
var tpixAdsManager = wbads; // legacy support for a minute


text:
use engine_traits::{KvEngine, MiscExt, Peekable, SyncMutable};

use super::default_engine;

#[test]
fn sync_basic() {
    let db = default_engine();
    db.engine.put(b"foo", b"bar").unwrap();
    db.engine.sync().unwrap();
    let value = db.engine.get_value(b"foo").unwrap();
    let value = value.expect("value");
    assert_eq!(b"bar", &*value);
}

#[test]
fn path() {
    let db = default_engine();
    let path = db.tempdir.path().to_str().unwrap();
    assert_eq!(db.engine.path(), path);
}


text:
<?php
/*
Plugin Name: Brainstorm Core
Plugin URI: https://brainstormforce.com
Author: Brainstorm Force
Author URI: https://brainstormforce.com
Version: 1.0
Description: Brainstorm Core
Text Domain: bsf
*/

/*
	Instrunctions - Product Registration & Updater
	# Copy "auto-upadater" folder to admin folder
	# Change "include_once" and "require_once" directory path as per your "auto-updater" path (Line no. 72, 78, 79)

*/
/* product registration */
require_once 'auto-update/admin-functions.php';
require_once 'auto-update/updater.php';

// abspath of groupi

if ( ! defined( 'BSF_UPDATER_PATH' ) ) {
	define( 'BSF_UPDATER_PATH', dirname(__FILE__) );
}

if(!function_exists('bsf_convert_core_path_to_relative')) {
	function bsf_convert_core_path_to_relative($path) {
		global $bsf_core_url;
		$plugin_dir = basename(PLUGINDIR);
		$theme_dir = basename(get_theme_root());
		if (strpos($path, $theme_dir) !== false) {
		    return rtrim(get_template_directory_uri().'/admin/bsf-core/', '/');
		}
		elseif(strpos($path, $plugin_dir) !== false) {
			return rtrim(plugin_dir_url( __FILE__ ),'/');
		}
		return false;
	}
}

add_action('admin_init', 'set_bsf_core_constant',1);
	if(!function_exists('set_bsf_core_constant')) {
	function set_bsf_core_constant() {
		if(!defined('BSF_CORE')) {
			define('BSF_CORE',true);
		}
	}
}

if ( ! function_exists( 'register_bsf_products_registration_page' ) ) {
	function register_bsf_products_registration_page() {
		if ( defined( 'BSF_UNREG_MENU' ) && ( BSF_UNREG_MENU === true || BSF_UNREG_MENU === 'true' ) ) {
			return false;
		}
		if ( empty ( $GLOBALS['admin_page_hooks']['bsf-registration'] ) ) {
			$place = bsf_get_free_menu_position( 200, 1 );
			if ( ! defined( 'BSF_MENU_POS' ) ) {
				define( 'BSF_MENU_POS', $place );
			}
			if(is_multisite()) {
				$page = add_menu_page('Brainstorm Force', 'Brainstorm', 'administrator', 'bsf-registration', 'bsf_registration','',$place);
			}
			else {
				if(defined('BSF_REG_MENU_TO_SETTINGS') && (BSF_REG_MENU_TO_SETTINGS == true || BSF_REG_MENU_TO_SETTINGS == 'true')) {
					$page = add_options_page('Brainstorm Force', 'Brainstorm', 'administrator', 'bsf-registration', 'bsf_registration' );
				}
				else {
					$page = add_dashboard_page( 'Brainstorm Force', 'Brainstorm', 'administrator', 'bsf-registration', 'bsf_registration' );
				}
			}
		}
	}
}
if ( ! function_exists( 'bsf_registration' ) ) {
	function bsf_registration() {
		include_once 'auto-update/index.php';
	}
}

if ( is_multisite() ) {
	add_action( 'network_admin_menu', 'register_bsf_products_registration_page', 98 );
} else {
	add_action( 'admin_menu', 'register_bsf_products_registration_page', 98 );
}

/*
	Instrunctions - Plugin Installer
	# Copy "plugin-installer" folder to theme's admin folder
	# Change "include_once" and "require_once" directory path as per your "plugin-installer" path (Line no. 101, 113)
*/
add_action( 'admin_init', 'init_bsf_plugin_installer' );
if ( ! function_exists( 'init_bsf_plugin_installer' ) ) {
	function init_bsf_plugin_installer() {
		require_once 'plugin-installer/admin-functions.php';

		/**
		 * Action will run after plugin installer is loaded
		 */
		do_action( 'bsf_after_plugin_installer' );
	}
}

if(!is_multisite())
	add_action('admin_menu', 'register_bsf_extension_page',999);
else
	add_action('network_admin_menu', 'register_bsf_extension_page_network',999);

if ( ! function_exists( 'register_bsf_extension_page' ) ) {

	function register_bsf_extension_page() {

		add_submenu_page(
			'imedica_options',
			__( 'Extensions', 'bsf' ),
			__( 'Extensions', 'bsf' ),
			'manage_options',
			'bsf-extensions-10395942',
			'bsf_extensions_callback'
		);

		$installer_menu = '';
		$reg_menu       = array();
		$reg_menu       = apply_filters( 'bsf_installer_menu', $reg_menu, $installer_menu );

		if ( is_array( $reg_menu ) ) {

			foreach ( $reg_menu as $installer => $attr ) {

				if ( empty ( $GLOBALS['admin_page_hooks'][ $attr['parent_slug'] ] ) &&
				     _bsf_maybe_add_dashboard_menu( $attr['product_id'] ) == true
				) {

					add_dashboard_page(
						$installer . ' ' . $attr['page_title'],
						$installer . ' ' . $attr['menu_title'],
						'manage_options',
						'bsf-extensions-' . $attr['product_id'],
						'bsf_extensions_callback'
					);

				} else {

					add_submenu_page(
						$attr['parent_slug'],
						$attr['page_title'],
						$attr['menu_title'],
						'manage_options',
						'bsf-extensions-' . $attr['product_id'],
						'bsf_extensions_callback'
					);

				}
			}

		}

	}

}

/**
 * Check if the dashboard menu for installer should be added.
 * Checks if theme or plugin is active, if it is not active, the menu for installer should not be registered.
 *
 * @param $product_id Product if of brainstorm product.
 *
 * @return boolean true - If menu is to be shown | false - if menu is not to be displayed.
 */
if ( ! function_exists( '_bsf_maybe_add_dashboard_menu' ) ) {

	function _bsf_maybe_add_dashboard_menu( $product_id ) {
		$brainstrom_products = ( get_option( 'brainstrom_products' ) ) ? get_option( 'brainstrom_products' ) : array();
		$template_plugin     = '';
		$template_theme      = '';
		$is_theme            = false;

		if ( is_multisite() ) {
			// Do not register menu if we are on multisite, multisite menu will be registered below the brainstorm menu.
			return false;
		}

		if ( $brainstrom_products !== array() ) {

			if ( isset( $brainstrom_products['plugins'] ) && isset( $brainstrom_products['plugins'][ $product_id ] ) ) {
				$template_plugin = $brainstrom_products['plugins'][ $product_id ]['template'];
			}

			if ( isset( $brainstrom_products['themes'] ) && isset( $brainstrom_products['themes'][ $product_id ] ) ) {
				$template_theme = $brainstrom_products['themes'][ $product_id ]['product_name'];
				$is_theme       = true;
			}

			if ( $is_theme == true && $template_theme !== '' ) {

				$themes = wp_get_theme();
				if ( $themes->get( 'Name' ) == $template_theme || $themes->parent()->get( 'Name' ) == $template_theme ) {
					// Theme / Parent theme is active, hence display menu
					return true;
				}

				// don't display menu if theme/parent theme does not need extension installer
				return false;

			} elseif ( $is_theme == false && $template_plugin !== '' ) {

				include_once( ABSPATH . 'wp-admin/includes/plugin.php' );

				if ( is_plugin_active( $template_plugin ) || is_plugin_active_for_network( $template_plugin ) ) {
					// Plugin is active, hence display menu
					return true;
				}

				// don't display menu if plugin does not need extension installer
				return false;

			}

		}

		// do not register menu if all conditions fail
		return false;

	}

}

if(!function_exists('register_bsf_extension_page_network')) {
	function register_bsf_extension_page_network() {

		$themes = wp_get_themes(array('allowed' => 'network'));

		foreach( $themes as $theme ) {
			if ( $theme->Name == 'iMedica' ) {
				add_submenu_page( 'bsf-registration', __('iMedica Extensions','bsf'), __('iMedica Extensions','bsf'), 'manage_options', 'bsf-extensions-10395942', 'bsf_extensions_callback' );
				break;
			}
		}

		$installer_menu = 	'';
		$reg_menu 		= 	array();
		$reg_menu 		=	get_site_option( 'bsf_installer_menu', array() );

		if( is_array( $reg_menu ) ) {

			foreach ( $reg_menu as $installer => $attr ) {
				add_submenu_page(
					'bsf-registration',
					$installer .' ' . $attr['page_title'],
					$installer .' ' . $attr['menu_title'],
					'manage_options',
					'bsf-extensions-' . $attr['product_id'],
					'bsf_extensions_callback'
				);
			}

		}

	}
}
if ( ! function_exists( 'bsf_extensions_callback' ) ) {
	function bsf_extensions_callback() {
		include_once 'plugin-installer/index.php';
	}
}

if(!function_exists('bsf_extract_product_id')) {
	function bsf_extract_product_id($path) {
		$id = false;
		$file = rtrim($path,'/').'/admin/bsf.yml';
		$file_fallback = rtrim($path,'/').'/bsf.yml';
		if(is_file($file))
			$file = $file;
		else if(is_file($file_fallback))
			$file = $file_fallback;
		else
			return false;
		$filelines = file_get_contents($file);
		if(stripos($filelines,'ID:[') !== false) {
			preg_match_all("/ID:\[(.*?)\]/", $filelines, $matches);
			if(isset($matches[1])) {
				$id = (isset($matches[1][0])) ? $matches[1][0] : '';
			}
		}
		return $id;
	}
}

add_action( 'admin_init', 'init_bsf_core' );
if(!function_exists('init_bsf_core')) {
	function init_bsf_core() {
		$plugins = get_plugins();
		$themes = wp_get_themes();

		$bsf_products = array();
		foreach($plugins as $plugin => $plugin_data)
		{
			if(trim($plugin_data['Author']) === 'Brainstorm Force')
			{
				$plugin_data['type'] = 'plugin';
				$plugin_data['template'] = $plugin;
				$plugin_data['path'] = dirname(realpath(WP_PLUGIN_DIR.'/'.$plugin));
				$id = bsf_extract_product_id($plugin_data['path']);
				if($id !== false)
					$plugin_data['id'] = $id; // without readme.txt filename
				array_push($bsf_products, $plugin_data);
			}
		}

		foreach($themes as $theme => $theme_data)
		{
			$temp = array();
			$theme_author = trim($theme_data->display('Author', FALSE));
			if($theme_author === 'Brainstorm Force')
			{
				$temp['Name'] = $theme_data->get('Name');
				$temp['ThemeURI'] = $theme_data->get('ThemeURI');
				$temp['Description'] = $theme_data->get('Description');
				$temp['Author'] = $theme_data->get('Author');
				$temp['AuthorURI'] = $theme_data->get('AuthorURI');
				$temp['Version'] = $theme_data->get('Version');
				$temp['type'] = 'theme';
				$temp['template'] = $theme;
				$temp['path'] = realpath(get_theme_root().'/'.$theme);
				$id = bsf_extract_product_id($temp['path']);
				if($id !== false)
					$temp['id'] = $id; // without readme.txt filename
				array_push($bsf_products, $temp);
			}
		}

		$brainstrom_products = ( get_option( 'brainstrom_products' ) ) ? get_option( 'brainstrom_products' ) : array();

		if(!empty($bsf_products)) {
			foreach ($bsf_products as $key => $product) {
				if(!(isset($product['id'])) || $product['id'] === '')
					continue;
				if(isset($brainstrom_products[$product['type'].'s'][$product['id']]))
					$bsf_product_info = $brainstrom_products[$product['type'].'s'][$product['id']];
				else
					$bsf_product_info = array();
				$bsf_product_info['template'] = $product['template'];
				$bsf_product_info['type'] = $product['type'];
				$bsf_product_info['id'] = $product['id'];
				$brainstrom_products[$product['type'].'s'][$product['id']] = $bsf_product_info;
			}
		}

		update_option('brainstrom_products', $brainstrom_products);
	}
}
if(is_multisite()) {
	$brainstrom_products = (get_option('brainstrom_products')) ? get_option('brainstrom_products') : array();
	if(!empty($brainstrom_products)) {
		$bsf_product_themes = (isset($brainstrom_products['themes'])) ? $brainstrom_products['themes'] : array();
		if(!empty($bsf_product_themes)) {
			foreach ($bsf_product_themes as $id => $theme) {
				global $bsf_theme_template;
				$template = $theme['template'];
				$bsf_theme_template = $template;
			}
		}
	}
}
// assets
add_action( 'admin_enqueue_scripts', 'register_bsf_core_admin_styles', 1 );
if(!function_exists('register_bsf_core_admin_styles')) {
	function register_bsf_core_admin_styles($hook) {
		//echo '--------------------------------------........'.$hook;die();

		// bsf core style
		$hook_array = array(
			'toplevel_page_bsf-registration',
			'update-core.php',
			'dashboard_page_bsf-registration',
			'index_page_bsf-registration',
			'admin_page_bsf-extensions',
			'settings_page_bsf-registration'
		);
		$hook_array = apply_filters('bsf_core_style_screens',$hook_array);

		if( in_array($hook, $hook_array) || strpos( $hook, 'bsf-extensions' ) !== false ){
			// add function here
			global $bsf_core_path;
			$bsf_core_url = bsf_convert_core_path_to_relative($bsf_core_path);
			$path = $bsf_core_url.'/assets/css/style.css';
			wp_register_style( 'bsf-core-admin', $path );
			wp_enqueue_style( 'bsf-core-admin' );
		}

		// frosty script
		$hook_frosty_array = array();
		$hook_frosty_array = apply_filters('bsf_core_frosty_screens',$hook_frosty_array);
		if(in_array($hook, $hook_frosty_array)){
			global $bsf_core_path;
			$bsf_core_url = bsf_convert_core_path_to_relative($bsf_core_path);

			$path = $bsf_core_url.'/assets/js/frosty.js';
			$css_path = $bsf_core_url.'/assets/css/frosty.css';

			wp_register_script( 'bsf-core-frosty', $path );
			wp_enqueue_script( 'bsf-core-frosty' );

			wp_register_style( 'bsf-core-frosty-style', $css_path );
			wp_enqueue_style( 'bsf-core-frosty-style' );
		}
	}
}
if(is_multisite()) {
	add_action('admin_print_scripts', 'print_bsf_styles');
	if(!function_exists('print_bsf_styles')) {
		function print_bsf_styles() {
			global $bsf_core_path;
			$bsf_core_url = bsf_convert_core_path_to_relative($bsf_core_path);

			$path = $bsf_core_url.'/assets/fonts';

			echo "";
		}
	}
}

if ( ! function_exists( 'bsf_flush_bundled_products' ) ) {

	function bsf_flush_bundled_products() {
		$bsf_force_check_extensions = get_site_option( 'bsf_force_check_extensions', false );

		if ( $bsf_force_check_extensions == true ) {
			delete_site_option( 'brainstrom_bundled_products' );
			delete_site_transient( 'bsf_get_bundled_products' );
			global $ultimate_referer;
			$ultimate_referer = 'on-flush-bundled-products';
			get_bundled_plugins();

			update_site_option( 'bsf_force_check_extensions', false );
		}
	}
}

add_action( 'bsf_after_plugin_installer', 'bsf_flush_bundled_products' );

/**
 * Return extension installer page URL
 */
if ( ! function_exists( 'bsf_exension_installer_url' ) ) {

	function bsf_exension_installer_url( $priduct_id ) {
		if ( is_multisite() ) {
			return network_admin_url( 'admin.php?page=bsf-extensions-' . $priduct_id );
		} else {
			return admin_url( 'admin.php?page=bsf-extensions-' . $priduct_id );
		}
	}
}

/**
 * Return array of bundled plugins for a specific
 *
 * @since Graupi 1.9
 */
if ( ! function_exists( 'bsf_bundled_plugins' ) ) {

	function bsf_bundled_plugins( $product_id = '' ) {
		$products = array();

		$brainstrom_bundled_products = get_option( 'brainstrom_bundled_products', '' );

		if ( $brainstrom_bundled_products !== '' ) {
			if ( array_key_exists( $product_id, $brainstrom_bundled_products ) ) {
				$products = $brainstrom_bundled_products[ $product_id ];
			}
		}

		return $products;
	}
}

/**
 * Get product name from product ID
 *
 * @since Graupi 1.9
 */
if ( ! function_exists( 'brainstrom_product_name' ) ) {

	function brainstrom_product_name( $product_id = '' ) {
		$product_name = '';
		$brainstrom_products =  get_option( 'brainstrom_products', '' );

		foreach ( $brainstrom_products as $key => $value ) {
			foreach ( $value as $key => $product ) {
				if ( $product_id == $key ) {
					$product_name = $product['product_name'];
				}
			}
		}

		return $product_name;
	}
}

/**
 * Dismiss Extension installer nag
 *
 * @since Graupi 1.9
 */
if ( ! function_exists( 'bsf_dismiss_extension_nag' ) ) {

	function bsf_dismiss_extension_nag() {
		if ( isset( $_GET['bsf-dismiss-notice'] ) ) {
			$product_id =  $_GET['bsf-dismiss-notice'];
			update_user_meta( get_current_user_id(), $product_id . '-bsf_nag_dismiss', true );
		}
	}

}

add_action( 'admin_head', 'bsf_dismiss_extension_nag' );

// For debugging uncomment line below and remove query var &bsf-dismiss-notice from url and nag will be restored.
// delete_user_meta( get_current_user_id(), 'bsf-next-bsf_nag_dismiss');

/**
 * Generate's markup to generate notice to ask users to install required extensions.
 *
 * @since Graupi 1.9
 *
 * $product_id (string) Product ID of the brainstorm product
 * $mu_updater (bool) If True - give nag to separately install brainstorm updater multisite plugin
 */
if ( ! function_exists( 'bsf_extension_nag' ) ) {

	function bsf_extension_nag( $product_id = '', $mu_updater = false ) {

		$display_nag = get_user_meta( get_current_user_id(), $product_id . '-bsf_nag_dismiss', true );

		if ( $mu_updater == true ) {
			bsf_nag_brainstorm_updater_multisite();
		}

		if ( $display_nag === '1' ||
			! user_can( get_current_user_id(), 'activate_plugins' ) ||
			! user_can( get_current_user_id(), 'install_plugins' ) ) {
			return;
		}

		$bsf_installed_plugins     = '';
		$bsf_not_installed_plugins = '';
		$bsf_not_activated_plugins = '';
		$installer                 = '';
		$bsf_install               = false;
		$bsf_activate              = false;
		$bsf_bundled_products      = bsf_bundled_plugins( $product_id );
		$bsf_product_name          = brainstrom_product_name( $product_id );

		foreach ( $bsf_bundled_products as $key => $plugin ) {

			if ( ! isset( $plugin->id ) || $plugin->id == '' || ! isset( $plugin->must_have_extension ) || $plugin->must_have_extension == 'false' ) {
				continue;
			}

			$plugin_abs_path = WP_PLUGIN_DIR . '/' . $plugin->init;
			if ( is_file( $plugin_abs_path ) ) {

				if ( ! is_plugin_active( $plugin->init ) ) {
					$bsf_not_activated_plugins .= $bsf_bundled_products[ $key ]->name . ', ';
				}
			} else {
				$bsf_not_installed_plugins .= $bsf_bundled_products[ $key ]->name . ', ';
			}

		}

		$bsf_not_activated_plugins = rtrim( $bsf_not_activated_plugins, ", " );
		$bsf_not_installed_plugins = rtrim( $bsf_not_installed_plugins, ", " );

		if ( $bsf_not_activated_plugins !== '' || $bsf_not_installed_plugins !== '' ) {
			echo '

';
			if ( $bsf_not_activated_plugins !== '' ) {
				echo '
';
				echo $bsf_product_name . __( ' requires following plugins to be active : ', 'bsf' );
				echo "";
				echo $bsf_not_activated_plugins;
				echo "";
				echo '
';
				$bsf_activate = true;
			}

			if ( $bsf_not_installed_plugins !== '' ) {
				echo '
';
				echo $bsf_product_name . __( ' requires following plugins to be installed and activated : ', 'bsf' );
				echo "";
				echo $bsf_not_installed_plugins;
				echo "";
				echo '
';
				$bsf_install = true;
			}

			if ( $bsf_activate == true ) {
				$installer .= '' . __( 'Begin activating plugins', 'bsf' ) . ' | ';
			}

			if ( $bsf_install == true ) {
				$installer .= '' . __( 'Begin installing plugins', 'bsf' ) . ' | ';
			}

			$installer .= '' . __( 'Dismiss This Notice', 'bsf' ) . '';

			$installer = ltrim( $installer, '| ' );
			echo '
';
			echo rtrim( $installer, ' |' );
			echo '
';

			echo '

';
		}
	}

}

if ( ! function_exists( 'bsf_nag_brainstorm_updater_multisite' ) ) {

	function bsf_nag_brainstorm_updater_multisite() {

		if ( ! function_exists( 'is_plugin_active_for_network' ) ) {
			require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
		}

		if ( ! is_multisite() || is_plugin_active_for_network( 'brainstorm-updater/index.php' ) ) {
			return;
		}

		echo '

';
		printf(
			__('Looks like you are on a WordPress Multisite, you will need to install and network activate %1$s Brainstorm Updater for Multisite %2$s plugin. Download it from %3$s here %4$s', 'bsf' ) ,
				'',
				'',
				'',
				''
			 );

		echo "
";
		echo "
";
	}

}

/**
 * Check if bundled products data on site is from old version of graupi and force refresh the data if required.
 */
function bsf_check_correct_updater_data() {
	$brainstrom_bundled_products = get_option( 'brainstrom_bundled_products', array() );
	$url = '';

	foreach ( $brainstrom_bundled_products  as $key => $value) {
		if ( is_object( $value ) || is_object( $brainstrom_bundled_products ) ) {
			if ( ! is_multisite() && is_admin() ) {
				$url = admin_url( 'index.php?page=bsf-registration&remove-bundled-products' );

				continue;
			}
		}
	}

	// if page is reloaded once dont check agan, this may result in redirect loop if brainstorm products are not being updated.
	if ( $url !== '' && ! isset( $_GET['bsf-reload-page'] ) ) {
		echo '';
	}

}

add_action( 'admin_init', 'bsf_check_correct_updater_data', 2 );

/*
 * Load BSF core frosty scripts on front end
*/
add_action( 'wp_enqueue_scripts', 'register_bsf_core_styles', 1 );
function register_bsf_core_styles( $hook ) {

	global $bsf_core_path;
	$bsf_core_url = bsf_convert_core_path_to_relative($bsf_core_path);
	$frosty_script_path = $bsf_core_url.'/assets/js/frosty.js';
	$frosty_style_path = $bsf_core_url.'/assets/css/frosty.css';

	// Register Frosty script and style
	wp_register_script( 'bsf-core-frosty', $frosty_script_path );
	wp_register_style( 'bsf-core-frosty-style', $frosty_style_path );

}

/**
 * Add link to debug settings for braisntorm updater on license registration page
 */
function bsf_core_debug_link( $text ) {
	$screen = get_current_screen();

	$screens = array(
		'dashboard_page_bsf-registration',
		'toplevel_page_bsf-registration-network'
		);

	if( ! in_array( $screen->id, $screens ) ) {
		return $text;
	}

	$url = bsf_registration_page_url( '&author' );
	$link = 'Brainstorm Updater debug settings';
	$text = $link .' | '. $text;
	return $text;
}

add_filter( 'update_footer', 'bsf_core_debug_link', 999 );

/**
 * Return brainstorm registration page URL
 *
 * @param $append (string) - Append at string at the end of the url
 */
if ( ! function_exists( 'bsf_registration_page_url' ) ) {

	function bsf_registration_page_url( $append = '' ) {
		if ( is_multisite() ) {
			return network_admin_url( 'admin.php?page=bsf-registration' . $append );
		} else {
			return admin_url( 'index.php?page=bsf-registration' . $append );
		}
	}
}


text:
package io.github.mikolasan.petprojectnavigator;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.loader.content.CursorLoader;
import androidx.cursoradapter.widget.CursorAdapter;

import com.mobeta.android.dslv.DragSortCursorAdapter;

class PetAnyLoader extends CursorLoader {
    protected PetDatabase petDatabase;
    private String[] columnNames;
    private int[] layoutItems;
    private int layoutId;
    private Bundle args;
    private CursorAdapter adapter;

    protected void fillView(View view, Context context, Cursor cursor) {}

    private class TrueCursorAdapter extends CursorAdapter
    {
        public TrueCursorAdapter(Context context, Cursor cursor) {
            super(context, cursor, 0);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return LayoutInflater.from(context).inflate(layoutId, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            fillView(view, context, cursor);
        }
    }

    private class TrueDragCursorAdapter extends DragSortCursorAdapter
    {
        public TrueDragCursorAdapter(Context context, Cursor cursor) {
            super(context, cursor, 0);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return LayoutInflater.from(context).inflate(layoutId, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            fillView(view, context, cursor);
        }
    }

    PetAnyLoader(Context context, PetDatabase petDatabase) {
        super(context);
        this.petDatabase = petDatabase;
    }

    void onCreate(int id, Bundle args) {
        setArgs(args);
    }

    CursorAdapter createAdapter(Cursor cursor) {
        return new TrueCursorAdapter(getContext(), cursor);
    }

    DragSortCursorAdapter createDragAdapter(Cursor cursor) {
        return new TrueDragCursorAdapter(getContext(), cursor);
    }

    public int getLayoutId() {
        return layoutId;
    }

    public void setLayoutId(int layoutId) {
        this.layoutId = layoutId;
    }

    String[] getColumnNames() {
        return columnNames;
    }

    int[] getLayoutItems() {
        return layoutItems;
    }

    public Bundle getArgs() {
        return args;
    }

    void setColumnNames(String[] columnNames) {
        this.columnNames = columnNames;
    }

    void setLayoutItems(int[] layoutItems) {
        this.layoutItems = layoutItems;
    }

    private void setArgs(Bundle args) {
        this.args = args;
    }
}