text:
package com.sleepycat.je.rep.vlsn;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import junit.framework.TestCase;

import com.sleepycat.je.DbInternal;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.dbi.EnvironmentImpl;
import com.sleepycat.je.log.LogEntryHeader;
import com.sleepycat.je.log.LogEntryType;
import com.sleepycat.je.log.LogItem;
import com.sleepycat.je.log.Provisional;
import com.sleepycat.je.log.ReplicationContext;
import com.sleepycat.je.log.entry.LogEntry;
import com.sleepycat.je.log.entry.SingleItemEntry;
import com.sleepycat.je.recovery.RecoveryInfo;
import com.sleepycat.je.rep.impl.node.NameIdPair;
import com.sleepycat.je.rep.utilint.RepTestUtils;
import com.sleepycat.je.rep.vlsn.VLSNIndex.ForwardVLSNScanner;
import com.sleepycat.je.txn.RollbackStart;
import com.sleepycat.je.util.TestUtils;
import com.sleepycat.je.utilint.DbLsn;
import com.sleepycat.je.utilint.VLSN;

/**
 */
public class MergeTest extends TestCase {

    private final String testMapDb = "TEST_MAP_DB";
    private final boolean verbose = Boolean.getBoolean("verbose");
    private final File envHome;
    private final byte lnType = LogEntryType.LOG_LN_TRANSACTIONAL.getTypeNum();

    private Environment env;
    private EnvironmentImpl envImpl;
    private int bucketStride = 4;
    private int bucketMaxMappings = 3;
    private int recoveryStride = 3;
    private int recoveryMaxMappings = 4;

    public MergeTest() {
        envHome = new File(System.getProperty(TestUtils.DEST_DIR));
    }

    @Override
    public void setUp() {
        RepTestUtils.removeRepEnvironments(envHome);
    }

    @Override
    public void tearDown() {
        RepTestUtils.removeRepEnvironments(envHome);
    }

    private Environment makeEnvironment() {

        EnvironmentConfig envConfig = new EnvironmentConfig();
        envConfig.setAllowCreate(true);
        envConfig.setTransactional(false);
        return new Environment(envHome, envConfig);
    }

    /**
     * Test the tricky business of recovering the VLSNIndex. See VLSNIndex(),
     * and how the vlsnIndex is initialized from what's persistent on disk, and
     * another tracker is filled with vlsn->lsn mappings gleaned from reading
     * the log during recovery. The recovery tracker's contents are used to
     * override what is on the on-disk tracker.
     */
    public void testMerge()
        throws Throwable {
        env = makeEnvironment();
        envImpl = DbInternal.getEnvironmentImpl(env);

        /*
         * VLSN ranges for the test:
         * start->initialSize are mapped before recovery
         * secondStart ->recoverySize are mapped in the recovery tracker.
         */
        long start = 1;
        long initialSize = 40;
        long secondStart = start + initialSize - 20;
        long recoverySize = 30;

        RecoveryTrackerGenerator generator =
            new NoRollbackGenerator(secondStart, recoverySize);
        try {
            doMerge(generator, initialSize);
        } finally {
            env.close();
        }
    }

    public void testSingleRBMerge()
        throws Throwable {
        env = makeEnvironment();
        envImpl = DbInternal.getEnvironmentImpl(env);

        long initialSize = 40;

        RecoveryTrackerGenerator generator = new RollbackGenerator
            (new RollbackInfo(new VLSN(20), DbLsn.makeLsn(5, 20 * 10)));

        try {
            doMerge(generator, initialSize);
        } finally {
            env.close();
        }
    }

    public void testMultiRBMerge()
        throws Throwable {
        env = makeEnvironment();
        envImpl = DbInternal.getEnvironmentImpl(env);

        long initialSize = 50;

        RecoveryTrackerGenerator generator = new RollbackGenerator
            (new RollbackInfo(new VLSN(30), DbLsn.makeLsn(5, 30 * 10)),
             new TestInfo(31, DbLsn.makeLsn(6, (31 * 30))),
             new TestInfo(32, DbLsn.makeLsn(6, (32 * 30))),
             new TestInfo(33, DbLsn.makeLsn(6, (33 * 30))),
             new TestInfo(34, DbLsn.makeLsn(6, (34 * 30))),
             new TestInfo(35, DbLsn.makeLsn(6, (35 * 30))),
             new TestInfo(36, DbLsn.makeLsn(6, (36 * 30))),
             new TestInfo(37, DbLsn.makeLsn(6, (37 * 30))),
             new RollbackInfo(new VLSN(33), DbLsn.makeLsn(6, (33 * 30))),
             new TestInfo(34, DbLsn.makeLsn(7, (34 * 40))),
             new TestInfo(35, DbLsn.makeLsn(7, (35 * 40))),
             new TestInfo(36, DbLsn.makeLsn(7, (36 * 40))),
             new TestInfo(37, DbLsn.makeLsn(7, (37 * 40))));

        try {
            doMerge(generator, initialSize);
        } finally {
            env.close();
        }
    }

    public void testRBInRecoveryLogMerge()
        throws Throwable {
        env = makeEnvironment();
        envImpl = DbInternal.getEnvironmentImpl(env);

        long initialSize = 50;

        RecoveryTrackerGenerator generator = new RollbackGenerator
            (new TestInfo(51, DbLsn.makeLsn(6, (51 * 30))),
             new TestInfo(52, DbLsn.makeLsn(6, (52 * 30))),
             new TestInfo(53, DbLsn.makeLsn(6, (53 * 30))),
             new TestInfo(54, DbLsn.makeLsn(6, (54 * 30))),
             new TestInfo(55, DbLsn.makeLsn(6, (55 * 30))),
             new TestInfo(56, DbLsn.makeLsn(6, (56 * 30))),
             new TestInfo(57, DbLsn.makeLsn(6, (57 * 30))),
             new TestInfo(58, DbLsn.makeLsn(6, (58 * 30))),
             new TestInfo(59, DbLsn.makeLsn(6, (59 * 30))),
             new TestInfo(60, DbLsn.makeLsn(6, (60 * 30))),
             new TestInfo(61, DbLsn.makeLsn(6, (61 * 30))),
             new RollbackInfo(new VLSN(55), DbLsn.makeLsn(6, (55 * 30))),
             new TestInfo(56, DbLsn.makeLsn(7, (56 * 40))),
             new TestInfo(57, DbLsn.makeLsn(7, (57 * 40))));

        try {
            doMerge(generator, initialSize);
        } finally {
            env.close();
        }
    }

    private void doMerge(RecoveryTrackerGenerator generator,
                         long initialSize)
        throws Throwable {

        for (int flushPoint = 1; flushPoint <= initialSize; flushPoint++) {
            if (verbose) {
                System.out.println("flush=" + flushPoint +
                                   " initSize = " + initialSize);
            }

            VLSNIndex vlsnIndex = new VLSNIndex(envImpl, testMapDb,
                                                new NameIdPair("node1", 1),
                                                bucketStride, bucketMaxMappings,
                                                10000, new RecoveryInfo());
            try {

                List<TestInfo> expected = new ArrayList<TestInfo>();

                populate(flushPoint, vlsnIndex, initialSize, expected);
                vlsnIndex.merge(generator.makeRecoveryTracker(expected));

                assertTrue(vlsnIndex.verify(verbose));
                checkMerge(vlsnIndex, expected);

            } catch (Throwable e) {
                e.printStackTrace();
                throw e;
            } finally {
                vlsnIndex.close();
                env.removeDatabase(null, testMapDb);
            }
        }
    }

    /**
     * Fill up an initial VLSNIndex, flushing at different spots to create a
     * different tracker/on-disk mix.
     */
    private void populate(int flushPoint,
                          VLSNIndex vlsnIndex,
                          long initialSize,
                          List<TestInfo> expected) {

        for (long i = 1; i <= initialSize; i++) {
            TestInfo info = new TestInfo(i, DbLsn.makeLsn(5, i * 10));

            /* populate vlsn index */
            vlsnIndex.put(makeLogItem(info));

            /* populate expected list */
            expected.add(info);

            if (i == flushPoint) {
                vlsnIndex.flushToDatabase();
            }
        }
    }

    private LogItem makeLogItem(TestInfo info) {
        LogItem item = new LogItem();
        item.header = info.header;
        item.newLsn = info.lsn;
        return item;
    }

    private void checkMerge(VLSNIndex vlsnIndex, List<TestInfo> expected) {

        /* The new tracker should have the right range. */
        VLSNRange range = vlsnIndex.getRange();
        assertEquals(new VLSN(1), range.getFirst());
        VLSN lastVLSN = expected.get(expected.size() - 1).vlsn;
        assertEquals(lastVLSN, range.getLast());

        // TODO: test that the sync and commit fields in the tracker are
        // correct.

        ForwardVLSNScanner scanner = new ForwardVLSNScanner(vlsnIndex);
        long firstLsn = scanner.getStartingLsn(expected.get(0).vlsn);
        assertEquals(DbLsn.getNoFormatString(expected.get(0).lsn) +
                     " saw first VLSN " + DbLsn.getNoFormatString(firstLsn),
                     expected.get(0).lsn, firstLsn);

        boolean vlsnForLastInRange = false;

        int validMappings = 0;
        for (TestInfo info : expected) {
            long lsn = scanner.getPreciseLsn(info.vlsn);
            if (lsn != DbLsn.NULL_LSN) {
                if (verbose) {
                    System.out.println(info);
                }

                assertEquals(DbLsn.getNoFormatString(info.lsn), info.lsn, lsn);
                validMappings++;

                if (info.vlsn.equals(lastVLSN)) {
                    vlsnForLastInRange = true;
                }
            }
        }

        /* Should see a lsn value for the last VLSN in the range. */
        assertTrue(vlsnForLastInRange);

        /* Some portion of the expected set should be mapped. */
        assertTrue(validMappings > (expected.size()/bucketStride) - 1);
    }

    interface RecoveryTrackerGenerator {
        public VLSNRecoveryTracker makeRecoveryTracker(List<TestInfo> expected);
    }

    private class NoRollbackGenerator implements RecoveryTrackerGenerator {

        private long secondStart;
        private long recoverySize;

        NoRollbackGenerator(long secondStart,
                            long recoverySize) {
            this.secondStart = secondStart;
            this.recoverySize = recoverySize;
        }

        public VLSNRecoveryTracker makeRecoveryTracker
            (List<TestInfo> expected) {

            VLSNRecoveryTracker recoveryTracker =
                new VLSNRecoveryTracker(envImpl,
                                        recoveryStride,
                                        recoveryMaxMappings,
                                        100000);

            /* Truncate the expected mappings list. */
            Iterator<TestInfo> iter = expected.iterator();
            while (iter.hasNext()) {
                TestInfo ti = iter.next();
                if (ti.vlsn.getSequence() >= secondStart) {
                    iter.remove();
                }
            }

            for (long i = secondStart; i < secondStart + recoverySize; i ++) {
                TestInfo info = new TestInfo(i, DbLsn.makeLsn(6,i * 20));
                recoveryTracker.trackMapping(info.lsn,
                                             info.header,
                                             info.entry);
                expected.add(info);
            }

            return recoveryTracker;
        }
    }

    private class RollbackGenerator implements RecoveryTrackerGenerator {
        private final Object[] recoveryLog;

        RollbackGenerator(Object ... recoveryLog) {
            this.recoveryLog = recoveryLog;
        }

        public VLSNRecoveryTracker
            makeRecoveryTracker(List<TestInfo> expected) {

            VLSNRecoveryTracker recoveryTracker =
                new VLSNRecoveryTracker(envImpl,
                                        recoveryStride,
                                        recoveryMaxMappings,
                                        100000);

            for (Object info : recoveryLog) {
                if (info instanceof TestInfo) {
                    TestInfo t = (TestInfo) info;
                    recoveryTracker.trackMapping(t.lsn, t.header, t.entry);
                    expected.add(t);
                } else if (info instanceof RollbackInfo) {
                    RollbackInfo r = (RollbackInfo) info;

                    /* Register the pseudo rollback with the tracker. */
                    recoveryTracker.trackMapping(0 /* lsn */,
                                                 r.header, r.rollbackEntry);

                    /* Truncate the expected mappings list. */
                    Iterator<TestInfo> iter = expected.iterator();
                    while (iter.hasNext()) {
                        TestInfo ti = iter.next();
                        if (ti.vlsn.compareTo(r.matchpointVLSN) > 0) {
                            iter.remove();
                        }
                    }
                }
            }

            return recoveryTracker;
        }
    }

