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

<TITLE>
SsoConnection.SSOLogoutException (VMware vSphere Web Services SDK JAXWS Java Samples Documentation)
</TITLE>

<META NAME="date" CONTENT="2013-08-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.vmware.connection

Class SsoConnection.SSOLogoutException

java.lang.Object
  java.lang.Throwable
      java.lang.Exception
          java.lang.RuntimeException
              com.vmware.connection.ConnectionException
                  com.vmware.connection.SsoConnection.SSOLogoutException

All Implemented Interfaces:
java.io.Serializable

Enclosing class:
SsoConnection

public class SsoConnection.SSOLogoutException
extends ConnectionException

thrown on logout when something fails

See Also:
Serialized Form

Constructor Summary

SsoConnection.SSOLogoutException(java.lang.String s,
                                 java.lang.Throwable t)

Method Summary

Methods inherited from class java.lang.Throwable

fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SsoConnection.SSOLogoutException

public SsoConnection.SSOLogoutException(java.lang.String s,
                                        java.lang.Throwable t)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package org.apache.phoenix.execute;

import static org.apache.phoenix.monitoring.TaskExecutionMetricsHolder.NO_OP_INSTANCE;
import static org.apache.phoenix.util.LogUtil.addCustomAnnotations;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.cache.ServerCacheClient.ServerCache;
import org.apache.phoenix.compile.ColumnProjector;
import org.apache.phoenix.compile.ExplainPlan;
import org.apache.phoenix.compile.FromCompiler;
import org.apache.phoenix.compile.QueryPlan;
import org.apache.phoenix.compile.RowProjector;
import org.apache.phoenix.compile.ScanRanges;
import org.apache.phoenix.compile.StatementContext;
import org.apache.phoenix.compile.WhereCompiler;
import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.exception.SQLExceptionInfo;
import org.apache.phoenix.expression.Determinism;
import org.apache.phoenix.expression.Expression;
import org.apache.phoenix.expression.InListExpression;
import org.apache.phoenix.expression.LiteralExpression;
import org.apache.phoenix.expression.RowValueConstructorExpression;
import org.apache.phoenix.iterate.DefaultParallelScanGrouper;
import org.apache.phoenix.iterate.FilterResultIterator;
import org.apache.phoenix.iterate.ParallelScanGrouper;
import org.apache.phoenix.iterate.ResultIterator;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.job.JobManager.JobCallable;
import org.apache.phoenix.join.HashCacheClient;
import org.apache.phoenix.join.HashJoinInfo;
import org.apache.phoenix.monitoring.TaskExecutionMetricsHolder;
import org.apache.phoenix.parse.FilterableStatement;
import org.apache.phoenix.parse.ParseNode;
import org.apache.phoenix.parse.SQLParser;
import org.apache.phoenix.parse.SelectStatement;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.schema.types.PArrayDataType;
import org.apache.phoenix.schema.types.PBoolean;
import org.apache.phoenix.schema.types.PDataType;
import org.apache.phoenix.schema.types.PVarbinary;
import org.apache.phoenix.util.SQLCloseable;
import org.apache.phoenix.util.SQLCloseables;

import com.google.common.collect.Lists;

public class HashJoinPlan extends DelegateQueryPlan {
    private static final Log LOG = LogFactory.getLog(HashJoinPlan.class);

    private final SelectStatement statement;
    private final HashJoinInfo joinInfo;
    private final SubPlan[] subPlans;
    private final boolean recompileWhereClause;
    private List<SQLCloseable> dependencies;
    private HashCacheClient hashClient;
    private int maxServerCacheTimeToLive;
    private AtomicLong firstJobEndTime;
    private List<Expression> keyRangeExpressions;

    public static HashJoinPlan create(SelectStatement statement,
            QueryPlan plan, HashJoinInfo joinInfo, SubPlan[] subPlans) {
        if (!(plan instanceof HashJoinPlan))
            return new HashJoinPlan(statement, plan, joinInfo, subPlans, joinInfo == null);

        HashJoinPlan hashJoinPlan = (HashJoinPlan) plan;
        assert (hashJoinPlan.joinInfo == null && hashJoinPlan.delegate instanceof BaseQueryPlan);
        SubPlan[] mergedSubPlans = new SubPlan[hashJoinPlan.subPlans.length + subPlans.length];
        int i = 0;
        for (SubPlan subPlan : hashJoinPlan.subPlans) {
            mergedSubPlans[i++] = subPlan;
        }
        for (SubPlan subPlan : subPlans) {
            mergedSubPlans[i++] = subPlan;
        }
        return new HashJoinPlan(statement, hashJoinPlan.delegate, joinInfo, mergedSubPlans, true);
    }

    private HashJoinPlan(SelectStatement statement,
            QueryPlan plan, HashJoinInfo joinInfo, SubPlan[] subPlans, boolean recompileWhereClause) {
        super(plan);
        this.statement = statement;
        this.joinInfo = joinInfo;
        this.subPlans = subPlans;
        this.recompileWhereClause = recompileWhereClause;
    }

    @Override
    public ResultIterator iterator() throws SQLException {
    	return iterator(DefaultParallelScanGrouper.getInstance());
    }