    private class TestInfo {
        final long lsn;
        final VLSN vlsn;
        final LogEntryHeader header;
        final LogEntry entry;

        TestInfo(long vlsnVal, long lsn, LogEntry entry) {
            this.lsn = lsn;
            this.vlsn = new VLSN(vlsnVal);
            this.header = new LogEntryHeader(entry.getLogType().getTypeNum(),
                                             0, 0, vlsn);
            this.entry = entry;
        }

        TestInfo(long vlsnVal, long lsn) {
            this.lsn = lsn;
            this.vlsn = new VLSN(vlsnVal);
            this.header = new LogEntryHeader(lnType, 0, 0, vlsn);
            this.entry = null;
        }

        @Override
        public String toString() {
            return "vlsn=" + vlsn + " lsn=" + DbLsn.getNoFormatString(lsn) +
                " entryType="  + header.getType();
        }
    }

    private class RollbackInfo {
        final VLSN matchpointVLSN;
        final LogEntryHeader header;
        final LogEntry rollbackEntry;

        RollbackInfo(VLSN matchpointVLSN, long matchpointLsn) {

            this.matchpointVLSN = matchpointVLSN;
            Set<Long> noActiveTxns = Collections.emptySet();
            rollbackEntry =
                new SingleItemEntry(LogEntryType.LOG_ROLLBACK_START,
                                    new RollbackStart(matchpointVLSN,
                                                      matchpointLsn,
                                                      noActiveTxns));

             header = new LogEntryHeader(rollbackEntry, Provisional.NO,
                                         ReplicationContext.NO_REPLICATE);
        }
    }
}


text:
#pragma warning(disable:4786)

#include <qsconv.h>
#include <qsfile.h>
#include <qsinit.h>
#include <qslog.h>
#include <qsmime.h>
#include <qsstl.h>
#include <qsstream.h>

#include <boost/bind.hpp>

#include "feed.h"

using namespace qmrss;
using namespace qm;
using namespace qs;

/****************************************************************************
 *
 * FeedList
 *
 */

qmrss::FeedList::FeedList(const WCHAR* pwszPath) :
	bModified_(false)
{
	wstrPath_ = allocWString(pwszPath);

	if (!load()) {
		Log log(InitThread::getInitThread().getLogger(), L"qmrss::FeedList");
		log.errorf(L"Failed to load feed list: %s", pwszPath);
	}
}

qmrss::FeedList::~FeedList()
{
	std::for_each(list_.begin(), list_.end(), boost::checked_deleter<Feed>());
}

const FeedList::List& qmrss::FeedList::getFeeds() const
{
	assert(isLocked());
	return list_;
}

const Feed* qmrss::FeedList::getFeed(const WCHAR* pwszURL) const
{
	Lock<FeedList> lock(*this);

	Feed feed(pwszURL, Time::getCurrentTime());
	List::const_iterator it = std::lower_bound(
		list_.begin(), list_.end(), &feed,
		boost::bind(string_less<WCHAR>(),
			boost::bind(&Feed::getURL, _1),
			boost::bind(&Feed::getURL, _2)));
	return it != list_.end() && wcscmp((*it)->getURL(), pwszURL) == 0 ? *it : 0;
}

void qmrss::FeedList::setFeed(std::auto_ptr<Feed> pFeed,
							  int nKeepDay)
{
	Lock<FeedList> lock(*this);

	List::iterator it = std::lower_bound(
		list_.begin(), list_.end(), pFeed.get(),
		boost::bind(string_less<WCHAR>(),
			boost::bind(&Feed::getURL, _1),
			boost::bind(&Feed::getURL, _2)));
	if (it != list_.end() && wcscmp((*it)->getURL(), pFeed->getURL()) == 0) {
		if (nKeepDay != -1)
			pFeed->merge(*it, Time::getCurrentTime().addDay(-nKeepDay));
		delete *it;
		*it = pFeed.release();
	}
	else {
		list_.insert(it, pFeed.get());
		pFeed.release();
	}

	bModified_ = true;
}

void qmrss::FeedList::removeFeed(const Feed* pFeed)
{
	assert(isLocked());

	List::iterator it = std::find(list_.begin(), list_.end(), pFeed);
	if (it != list_.end()) {
		delete *it;
		list_.erase(it);
		bModified_ = true;
	}
}

bool qmrss::FeedList::save()
{
	Lock<FeedList> lock(*this);

	if (!bModified_)
		return true;

	TemporaryFileRenamer renamer(wstrPath_.get());

	FileOutputStream stream(renamer.getPath());
	if (!stream)
		return false;
	BufferedOutputStream bufferedStream(&stream, false);
	OutputStreamWriter writer(&bufferedStream, false, L"utf-8");
	if (!writer)
		return false;

	FeedWriter w(&writer, L"utf-8");
	if (!w.write(*this))
		return false;

	if (!writer.close())
		return false;

	if (!renamer.rename())
		return false;

	bModified_ = false;

	return true;
}

void qmrss::FeedList::lock() const
{
	cs_.lock();
#ifndef NDEBUG
	++nLock_;
#endif
}

void qmrss::FeedList::unlock() const
{
#ifndef NDEBUG
	--nLock_;
#endif
	cs_.unlock();
}

#ifndef NDEBUG
bool qmrss::FeedList::isLocked() const
{
	return nLock_ != 0;
}
#endif

void qmrss::FeedList::setFeeds(List& l)
{
	assert(list_.empty());

	sortFeeds(l);
	list_.swap(l);
}

bool qmrss::FeedList::load()
{
	if (File::isFileExisting(wstrPath_.get())) {
		XMLReader reader;
		FeedContentHandler handler(this);
		reader.setContentHandler(&handler);
		if (!reader.parse(wstrPath_.get()))
			return false;
	}

	bModified_ = false;

	return true;
}

void qmrss::FeedList::sortFeeds(List& l)
{
	std::sort(l.begin(), l.end(),
		boost::bind(string_less<WCHAR>(),
			boost::bind(&Feed::getURL, _1),
			boost::bind(&Feed::getURL, _2)));
}

/****************************************************************************
 *
 * Feed
 *
 */

qmrss::Feed::Feed(const WCHAR* pwszURL,
				  const Time& timeLastModified) :
	timeLastModified_(timeLastModified)
{
	assert(pwszURL);

	wstrURL_ = allocWString(pwszURL);
}

qmrss::Feed::Feed(const Feed* pFeed,
				  const Time& time) :
	timeLastModified_(pFeed->getLastModified())
{
	assert(pFeed);

	wstrURL_ = allocWString(pFeed->getURL());

	FeedItem::Date date(FeedItem::convertTimeToDate(time));

	const ItemList& l = pFeed->listItem_;
	listItem_.reserve(l.size());
	for (ItemList::const_iterator it = l.begin(); it != l.end(); ++it) {
		const FeedItem* pItem = *it;
		listItem_.push_back(new FeedItem(pItem->getKey(), date));
	}
}

qmrss::Feed::~Feed()
{
	std::for_each(listItem_.begin(), listItem_.end(),
		boost::checked_deleter<FeedItem>());
}

const WCHAR* qmrss::Feed::getURL() const
{
	return wstrURL_.get();
}

const Time& qmrss::Feed::getLastModified() const
{
	return timeLastModified_;
}

const Feed::ItemList& qmrss::Feed::getItems() const
{
	return listItem_;
}

const FeedItem* qmrss::Feed::getItem(const WCHAR* pwszKey) const
{
	FeedItem::Date date = { 0, 0, 0 };
	FeedItem item(pwszKey, date);
	ItemList::const_iterator it = std::lower_bound(
		listItem_.begin(), listItem_.end(), &item,
		boost::bind(string_less<WCHAR>(),
			boost::bind(&FeedItem::getKey, _1),
			boost::bind(&FeedItem::getKey, _2)));
	return it != listItem_.end() && wcscmp((*it)->getKey(), pwszKey) == 0 ? *it : 0;
}

void qmrss::Feed::addItem(std::auto_ptr<FeedItem> pItem)
{
	ItemList::iterator it = std::lower_bound(
		listItem_.begin(), listItem_.end(), pItem.get(),
		boost::bind(string_less<WCHAR>(),
			boost::bind(&FeedItem::getKey, _1),
			boost::bind(&FeedItem::getKey, _2)));
	if (it == listItem_.end() || wcscmp((*it)->getKey(), pItem->getKey()) != 0) {
		listItem_.insert(it, pItem.get());
		pItem.release();
	}
}

void qmrss::Feed::merge(Feed* pFeed,
						const Time& timeAfter)
{
	ItemList& l = pFeed->listItem_;
	bool bAdded = false;
	for (ItemList::iterator it = l.begin(); it != l.end(); ) {
		FeedItem* pItem = *it;

		if (!getItem(pItem->getKey())) {
			const FeedItem::Date& date = pItem->getDate();
			Time t(date.nYear_, date.nMonth_, 0, date.nDay_, 0, 0, 0, 0, 0);
			if (t > timeAfter) {
				listItem_.push_back(pItem);
				it = l.erase(it);
				bAdded = true;
			}
			else {
				++it;
			}
		}
		else {
			++it;
		}
	}

	if (bAdded)
		sortItems(listItem_);
}

void qmrss::Feed::setItems(ItemList& listItem)
{
	assert(listItem_.empty());

	sortItems(listItem);
	listItem_.swap(listItem);
}

void qmrss::Feed::sortItems(ItemList& listItem)
{
	std::sort(listItem.begin(), listItem.end(),
		boost::bind(string_less<WCHAR>(),
			boost::bind(&FeedItem::getKey, _1),
			boost::bind(&FeedItem::getKey, _2)));
}

/****************************************************************************
 *
 * FeedItem
 *
 */

qmrss::FeedItem::FeedItem(const WCHAR* pwszKey,
						  const Date& date) :
	date_(date)
{
	wstrKey_ = allocWString(pwszKey);
}

qmrss::FeedItem::~FeedItem()
{
}

const WCHAR* qmrss::FeedItem::getKey() const
{
	return wstrKey_.get();
}

const FeedItem::Date& qmrss::FeedItem::getDate() const
{
	return date_;
}

FeedItem::Date qmrss::FeedItem::convertTimeToDate(const qs::Time& time)
{
	Date date = {
		time.wYear,
		time.wMonth,
		time.wDay
	};
	return date;
}

/****************************************************************************
 *
 * FeedManager
 *
 */

qmrss::FeedManager::FeedManager()
{
}

qmrss::FeedManager::~FeedManager()
{
	std::for_each(map_.begin(), map_.end(),
		boost::bind(boost::checked_deleter<FeedList>(),
			boost::bind(&Map::value_type::second, _1)));
}

FeedList* qmrss::FeedManager::get(qm::Account* pAccount)
{
	Lock<CriticalSection> lock(cs_);

	Map::iterator it = std::find_if(map_.begin(), map_.end(),
		boost::bind(&Map::value_type::first, _1) == pAccount);
	if (it != map_.end())
		return (*it).second;

	wstring_ptr wstrPath(concat(pAccount->getPath(), L"\\feed.xml"));
	std::auto_ptr<FeedList> pFeedList(new FeedList(wstrPath.get()));
	map_.push_back(std::make_pair(pAccount, pFeedList.get()));
	return pFeedList.release();
}

/****************************************************************************
 *
 * FeedContentHandler
 *
 */

qmrss::FeedContentHandler::FeedContentHandler(FeedList* pList) :
	pList_(pList),
	state_(STATE_ROOT),
	pCurrentFeed_(0)
{
}

qmrss::FeedContentHandler::~FeedContentHandler()
{
	std::for_each(listItem_.begin(), listItem_.end(),
		boost::checked_deleter<FeedItem>());
	std::for_each(list_.begin(), list_.end(),
		boost::checked_deleter<Feed>());
}

bool qmrss::FeedContentHandler::startElement(const WCHAR* pwszNamespaceURI,
											 const WCHAR* pwszLocalName,
											 const WCHAR* pwszQName,
											 const Attributes& attributes)
{
	if (wcscmp(pwszLocalName, L"feedList") == 0) {
		if (state_ != STATE_ROOT)
			return false;
		state_ = STATE_FEEDLIST;
	}
	else if (wcscmp(pwszLocalName, L"feed") == 0) {
		if (state_ != STATE_FEEDLIST)
			return false;

		const WCHAR* pwszURL = 0;
		const WCHAR* pwszLastModified = 0;
		for (int n = 0; n < attributes.getLength(); ++n) {
			const WCHAR* pwszAttrName = attributes.getLocalName(n);
			if (wcscmp(pwszAttrName, L"url") == 0)
				pwszURL = attributes.getValue(n);
			else if (wcscmp(pwszAttrName, L"lastModified") == 0)
				pwszLastModified = attributes.getValue(n);
			else
				return false;
		}
		if (!pwszURL || !pwszLastModified)
			return false;

		string_ptr strLastModified(wcs2mbs(pwszLastModified));
		Time timeLastModified;
		if (!DateParser::parse(strLastModified.get(),
			-1, DateParser::FLAG_NONE, &timeLastModified))
			return false;

		assert(!pCurrentFeed_);
		std::auto_ptr<Feed> pFeed(new Feed(pwszURL, timeLastModified));
		pCurrentFeed_ = pFeed.get();
		list_.push_back(pFeed.get());
		pFeed.release();

		state_ = STATE_FEED;
	}
	else if (wcscmp(pwszLocalName, L"item") == 0) {
		if (state_ != STATE_FEED)
			return false;

		const WCHAR* pwszDate = 0;
		for (int n = 0; n < attributes.getLength(); ++n) {
			const WCHAR* pwszAttrName = attributes.getLocalName(n);
			if (wcscmp(pwszAttrName, L"date") == 0)
				pwszDate = attributes.getValue(n);
			else
				return false;
		}

		// TODO
		// Allow that time is not specified for compatibility.
		// Make it error in the future.
		if (pwszDate) {
			int nYear = 0;
			int nMonth = 0;
			int nDay = 0;
			if (swscanf(pwszDate, L"%04d-%02d-%02d", &nYear, &nMonth, &nDay) != 3)
				return false;
			itemDate_.nYear_ = nYear;
			itemDate_.nMonth_ = nMonth;
			itemDate_.nDay_ = nDay;
		}
		else {
			itemDate_ = FeedItem::convertTimeToDate(Time::getCurrentTime());
		}

		state_ = STATE_ITEM;
	}
	else {
		return false;
	}

	return true;
}

bool qmrss::FeedContentHandler::endElement(const WCHAR* pwszNamespaceURI,
										   const WCHAR* pwszLocalName,
										   const WCHAR* pwszQName)
{
	if (wcscmp(pwszLocalName, L"feedList") == 0) {
		assert(state_ == STATE_FEEDLIST);

		pList_->setFeeds(list_);

		state_ = STATE_ROOT;
	}
	else if (wcscmp(pwszLocalName, L"feed") == 0) {
		assert(state_ == STATE_FEED);
		assert(pCurrentFeed_);

		pCurrentFeed_->setItems(listItem_);

		pCurrentFeed_ = 0;
		state_ = STATE_FEEDLIST;
	}
	else if (wcscmp(pwszLocalName, L"item") == 0) {
		assert(state_ == STATE_ITEM);

		if (buffer_.getLength() == 0)
			return false;

		std::auto_ptr<FeedItem> pItem(new FeedItem(
			buffer_.getCharArray(), itemDate_));
		listItem_.push_back(pItem.get());
		pItem.release();

		buffer_.remove();

		state_ = STATE_FEED;
	}
	else {
		return false;
	}

	return true;
}

bool qmrss::FeedContentHandler::characters(const WCHAR* pwsz,
										   size_t nStart,
										   size_t nLength)
{
	if (state_ == STATE_ITEM) {
		buffer_.append(pwsz + nStart, nLength);
	}
	else {
		const WCHAR* p = pwsz + nStart;
		for (size_t n = 0; n < nLength; ++n, ++p) {
			if (*p != L' ' && *p != L'\t' && *p != '\n')
				return false;
		}
	}

	return true;
}

/****************************************************************************
 *
 * FeedWriter
 *
 */

qmrss::FeedWriter::FeedWriter(Writer* pWriter,
							  const WCHAR* pwszEncoding) :
	handler_(pWriter, pwszEncoding)
{
}

qmrss::FeedWriter::~FeedWriter()
{
}