    @Override
    public ResultIterator iterator(ParallelScanGrouper scanGrouper) throws SQLException {
        int count = subPlans.length;
        PhoenixConnection connection = getContext().getConnection();
        ConnectionQueryServices services = connection.getQueryServices();
        ExecutorService executor = services.getExecutor();
        List<Future<Object>> futures = Lists.<Future<Object>>newArrayListWithExpectedSize(count);
        dependencies = Lists.newArrayList();
        if (joinInfo != null) {
            hashClient = new HashCacheClient(delegate.getContext().getConnection());
            maxServerCacheTimeToLive = services.getProps().getInt(QueryServices.MAX_SERVER_CACHE_TIME_TO_LIVE_MS_ATTRIB, QueryServicesOptions.DEFAULT_MAX_SERVER_CACHE_TIME_TO_LIVE_MS);
            firstJobEndTime = new AtomicLong(0);
            keyRangeExpressions = new CopyOnWriteArrayList<Expression>();
        }

        for (int i = 0; i < count; i++) {
            final int index = i;
            futures.add(executor.submit(new JobCallable<Object>() {

                @Override
                public Object call() throws Exception {
                    return subPlans[index].execute(HashJoinPlan.this);
                }

                @Override
                public Object getJobId() {
                    return HashJoinPlan.this;
                }

                @Override
                public TaskExecutionMetricsHolder getTaskExecutionMetric() {
                    return NO_OP_INSTANCE;
                }
            }));
        }

        SQLException firstException = null;
        for (int i = 0; i < count; i++) {
            try {
                Object result = futures.get(i).get();
                subPlans[i].postProcess(result, this);
            } catch (InterruptedException e) {
                if (firstException == null) {
                    firstException = new SQLException("Sub plan [" + i + "] execution interrupted.", e);
                }
            } catch (ExecutionException e) {
                if (firstException == null) {
                    firstException = new SQLException("Encountered exception in sub plan [" + i + "] execution.",
                            e.getCause());
                }
            }
        }
        if (firstException != null) {
            SQLCloseables.closeAllQuietly(dependencies);
            throw firstException;
        }

        Expression postFilter = null;
        boolean hasKeyRangeExpressions = keyRangeExpressions != null && !keyRangeExpressions.isEmpty();
        if (recompileWhereClause || hasKeyRangeExpressions) {
            StatementContext context = delegate.getContext();
            PTable table = context.getCurrentTable().getTable();
            ParseNode viewWhere = table.getViewStatement() == null ? null : new SQLParser(table.getViewStatement()).parseQuery().getWhere();
            context.setResolver(FromCompiler.getResolverForQuery((SelectStatement) (delegate.getStatement()), delegate.getContext().getConnection()));
            if (recompileWhereClause) {
                postFilter = WhereCompiler.compile(delegate.getContext(), delegate.getStatement(), viewWhere, null);
            }
            if (hasKeyRangeExpressions) {
                WhereCompiler.compile(delegate.getContext(), delegate.getStatement(), viewWhere, keyRangeExpressions, true, null);
            }
        }

        if (joinInfo != null) {
            Scan scan = delegate.getContext().getScan();
            HashJoinInfo.serializeHashJoinIntoScan(scan, joinInfo);
        }

        ResultIterator iterator = joinInfo == null ? delegate.iterator(scanGrouper) : ((BaseQueryPlan) delegate).iterator(dependencies, scanGrouper);
        if (statement.getInnerSelectStatement() != null && postFilter != null) {
            iterator = new FilterResultIterator(iterator, postFilter);
        }

        return iterator;
    }

    private Expression createKeyRangeExpression(Expression lhsExpression,
            Expression rhsExpression, List<Expression> rhsValues,
            ImmutableBytesWritable ptr) throws SQLException {
        if (rhsValues.isEmpty())
            return LiteralExpression.newConstant(false, PBoolean.INSTANCE, Determinism.ALWAYS);

        rhsValues.add(0, lhsExpression);

        return InListExpression.create(rhsValues, false, ptr);
    }

    @Override
    public ExplainPlan getExplainPlan() throws SQLException {
        List<String> planSteps = Lists.newArrayList(delegate.getExplainPlan().getPlanSteps());
        int count = subPlans.length;
        for (int i = 0; i < count; i++) {
            planSteps.addAll(subPlans[i].getPreSteps(this));
        }
        for (int i = 0; i < count; i++) {
            planSteps.addAll(subPlans[i].getPostSteps(this));
        }

        if (joinInfo != null && joinInfo.getPostJoinFilterExpression() != null) {
            planSteps.add("    AFTER-JOIN SERVER FILTER BY " + joinInfo.getPostJoinFilterExpression().toString());
        }
        if (joinInfo != null && joinInfo.getLimit() != null) {
            planSteps.add("    JOIN-SCANNER " + joinInfo.getLimit() + " ROW LIMIT");
        }

        return new ExplainPlan(planSteps);
    }

    @Override
    public FilterableStatement getStatement() {
        return statement;
    }

    protected interface SubPlan {
        public Object execute(HashJoinPlan parent) throws SQLException;
        public void postProcess(Object result, HashJoinPlan parent) throws SQLException;
        public List<String> getPreSteps(HashJoinPlan parent) throws SQLException;
        public List<String> getPostSteps(HashJoinPlan parent) throws SQLException;
    }

    public static class WhereClauseSubPlan implements SubPlan {
        private final QueryPlan plan;
        private final SelectStatement select;
        private final boolean expectSingleRow;