bool qmrss::FeedWriter::write(const FeedList& l)
{
	if (!handler_.startDocument() ||
		!handler_.startElement(0, 0, L"feedList", DefaultAttributes()))
		return false;

	const FeedList::List& list = l.getFeeds();
	for (FeedList::List::const_iterator itF = list.begin(); itF != list.end(); ++itF) {
		const Feed* pFeed = *itF;

		wstring_ptr wstrLastModified(DateParser::unparse(pFeed->getLastModified()));
		SimpleAttributes::Item items[] = {
			{ L"url",			pFeed->getURL()			},
			{ L"lastModified",	wstrLastModified.get()	}
		};
		SimpleAttributes attrs(items, countof(items));
		if (!handler_.startElement(0, 0, L"feed", attrs))
			return false;

		const Feed::ItemList& listItem = pFeed->getItems();
		for (Feed::ItemList::const_iterator itI = listItem.begin(); itI != listItem.end(); ++itI) {
			const FeedItem* pItem = *itI;

			const FeedItem::Date& date = pItem->getDate();
			WCHAR wszDate[32];
			_snwprintf(wszDate, countof(wszDate), L"%04d-%02d-%02d",
				date.nYear_, date.nMonth_, date.nDay_);

			if (!handler_.startElement(0, 0, L"item", SimpleAttributes(L"date", wszDate)) ||
				!handler_.characters(pItem->getKey(), 0, wcslen(pItem->getKey())) ||
				!handler_.endElement(0, 0, L"item"))
				return false;
		}

		if (!handler_.endElement(0, 0, L"feed"))
			return false;
	}

	if (!handler_.endElement(0, 0, L"feedList") ||
		!handler_.endDocument())
		return false;

	return true;
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 337779 $ -->

<refentry xml:id="intlchar.istitle" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>IntlChar::istitle</refname>
  <refpurpose>Check if code point is a titlecase letter</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <modifier>static</modifier> <type>bool</type><methodname>IntlChar::istitle</methodname>
   <methodparam><type>mixed</type><parameter>codepoint</parameter></methodparam>
  </methodsynopsis>
  <para>
   Determines whether the specified code point is a titlecase letter.
  </para>
  <para>
   &true; for general category "Lt" (titlecase letter).
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <variablelist>
   <varlistentry>
    <term><parameter>codepoint</parameter></term>
    <listitem>
     &intl.codepoint.parameter;
    </listitem>
   </varlistentry>
  </variablelist>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Returns &true; if
   <parameter>codepoint</parameter> is a titlecase letter, &false; if not.
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <example>
   <title>&intl.codepoint.example;</title>
   <programlisting role="php">
    <![CDATA[
<?php
var_dump(IntlChar::istitle("A"));
var_dump(IntlChar::istitle("a"));
var_dump(IntlChar::istitle("Φ"));
var_dump(IntlChar::istitle("φ"));
var_dump(IntlChar::istitle("1"));
?>
]]>
   </programlisting>
   &example.outputs;
   <screen>
    <![CDATA[
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
]]>
   </screen>
  </example>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>IntlChar::isupper</function></member>
    <member><function>IntlChar::islower</function></member>
    <member><function>IntlChar::totitle</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package com.amazonaws.services.route53.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.route53.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.XMLWriter;

/**
 * ListTrafficPoliciesRequest Marshaller
 */

public class ListTrafficPoliciesRequestMarshaller
        implements
        Marshaller<Request<ListTrafficPoliciesRequest>, ListTrafficPoliciesRequest> {

    public Request<ListTrafficPoliciesRequest> marshall(
            ListTrafficPoliciesRequest listTrafficPoliciesRequest) {

        if (listTrafficPoliciesRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<ListTrafficPoliciesRequest> request = new DefaultRequest<ListTrafficPoliciesRequest>(
                listTrafficPoliciesRequest, "AmazonRoute53");

        request.setHttpMethod(HttpMethodName.GET);

        String uriResourcePath = "/2013-04-01/trafficpolicies";

        request.setResourcePath(uriResourcePath);

        if (listTrafficPoliciesRequest.getTrafficPolicyIdMarker() != null) {
            request.addParameter("trafficpolicyid", StringUtils
                    .fromString(listTrafficPoliciesRequest
                            .getTrafficPolicyIdMarker()));
        }

        if (listTrafficPoliciesRequest.getMaxItems() != null) {
            request.addParameter("maxitems", StringUtils
                    .fromString(listTrafficPoliciesRequest.getMaxItems()));
        }

        return request;
    }

}


text:
@interface Tools : NSObject

+ (UIView *)customSnapShotFromView:(UIView *)inputView;

@end


text:
<?php
namespace Party\Model;

use Zend\Db\TableGateway\TableGateway;

class Party
{
	protected $tableGateway;

	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;

	}

	public function fetchAll()
	{
		$resultSet = $this->tableGateway->select();
		return $resultSet;
	}

	public function getParty($id)
	{
		$id  = (int) $id;
		$rowset = $this->tableGateway->select(array('id' => $id));
		$row = $rowset->current();
		if (!$row) {
			throw new \Exception("Could not find row $id");
		}
	}

	public function saveParty(PartyTable $PartyTable)
	{
		$data = array(
			user_name  =>$PartyTable->user_name,
			user_phone =>$PartyTable->user_phone,
			user_qq    =>$PartyTable->user_qq,
			user_call  =>$PartyTable->user_call,
			user_email =>$PartyTable->user_email,
			user_province =>$PartyTable->user_province,
			user_city =>$PartyTable->user_city,
			user_group =>$PartyTable->user_group,
			freetime_begin =>$PartyTable->freetime_begin,
			freetime_end =>$PartyTable->freetime_end,
			content =>$PartyTable->content,
			submit_time =>$PartyTable->submit_ip,
			submit_ip =>$PartyTable->submit_time,
		);
		$id = (int)$PartyTable->id;
		if ($id == 0) {
			$this->tableGateway->insert($data);
		}else {
			if ($this->getParty($id)) {
				$this->tableGateway->update($data, array('id' => $id));
			} else {
				throw new \Exception('Form id does not exist');
			}
		}
	}

	public function deleteParty($id)
	{
		$this->tableGateway->delete(array('id' => $id));
	}
}


text:
package org.jdesktop.html.form;

import org.jdesktop.http.Method;

/**
 * Represents the model portion of the HTML <form&gh; element. It does not
 * represent any information related to the structure of the HTML document (for
 * example, there is no id or name property), or any visual information.
 *
 * @author rbair
 */
public interface Form {
    /**
     * Returns the base url. The getAction() method is appended to this base
     * url to form the target url, if the action is a relative url.
     *
     * @return a string representing the base url, or null if there is not one.
     */
    public String getBaseUrl();
    /**
     * Returns the url that should be used when the form is submitted.
     *
     * @return a string representing the url to use. This may be a relative
     *         or absolute url.
     */
    public String getAction();

    /**
     * Gets the HTTP {@link Method} to use when the form is submitted.
     *
     * @return the Method to use on submit.
     */
    public Method getMethod();

    /**
     * Gets the array of {@link Input}s for this Form.
     *
     * @return an array of Inputs. The ordering of elements in
     *         this array is not guaranteed.
     */
    public Input[] getInputs();

    /**
     * Gets the Input with the given name. If more than one
     * Input has this name, it is unspecified which will be returned.
     *
     * @return the Input with the given name. May be null.
     */
    public Input getInput(String name);

    /**
     * Returns the {@link Encoding} used with this Form. By default, this is
     * UrlEncoded. The encoding is honored when submitting the form.
     *
     * @return a non-null value for the Encoding for this Form.
     */
    public Encoding getEncoding();
}


text:
package org.apache.hc.client5.http.impl.io;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.hc.client5.http.impl.Wire;

class LoggingOutputStream extends OutputStream {

    private final OutputStream out;
    private final Wire wire;

    public LoggingOutputStream(final OutputStream out, final Wire wire) {
        super();
        this.out = out;
        this.wire = wire;
    }

    @Override
    public void write(final int b) throws IOException {
        try {
            out.write(b);
            wire.output(b);
        } catch (final IOException ex) {
            wire.output("[write] I/O error: " + ex.getMessage());
            throw ex;
        }
    }

    @Override
    public void write(final byte[] b) throws IOException {
        try {
            wire.output(b);
            out.write(b);
        } catch (final IOException ex) {
            wire.output("[write] I/O error: " + ex.getMessage());
            throw ex;
        }
    }

    @Override
    public void write(final byte[] b, final int off, final int len) throws IOException {
        try {
            wire.output(b, off, len);
            out.write(b, off, len);
        } catch (final IOException ex) {
            wire.output("[write] I/O error: " + ex.getMessage());
            throw ex;
        }
    }

    @Override
    public void flush() throws IOException {
        try {
            out.flush();
        } catch (final IOException ex) {
            wire.output("[flush] I/O error: " + ex.getMessage());
            throw ex;
        }
    }

    @Override
    public void close() throws IOException {
        try {
            out.close();
        } catch (final IOException ex) {
            wire.output("[close] I/O error: " + ex.getMessage());
            throw ex;
        }
    }

}


text:
/**
 * This software is released as part of the Pumpernickel project.
 *
 * All com.pump resources in the Pumpernickel project are distributed under the
 * MIT License:
 * https://github.com/mickleness/pumpernickel/raw/master/License.txt
 *
 * More information about the Pumpernickel project is available here:
 * https://mickleness.github.io/pumpernickel/
 */
package com.pump.plaf;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;

import com.pump.swing.JGradientSlider;
import com.pump.swing.MultiThumbSlider;

/**
 * The UI for the GradientSlider class.
 *
 * There are a few properties you can use to customize the UI of a
 * GradientSlider. You can set these for each slider by calling:

 * slider.putClientProperty(key,value);
 *

 * Or you can set these globally by calling:

 * UIManager.put(key,value);
 *

 * The available properties are:
 *

 *

 *

 * Property Name
 * Default Value
 * Description
 *

 *

 * GradientSlider.useBevel
 * "false"
 * If this is true, then this slider will be painted in a
 * rectangle with a bevel effect around the borders. If this is
 * false, then this slider will be painted in a rounded rectangle.
 *

 *

 * GradientSlider.showTranslucency
 * "true"
 * If this is true, then the slider will reflect the opacity of
 * the colors in the gradient, and paint a checkered background underneath the
 * colors to indicate opacity. If this is false, then this slider
 * will always paint with completely opaque colors, although the actual colors
 * may be translucent.
 *

 *

 * GradientSlider.colorPickerIncludesOpacity
 * "true"
 * This is used when the user double-clicks a color and a JColorPicker
 * dialog is invoked. (So this value may not have any meaning if you override
 * GradientSlider.doDoubleClick().) This controls whether the
 * opacity/alpha controls are available in that dialog. This does not
 * control whether translucent colors can be used in this slider: translucent
 * colors are always allowed, if the user can enter them.
 *

 *

 * MultiThumbSlider.indicateComponent
 * "true"
 * If this is true, then the thumbs will only paint on this
 * component when the mouse is inside this slider or when this slider as
 * the keyboard focus.
 *

 *

 * MultiThumbSlider.indicateThumb
 * "true"
 * If this is true, then the thumb the mouse is over will
 * gently fade into a slightly different color.
 *

 *

 *
 */
public class GradientSliderUI extends MultiThumbSliderUI<Color> {
	int TRIANGLE_SIZE = 8;
	/**
	 * The width of this image is the absolute widest the track will ever
	 * become.
	 */
	BufferedImage img = new BufferedImage(1000, 1, BufferedImage.TYPE_INT_ARGB);
	/** A temporary array used for the buffered image */
	int[] array = new int[img.getWidth()];

	public GradientSliderUI(JGradientSlider slider) {
		super(slider);
	}

	@Override
	protected int getPreferredComponentDepth() {
		return 2 * TRIANGLE_SIZE;
	}

	protected void calculateImage() {
		float[] f = slider.getThumbPositions();
		Color[] c = slider.getValues();

		/**
		 * make sure we DO have a value at 0 and 1:
		 */
		if (f[0] != 0) {
			float[] f2 = new float[f.length + 1];
			System.arraycopy(f, 0, f2, 1, f.length);
			Color[] c2 = new Color[c.length + 1];
			System.arraycopy(c, 0, c2, 1, f.length);
			f = f2;
			c = c2;
			f[0] = 0;
			c[0] = c[1];
		}
		if (f[f.length - 1] != 1) {
			float[] f2 = new float[f.length + 1];
			System.arraycopy(f, 0, f2, 0, f.length);
			Color[] c2 = new Color[c.length + 1];
			System.arraycopy(c, 0, c2, 0, f.length);
			f = f2;
			c = c2;
			f[f.length - 1] = 1;
			c[c.length - 1] = c[c.length - 2];
		}

		/** Now, finally paint */
		int[] argb = new int[c.length];
		for (int a = 0; a < argb.length; a++) {
			argb[a] = ((c[a].getAlpha() & 0xff) << 24)
					+ ((c[a].getRed() & 0xff) << 16)
					+ ((c[a].getGreen() & 0xff) << 8)
					+ ((c[a].getBlue() & 0xff) << 0);
		}
		int max;
		if (slider.getOrientation() == MultiThumbSlider.HORIZONTAL) {
			max = trackRect.width;
		} else {
			max = trackRect.height;
		}
		if (max <= 0)
			return;

		boolean alwaysOpaque = getProperty(slider,
				"GradientSlider.showTranslucency", "true").equals("false");

		float fraction;
		int i1 = 0;
		int i2 = 1;
		int a1 = (argb[0] >> 24) & 0xff;
		int r1 = (argb[0] & 0x00ff0000) >> 16;
		int g1 = (argb[0] & 0x0000ff00) >> 8;
		int b1 = (argb[0] & 0x000000ff) >> 0;
		int a2 = (argb[1] >> 24) & 0xff;
		int r2 = (argb[1] & 0x00ff0000) >> 16;
		int g2 = (argb[1] & 0x0000ff00) >> 8;
		int b2 = (argb[1] & 0x000000ff) >> 0;
		for (int z = 0; z < max; z++) {
			fraction = ((float) z) / ((float) (max - 1));
			if (fraction < 1 && fraction >= f[i2]) {
				while (fraction < 1 && fraction >= f[i2]) {
					i1++;
					i2++;
				}

				a1 = (argb[i1] >> 24) & 0xff;
				r1 = (argb[i1] & 0x00ff0000) >> 16;
				g1 = (argb[i1] & 0x0000ff00) >> 8;
				b1 = (argb[i1] & 0x000000ff) >> 0;
				a2 = (argb[i2] >> 24) & 0xff;
				r2 = (argb[i2] & 0x00ff0000) >> 16;
				g2 = (argb[i2] & 0x0000ff00) >> 8;
				b2 = (argb[i2] & 0x000000ff) >> 0;
			}
			float colorFraction = (fraction - f[i1]) / (f[i2] - f[i1]);
			if (colorFraction > 1)
				colorFraction = 1;
			if (colorFraction < 0)
				colorFraction = 0;
			if (alwaysOpaque) {
				a1 = 255;
				a2 = 255;
			}
			array[z] = (((int) (a1 * (1 - colorFraction) + a2 * colorFraction)) << 24)
					+ (((int) (r1 * (1 - colorFraction) + r2 * colorFraction)) << 16)
					+ (((int) (g1 * (1 - colorFraction) + g2 * colorFraction)) << 8)
					+ (((int) (b1 * (1 - colorFraction) + b2 * colorFraction)));
		}
		img.getRaster().setDataElements(0, 0, max, 1, array);
	}

	@Override
	public Dimension getMinimumSize(JComponent s) {
		Dimension d = super.getMinimumSize(s);
		if (slider.getOrientation() == MultiThumbSlider.HORIZONTAL) {
			d.height += 2;
		} else {
			d.width += 2;
		}
		return d;
	}

	@Override
	public Dimension getPreferredSize(JComponent s) {
		Dimension d = super.getPreferredSize(s);
		if (slider.getOrientation() == MultiThumbSlider.HORIZONTAL) {
			d.height += 2;
		} else {
			d.width += 2;
		}
		return d;
	}

	@Override
	protected Rectangle calculateTrackRect() {
		int w = slider.getWidth();
		int h = slider.getHeight();

		Rectangle r = new Rectangle();

		if (slider.getOrientation() == MultiThumbSlider.HORIZONTAL) {
			r.x = TRIANGLE_SIZE;
			r.y = 3;
			r.height = h - TRIANGLE_SIZE - r.y;
			r.width = w - 2 * TRIANGLE_SIZE;
			if (r.width > img.getWidth()) {
				r.width = img.getWidth();
				r.x = (w - 2 * TRIANGLE_SIZE) / 2 - r.width / 2;
			}
			if (r.height > 2 * DEPTH) {
				r.height = 2 * DEPTH;
				r.y = (h - TRIANGLE_SIZE) / 2 - r.height / 2;
			}
		} else {
			r.x = 3;
			r.y = TRIANGLE_SIZE;
			r.width = w - TRIANGLE_SIZE - r.x;
			r.height = h - 2 * TRIANGLE_SIZE;
			if (r.height > img.getWidth()) {
				r.height = img.getWidth();
				r.y = (h - 2 * TRIANGLE_SIZE) / 2 - r.height / 2;
			}
			if (r.width > 2 * DEPTH) {
				r.width = 2 * DEPTH;
				r.x = (w - TRIANGLE_SIZE) / 2 - r.width / 2;
			}
		}
		return r;
	}

	@Override
	protected void calculateGeometry() {
		super.calculateGeometry();
		calculateImage();
	}

	static TexturePaint checkerPaint;

	private static void createCheckerPaint() {
		int k = 4;
		BufferedImage bi = new BufferedImage(2 * k, 2 * k,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = bi.createGraphics();
		g.setColor(Color.white);
		g.fillRect(0, 0, 2 * k, 2 * k);
		g.setColor(Color.lightGray);
		g.fillRect(0, 0, k, k);
		g.fillRect(k, k, k, k);
		checkerPaint = new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(),
				bi.getHeight()));
	}

	/**
	 * The "frame" includes the trackRect and possible some extra padding. For
	 * example, the frame might be the rounded rectangle enclosing the track (if
	 * rounded rectangles are turned on)
	 *
	 * @return
	 */
	private Shape getFrame() {

		if (getProperty(slider, "GradientSlider.useBevel", "false").equals(
				"true")) {
			return trackRect;
		}

		if (slider.getOrientation() == MultiThumbSlider.HORIZONTAL) {
			int curve = Math.min(TRIANGLE_SIZE - 2, trackRect.height / 2);
			return new RoundRectangle2D.Float(trackRect.x - curve, trackRect.y,
					trackRect.width + 2 * curve, trackRect.height, curve * 2,
					curve * 2);
		} else {
			int curve = Math.min(TRIANGLE_SIZE - 2, trackRect.width / 2);
			return new RoundRectangle2D.Float(trackRect.x, trackRect.y - curve,
					trackRect.width, trackRect.height + 2 * curve, curve * 2,
					curve * 2);
		}
	}

	@Override
	protected void paintTrack(Graphics2D g) {
		Composite oldComposite = g.getComposite();
		float alpha = slider.isEnabled() ? 1 : .5f;
		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
				alpha));

		Shape frame = getFrame();

		boolean alwaysOpaque = getProperty(slider,
				"GradientSlider.showTranslucency", "true").equals("false");

		if (alwaysOpaque == false) {
			if (checkerPaint == null)
				createCheckerPaint();
			g.setPaint(checkerPaint);
			g.fill(frame);
		}

		TexturePaint tp = new TexturePaint(img, new Rectangle(trackRect.x, 0,
				img.getWidth(), 1));
		g.setPaint(tp);
		AffineTransform oldTransform = null;

		oldTransform = g.getTransform();
		AffineTransform transform = new AffineTransform();
		if (slider.getOrientation() == MultiThumbSlider.VERTICAL) {
			if (slider.isInverted()) {
				transform.rotate(Math.PI / 2, trackRect.x, trackRect.y);
			} else {
				transform.rotate(-Math.PI / 2, trackRect.x, trackRect.y
						+ trackRect.height);
			}
		} else {
			if (slider.isInverted()) {
				// flip horizontal:
				double x1 = trackRect.x;
				double x2 = trackRect.x + trackRect.width;
				// m00*x1+m02 = x2
				// m00*x2+m02 = x1
				double m00 = (x2 - x1) / (x1 - x2);
				double m02 = x1 - m00 * x2;
				transform.setTransform(m00, 0, 0, 1, m02, 0);
			} else {
				// no transform necessary
			}
		}

		g.transform(transform);

		try {
			g.fill(transform.createInverse().createTransformedShape(trackRect));
		} catch (NoninvertibleTransformException e) {
			// this won't happen; unless a width/height
			// is zero somewhere, in which case we have nothing to paint anyway.
		}
		if (oldTransform != null) {
			g.setTransform(oldTransform);
		}
		if (getProperty(slider, "GradientSlider.useBevel", "false").equals(
				"true")) {
			PlafPaintUtils.drawBevel(g, trackRect);
		} else {
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
					RenderingHints.VALUE_ANTIALIAS_ON);
			Shape oldClip = g.getClip();
			int first, last;
			Color[] colors = slider.getValues();
			float[] f = slider.getThumbPositions();
			if ((slider.isInverted() == false && slider.getOrientation() == MultiThumbSlider.HORIZONTAL)
					|| (slider.isInverted() == true && slider.getOrientation() == MultiThumbSlider.VERTICAL)) {
				first = 0;
				last = colors.length - 1;
				while (f[first] < 0) {
					first++;
				}
				while (f[last] > 1) {
					last--;
				}
			} else {
				last = 0;
				first = colors.length - 1;
				while (f[last] < 0) {
					last++;
				}
				while (f[first] > 1) {
					first--;
				}
			}
			if (slider.getOrientation() == MultiThumbSlider.HORIZONTAL) {
				g.clip(frame);
				g.setColor(colors[first]);
				g.fillRect(0, 0, trackRect.x, slider.getHeight());
				g.setColor(colors[last]);
				g.fillRect(trackRect.x + trackRect.width, 0, slider.getWidth()
						- (trackRect.x + trackRect.width), slider.getHeight());
			} else {
				g.clip(frame);
				g.setColor(colors[first]);
				g.fillRect(0, 0, slider.getWidth(), trackRect.y);
				g.setColor(colors[last]);
				g.fillRect(0, trackRect.y + trackRect.height,
						slider.getWidth(), slider.getHeight()
								- (trackRect.y + trackRect.height));
			}
			g.setStroke(new BasicStroke(1));
			g.setClip(oldClip);
			g.setColor(new Color(0, 0, 0, 130));
			g.draw(frame);

			g.setColor(new Color(0, 0, 0, 130));
		}

		if (slider.isPaintTicks()) {
			paintTick(g, .25f, 2);
			paintTick(g, .5f, 2);
			paintTick(g, .75f, 2);
			paintTick(g, 0f, 2);
			paintTick(g, 1f, 2);
		}
		g.setComposite(oldComposite);
	}

	protected void paintTick(Graphics2D g, float f, int d) {
		if (slider.getOrientation() == MultiThumbSlider.HORIZONTAL) {
			int x = (int) (trackRect.x + trackRect.width * f + .5f);
			int y = trackRect.y + trackRect.height;
			g.drawLine(x, y, x, y + d);
			y = trackRect.y;
			g.drawLine(x, y, x, y - d);
		} else {
			int y = (int) (trackRect.y + trackRect.height * f + .5f);
			int x = trackRect.x + trackRect.width;
			g.drawLine(x, y, x + d, y);
			x = trackRect.x;
			g.drawLine(x, y, x - d, y);
		}
	}

	@Override
	protected void paintFocus(Graphics2D g) {

	}

	static GeneralPath hTriangle = null;
	static GeneralPath vTriangle = null;

	@Override
	protected void paintThumbs(Graphics2D g) {
		if (slider.isEnabled() == false)
			return;

		if (hTriangle == null) {
			hTriangle = new GeneralPath();
			hTriangle.moveTo(0, 0);
			hTriangle.lineTo(TRIANGLE_SIZE, TRIANGLE_SIZE);
			hTriangle.lineTo(-TRIANGLE_SIZE, TRIANGLE_SIZE);
			hTriangle.lineTo(0, 0);
			hTriangle.closePath();
			vTriangle = new GeneralPath();
			vTriangle.moveTo(0, 0);
			vTriangle.lineTo(TRIANGLE_SIZE, TRIANGLE_SIZE);
			vTriangle.lineTo(TRIANGLE_SIZE, -TRIANGLE_SIZE);
			vTriangle.lineTo(0, 0);
			vTriangle.closePath();
		}

		AffineTransform t = new AffineTransform();
		int dx = trackRect.x + trackRect.width;
		int dy = trackRect.y + trackRect.height;
		dy -= trackRect.height / 6;
		dx -= trackRect.width / 6;
		int selected = slider.getSelectedThumb(false);
		float[] f = slider.getThumbPositions();
		int orientation = slider.getOrientation();
		Shape shape;

		Composite oldComposite = g.getComposite();

		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
				indication));

		for (int a = 0; a < thumbPositions.length; a++) {
			if (f[a] >= 0 && f[a] <= 1 && a != selected) {
				if (orientation == MultiThumbSlider.HORIZONTAL) {
					dx = thumbPositions[a];
					shape = hTriangle;
				} else {
					dy = thumbPositions[a];
					shape = vTriangle;
				}
				t.setToTranslation(dx, dy);
				g.transform(t);

				float brightness = Math.max(0, thumbIndications[a] * .6f);

				g.setColor(new Color((int) (255 * brightness),
						(int) (255 * brightness), (int) (255 * brightness)));
				g.fill(shape);
				g.translate(-.5f, -.5f);

				g.setColor(new Color(255, 255, 255));

				g.draw(shape);
				g.translate(.5f, .5f);

				t.setToTranslation(-dx, -dy);
				g.transform(t);
			}
		}

		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
				indication));

		if (selected != -1 && f[selected] >= 0 && f[selected] <= 1) {
			if (orientation == MultiThumbSlider.HORIZONTAL) {
				dx = thumbPositions[selected];
				shape = hTriangle;
			} else {
				dy = thumbPositions[selected];
				shape = vTriangle;
			}
			t.setToTranslation(dx, dy);
			g.transform(t);

			g.setColor(new Color(255, 255, 255));
			g.fill(shape);
			g.translate(-.5f, -.5f);

			g.setColor(new Color(0, 0, 0));

			g.draw(shape);
			g.translate(.5f, .5f);

			t.setToTranslation(-dx, -dy);
			g.transform(t);
		}

		g.setComposite(oldComposite);
	}
}


text:
import os
import sys
import logging
import requests
import time
import traceback

import pytest
import ray
from ray.new_dashboard.tests.conftest import *  # noqa
from ray.test_utils import (
    format_web_url,
    wait_until_server_available,
    wait_for_condition,
)

logger = logging.getLogger(__name__)

def test_node_info(disable_aiohttp_cache, ray_start_with_dashboard):
    @ray.remote
    class Actor:
        def getpid(self):
            return os.getpid()

    actors = [Actor.remote(), Actor.remote()]
    actor_pids = [actor.getpid.remote() for actor in actors]
    actor_pids = set(ray.get(actor_pids))

    assert (wait_until_server_available(ray_start_with_dashboard["webui_url"])
            is True)
    webui_url = ray_start_with_dashboard["webui_url"]
    webui_url = format_web_url(webui_url)
    node_id = ray_start_with_dashboard["node_id"]

    timeout_seconds = 10
    start_time = time.time()
    last_ex = None
    while True:
        time.sleep(1)
        try:
            response = requests.get(webui_url + "/nodes?view=hostnamelist")
            response.raise_for_status()
            hostname_list = response.json()
            assert hostname_list["result"] is True, hostname_list["msg"]
            hostname_list = hostname_list["data"]["hostNameList"]
            assert len(hostname_list) == 1

            hostname = hostname_list[0]
            response = requests.get(webui_url + f"/nodes/{node_id}")
            response.raise_for_status()
            detail = response.json()
            assert detail["result"] is True, detail["msg"]
            detail = detail["data"]["detail"]
            assert detail["hostname"] == hostname
            assert detail["raylet"]["state"] == "ALIVE"
            assert "raylet" in detail["cmdline"][0]
            assert len(detail["workers"]) >= 2
            assert len(detail["actors"]) == 2, detail["actors"]
            assert len(detail["raylet"]["viewData"]) > 0

            actor_worker_pids = set()
            for worker in detail["workers"]:
                if "ray::Actor" in worker["cmdline"][0]:
                    actor_worker_pids.add(worker["pid"])
            assert actor_worker_pids == actor_pids

            response = requests.get(webui_url + "/nodes?view=summary")
            response.raise_for_status()
            summary = response.json()
            assert summary["result"] is True, summary["msg"]
            assert len(summary["data"]["summary"]) == 1
            summary = summary["data"]["summary"][0]
            assert summary["hostname"] == hostname
            assert summary["raylet"]["state"] == "ALIVE"
            assert "raylet" in summary["cmdline"][0]
            assert "workers" not in summary
            assert "actors" not in summary
            assert "viewData" not in summary["raylet"]
            break
        except Exception as ex:
            last_ex = ex
        finally:
            if time.time() > start_time + timeout_seconds:
                ex_stack = traceback.format_exception(
                    type(last_ex), last_ex,
                    last_ex.__traceback__) if last_ex else []
                ex_stack = "".join(ex_stack)
                raise Exception(f"Timed out while testing, {ex_stack}")

def test_memory_table(disable_aiohttp_cache, ray_start_with_dashboard):
    assert (wait_until_server_available(ray_start_with_dashboard["webui_url"]))

    @ray.remote
    class ActorWithObjs:
        def __init__(self):
            self.obj_ref = ray.put([1, 2, 3])

        def get_obj(self):
            return ray.get(self.obj_ref)

    my_obj = ray.put([1, 2, 3] * 100)  # noqa
    actors = [ActorWithObjs.remote() for _ in range(2)]  # noqa
    results = ray.get([actor.get_obj.remote() for actor in actors])  # noqa
    webui_url = format_web_url(ray_start_with_dashboard["webui_url"])
    resp = requests.get(
        webui_url + "/memory/set_fetch", params={"shouldFetch": "true"})
    resp.raise_for_status()

    def check_mem_table():
        resp = requests.get(f"{webui_url}/memory/memory_table")
        resp_data = resp.json()
        if not resp_data["result"]:
            return False
        latest_memory_table = resp_data["data"]["memoryTable"]
        summary = latest_memory_table["summary"]
        try:
            # 1 ref per handle and per object the actor has a ref to
            assert summary["totalActorHandles"] == len(actors) * 2
            # 1 ref for my_obj
            assert summary["totalLocalRefCount"] == 1
            return True
        except AssertionError:
            return False

    wait_for_condition(check_mem_table, 10)

def test_get_all_node_details(disable_aiohttp_cache, ray_start_with_dashboard):
    assert (wait_until_server_available(ray_start_with_dashboard["webui_url"]))

    webui_url = format_web_url(ray_start_with_dashboard["webui_url"])

    @ray.remote
    class ActorWithObjs:
        def __init__(self):
            print("I also log a line")
            self.obj_ref = ray.put([1, 2, 3])

        def get_obj(self):
            return ray.get(self.obj_ref)

    actors = [ActorWithObjs.remote() for _ in range(2)]  # noqa
    timeout_seconds = 20
    start_time = time.time()
    last_ex = None

    def check_node_details():
        resp = requests.get(f"{webui_url}/nodes?view=details")
        resp_json = resp.json()
        resp_data = resp_json["data"]
        clients = resp_data["clients"]
        node = clients[0]
        assert len(clients) == 1
        assert len(node.get("actors")) == 2
        # Workers information should be in the detailed payload
        assert "workers" in node
        assert "logCount" in node
        assert node["logCount"] == 2
        print(node["workers"])
        assert len(node["workers"]) == 2
        assert node["workers"][0]["logCount"] == 1

    while True:
        time.sleep(1)
        try:
            check_node_details()
            break
        except (AssertionError, KeyError, IndexError) as ex:
            last_ex = ex
        finally:
            if time.time() > start_time + timeout_seconds:
                ex_stack = traceback.format_exception(
                    type(last_ex), last_ex,
                    last_ex.__traceback__) if last_ex else []
                ex_stack = "".join(ex_stack)
                raise Exception(f"Timed out while testing, {ex_stack}")