        public WhereClauseSubPlan(QueryPlan plan, SelectStatement select, boolean expectSingleRow) {
            this.plan = plan;
            this.select = select;
            this.expectSingleRow = expectSingleRow;
        }

        @Override
        public Object execute(HashJoinPlan parent) throws SQLException {
            List<Object> values = Lists.<Object> newArrayList();
            ResultIterator iterator = plan.iterator();
            RowProjector projector = plan.getProjector();
            ImmutableBytesWritable ptr = new ImmutableBytesWritable();
            int columnCount = projector.getColumnCount();
            int rowCount = 0;
            PDataType baseType = PVarbinary.INSTANCE;
            for (Tuple tuple = iterator.next(); tuple != null; tuple = iterator.next()) {
                if (expectSingleRow && rowCount >= 1)
                    throw new SQLExceptionInfo.Builder(SQLExceptionCode.SINGLE_ROW_SUBQUERY_RETURNS_MULTIPLE_ROWS).build().buildException();

                if (columnCount == 1) {
                    ColumnProjector columnProjector = projector.getColumnProjector(0);
                    baseType = columnProjector.getExpression().getDataType();
                    Object value = columnProjector.getValue(tuple, baseType, ptr);
                    values.add(value);
                } else {
                    List<Expression> expressions = Lists.<Expression>newArrayListWithExpectedSize(columnCount);
                    for (int i = 0; i < columnCount; i++) {
                        ColumnProjector columnProjector = projector.getColumnProjector(i);
                        PDataType type = columnProjector.getExpression().getDataType();
                        Object value = columnProjector.getValue(tuple, type, ptr);
                        expressions.add(LiteralExpression.newConstant(value, type));
                    }
                    Expression expression = new RowValueConstructorExpression(expressions, true);
                    baseType = expression.getDataType();
                    expression.evaluate(null, ptr);
                    values.add(baseType.toObject(ptr));
                }
                rowCount++;
            }

            Object result = expectSingleRow ? (values.isEmpty() ? null : values.get(0)) : PArrayDataType.instantiatePhoenixArray(baseType, values.toArray());
            parent.getContext().setSubqueryResult(select, result);
            return null;
        }

        @Override
        public void postProcess(Object result, HashJoinPlan parent) throws SQLException {
        }

        @Override
        public List<String> getPreSteps(HashJoinPlan parent) throws SQLException {
            List<String> steps = Lists.newArrayList();
            steps.add("    EXECUTE " + (expectSingleRow ? "SINGLE" : "MULTIPLE") + "-ROW SUBQUERY");
            for (String step : plan.getExplainPlan().getPlanSteps()) {
                steps.add("        " + step);
            }
            return steps;
        }

        @Override
        public List<String> getPostSteps(HashJoinPlan parent) throws SQLException {
            return Collections.<String>emptyList();
        }
    }

    public static class HashSubPlan implements SubPlan {
        private final int index;
        private final QueryPlan plan;
        private final List<Expression> hashExpressions;
        private final boolean singleValueOnly;
        private final Expression keyRangeLhsExpression;
        private final Expression keyRangeRhsExpression;

        public HashSubPlan(int index, QueryPlan subPlan,
                List<Expression> hashExpressions,
                boolean singleValueOnly,
                Expression keyRangeLhsExpression,
                Expression keyRangeRhsExpression) {
            this.index = index;
            this.plan = subPlan;
            this.hashExpressions = hashExpressions;
            this.singleValueOnly = singleValueOnly;
            this.keyRangeLhsExpression = keyRangeLhsExpression;
            this.keyRangeRhsExpression = keyRangeRhsExpression;
        }

        @Override
        public Object execute(HashJoinPlan parent) throws SQLException {
            ScanRanges ranges = parent.delegate.getContext().getScanRanges();
            List<Expression> keyRangeRhsValues = null;
            if (keyRangeRhsExpression != null) {
                keyRangeRhsValues = Lists.<Expression>newArrayList();
            }
            ServerCache cache = null;
            if (hashExpressions != null) {
                cache = parent.hashClient.addHashCache(ranges, plan.iterator(),
                        plan.getEstimatedSize(), hashExpressions, singleValueOnly, parent.delegate.getTableRef(), keyRangeRhsExpression, keyRangeRhsValues);
                long endTime = System.currentTimeMillis();
                boolean isSet = parent.firstJobEndTime.compareAndSet(0, endTime);
                if (!isSet && (endTime - parent.firstJobEndTime.get()) > parent.maxServerCacheTimeToLive) {
                    LOG.warn(addCustomAnnotations("Hash plan [" + index + "] execution seems too slow. Earlier hash cache(s) might have expired on servers.", parent.delegate.getContext().getConnection()));
                }
            } else {
                assert(keyRangeRhsExpression != null);
                ResultIterator iterator = plan.iterator();
                for (Tuple result = iterator.next(); result != null; result = iterator.next()) {
                    // Evaluate key expressions for hash join key range optimization.
                    keyRangeRhsValues.add(HashCacheClient.evaluateKeyExpression(keyRangeRhsExpression, result, plan.getContext().getTempPtr()));
                }
            }
            if (keyRangeRhsValues != null) {
                parent.keyRangeExpressions.add(parent.createKeyRangeExpression(keyRangeLhsExpression, keyRangeRhsExpression, keyRangeRhsValues, plan.getContext().getTempPtr()));
            }
            return cache;
        }

        @Override
        public void postProcess(Object result, HashJoinPlan parent)
                throws SQLException {
            ServerCache cache = (ServerCache) result;
            if (cache != null) {
                parent.joinInfo.getJoinIds()[index].set(cache.getId());
                parent.dependencies.add(cache);
            }
        }

        @Override
        public List<String> getPreSteps(HashJoinPlan parent) throws SQLException {
            List<String> steps = Lists.newArrayList();
            boolean earlyEvaluation = parent.joinInfo.earlyEvaluation()[index];
            boolean skipMerge = parent.joinInfo.getSchemas()[index].getFieldCount() == 0;
            if (hashExpressions != null) {
                steps.add("    PARALLEL " + parent.joinInfo.getJoinTypes()[index].toString().toUpperCase()
                        + "-JOIN TABLE " + index + (earlyEvaluation ? "" : "(DELAYED EVALUATION)") + (skipMerge ? " (SKIP MERGE)" : ""));
            }
            else {
                steps.add("    SKIP-SCAN-JOIN TABLE " + index);
            }
            for (String step : plan.getExplainPlan().getPlanSteps()) {
                steps.add("        " + step);
            }
            return steps;
        }

        @Override
        public List<String> getPostSteps(HashJoinPlan parent) throws SQLException {
            if (keyRangeLhsExpression == null)
                return Collections.<String> emptyList();

            String step = "    DYNAMIC SERVER FILTER BY " + keyRangeLhsExpression.toString()
                    + " IN (" + keyRangeRhsExpression.toString() + ")";
            return Collections.<String> singletonList(step);
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const nedb = require(`nedb`);
const bluebird = require(`bluebird`);
const bcrypt = require(`bcrypt`);
const path = require(`path`);
const crypto = require(`crypto`);

const userData = bluebird.promisifyAll(new nedb({filename: path.join(__dirname, `../`, `data`, `users.db`), autoload: true}));

class user {
    constructor() {
        this.userData = userData;
    }

    register(username, password) {
        return this.userData.findOneAsync({username}).then((user) => {
            if (user) {
                return bluebird.reject(`Username ${username} already exists`);
            }

            return bcrypt.hash(password, 10);
        }).then((hash) => {
            return this.userData.insertAsync({
                username,
                password: hash,
                tokens: []
            });
        });
    }

    authenticate(username, password) {
        return this.userData.findOneAsync({username}).then((userDoc) => {
            if (!userDoc) {
                return bluebird.reject();
            }

            return bcrypt.compare(password, userDoc.password);
        }).then((matched) => {
            if (!matched) {
                return bluebird.reject();
            }

            return this.generateToken(username);
        }).catch(() => {
            return bluebird.reject(`Incorrect account details`)
        });
    }

    verifyToken(token) {
        return this.userData.findOneAsync({tokens: {$elemMatch: token}}).then((userDoc) => {
            if (userDoc) {
                return bluebird.resolve(true);
            }

            return bluebird.reject('Invalid token');
        });
    }

    generateToken(username) {
        const hash = crypto.createHash(`sha256`);

        hash.update(username + Date.now());

        const token = hash.digest(`hex`);

        return this.userData.updateAsync({username}, {$push: {tokens: token}}).then(() => {
            return token;
        });
    }
}

module.exports = user;


text:
#include "arch/win32/ArchTaskBarWindows.h"
#include "arch/win32/ArchMiscWindows.h"
#include "arch/IArchTaskBarReceiver.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "synergy/win32/AppUtilWindows.h"

#include <string.h>
#include <shellapi.h>

static const UINT		kAddReceiver     = WM_USER + 10;
static const UINT		kRemoveReceiver  = WM_USER + 11;
static const UINT		kUpdateReceiver  = WM_USER + 12;
static const UINT		kNotifyReceiver  = WM_USER + 13;
static const UINT		kFirstReceiverID = WM_USER + 14;

//
// ArchTaskBarWindows
//

ArchTaskBarWindows*	ArchTaskBarWindows::s_instance    = NULL;

ArchTaskBarWindows::ArchTaskBarWindows() :
	m_nextID(kFirstReceiverID),
	m_thread(NULL),
	m_condVar(NULL),
	m_mutex(NULL)
{
	// save the singleton instance
	s_instance    = this;
}

ArchTaskBarWindows::~ArchTaskBarWindows()
{
	if (m_thread != NULL) {
		PostMessage(m_hwnd, WM_QUIT, 0, 0);
		ARCH->wait(m_thread, -1.0);
		ARCH->closeThread(m_thread);
	}
	if (m_condVar != NULL) {
		ARCH->closeCondVar(m_condVar);
	}
	if (m_mutex != NULL) {
		ARCH->closeMutex(m_mutex);
	}
	s_instance = NULL;
}

void
ArchTaskBarWindows::init()
{
	// we need a mutex
	m_mutex       = ARCH->newMutex();

	// and a condition variable which uses the above mutex
	m_ready       = false;
	m_condVar     = ARCH->newCondVar();

	// we're going to want to get a result from the thread we're
	// about to create to know if it initialized successfully.
	// so we lock the condition variable.
	ARCH->lockMutex(m_mutex);

	// open a window and run an event loop in a separate thread.
	// this has to happen in a separate thread because if we
	// create a window on the current desktop with the current
	// thread then the current thread won't be able to switch
	// desktops if it needs to.
	m_thread      = ARCH->newThread(&ArchTaskBarWindows::threadEntry, this);

	// wait for child thread
	while (!m_ready) {
		ARCH->waitCondVar(m_condVar, m_mutex, -1.0);
	}

	// ready
	ARCH->unlockMutex(m_mutex);
}

void
ArchTaskBarWindows::addDialog(HWND hwnd)
{
	ArchMiscWindows::addDialog(hwnd);
}

void
ArchTaskBarWindows::removeDialog(HWND hwnd)
{
	ArchMiscWindows::removeDialog(hwnd);
}

void
ArchTaskBarWindows::addReceiver(IArchTaskBarReceiver* receiver)
{
	// ignore bogus receiver
	if (receiver == NULL) {
		return;
	}

	// add receiver if necessary
	ReceiverToInfoMap::iterator index = m_receivers.find(receiver);
	if (index == m_receivers.end()) {
		// add it, creating a new message ID for it
		ReceiverInfo info;
		info.m_id = getNextID();
		index = m_receivers.insert(std::make_pair(receiver, info)).first;

		// add ID to receiver mapping
		m_idTable.insert(std::make_pair(info.m_id, index));
	}

	// add receiver
	PostMessage(m_hwnd, kAddReceiver, index->second.m_id, 0);
}

void
ArchTaskBarWindows::removeReceiver(IArchTaskBarReceiver* receiver)
{
	// find receiver
	ReceiverToInfoMap::iterator index = m_receivers.find(receiver);
	if (index == m_receivers.end()) {
		return;
	}

	// remove icon.  wait for this to finish before returning.
	SendMessage(m_hwnd, kRemoveReceiver, index->second.m_id, 0);

	// recycle the ID
	recycleID(index->second.m_id);

	// discard
	m_idTable.erase(index->second.m_id);
	m_receivers.erase(index);
}

void
ArchTaskBarWindows::updateReceiver(IArchTaskBarReceiver* receiver)
{
	// find receiver
	ReceiverToInfoMap::const_iterator index = m_receivers.find(receiver);
	if (index == m_receivers.end()) {
		return;
	}

	// update icon and tool tip
	PostMessage(m_hwnd, kUpdateReceiver, index->second.m_id, 0);
}

UINT
ArchTaskBarWindows::getNextID()
{
	if (m_oldIDs.empty()) {
		return m_nextID++;
	}
	UINT id = m_oldIDs.back();
	m_oldIDs.pop_back();
	return id;
}

void
ArchTaskBarWindows::recycleID(UINT id)
{
	m_oldIDs.push_back(id);
}

void
ArchTaskBarWindows::addIcon(UINT id)
{
	ARCH->lockMutex(m_mutex);
	CIDToReceiverMap::const_iterator index = m_idTable.find(id);
	if (index != m_idTable.end()) {
		modifyIconNoLock(index->second, NIM_ADD);
	}
	ARCH->unlockMutex(m_mutex);
}

void
ArchTaskBarWindows::removeIcon(UINT id)
{
	ARCH->lockMutex(m_mutex);
	removeIconNoLock(id);
	ARCH->unlockMutex(m_mutex);
}

void
ArchTaskBarWindows::updateIcon(UINT id)
{
	ARCH->lockMutex(m_mutex);
	CIDToReceiverMap::const_iterator index = m_idTable.find(id);
	if (index != m_idTable.end()) {
		modifyIconNoLock(index->second, NIM_MODIFY);
	}
	ARCH->unlockMutex(m_mutex);
}

void
ArchTaskBarWindows::addAllIcons()
{
	ARCH->lockMutex(m_mutex);
	for (ReceiverToInfoMap::const_iterator index = m_receivers.begin();
									index != m_receivers.end(); ++index) {
		modifyIconNoLock(index, NIM_ADD);
	}
	ARCH->unlockMutex(m_mutex);
}

void
ArchTaskBarWindows::removeAllIcons()
{
	ARCH->lockMutex(m_mutex);
	for (ReceiverToInfoMap::const_iterator index = m_receivers.begin();
									index != m_receivers.end(); ++index) {
		removeIconNoLock(index->second.m_id);
	}
	ARCH->unlockMutex(m_mutex);
}

void
ArchTaskBarWindows::modifyIconNoLock(
				ReceiverToInfoMap::const_iterator index, DWORD taskBarMessage)
{
	// get receiver
	UINT id                        = index->second.m_id;
	IArchTaskBarReceiver* receiver = index->first;

	// lock receiver so icon and tool tip are guaranteed to be consistent
	receiver->lock();

	// get icon data
	HICON icon = reinterpret_cast<HICON>(
				const_cast<IArchTaskBarReceiver::Icon>(receiver->getIcon()));

	// get tool tip
	std::string toolTip = receiver->getToolTip();

	// done querying
	receiver->unlock();

	// prepare to add icon
	NOTIFYICONDATA data;
	data.cbSize           = sizeof(NOTIFYICONDATA);
	data.hWnd             = m_hwnd;
	data.uID              = id;
	data.uFlags           = NIF_MESSAGE;
	data.uCallbackMessage = kNotifyReceiver;
	data.hIcon            = icon;
	if (icon != NULL) {
		data.uFlags |= NIF_ICON;
	}
	if (!toolTip.empty()) {
		strncpy(data.szTip, toolTip.c_str(), sizeof(data.szTip));
		data.szTip[sizeof(data.szTip) - 1] = '\0';
		data.uFlags                       |= NIF_TIP;
	}
	else {
		data.szTip[0] = '\0';
	}

	// add icon
	if (Shell_NotifyIcon(taskBarMessage, &data) == 0) {
		// failed
	}
}

void
ArchTaskBarWindows::removeIconNoLock(UINT id)
{
	NOTIFYICONDATA data;
	data.cbSize = sizeof(NOTIFYICONDATA);
	data.hWnd   = m_hwnd;
	data.uID    = id;
	if (Shell_NotifyIcon(NIM_DELETE, &data) == 0) {
		// failed
	}
}

void
ArchTaskBarWindows::handleIconMessage(
				IArchTaskBarReceiver* receiver, LPARAM lParam)
{
	// process message
	switch (lParam) {
	case WM_LBUTTONDOWN:
		receiver->showStatus();
		break;

	case WM_LBUTTONDBLCLK:
		receiver->primaryAction();
		break;

	case WM_RBUTTONUP: {
		POINT p;
		GetCursorPos(&p);
		receiver->runMenu(p.x, p.y);
		break;
	}

	case WM_MOUSEMOVE:
		// currently unused
		break;

	default:
		// unused
		break;
	}
}

bool
ArchTaskBarWindows::processDialogs(MSG* msg)
{
	// only one thread can be in this method on any particular object
	// at any given time.  that's not a problem since only our event
	// loop calls this method and there's just one of those.

	ARCH->lockMutex(m_mutex);

	// remove removed dialogs
	m_dialogs.erase(false);

	// merge added dialogs into the dialog list
	for (Dialogs::const_iterator index = m_addedDialogs.begin();
							index != m_addedDialogs.end(); ++index) {
		m_dialogs.insert(std::make_pair(index->first, index->second));
	}
	m_addedDialogs.clear();

	ARCH->unlockMutex(m_mutex);

	// check message against all dialogs until one handles it.
	// note that we don't hold a lock while checking because
	// the message is processed and may make calls to this
	// object.  that's okay because addDialog() and
	// removeDialog() don't change the map itself (just the
	// values of some elements).
	ARCH->lockMutex(m_mutex);
	for (Dialogs::const_iterator index = m_dialogs.begin();
							index != m_dialogs.end(); ++index) {
		if (index->second) {
			ARCH->unlockMutex(m_mutex);
			if (IsDialogMessage(index->first, msg)) {
				return true;
			}
			ARCH->lockMutex(m_mutex);
		}
	}
	ARCH->unlockMutex(m_mutex);

	return false;
}

LRESULT
ArchTaskBarWindows::wndProc(HWND hwnd,
				UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) {
	case kNotifyReceiver: {
		// lookup receiver
		CIDToReceiverMap::const_iterator index = m_idTable.find((UINT)wParam);
		if (index != m_idTable.end()) {
			IArchTaskBarReceiver* receiver = index->second->first;
			handleIconMessage(receiver, lParam);
			return 0;
		}
		break;
	}

	case kAddReceiver:
		addIcon((UINT)wParam);
		break;

	case kRemoveReceiver:
		removeIcon((UINT)wParam);
		break;

	case kUpdateReceiver:
		updateIcon((UINT)wParam);
		break;

	default:
		if (msg == m_taskBarRestart) {
			// task bar was recreated so re-add our icons
			addAllIcons();
		}
		break;
	}

	return DefWindowProc(hwnd, msg, wParam, lParam);
}

LRESULT CALLBACK
ArchTaskBarWindows::staticWndProc(HWND hwnd, UINT msg,
				WPARAM wParam, LPARAM lParam)
{
	// if msg is WM_NCCREATE, extract the ArchTaskBarWindows* and put
	// it in the extra window data then forward the call.
	ArchTaskBarWindows* self = NULL;
	if (msg == WM_NCCREATE) {
		CREATESTRUCT* createInfo;
		createInfo = reinterpret_cast<CREATESTRUCT*>(lParam);
		self       = reinterpret_cast<ArchTaskBarWindows*>(
												createInfo->lpCreateParams);
		SetWindowLong(hwnd, 0, reinterpret_cast<LONG>(self));
	}
	else {
		// get the extra window data and forward the call
		LONG data = GetWindowLong(hwnd, 0);
		if (data != 0) {
			self = reinterpret_cast<ArchTaskBarWindows*>(
							reinterpret_cast<void*>(data));
		}
	}

	// forward the message
	if (self != NULL) {
		return self->wndProc(hwnd, msg, wParam, lParam);
	}
	else {
		return DefWindowProc(hwnd, msg, wParam, lParam);
	}
}

void
ArchTaskBarWindows::threadMainLoop()
{
	// register the task bar restart message
	m_taskBarRestart        = RegisterWindowMessage(TEXT("TaskbarCreated"));

	// register a window class
	WNDCLASSEX classInfo;
	classInfo.cbSize        = sizeof(classInfo);
	classInfo.style         = CS_NOCLOSE;
	classInfo.lpfnWndProc   = &ArchTaskBarWindows::staticWndProc;
	classInfo.cbClsExtra    = 0;
	classInfo.cbWndExtra    = sizeof(ArchTaskBarWindows*);
	classInfo.hInstance     = instanceWin32();
	classInfo.hIcon         = NULL;
	classInfo.hCursor       = NULL;
	classInfo.hbrBackground = NULL;
	classInfo.lpszMenuName  = NULL;
	classInfo.lpszClassName = TEXT("SynergyTaskBar");
	classInfo.hIconSm       = NULL;
	ATOM windowClass        = RegisterClassEx(&classInfo);

	// create window
	m_hwnd = CreateWindowEx(WS_EX_TOOLWINDOW,
							reinterpret_cast<LPCTSTR>(windowClass),
							TEXT("Synergy Task Bar"),
							WS_POPUP,
							0, 0, 1, 1,
							NULL,
							NULL,
							instanceWin32(),
							reinterpret_cast<void*>(this));

	// signal ready
	ARCH->lockMutex(m_mutex);
	m_ready = true;
	ARCH->broadcastCondVar(m_condVar);
	ARCH->unlockMutex(m_mutex);

	// handle failure
	if (m_hwnd == NULL) {
		UnregisterClass(reinterpret_cast<LPCTSTR>(windowClass), instanceWin32());
		return;
	}

	// main loop
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) {
		if (!processDialogs(&msg)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	// clean up
	removeAllIcons();
	DestroyWindow(m_hwnd);
	UnregisterClass(reinterpret_cast<LPCTSTR>(windowClass), instanceWin32());
}

void*
ArchTaskBarWindows::threadEntry(void* self)
{
	reinterpret_cast<ArchTaskBarWindows*>(self)->threadMainLoop();
	return NULL;
}

HINSTANCE ArchTaskBarWindows::instanceWin32()
{
	return ArchMiscWindows::instanceWin32();
}


text: Tutorials and sandbox apps to use for HyperIsland


text:
'''
Created on May 8, 2013
Copyright: Jev Kuznetsov
License: BSD

Module for downloading historic data from IB

'''

import ib
import pandas as pd
from ib.ext.Contract import Contract
from ib.opt import ibConnection, message

import logger as logger

from pandas import DataFrame, Index

import os
import datetime as dt
import time
from time import sleep
from extra import timeFormat, dateFormat

class Downloader(object):
    def __init__(self,debug=False):
        self._log = logger.getLogger('DLD')
        self._log.debug('Initializing data dwonloader. Pandas version={0}, ibpy version:{1}'.format(pd.__version__,ib.version))

        self.tws = ibConnection()
        self._dataHandler = _HistDataHandler(self.tws)

        if debug:
            self.tws.registerAll(self._debugHandler)
            self.tws.unregister(self._debugHandler,message.HistoricalData)

        self._log.debug('Connecting to tws')
        self.tws.connect()

        self._timeKeeper = TimeKeeper() # keep track of past requests
        self._reqId = 1 # current request id

    def _debugHandler(self,msg):
        print '[debug]', msg

    def requestData(self,contract,endDateTime,durationStr='1 D',barSizeSetting='30 secs',whatToShow='TRADES',useRTH=1,formatDate=1):

        if isinstance(endDateTime,dt.datetime): # convert to string
            endDateTime = endDateTime.strftime(timeFormat)

        self._log.debug('Requesting data for %s end time %s.' % (contract.m_symbol,endDateTime))

        while self._timeKeeper.nrRequests(timeSpan=600) > 59:
            print 'Too many requests done. Waiting... '
            time.sleep(10)

        self._timeKeeper.addRequest()
        self._dataHandler.reset()
        self.tws.reqHistoricalData(self._reqId,contract,endDateTime,durationStr,barSizeSetting,whatToShow,useRTH,formatDate)
        self._reqId+=1

        #wait for data
        startTime = time.time()
        timeout = 3
        while not self._dataHandler.dataReady and (time.time()-startTime < timeout):
            sleep(2)

        if not self._dataHandler.dataReady:
            self._log.error('Data timeout')

        print self._dataHandler.data

        return self._dataHandler.data

#     def getIntradayData(self,contract, dateTuple ):
#         ''' get full day data on 1-s interval
#             date: a tuple of (yyyy,mm,dd)
#         '''
#
#         openTime = dt.datetime(*dateTuple)+dt.timedelta(hours=16)
#         closeTime =  dt.datetime(*dateTuple)+dt.timedelta(hours=22)
#
#         timeRange = pd.date_range(openTime,closeTime,freq='30min')
#
#         datasets = []
#
#         for t in timeRange:
#             datasets.append(self.requestData(contract,t.strftime(timeFormat)))
#
#         return pd.concat(datasets)

    def disconnect(self):
        self.tws.disconnect()

class _HistDataHandler(object):
    ''' handles incoming messages '''
    def __init__(self,tws):
        self._log = logger.getLogger('DH')
        tws.register(self.msgHandler,message.HistoricalData)
        self.reset()

    def reset(self):
        self._log.debug('Resetting data')
        self.dataReady = False
        self._timestamp = []
        self._data = {'open':[],'high':[],'low':[],'close':[],'volume':[],'count':[],'WAP':[]}

    def msgHandler(self,msg):
        #print '[msg]', msg

        if msg.date[:8] == 'finished':
            self._log.debug('Data recieved')
            self.dataReady = True
            return

        if len(msg.date) > 8:
            self._timestamp.append(dt.datetime.strptime(msg.date,timeFormat))
        else:
            self._timestamp.append(dt.datetime.strptime(msg.date,dateFormat))

        for k in self._data.keys():
            self._data[k].append(getattr(msg, k))

    @property
    def data(self):
        ''' return  downloaded data as a DataFrame '''
        df = DataFrame(data=self._data,index=Index(self._timestamp))
        return df

class TimeKeeper(object):
    '''
    class for keeping track of previous requests, to satify the IB requirements
    (max 60 requests / 10 min)

    each time a requiest is made, a timestamp is added to a txt file in the user dir.

    '''

    def __init__(self):
        self._log = logger.getLogger('TK')
        dataDir = os.path.expanduser('~')+'/twpData'

        if not os.path.exists(dataDir):
            os.mkdir(dataDir)

        self._timeFormat = "%Y%m%d %H:%M:%S"
        self.dataFile = os.path.normpath(os.path.join(dataDir,'requests.txt'))
        self._log.debug('Data file: {0}'.format(self.dataFile))

    def addRequest(self):
        ''' adds a timestamp of current request'''
        with open(self.dataFile,'a') as f:
            f.write(dt.datetime.now().strftime(self._timeFormat)+'\n')

    def nrRequests(self,timeSpan=600):
        ''' return number of requests in past timespan (s) '''
        delta = dt.timedelta(seconds=timeSpan)
        now = dt.datetime.now()
        requests = 0

        with open(self.dataFile,'r') as f:
            lines = f.readlines()

        for line in lines:
            if now-dt.datetime.strptime(line.strip(),self._timeFormat) < delta:
                requests+=1

        if requests==0: # erase all contents if no requests are relevant
            open(self.dataFile,'w').close()

        self._log.debug('past requests: {0}'.format(requests))
        return requests


text:
import os
import requests, time, csv, ast, sys, pymysql, os
import out1_pro,os
import NameExtractor,EmailToNameMapping
from configuration import DATABASE_NAME, TABLE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_HOST

cnx = pymysql.connect(host=DATABASE_HOST, user=DATABASE_USERNAME, passwd=DATABASE_PASSWORD, db=DATABASE_NAME)
cursor = cnx.cursor()

add_record = ("INSERT INTO "+TABLE_NAME+" (email, name, info, website) VALUES (%s, %s, %s, %s)")

def fire(name="", email="", info="", site=''):
    global add_record, cursor, cnx
    data_record = (email, name, info, site)
    cursor.execute(add_record, data_record )
    cnx.commit()

folders = []
i = 0
# recurse is not used. only for testing purposes
def recurse(folder):
    global i, folders
    for root, subdirs, files in os.walk(folder):
        i += 1
        if i == 1:
            folders = subdirs

def recursion(path2, folder):
    for root, subdirs, files in os.walk(path2):
        for filename in  files:
            # print("this is the name of file")
            # print(filename)
            # print("\n\n")
            if filename[-4:] == ".xml":
                path = os.path.join(root, filename)
                text,emails = out1_pro.callMe(path)
                if text != None:
                    list_of_names = NameExtractor.textToNames(text)
                    w = EmailToNameMapping.emailToNameMapping(emails,list_of_names)
                    for item in w:
                        # print(item, w[item],filename[:-4], folder)
                        try:
                            fire(w[item], item, filename[:-4], folder)
                        except Exception as e:
                            print("Exception in database updation " + str(e))
                            continue
                    # print("-----------------------xxxxxxxxxxxxxxxxxxxxxxxxxxxx")

def recurse2(path):
    global folders
    recurse(path)
    for folder in folders:
        path2 = os.path.join(path, folder)
        recursion(path2, folder)

'''
 Function: fire
    Helper function to update database.

 Parameters:
    name - Name of the person
    email - Email
    info - Information
    site - website from where it was downloaded

 Returns:
    Nothing, just updates the Database.

 Note to User:
    Helper function to fire queries on DB.
'''
'''
 Function: recursion
    Helps recurse2 function that recursively visits all the xml files and calls other functions to extract name-email pairs and to saves
    rhem in a database.
 Parameters:
    path2 - the base path to the folder(name is base site), where all files of that website are saved.
    folder - specific folder(whose name is the base site from which the file is downloaded)

 Returns:
    Nothing

 Note to User:
    Don't call it directly. recurse2 calls it.
'''
'''
 Function: recurse2
    Main files which after extracting name-email pairs saves them in a database.

 Parameters:
    path - the path to folder which contains the xml files(converted from pdf).

 Returns:
    Nothing

 Note to User:
    Run this function after you have got the .xml files converted from .pdf files. Put this file in the top level folder.
'''


text:
function [imageRGB, outsideGamut] = LMStoRGBforSpecificDisplay(imageLMS, displaySPDs, coneFundamentals)
    [tmp, nCols, mRows] = ImageToCalFormat(imageLMS);
    tmp = inv(coneFundamentals' * displaySPDs) * tmp;
    for channelIndex = 1:3
        outsideGamut(channelIndex,1) = numel(find(squeeze(tmp(channelIndex,:)) < 0));
        outsideGamut(channelIndex,2) = numel(find(squeeze(tmp(channelIndex,:)) > 1));
    end
    imageRGB = CalFormatToImage(tmp, nCols, mRows);
end


text:
require('./test-file');
//require('./test-gettext');