@pytest.mark.parametrize(
    "ray_start_cluster_head", [{
        "include_dashboard": True
    }], indirect=True)
def test_multi_nodes_info(enable_test_module, disable_aiohttp_cache,
                          ray_start_cluster_head):
    cluster = ray_start_cluster_head
    assert (wait_until_server_available(cluster.webui_url) is True)
    webui_url = cluster.webui_url
    webui_url = format_web_url(webui_url)
    cluster.add_node()
    cluster.add_node()

    def _check_nodes():
        try:
            response = requests.get(webui_url + "/nodes?view=summary")
            response.raise_for_status()
            summary = response.json()
            assert summary["result"] is True, summary["msg"]
            summary = summary["data"]["summary"]
            assert len(summary) == 3
            for node_info in summary:
                node_id = node_info["raylet"]["nodeId"]
                response = requests.get(webui_url + f"/nodes/{node_id}")
                response.raise_for_status()
                detail = response.json()
                assert detail["result"] is True, detail["msg"]
                detail = detail["data"]["detail"]
                assert detail["raylet"]["state"] == "ALIVE"
            response = requests.get(webui_url + "/test/dump?key=agents")
            response.raise_for_status()
            agents = response.json()
            assert len(agents["data"]["agents"]) == 3
            return True
        except Exception as ex:
            logger.info(ex)
            return False

    wait_for_condition(_check_nodes, timeout=10)

if __name__ == "__main__":
    sys.exit(pytest.main(["-v", __file__]))


text:
<?php

namespace Symfony\Tests\Component\Form;

require_once __DIR__ . '/Fixtures/Author.php';
require_once __DIR__ . '/Fixtures/TestField.php';

use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormConfiguration;
use Symfony\Component\Form\Field;
use Symfony\Component\Form\HiddenField;
use Symfony\Component\Form\FieldGroup;
use Symfony\Component\Form\PropertyPath;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Tests\Component\Form\Fixtures\Author;
use Symfony\Tests\Component\Form\Fixtures\TestField;

class FormTest_PreconfiguredForm extends Form
{
    protected function configure()
    {
        $this->add(new Field('firstName'));

        parent::configure();
    }
}

class TestSetDataBeforeConfigureForm extends Form
{
    protected $testCase;
    protected $object;

    public function __construct($testCase, $name, $object, $validator)
    {
        $this->testCase = $testCase;
        $this->object = $object;

        parent::__construct($name, $object, $validator);
    }

    protected function configure()
    {
        $this->testCase->assertEquals($this->object, $this->getData());

        parent::configure();
    }
}

class FormTest extends \PHPUnit_Framework_TestCase
{
    protected $validator;
    protected $form;

    public static function setUpBeforeClass()
    {
        @session_start();
    }

    protected function setUp()
    {
        FormConfiguration::disableDefaultCsrfProtection();
        FormConfiguration::setDefaultCsrfSecret(null);
        $this->validator = $this->createMockValidator();
        $this->form = new Form('author', new Author(), $this->validator);
    }

    public function testConstructInitializesObject()
    {
        $this->assertEquals(new Author(), $this->form->getData());
    }

    public function testSetDataBeforeConfigure()
    {
        new TestSetDataBeforeConfigureForm($this, 'author', new Author(), $this->validator);
    }

    public function testIsCsrfProtected()
    {
        $this->assertFalse($this->form->isCsrfProtected());

        $this->form->enableCsrfProtection();

        $this->assertTrue($this->form->isCsrfProtected());

        $this->form->disableCsrfProtection();

        $this->assertFalse($this->form->isCsrfProtected());
    }

    public function testNoCsrfProtectionByDefault()
    {
        $form = new Form('author', new Author(), $this->validator);

        $this->assertFalse($form->isCsrfProtected());
    }

    public function testDefaultCsrfProtectionCanBeEnabled()
    {
        FormConfiguration::enableDefaultCsrfProtection();
        $form = new Form('author', new Author(), $this->validator);

        $this->assertTrue($form->isCsrfProtected());
    }

    public function testGeneratedCsrfSecretByDefault()
    {
        $form = new Form('author', new Author(), $this->validator);
        $form->enableCsrfProtection();

        $this->assertTrue(strlen($form->getCsrfSecret()) >= 32);
    }

    public function testDefaultCsrfSecretCanBeSet()
    {
        FormConfiguration::setDefaultCsrfSecret('foobar');
        $form = new Form('author', new Author(), $this->validator);
        $form->enableCsrfProtection();

        $this->assertEquals('foobar', $form->getCsrfSecret());
    }

    public function testDefaultCsrfFieldNameCanBeSet()
    {
        FormConfiguration::setDefaultCsrfFieldName('foobar');
        $form = new Form('author', new Author(), $this->validator);
        $form->enableCsrfProtection();

        $this->assertEquals('foobar', $form->getCsrfFieldName());
    }

    public function testCsrfProtectedFormsHaveExtraField()
    {
        $this->form->enableCsrfProtection();

        $this->assertTrue($this->form->has($this->form->getCsrfFieldName()));

        $field = $this->form->get($this->form->getCsrfFieldName());

        $this->assertTrue($field instanceof HiddenField);
        $this->assertGreaterThanOrEqual(32, strlen($field->getDisplayedData()));
    }

    public function testIsCsrfTokenValidPassesIfCsrfProtectionIsDisabled()
    {
        $this->form->bind(array());

        $this->assertTrue($this->form->isCsrfTokenValid());
    }

    public function testIsCsrfTokenValidPasses()
    {
        $this->form->enableCsrfProtection();

        $field = $this->form->getCsrfFieldName();
        $token = $this->form->get($field)->getDisplayedData();

        $this->form->bind(array($field => $token));

        $this->assertTrue($this->form->isCsrfTokenValid());
    }

    public function testIsCsrfTokenValidFails()
    {
        $this->form->enableCsrfProtection();

        $field = $this->form->getCsrfFieldName();

        $this->form->bind(array($field => 'foobar'));

        $this->assertFalse($this->form->isCsrfTokenValid());
    }

    public function testValidationGroupsCanBeSet()
    {
        $form = new Form('author', new Author(), $this->validator);

        $this->assertNull($form->getValidationGroups());
        $form->setValidationGroups('group');
        $this->assertEquals(array('group'), $form->getValidationGroups());
        $form->setValidationGroups(array('group1', 'group2'));
        $this->assertEquals(array('group1', 'group2'), $form->getValidationGroups());
        $form->setValidationGroups(null);
        $this->assertNull($form->getValidationGroups());
    }

    public function testBindUsesValidationGroups()
    {
        $field = $this->createMockField('firstName');
        $form = new Form('author', new Author(), $this->validator);
        $form->add($field);
        $form->setValidationGroups('group');

        $this->validator->expects($this->once())
                                        ->method('validate')
                                        ->with($this->equalTo($form), $this->equalTo(array('group')));

        $form->bind(array()); // irrelevant
    }

    public function testBindThrowsExceptionIfNoValidatorIsSet()
    {
        $field = $this->createMockField('firstName');
        $form = new Form('author', new Author());
        $form->add($field);
        $form->setValidationGroups('group');

        $this->setExpectedException('Symfony\Component\Form\Exception\FormException');

        $form->bind(array()); // irrelevant
    }

    public function testMultipartFormsWithoutParentsRequireFiles()
    {
        $form = new Form('author', new Author(), $this->validator);
        $form->add($this->createMultipartMockField('file'));

        $this->setExpectedException('InvalidArgumentException');

        // should be given in second argument
        $form->bind(array('file' => 'test.txt'));
    }

    public function testMultipartFormsWithParentsRequireNoFiles()
    {
        $form = new Form('author', new Author(), $this->validator);
        $form->add($this->createMultipartMockField('file'));

        $form->setParent($this->createMockField('group'));

        // files are expected to be converted by the parent
        $form->bind(array('file' => 'test.txt'));
    }

    public function testUpdateFromPropertyIsIgnoredIfFormHasObject()
    {
        $author = new Author();
        $author->child = new Author();
        $standaloneChild = new Author();

        $form = new Form('child', $standaloneChild);
        $form->updateFromProperty($author);

        // should not be $author->child!!
        $this->assertSame($standaloneChild, $form->getData());
    }

    public function testUpdateFromPropertyIsNotIgnoredIfFormHasNoObject()
    {
        $author = new Author();
        $author->child = new Author();

        $form = new Form('child');
        $form->updateFromProperty($author);

        // should not be $author->child!!
        $this->assertSame($author->child, $form->getData());
    }

    public function testUpdatePropertyIsIgnoredIfFormHasObject()
    {
        $author = new Author();
        $author->child = $child = new Author();
        $standaloneChild = new Author();

        $form = new Form('child', $standaloneChild);
        $form->updateProperty($author);

        // $author->child was not modified
        $this->assertSame($child, $author->child);
    }

    public function testUpdatePropertyIsNotIgnoredIfFormHasNoObject()
    {
        $author = new Author();
        $child = new Author();

        $form = new Form('child');
        $form->setData($child);
        $form->updateProperty($author);

        // $author->child was set
        $this->assertSame($child, $author->child);
    }

    protected function createMockField($key)
    {
        $field = $this->getMock(
            'Symfony\Component\Form\FieldInterface',
            array(),
            array(),
            '',
            false, // don't use constructor
            false  // don't call parent::__clone
        );

        $field->expects($this->any())
                    ->method('getKey')
                    ->will($this->returnValue($key));

        return $field;
    }

    protected function createMockFieldGroup($key)
    {
        $field = $this->getMock(
            'Symfony\Component\Form\FieldGroup',
            array(),
            array(),
            '',
            false, // don't use constructor
            false  // don't call parent::__clone
        );

        $field->expects($this->any())
                    ->method('getKey')
                    ->will($this->returnValue($key));

        return $field;
    }

    protected function createMultipartMockField($key)
    {
        $field = $this->createMockField($key);
        $field->expects($this->any())
                    ->method('isMultipart')
                    ->will($this->returnValue(true));

        return $field;
    }

    protected function createMockValidator()
    {
        return $this->getMock('Symfony\Component\Validator\ValidatorInterface');
    }
}


text:
package client

import (
	"bytes"
	"fmt"
	"io"
	"net"
	"net/url"
)

const (
	// UDPPayloadSize is a reasonable default payload size for UDP packets that
	// could be travelling over the internet.
	UDPPayloadSize = 512
)

// UDPConfig is the config data needed to create a UDP Client
type UDPConfig struct {
	// URL should be of the form "udp://host:port"
	// or "udp://[ipv6-host%zone]:port".
	URL string

	// PayloadSize is the maximum size of a UDP client message, optional
	// Tune this based on your network. Defaults to UDPPayloadSize.
	PayloadSize int
}

// NewUDP will return an instance of the telegraf UDP output plugin for influxdb
func NewUDP(config UDPConfig) (Client, error) {
	p, err := url.Parse(config.URL)
	if err != nil {
		return nil, fmt.Errorf("Error parsing UDP url [%s]: %s", config.URL, err)
	}

	udpAddr, err := net.ResolveUDPAddr("udp", p.Host)
	if err != nil {
		return nil, fmt.Errorf("Error resolving UDP Address [%s]: %s", p.Host, err)
	}

	conn, err := net.DialUDP("udp", nil, udpAddr)
	if err != nil {
		return nil, fmt.Errorf("Error dialing UDP address [%s]: %s",
			udpAddr.String(), err)
	}

	size := config.PayloadSize
	if size == 0 {
		size = UDPPayloadSize
	}
	buf := make([]byte, size)
	return &udpClient{conn: conn, buffer: buf}, nil
}

type udpClient struct {
	conn   *net.UDPConn
	buffer []byte
}

// Query will send the provided query command to the client, returning an error if any issues arise
func (c *udpClient) Query(command string) error {
	return nil
}

// Write will send the byte stream to the given UDP client endpoint
func (c *udpClient) Write(b []byte) (int, error) {
	return c.WriteStream(bytes.NewReader(b), -1)
}

// WriteWithParams are ignored by the UDP client, will forward to WriteStream
func (c *udpClient) WriteWithParams(b []byte, wp WriteParams) (int, error) {
	return c.WriteStream(bytes.NewReader(b), -1)
}

// WriteStream will send the provided data through to the client, contentLength is ignored by the UDP client
func (c *udpClient) WriteStream(r io.Reader, contentLength int) (int, error) {
	var totaln int
	for {
		nR, err := r.Read(c.buffer)
		if nR == 0 {
			break
		}
		if err != io.EOF && err != nil {
			return totaln, err
		}
		nW, err := c.conn.Write(c.buffer[0:nR])
		totaln += nW
		if err != nil {
			return totaln, err
		}
	}
	return totaln, nil
}

// WriteStreamWithParams will forward the stream to the client backend, contentLength is ignored by the UDP client
// write params are ignored by the UDP client
func (c *udpClient) WriteStreamWithParams(r io.Reader, contentLength int, wp WriteParams) (int, error) {
	return c.WriteStream(r, -1)
}

// Close will terminate the provided client connection
func (c *udpClient) Close() error {
	return c.conn.Close()
}


text:
<?php $this->pageTitle = Yii::$app->name . ' - ' . Yii::t('mypurse', 'My Purse') . ": " . Yii::t('mypurse', 'Withdraw Money'). ": " . $PaymentSystem->getName(); ?>

<?php print Yii::t('mypurse', 'My Purse') . " » " . Yii::t('mypurse', 'Withdraw Money') . " » " . $PaymentSystem->getName(); ?>

<?php $this->renderPartial('//layouts/messages'); ?>

<?php print Yii::t('mypurse', 'Your Balance') ?>: $<?php print $model->balance ?>

        <?php $form = $this->beginWidget('CActiveForm'); ?>

            <?php echo CHtml::image($PaymentSystem->withdrawLogo(), $PaymentSystem->getName(), array('class'=>'withdraw-logo')); ?>

            <?php echo $form->labelEx($model, 'amount'); ?>
            <?php echo $form->textField($model, 'amount', array('class' => 'text')); ?>
            <?php echo $form->error($model, 'amount'); ?>

            <?php echo $form->labelEx($model, 'paymentSystemInfo'); ?>
            <?php echo $PaymentSystem->getField($form, $model); ?>
            <?php echo $form->error($model, 'paymentSystemInfo'); ?>

            <?php echo $form->labelEx($model, 'clientWish'); ?>
            <?php echo $form->textArea($model, 'clientWish', array('class' => 'text')); ?>
            <?php echo $form->error($model, 'clientWish'); ?>

            1 USD = <?= Currency::getUSDCrossCurs('RUR'); ?> RUR

            1 USD = <?= Currency::getUSDCrossCurs('UAH'); ?> UAH

            <?= Yii::t('mypurse', 'Currency exchange is taken twice a day from the official site').' '. CHtml::link(Yii::t('mypurse', 'CBR'), 'http://www.cbr.ru', array('target' => '_blank')) ?>

            <?= Yii::t('mypurse', 'For withdrawal of funds in russian rubles  - usage the official rate of exchange').' '. CHtml::link(Yii::t('mypurse', 'CBR'), 'http://www.cbr.ru', array('target' => '_blank')) ?>

            <?= Yii::t('mypurse', 'For withdrawal of funds in U.S. dollars - the exchange rate is not considered') ?>

            <?= Yii::t('mypurse', 'If you withdraw funds in any other foreign currency - calculate cross-rate for the selected currency') ?>

            <?php print CHtml::link(Yii::t('mypurse', 'Choose another method'), array('index'), array('class' => 'styling grey_button')); ?>
            <?php echo CHtml::submitButton(Yii::t('mypurse', 'Send Request'), array('class' => 'submit')); ?>

        <?php $this->endWidget(); ?>


text:
/**
 * TODO fillme.
 */
package org.apache.ibatis.logging.commons;


text:
static NSString *cellId = @"cellId";

@interface ViewController ()<UITableViewDataSource>

@property (nonatomic,copy)NSArray <CZAppInfo *>*applist;

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSOperationQueue *downloadQueue;

//内存缓存池
@property (nonatomic,strong)NSMutableDictionary *imageCache;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _downloadQueue = [[NSOperationQueue alloc]init];

    //异步执行加载数据,方法完成后,不会立即得到结果
    [self loadData];
}

-(void)loadView {
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];

    self.view = _tableView;

    _tableView.rowHeight = 100;
    [_tableView registerNib:[UINib nibWithNibName:@"CZAppCell" bundle:nil] forCellReuseIdentifier:cellId];

    _tableView.dataSource = self;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loadData {

    //1.管理器

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    //2.get请求数据
    [manager GET:@"https://raw.githubusercontent.com/jingyu982887078/Demo/master/apps.json" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSArray * responseObject) {

        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in responseObject) {

            //创建模型
            CZAppInfo *model = [[CZAppInfo alloc]init];

            //字典转模型
            [model setValuesForKeysWithDictionary:dict];

            //添加到数组
            [arrayM addObject:model];

        }
        self.applist = arrayM;

        [self.tableView reloadData];
    }
         failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"错误是%@",error);
    }];

}

#pragma mark -UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _applist.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZAppCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];

    cell.nameLabel.text = _applist[indexPath.row].name;
    cell.downLabel.text = _applist[indexPath.row].download;

    if (cell.iconView.image != nil) {
//        cell.iconView.image = _applist[indexPath.row].image;
        NSLog(@"内存缓存");
        return cell;

    }

    NSURL *url = [NSURL URLWithString:_applist[indexPath.row].icon];

    //添加站位图像,不适用站位凸显个,会出现cell的复用现象
    UIImage *placehoder = [UIImage imageNamed:@"user_default"];
    cell.iconView.image  = placehoder;

    //加载图像
    //创建操作
    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{

        [NSThread sleepForTimeInterval:1];
        //将url转换成二进制数据
        NSData *data = [NSData dataWithContentsOfURL:url];
        //二进制数据转换成图片
        UIImage *image = [UIImage imageWithData:data];

        _applist[indexPath.row].image = image;
        //主线程更新ui
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{

            cell.iconView.image = image;
        }];

    }];
    //将操作添加到队列
    [_downloadQueue addOperation:op];

    return cell;
}

@end


text:
import unittest

import signac.db

try:
    signac.db.get_database('testing', hostname='testing')
except signac.common.errors.ConfigError:
    SKIP_REASON = "No 'testing' host configured."
except ImportError:
    SKIP_REASON = "pymongo not available"
else:
    SKIP_REASON = None
    import signac.common.host

@unittest.skipIf(SKIP_REASON is not None, SKIP_REASON)
class DBTest(unittest.TestCase):

    def get_test_db(self):
        signac.db.get_database('testing', hostname='testing')

    def test_get_connector(self):
        host_config = signac.common.host.get_host_config(hostname='testing')
        signac.common.host.get_connector(host_config)

    def test_get_connector_no_client(self):
        host_config = signac.common.host.get_host_config(hostname='testing')
        c = signac.common.host.get_connector(host_config)
        with self.assertRaises(RuntimeError):
            c.client

    def test_get_client(self):
        host_config = signac.common.host.get_host_config(hostname='testing')
        signac.common.host.get_client(host_config)

    def test_connector_get_host(self):
        host_config = signac.common.host.get_host_config(hostname='testing')
        c = signac.common.host.get_connector(host_config)
        self.assertEqual(host_config['url'], c.host)
        self.assertEqual(host_config, c.config)

    def test_logout(self):
        host_config = signac.common.host.get_host_config(hostname='testing')
        c = signac.common.host.get_connector(host_config)
        with self.assertRaises(RuntimeError):
            c.client
        c.connect()
        c.client
        c.authenticate()
        c.logout()

if __name__ == '__main__':
    unittest.main()


text:
This library provides an interface to the KCL MultiLangDaemon, which is part of the
[Amazon Kinesis Client Library](https://github.com/awslabs/amazon-kinesis-client). This interface manages the
interaction with the MultiLangDaemon so that developers can focus on
implementing their record processor executable. A record processor executable
typically looks something like:

```go
package main

import(
	"github.com/marcy-go/kcl"
)

type Sample struct {}

func (s *Sample) Init(str string) error {
	return nil
}

func (s *Sample) ProcessRecords(rs []*kcl.Record, cp *kcl.CheckPointer) error {
	return nil
}

func (s *Sample) Shutdown(cp *kcl.CheckPointer, reason string) error {
	return nil
}

func main() {
	var rp kcl.RecordProcessor
	rp = &Sample{}
	p := kcl.NewProcess(rp)
	p.Run()
}
```

Note, the initial implementation of this library is largely based on the reference [Amazon Kinesis Client Library for Python](https://github.com/awslabs/amazon-kinesis-client-python) provided by Amazon.

## Usage
#### 1. Write and build your `RecordProcessor`.
If your want to run a sample implementation, you get the sample binary from here:
https://drone.io/github.com/marcy-go/kclsample/files
#### 2. Write `properties` file like this:
```properties
executableName          = /path/to/kclsample
streamName              = kclsample
applicationName         = GoKCLSample
AWSCredentialsProvider  = DefaultAWSCredentialsProviderChain
processingLanguage      = go/1.3.1
initialPositionInStream = TRIM_HORIZON
regionName              = ap-northeast-1
```
#### 3. Get `kclhelper` binary for your environment from here:
https://drone.io/github.com/marcy-go/kclhelper/files
#### 4. Exec `kclhelper` command.
```sh
# Get Jar files from Maven projects
kclhelper setup
# Run KCL
kclhelper run -p <path-to-properties> [-j <path-to-java>]
```

# Changelog

See [CHANGELOG](https://github.com/marcy-go/kcl/blob/master/CHANGELOG.md)

## Contributing

1. Fork it ( https://github.com/marcy-go/kcl/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

# License

[MIT License](https://github.com/marcy-go/kcl/blob/master/LICENSE.txt)


text:
<?php

use Illuminate\Database\Migrations\Migration;

class UpdateDbEncodingToUt8mb4 extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Migration removed due to issues during live migration.
        // Instead you can run the command `artisan bookstack:db-utf8mb4`
        // which will generate out the SQL request to upgrade your DB to utf8mb4.
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>SoundManager 2 Start-up Test / Troubleshooting Tool</title>
<meta name="description" content="A standalone version of the SoundManager 2 Start-up Troubleshooting Tool." />
<meta name="keywords" content="javascript sound, javascript audio, javascript play mp3, javascript sound control, javascript video, mp3, mp4, mpeg4" />
<meta name="robots" content="all" />
<meta name="author" content="Scott Schiller" />
<meta name="copyright" content="Copyright (C) 1997 onwards Scott Schiller" />
<meta name="language" content="en-us" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="screen" href="../demo/index.css" />
<link rel="stylesheet" type="text/css" media="screen" href="debug.css" />

<link rel="stylesheet" type="text/css" href="../flashblock/flashblock.css" />

Flash options: Flash 8 (default), Flash 9 (normal) or Flash 9 + highPerformance + fastPolling modes.

OKFAILN/AUnknownSoundManager 2 start-up

soundManager onready() or ontimeout() events are ultimately called when start-up completes.

If you're seeing a failure, refer to the below for troubleshooting details for common causes.

OKErrorN/AUnknownFlash

Flash 8 or 9 may be required for SoundManager 2 to start, depending on HTML5 support. You are currently using [unknown].

OKErrorN/AUnknownFlash SWF

SoundManager 2 must load a flash movie before initialisation can proceed. If you have errors here, check that soundManager.url is correctly defined and that the URL being loaded is correct.

If the Flash movie URL is OK, Flash security or flash blockers are the likely cause. Check the section below.

OKErrorN/AUnknownFlash -> JS

Once the flash component of SM2 has loaded, it tries to make a call to Javascript-land. This is a common point of failure, for security reasons:

Have a flash blocker? Check that the SM2 flash movie (below) is loading and is not being blocked.

	Is your browser URL at file:// or c:/path/ or otherwise not using HTTP? Flash security "whitelisting" is required to allow Flash + JS to work when offline, placing it in the "LocalTrusted" Flash security sandbox rather than "localWithFile".

Offline viewing: Adding a "trusted location" to the Flash Security Settings Panel

The Flash Player Global Security Settings Panel is a web-based control panel which allows you to configure Flash security. You will need to add the path of the SoundManager 2 project in order for it to work "offline" (ie., when viewing via file:// or c:/)

Show me how: Adding a "trusted location"

Illustrated guide: Adding a "trusted location" in Flash

Below: Adding a location, and selecting "Browse for folder" (or directory), to whitelist the SoundManager 2 project directory for offline viewing.

Launch the Flash Security Settings Panel

Flash blockers (FlashBlock, "click to flash" etc.) preventing flash load and start-up - need whitelisting/"allow this domain" to work smoothly. If you suspect blocking is the issue, try the SoundManager 2 Flashblock demo.

Online viewing (HTTP/S): Same-domain security rules apply to HTML + Flash content by default (crossdomain.xml/allowDomain() in .AS source required to override.)

See Flash debug output for more security error details.

Online viewing: Cross-domain security restrictions

HTML page on domain A loading .SWF from domain B: Flash security prevents JS + Flash when a cross-domain XML permission file is not available on domain B, and/or flash movie was not compiled with allowDomain('domainA') or allowDomain('*') - note that the SWF distributed with SM2 does not use this by default; try using the cross-domain version of the SWF, or compile your own which whitelists your own domain(s).

Flash Blockers

Browser extensions/add-ons like "FlashBlock" and "click to flash" can prevent the .SWF from loading, and this will mean SM2 will time-out and fail waiting for a response from Flash. For development, it's best to whitelist the domain(s) or the .SWF for SM2 to allow it to work.

Have a flash blocker installed? Want to test it? Try the SoundManager 2 Flashblock demo.

OKErrorN/AUnknownJS -> Flash

At this point, Javascript attempts to respond to Flash's initial outgoing Flash -> JS call, completing the test for JS/flash communication. If SM2 does not receive a response from flash, it will eventually fail.

Offline viewing conditions and cross-domain security rules will prevent Flash <-> JS communication. See the details of Flash -> JS for information.

Special Firefox Note: Some versions of Firefox (9.0 and newer?) may break JS/Flash in the file:// or offline case even when the path has been whitelisted in the Flash player security settings panel. IE, Chrome, Safari and Opera do not have this issue.

OKErrorN/AUnknownSound test

Here, a simple createSound() call is made to test SM2's actual operation. A sound should load and play provided SM2 was able to start successfully.


text:
@interface DFLiveDetailInfoView : UIView

@property(nonatomic,strong) UIView          *toolbarView;

@property(nonatomic,strong) UIImageView     *liverHeadView;

@property(nonatomic,strong) UILabel         *liverNameLabel;

@property(nonatomic,strong) UIButton        *fullScreenBtn;

@property(nonatomic,strong) UIButton        *chatBtn;

@property(nonatomic,strong) UIButton        *shareBtn;

@property(nonatomic,strong) UIView          *descriptionView;

@property(nonatomic,strong) UILabel         *descriptionTitleLabel;

@property(nonatomic,strong) UILabel         *descriptionContentLabel;

@property(nonatomic,strong) UIButton        *remindMeBtn;

@end


text:
---
layout: post
title: "CWAC-Camera - An Easier Way to Take Photos in Android"
author: Curtis Martin
categories: [development, libraries, tools]
tags: [camera, opensource]

redirect_to: http://www.ticketmastermobilestudio.com/blog/cwac-camera
---

One of Android's greatest strengths is its ability to run on a plethora of different types of devices and hardware configurations. For developers, however, this presents an interesting problem: how do you go about supporting all these different hardware variations? While Google has done a fine job of abstracting the finer details of hardware interaction away from the developer in most cases, the Android camera API still poses a substantial number of hurdles to this day.<!--more-->

In order to use a device's camera, an application must perform roughly the following steps:

1. Declare the **android.permission.CAMERA** permission in the manifest
2. Get a reference to a device's camera (front-facing, back, etc.) and **open()** it
3. Set parameters on the camera, including the focus mode, flash mode, photo resolution, etc.
4. Create a SurfaceView on which to render the camera preview and pass its reference to **setPreviewDisplay()**
5. Start the camera preview
6. Take the photo
7. Handle the data that the camera passes back to save your photo properly
8. Stop the preview
9. Release the camera so other applications can now use it

Note that this just covers taking a single photo. If you want to handle retaking a photo, taking video, or any other action, that list grows significantly. The trickiest part, however, is that performing any of these actions at the wrong time can result in the camera outright failing until it is reinitialized. It's harrowing stuff, to be sure.

Enter **CWAC-Camera**: https://github.com/commonsguy/cwac-camera

The CWAC-Camera library was written by Mark Murphy, aka CommonsWare (that guy who has answered half of your Android-related Stack Overflow questions). It removes much of the pain that can come with the Android camera API, as well as the guesswork sometimes required to perform simple camera actions. The CWAC-Camera API revolves around three main components: **CameraView**, **CameraFragment**, and **CameraHost**.

CameraView abstracts away the main components of the camera API, and largely doesn't even need to be touched by the developer. It handles creation of the preview rendering surface automatically, including maintaining the aspect ratio of the camera preview on all device resolutions and screen sizes, and provides simplified API calls to access the main features of the camera.

CameraFragment is a Fragment that houses and interacts with the CameraView. The developer simply has to create an instance of a CameraFragment, add it to the Activity using the FragmentManager, and call methods like **autofocus()**, **takePicture()**, and **startRecording()** on it to control the camera with very little setup required.

CameraHost provides an interface class that receives callbacks from the camera. By implementing CameraHost, you can set the camera's configuration, preview size, and picture size, as well as handle the data coming back from the camera once a photo is taken. CommonsWare provides a simple implementation of this interface, appropriately called SimpleCameraHost, that serves as a great template for how to handle these callbacks. You can check it out [here](https://github.com/commonsguy/cwac-camera/blob/master/camera/src/com/commonsware/cwac/camera/SimpleCameraHost.java). Here's a snippet of some of the major pieces of this CameraHost implementation:

```java
public class SimpleCameraHost implements CameraHost {

	/**
	*This callback happens just before the camera takes a picture. Here you
	*can adjust the passed in Camera.Parameters object with methods like
	*parameters.setFocusMode(), parameters.setFlashMode(), etc. Any modifications
	*Made here are passed back to the camera automatically.
	*/
	@Override
  	public Camera.Parameters adjustPictureParameters(PictureTransaction xact,
                                                   Camera.Parameters parameters) {
    	return(parameters);
  	}

	/**
	*This callback happens just before the camera starts showing a preview. This method
	*works the same way as adjustPictureParameters, but the callback occurs earlier
	*in case the camera needs to behave differently prior to the user snapping a picture.
	*/
  	@Override
  	public Camera.Parameters adjustPreviewParameters(Camera.Parameters parameters) {
    	return(parameters);
  	}

	/**
	*Implementing this method allows you to get a callback at the moment a picture is taken.
	*One example of a good use for this is displaying unhiding Views that assist the user
	*in previewing the captured photo.
	*/
	@Override
	public Camera.ShutterCallback getShutterCallback() {
	    return(null);
	}

	/**
	*SimpleCameraHost does not use this particular saveImage method (there's
	*another one that gives you a byte[] representation of the image), but implementing
	*this gives you a chance to save your photo off to the filesystem, display it
	*in an ImageView, or any number of other things. It also packages the photo
	*up in a Bitmap, which is a bit easier to deal with than a byte[].
	*/
	@Override
	public void saveImage(PictureTransaction xact, Bitmap bitmap) {
	  	// no-op
	}
}
```

So, how easy is it to use CWAC-Camera to perform the steps I outlined above? Let's look at an example:

```java
public class CameraDemoActivity extends Activity {

    private final String TAG_CAMERA_FRAGMENT = "camera_fragment";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_demo);

        //Create the CameraFragment and add it to the layout
        CameraFragment f = new CameraFragment();
        getFragmentManager().beginTransaction()
                .add(R.id.container, f, TAG_CAMERA_FRAGMENT)
                .commit();

        //Set the CameraHost
        f.setHost(new SimpleCameraHost(this));

        //Set an onClickListener for a shutter button
        findViewById(R.id.shutter_button).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                takePicture();
            }
        });
    }

    /**
     * Checks that the CameraFragment exists and is visible to the user,
     * then takes a picture.
     */
    private void takePicture() {
        CameraFragment f = (CameraFragment) getFragmentManager().findFragmentByTag(TAG_CAMERA_FRAGMENT);
        if (f != null && f.isVisible()) {
            f.takePicture();
        }
    }
}
```

Assuming that your CameraHost implementation is correct (or you're extending SimpleCameraHost), then this is all you need to take a picture. By default, SimpleCameraHost will allow the user to continue taking photos. If you want to limit the user to one photo and then show a preview of the captured image, all you have to do is implement the **useSingleShotMode()** method in your CameraHost, like so:

```java
@Override
public boolean useSingleShotMode() {
	return true;
}
```

Want to make the camera focus? That's easy too. Just get a reference to your CameraFragment and call **autofocus()**:

```java
CameraFragment f = (CameraFragment) getFragmentMananger().findFragmentByTag(TAG_CAMERA_FRAGMENT);
f.autofocus();
```

There's a lot more you can do with the CWAC-Camera library than what you see here, such as video recording. It's extremely useful for any developer out there who wants to create an app with a custom camera implementation, and it is updated frequently (9 days ago as of this writing). If you're rolling your own camera app, I highly recommend checking it out.


text:
import React, {PropTypes} from 'react'
import { Router, browserHistory } from 'react-router';
import { Navbar, NavbarHeader, Nav, NavItem, Glyphicon } from 'react-bootstrap'
// import { LinkContainer, IndexLinkContainer } from 'react-router-bootstrap'

import './styles.scss';

export default class TopNavbar extends React.Component {
  // static propTypes = {
  //   routes: React.PropTypes.array.isRequired,
  // }
  static propTypes = {
    title: PropTypes.string
  }
  goBack = () => {
    browserHistory.goBack();
  }
  render () {
    return (

          <Glyphicon glyph="chevron-left"></Glyphicon>

          {this.props.title}

          <Glyphicon glyph="search"></Glyphicon>

    )
  }
}


text:
import {Component,ElementRef,OnInit,Input} from 'angular2/core';
import {MapComponent} from "./leaflet/map.component";
import {MarkerDirective} from "./leaflet/marker.directive";
import {PopupComponent} from "./leaflet/popup-component";
import {PonyService} from "./pony.service"
import {Pony} from "./pony"
import {RouterLink} from "angular2/router";
import {TimePassedPipe} from "./time-passed.pipe";
import {DistancePipe} from "./distance.pipe";
@Component({
selector:"pony-map",
directives:[MapComponent,MarkerDirective,PopupComponent,RouterLink],
providers:[PonyService],
pipes:[DistancePipe,TimePassedPipe],
template:`<leaflet-map [center]="[46,13.3]">
   <leaflet-marker *ngFor="#pony of ponies;#i=index" [pos]="pony.loc" >
    <leaflet-popup>

{{pony.firstname}} {{pony.lastname}}

Age: {{pony?.dateofBirth|TimePassed}}

 Distance: {{pony?.loc | distance}}

    </leaflet-popup>
  </leaflet-marker>
   </leaflet-map>`
})
export class PonyMapComponent implements OnInit
{
  public ponies:Pony[]=[];
  public errorMessage;
  constructor(private _PonyService:PonyService)
  {

  }
  getPonies()
  {
   this._PonyService.getPonies()
   .subscribe(
                  ponies=> {console.log(ponies);this.ponies = ponies},
                  error =>  this.errorMessage = <any>error);
                    console.log(this.ponies);
  }
  ngOnInit()
  {
    this.getPonies();
  }
}