text:
package com.amazon.titan.diskstorage.dynamodb;

import com.amazonaws.services.dynamodbv2.model.QueryResult;
import com.thinkaurelius.titan.diskstorage.StaticBuffer;

public class QueryResultWrapper {

    private StaticBuffer titanKey;
    private QueryResult dynamoDBResult;

    public QueryResultWrapper(StaticBuffer titanKey, QueryResult dynamoDBResult) {
        this.titanKey = titanKey;
        this.dynamoDBResult = dynamoDBResult;
    }

    public StaticBuffer getTitanKey() {
        return titanKey;
    }

    public QueryResult getDynamoDBResult() {
        return dynamoDBResult;
    }
}


text:
name: validator
---

# Validator metatable

Provides access to data validation functions.

- [validator:escapeString(string)](#escapestring)
- [validator:validQRToken(token, secret)](#validqrtoken)
- [validator:validGuildName(name)](#validguildname)
- [validator:validGuildRank(rank)](#validguildrank)
- [validator:validVocation(name or id, base = false)](#validvocation)
- [validator:validTown(name or id)](#validtown)
- [validator:validUsername(name)](#validusername)
- [validator:blackList(data, tokens)](#blacklist)
- [validator:validate(method, data)](#validate)

# escapeString

Escapes the given string returning a secure string to use for RAW SQL queries. If you use placeholders on your queries you dont need this

```lua
local notSafe = "This ; is not ; safe, 'hello' . 'world'"
local safe = validator:escapeString(notSafe)
-- safe = "This \x1a is not \x1a safe, \'hello\' . \'world\'"
```

# validQRToken

Validates the given token against a secret key. Castro uses this function for the two-factor authentication.

```lua
local status = validator:validQRToken("token", "secret")
-- status = false
```

# validGuildName

Validates the given guild name. The name must be between 5 to 20 characters long and must compile against this regular expression:

```
^[a-zA-Z ]+$
```

```lua
local valid = validator:validGuildName("This is not valid!!")
-- valid = false
```

# validGuildRank

Validates the given guild rank. The rank must be between 5 to 15 characters long and must compile against this regular expression:

```
^[a-zA-Z ]+$
```

```lua
local valid = validator:validGuildRank("This is not valid!!")
-- valid = false
```

# validVocation

Validates the given vocation by its identifier or name. You can also pass a second parameter to only validate base vocations.

```lua
local valid = validator:validVocation("Sorcerer")
-- valid = true
```

```lua
local valid = validator:validVocation(10)
-- valid = true
```

# validTown

Validates the given town by its identifier or name.

```lua
local valid = validator:validTown("Thais")
-- valid = true
```

```lua
local valid = validator:validTown(10)
-- valid = true
```

# validUsername

Validates the given character name. Must compile against this regular expression:

```
^[a-zA-Z ]+$
```

```lua
local valid = validator:validUsername("Not_valid!")
-- valid = false
```

# blackList

Validates the given data to check if any token exists.

```lua
local valid = validator:blackList("This is _not_ allowed!", "-!")
--- valid = false
```

# validate

Calls a validator method. The list of valid methods are the following:

- IsURL
- IsAlpha
- IsAlphanumeric
- IsEmail
- IsJson
- IsNull
- IsEmpty
- IsASCII
- IsUpperCase
- IsLowerCase
- IsInt

This function takes a string as a second argument. All methods return `true` or `false`

redpajama_set_name: RedPajamaGithub


text:
import fcntl
import inspect
import json
import logging
import os
import socket
import signal
import struct
import sys
import time

from functools import wraps

import consul as pyconsul
#import manta
from pymongo import MongoClient
from pymongo.errors import *

consul = pyconsul.Consul(host=os.environ.get('CONSUL', 'consul'))
logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s',
                    stream=sys.stdout,
                    level=logging.getLevelName(
                        os.environ.get('LOG_LEVEL', 'INFO')))

log = logging.getLogger('manage.py')

def debug(fn):
    """
    Function/method decorator to trace calls via debug logging.
    Is a pass-thru if we're not at LOG_LEVEL=DEBUG. Normally this
    would have a lot of perf impact but this application doesn't
    have significant throughput.
    """
    @wraps(fn)
    def wrapper(*args, **kwargs):
        try:
            # because we have concurrent processes running we want
            # to tag each stack with an identifier for that process
            arg = "[{}]".format(sys.argv[1])
        except IndexError:
            arg = "[pre_start]"
        name = '{}{}{}'.format(arg, (len(inspect.stack()) * " "), fn.__name__)
        log.debug('%s' % name)
        out = apply(fn, args, kwargs)
        log.debug('%s: %s', name, out)
        return out
    return wrapper

def get_environ(key, default):
    """
    Gets an environment variable and trims away comments and whitespace.
    """
    val = os.environ.get(key, default)
    try:
        val = val.split('#')[0]
        val = val.strip()
        val = os.path.expandvars(val)
    finally:
        # just swallow AttributeErrors for non-strings
        return val

# ---------------------------------------------------------

SESSION_CACHE_FILE = get_environ('SESSION_CACHE_FILE', '/tmp/mongodb-session')
SESSION_NAME = get_environ('SESSION_NAME', 'mongodb-replica-set-lock')
SESSION_TTL = int(get_environ('SESSION_TTL', 60))

# consts for node state
PRIMARY = 'mongodb-replicaset'
#SECONDARY = 'mongodb-secondary'

# key where primary will be stored in consul
PRIMARY_KEY = get_environ('PRIMARY_KEY', 'mongodb-primary')

# how many time to retry connecting to mongo
# be aware that the health check may timeout before this is reached
MONGO_RETRY_TIMES=int(get_environ('MONGO_RETRY_TIMES', 10))

# timeouts when the primary node gets a SIGTERM and needs to step down as primary
MONGO_STEPDOWN_TIME=int(get_environ('MONGO_STEPDOWN_TIME', 60))
MONGO_SECONDARY_CATCHUP_PERIOD=int(get_environ('MONGO_SECONDARY_CATCHUP_PERIOD', 8))
MONGO_ELECTION_TIMEOUT=int(get_environ('MONGO_ELECTION_TIMEOUT', 30))

# ---------------------------------------------------------
# Top-level functions called by ContainerPilot or forked by this program

@debug
def pre_start():
    """
    MongoDB must be running in order to execute most of our setup behavior
    """
    # TODO is there anything that needs to be done before starting mongo?
    sys.exit(0)

@debug
def pre_stop():
    """
    If we are the primary in the MongoDB replica set, we need to step down
    because we are about to be shut down
    """

    ip = get_ip()
    local_mongo = MongoClient(ip, connect=False)

    # since we are shutting down, it is ok to stop if mongo is already non-responsive
    if not is_mongo_up(local_mongo):
        return True

    try:
        repl_status = local_mongo.admin.command('replSetGetStatus')
        is_mongo_primary = repl_status['myState'] == 1
        # ref https://docs.mongodb.com/manual/reference/replica-states/
    except Exception as e:
        log.error(e, 'unable to get primary status while shuting down')
        return True

    if is_mongo_primary:
        # the primary will wait up to X seconds for a secondary member
        # to catch up and sets itself as ineligible to be primary again for 60 seconds
        # https://docs.mongodb.com/manual/reference/command/replSetStepDown/
        # this is set to 8 so that we timeout before `docker stop` would send a sigkill
        try:
            local_mongo.admin.command('replSetStepDown', MONGO_STEPDOWN_TIME, secondaryCatchUpPeriodSecs=MONGO_SECONDARY_CATCHUP_PERIOD)
        except ConnectionFailure:
            # this means mongo closed all connections and this node is no longer primary
            wait_for_election = True
        except ExecutionTimeout as e:
            # stepdown fails, ie no secondary that is caught up
            log.debug(e)
            try:
                # force
                local_mongo.admin.command('replSetStepDown', MONGO_STEPDOWN_TIME, force=True)
            except ConnectionFailure:
                # this means mongo closed all connections and this node is no longer primary
                wait_for_election = True

        if wait_for_election:
            timeout = 0
            while True:
                if timeout >= MONGO_ELECTION_TIMEOUT:
                    log.error('did not see mongodb election results of new primary after %i times' % timeout)
                    return False
                timeout += 1
                # use a replica client so that we get "primary" data
                mongo_client = MongoClient(ip, connect=False, replicaset=repl_status['set'], serverSelectionTimeoutMS=500)
                # is_mongo_up will sleep on failure, so we don't need a "time.sleep(1)"
                if is_mongo_up(mongo_client, 1):
                    primary = mongo_client.primary
                    if primary != None:
                        log.debug('primary elected: {0!s}'.format(primary))
                        return True

    return True

@debug
def health():
    """
    Run a simple health check. Also acts as a check for whether the
    ContainerPilot configuration needs to be reloaded (if it's been
    changed externally).
    """
    # TODO periodic mongodumps to Manta

    hostname = socket.gethostname()
    ip = get_ip()
    local_mongo = MongoClient(ip, connect=False)

    # check that mongo is responsive
    if not is_mongo_up(local_mongo):
        return False

    # make sure this node has a valid consul session to work with
    get_session()

    try:
        repl_status = local_mongo.admin.command('replSetGetStatus')
        # TODO handle non-exceptional states
        if repl_status['myState'] == 1:
            return True # PRIMARY
#            # ref https://docs.mongodb.com/manual/reference/replica-states/
#            state = PRIMARY
#            # mongo_update_replset_config is not required in the health check
#            # but may speed up adding of new members
#            # dropping to keep consul traffic minimal
#            #mongo_update_replset_config(local_mongo, hostname)
        elif repl_status['myState'] == 2:
            return True # SECONDARY
#        elif repl_status['myState'] in (2, 3, 5):
#            # mongo states of: SECONDARY or RECOVERING or STARTUP2
#            state = SECONDARY
    except OperationFailure as e:
        # happens when replica set is not initialized
        log.debug(e)
        consul_primary = get_primary_node_from_consul()
        if not consul_primary:
            # this should only happen at the beginning when there is no replica set
            # so the first node to get the lock in consul will initialize the set
            # by setting self as primary in consul and then rs.init()
            mark_as_primary(hostname)
            #state = PRIMARY
            local_mongo.admin.command('replSetInitiate')
        #else:
            # this happens when the primary node is still initializing
            # wait for it to finish so that it can add this node to the replica set
            # while waiting, we are a "healthy" node, since mongo is responsive
            # TODO maybe make this a second state of "recovering/initializing" node?
            #return True

    return False

@debug
def on_change():
    '''
    called when there is a change in the list of IPs and ports for this backend
    '''
    hostname = socket.gethostname()
    ip = get_ip()
    local_mongo = MongoClient(ip, connect=False)

    try:
        repl_status = local_mongo.admin.command('replSetGetStatus')
        is_mongo_primary = repl_status['myState'] == 1
        # ref https://docs.mongodb.com/manual/reference/replica-states/
    except Exception as e:
        log.error(e, 'unable to get primary status')
        return False

    if is_mongo_primary:
        return mongo_update_replset_config(local_mongo, ip)
    else:
        return True

# ---------------------------------------------------------

def is_mongo_up(local_mongo, max_timeout=MONGO_RETRY_TIMES):
    '''
    check to see if mongo is up yet, retying the given number of times
    '''
    timeout = 0
    ip = get_ip()
    while True:
        if timeout >= max_timeout:
            if timeout != 1:
                log.error('unable to connect to mongodb or replica set after %i times' % timeout)
            return False
        timeout += 1

        try:
            # check that mongo is up
            server_info = local_mongo.server_info()
            if not server_info['ok']:
                log.info('Mongo response not "ok" on %s; retrying...' % ip)
                time.sleep(1)
                continue
            break
        except (AutoReconnect, ServerSelectionTimeoutError) as e:
            log.info('Mongo or specified replica set not yet available on %s; retrying...' % ip)
            time.sleep(1)
            continue
        except (ConnectionFailure, NetworkTimeout, NotMasterError) as e:
            # TODO retry like AutoReconnect error above?
            log.info(e)
            time.sleep(1)
            return False
        except Exception as e:
            # just bail on unexpected exceptions when trying to connect
            log.error(e)
            return False
    return True

@debug
def mongo_update_replset_config(local_mongo, hostname):
    '''
    called from the primary node to update the replica config in mongo
    using the current set of healthy mongo containers listed in consul
    '''
    try:
        # get current replica config from mongodb
        repl_config = local_mongo.admin.command('replSetGetConfig')
        if not repl_config['ok']:
            raise Exception('could not get replica config: %s' % repl_config['errmsg'])
        repl_config = repl_config['config']

        # TODO use consul.agent.health() instead?
        # get list of mongo servers from consul
        consul_services = consul.agent.services()

        # translate the name stored by consul to be the "host" name stored
        # in mongo config, skipping any non-mongo services
        mongos_in_consul = [consul_to_mongo_hostname(consul_services[svc]) for svc in consul_services]
        mongos_in_consul = [svc for svc in mongos_in_consul if svc]
        # empty list from consul means we have nothing to compare against
        if not mongos_in_consul:
            return
        # if the master node is not in the consul services list we need to
        # wait a little longer before configuring mongo
        if not hostname + ':27017' in mongos_in_consul:
            return

        members = repl_config['members']
        existing_hosts, ids = zip(*[(member['host'], member['_id']) for member in members])
        ids = list(ids)
        existing = set(existing_hosts)
        current = set(mongos_in_consul)

        new_mongos = current - existing
        stale_mongos = existing - current

        if not new_mongos and not stale_mongos:
            return # no change

        # don't keep mongo replica members that are not listed in consul
        for member in members:
            if member['host'] in stale_mongos:
                members.remove(member)
        for new_mongo in new_mongos:
            new_id = max(ids) + 1
            ids.append(new_id)
            members.append({'_id': new_id, 'host': new_mongo})

        # TODO voting membership
        # https://docs.mongodb.com/manual/core/replica-set-architectures/#maximum-number-of-voting-members
        # ERROR manage.py Replica set configuration contains 10 voting members, but must be at least 1 and no more than 7
        # it should also be odd for tie breaking
        # also limit number of nodes to 50, since that is all a replica set can have

        repl_config['members'] = members
        repl_config['version'] += 1
        local_mongo.admin.command('replSetReconfig', repl_config)

        log.info('updating replica config in mongo from consul info')
        return repl_config

    except Exception as e:
        log.exception(e)
        sys.exit(1)

def consul_to_mongo_hostname(service):
#    if name.startswith(SECONDARY + '-'):
#        prefix = SECONDARY + '-'
    if service['ID'].startswith(PRIMARY + '-'):
        return service['Address'] + ':' + str(service['Port'])
    else:
        return None

# ---------------------------------------------------------

@debug
def get_primary_node_from_consul(timeout=10):
    while timeout > 0:
        try:
            result = consul.kv.get(PRIMARY_KEY)
            if result[1]:
                if result[1].get('Session', False):
                    return result[1]['Value']
            # either there is no primary or the session has expired
            return None
        except Exception as e:
            timeout = timeout - 1
            time.sleep(1)
    raise e

@debug
def mark_as_primary(hostname):
    """ Write flag to Consul to mark this node as primary """
    session_id = get_session()
    if not mark_with_session(PRIMARY_KEY, hostname, session_id):
        log.error('Tried to mark node primary but primary exists, '
                  'exiting for retry on next check.')
        sys.exit(1)

@debug
def mark_with_session(key, val, session_id, timeout=10):
    while timeout > 0:
        try:
            return consul.kv.put(key, val, acquire=session_id)
        except Exception as e:
            log.debug(e)
            timeout = timeout - 1
            time.sleep(1)
    raise e

def get_session(no_cache=False):
    """
    Gets a Consul session ID from the on-disk cache or calls into
    `create_session` to generate and cache a new one.
    Also, renews the session TTL of on-disk key, to ensure it is valid
    in Consul
    """
    if no_cache:
        return create_session()

    try:
        with open(SESSION_CACHE_FILE, 'r') as f:
            session_id = f.read()

        # ensure the session_id is valid and refresh it
        consul.session.renew(session_id)
    except (IOError, pyconsul.base.NotFound) as e:
        # this means we have don't have a key locally, or
        # it is expired, so get a new one
        session_id = create_session()

    return session_id

def create_session(ttl=None):
    """
    We can't rely on storing Consul session IDs in memory because
    `health` and `onChange` handler calls happen in a subsequent
    process. Here we creates a session on Consul and cache the
    session ID to disk. Returns the session ID.
    """
    session_id = consul.session.create(name=SESSION_NAME,
                                       behavior='release',
                                       ttl=ttl)
    with open(SESSION_CACHE_FILE, 'w') as f:
        f.write(session_id)
    return session_id

# ---------------------------------------------------------
# utility functions

def get_ip(iface='eth0'):
    """
    Use Linux SIOCGIFADDR ioctl to get the IP for the interface.
    ref http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/
    """
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    return socket.inet_ntoa(fcntl.ioctl(
        sock.fileno(),
        0x8915, # SIOCGIFADDR
        struct.pack('256s', iface[:15])
    )[20:24])

# ---------------------------------------------------------

if __name__ == '__main__':

#    manta_config = Manta()

    if len(sys.argv) > 1:
        func = sys.argv[1]
        try:
            if not locals()[func]():
                log.info('Function failed %s' % func)
                sys.exit(1)
        except KeyError:
            log.error('Invalid command %s', func)
            sys.exit(1)
    else:
        # default behavior will be to start mysqld, running the
        # initialization if required
        pre_start()


text: <parent><!--text--><child></child></parent>


text:
<title>rpmatch - Untitled</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Untitled">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Stdlib.html#Stdlib" title="Stdlib">
<link rel="prev" href="rand48.html#rand48" title="rand48">
<link rel="next" href="strtod.html#strtod" title="strtod">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<meta http-equiv="Content-Style-Type" content="text/css">

Next: strtod,
Previous: rand48,
Up: Stdlib

2.36 rpmatch—determine whether response to question is affirmative or negative

Synopsis

     #include <stdlib.h>
     int rpmatch(const char *<var>response</var>);

Description

The rpmatch function determines whether <var>response</var> is an affirmative
or negative response to a question according to the current locale.

Returns

rpmatch returns 1 if <var>response</var> is affirmative, 0 if negative, or -1
if not recognized as either.

Portability

rpmatch is a BSD extension also found in glibc.


text:
<?php
/**
 * @var int 系统消息
 */
define('MESSAGE_CATEGORY_SYSTEM',0);
/**
 * @var 系统消息之升级
 */
define('MESSAGE_CATEGORY_SYSTEM_UPGRADE',0);
/**
 * @var 系统消息之后台推送
 */
define('MESSAGE_CATEGORY_SYSTEM_PUSH',1);
/**
 * @var 系统消息之全站消息
 */
define('MESSAGE_CATEGORY_SYSTEM_SITE',2);
/**
 * @var 系统消息之主播开播
 */
define('MESSAGE_CATEGORY_SYSTEM_KAIBO',3);
/**
 * @var 家族消息
 */
define('MESSAGE_CATEGORY_FAMILY',1);
/**
 * @var 家族消息之加入与退出
 */
define('MESSAGE_CATEGORY_FAMILY_JOIN',0);
/**
 * @var 家族消息之管理
 */
define('MESSAGE_CATEGORY_FAMILY_MANAGE',1);
/**
 * @var 家族消息之升级
 */
define('MESSAGE_CATEGORY_FAMILY_UPGRADE',2);

define('MESSAGE_PUSH_TYPE_GLOBAL',0);#全站所有人
define('MESSAGE_PUSH_TYPE_USER',1);#指定用户
define('MESSAGE_PUSH_TYPE_LIVE',2);#指定直播间
define('MESSAGE_PUSH_TYPE_DOTEY', 3);#指定主播

/**
 * 消息服务层
 *
 * the last known user to change this file in the repository  <$LastChangedBy: hexin $>
 * @author Su qian <suqian@pipi.cn>
 * @version $Id: MessageService.php 16912 2013-12-11 03:10:35Z hexin $
 * @package service
 *
 */
class MessageService extends PipiService {
	/**
	 * 存储用户发送消息
	 *
	 * @param array $message
	 * @return int
	 */
	public function sendMessage(array $message){
		if(!isset($message['uid']) || $message['uid'] < 0){
			return $this->setNotice('message.param',Yii::t('common','Parameter is empty'),0);
		}

		if(!isset($message['category']) || !isset($message['sub_category'])){
			return $this->setNotice('message.param',Yii::t('common','Parameter is empty'),0);
		}

		if(isset($message['extra'])){
			if(is_array($message['extra'])){
				$message['extra'] = json_encode($message['extra']);
			}
		}

		$counterField = $this->mapMessageTypeCounter($message['category'],$message['sub_category']);
		if(empty($counterField)){
			 return $this->setNotice('message.counter',Yii::t('message','counter is empty'),0);
		}
		if(isset($message['to_uid'])){
			$message['receive_uid'] = $message['to_uid'];
			if(is_array($message['receive_uid']))
				$message['receive_uid'] = implode(',', $message['receive_uid']);
		}
		$senderUid = $message['uid'];
		$isRead = $this->array_get($message,'is_read');
		$toUids = $this->checkBlackList($senderUid,$this->array_get($message,'to_uid'));
		if(empty($toUids)){
			//不是全站消息,接收者UID必须存在
			if((!isset($message['is_site']) || !$message['is_site'])){
				 return $this->setNotice('message.recevive',Yii::t('message','Recipient is empty'),0);
			}
		}

		$message['create_time'] = time();
		$message['update_time'] = time();
		$messageContentModel = new MessageContentModel();
		$this->attachAttribute($messageContentModel,$message);
		if(!$messageContentModel->validate()){
				return $this->setNotices($messageContentModel->getErrors(),0);
		}
		if($messageContentModel->insert()){
			if(isset($message['is_site']) && $message['is_site']){
				return $messageContentModel->getPrimaryKey();
			}
			$toUids = array_unique($toUids);
			//更新接收消息人未读消息数
			if(!$isRead){
				$this->updateMessageStatisticsCounters($toUids,array($counterField=>1));
			}
			$relation = array();
			if($senderUid > 0){
				$toUids[$senderUid] = $senderUid;
			}
			$rows = 0;
			foreach($toUids as $uid){
				if($uid == $senderUid){
					$relation[$rows]['is_own'] = 1;
					$relation[$rows]['is_read'] = 0;
				}else{
					$relation[$rows]['is_own'] = 0;
					$relation[$rows]['is_read'] = (int)$isRead;
				}
				$relation[$rows]['uid'] = $uid;
				$relation[$rows]['message_id'] = $messageContentModel->getPrimaryKey();
				$relation[$rows]['create_time'] = time();
				$rows++;
			}
			$this->saveMultiMessageRelation($relation);
		}
		return $messageContentModel->getPrimaryKey();

	}

	/**
	 * 添加推送消息
	 *
	 * @param array $message
	 * @return number
	 */
	public function pushMessage(array $message){
		if(isset($message['title']) && empty($message['title'])){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}

		if(!isset($message['content']) || empty($message['content'])){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}

		if (isset($message['extra'])){
			$message['extra'] = json_encode($message['extra']);
		}

		$messagePushModel = new MessagePushModel();
		if(isset($message['push_id'])){
			$_messagePushModel = $messagePushModel->findByPk($message['push_id']);
			if(empty($_messagePushModel)){
				return $this->setNotice('message',Yii::t('user','The push message does not exist'),0);
			}
			$this->attachAttribute($_messagePushModel,$message);
			$_messagePushModel->save();
			return $_messagePushModel->getPrimaryKey();
		}else{
			$this->attachAttribute($messagePushModel,$message);
			$messagePushModel->save();
			return $messagePushModel->getPrimaryKey();
		}
		return 0;
	}
	/**
	 * 获取用户收到的消息
	 *
	 * @param int $uid 用户ID
	 * @param int $category 消息分类
	 * @param int $subcategory 消息子分类
	 * @param array $extendCondition 额外扩展条件
	 * @return array
	 */
	public function getUserReceiveMessagesByUid($uid,$category,$subcategory,array $extendCondition = array()){
		if($uid <= 0){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		$condition = array();
		$condition['uid'] = $uid;
		$condition['is_own'] = 0;
		if($category>=0)
			$condition['category'] = $category;
		if(!is_null($subcategory))
			$condition['sub_category'] = $subcategory;
		$condition = array_merge($condition,$extendCondition);
		$relationModel =  MessageRelationModel::model();
		$userMessages = $relationModel->getUserMessageByUidsCondition($condition);
		return $this->buildUserMessage($userMessages);
	}

	/**
	 * 统计获取用户收到的消息数量
	 * @param int $uid 用户ID
	 * @param int $category 消息分类
	 * @param mixed $subcategory 消息子分类
	 * @param array $extendCondition 额外扩展条件
	 * @return array
	 */
	public function countUserReceiveMessages($uid,$category,$subcategory,array $extendCondition = array())
	{
		if($uid <= 0){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		$condition = array();
		$condition['uid'] = $uid;
		$condition['is_own'] = 0;
		if($category>=0)
			$condition['category'] = $category;
		if(!is_null($subcategory))
			$condition['sub_category'] = $subcategory;

		$condition = array_merge($condition,$extendCondition);
		$relationModel =  MessageRelationModel::model();
		return $relationModel->countUserMessageByUidsCondition($condition);
	}

	/**
	 * 获取用户发送的消息
	 *
	 * @param int $uid 用户ID
	 * @param int $category 消息分类
	 * @param int $subcategory 消息子分类
	 * @param array $extendCondition 额外扩展条件
	 * @return array
	 */
	public function getUserSendMessagesByUid($uid,$category,$subcategory,array $extendCondition = array()){
		if($uid <= 0){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		$condition = array();
		$condition['uid'] = $uid;
		$condition['is_own'] = 1;
		if($category >= 0)
			$condition['category'] = $category;
		if(!is_null($subcategory))
			$condition['sub_category'] = $subcategory;

		$condition = array_merge($condition,$extendCondition);
		$relationModel =  MessageRelationModel::model();
		$userMessages = $relationModel->getUserMessageByUidsCondition($condition);
		return $this->buildUserMessage($userMessages);
	}

	/**
	 * 取得全站信息
	 *
	 * @param int $uid
	 * @param int $limit
	 * @param int $offset
	 * @return array
	 */
	public function getUserReceiveSiteMessagesByUid($uid,$limit,$offset){
		$messageContentModel = new MessageContentModel();
		$messages = $messageContentModel->getUserReceiveSiteMessagesByUid($limit,$offset);
		if(empty($messages)){
			return array();
		}
		$messages = $this->arToArray($messages);
		$messages = $this->buildUserMessage($messages);
		$messagesIds = array_keys($messages);
		$unReadMessages = $this->getUserUnReadSiteMessagesByUid($uid,$messagesIds);
		$delSiteMessages = $this->getUserDelSiteMessagesByUid($uid,$messagesIds);
		foreach($messages as $id => $_message){
			if(isset($unReadMessages[$id])){
				$messages[$id]['is_read'] = 0;
			}else{
				$messages[$id]['is_read'] = 1;
			}
			if(isset($delSiteMessages[$id])){
				unset($messages[$id]);
			}
		}
		return $messages;

	}
	/**
	 * 计算用户读取全的全站消息总数
	 *
	 * @param $uid
	 * @return int
	 */
	public function countUserReceiveSiteMessagesByUid($uid){
		 return MessageContentModel::model()->countUserReceiveSiteMessagesByUid() - MessageContentModel::model()->countDelSiteMessagesByUid($uid);
	}
	/**
	 * 计算用户未读取全的全站消息的总数
	 *
	 * @param $uid
	 * @return int
	 */
	public function countUserUnReadSiteMessagesByUid($uid){
		return MessageContentModel::model()->countUserUnReadSiteMessagesByUid($uid);
	}

	/**
	 * 获取用户删除的全站消息总数
	 *
	 * @param int $uid
	 * @return int
	 */
	public function countDelSiteMessagesByUid($uid){
		return MessageContentModel::model()->countDelSiteMessagesByUid($uid);
	}

	public function getUserUnReadSiteMessagesByUid($uid,array $messageIds = array()){
		$messageContentModel = new MessageContentModel();
		$messages = $messageContentModel->getUserUnReadSiteMessagesByUid($uid,$messageIds);
		return $this->buildDataByIndex($messages,'message_id');
	}

	public function getUserDelSiteMessagesByUid($uid,array $messageIds = array()){
		$messageContentModel = new MessageContentModel();
		$messages = $messageContentModel->getUserDelSiteMessagesByUid($uid,$messageIds);
		return $this->buildDataByIndex($messages,'message_id');
	}
	/**
	 * 获取用户配置
	 *
	 * @param int $uid 用户ID
	 * @return array
	 */
	public function getMessageConfigByUid($uid){
		if($uid <= 0){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}

		$userConfigModel =   UserConfigModel::model();
		$orgMessageConfigModel = $userConfigModel->findByPk($uid);
		if($orgMessageConfigModel){
			$orgMessageConfigModel->blacklist = unserialize($orgMessageConfigModel->blacklist);
			$orgMessageConfigModel->sheildmessage = unserialize($orgMessageConfigModel->sheildmessage);
			return $orgMessageConfigModel->attributes;
		}
		return array();
	}

	/**
	 * 获取用户配置
	 *
	 * @param array $uids 用户ID
	 * @return array
	 */
	private function getMessageConfigByUids(array $uids){
		if(empty($uids)){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}

		$userConfigModel =   UserConfigModel::model();
		$messageConfigs = $userConfigModel->getUserConfigByUids($uids);
		$attriubes = array();
		foreach($messageConfigs as $key=>$config){
			$config->blacklist = unserialize($config->blacklist);
			$config->sheildmessage = unserialize($config->sheildmessage);
			$attriubes[$config->uid] = $config->attributes;
		}
		return $attriubes;
	}

	/**
	 * 删除消息
	 *
	 * @param int $ids 消息ID
	 * @return array
	 */
	public function delMessageByIds(array $ids){
		if(empty($ids)){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		$this->delMessageRelationByMessageIds($ids);
		return MessageContentModel::model()->delMessageByIds($ids);
	}

	/**
	 * 删除摄推送消息
	 *
	 * @param array $pushIds 消息ID
	 * @return array
	 */
	public function delPushByIds(array $pushIds){
		if(empty($pushIds)){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		return MessagePushModel::model()->delPushByIds($pushIds);
	}

	/**
	 * 标记消息已读
	 *
	 * @param int $uid
	 * @param int $messageId
	 * @param  int $type
	 * @return boolean
	 */
	public function markReadMessage($uid,$messageId,$type = NULL){
		if($messageId <=0 || $uid <= 0){
			return $this->setError(Yii::t('common','Parameter is empty'),false);
		}
		$condition = array('uid'=>$uid,'message_id'=>$messageId);
		if($type == 'site'){
			$messagePushModel = new MessagePushReadModel();
			if($messagePushModel->findByAttributes($condition)){
				return false;
			}
			$messagePushModel->uid = $uid;
			$messagePushModel->message_id = $messageId;
			$messagePushModel->is_del = 0;
			$messagePushModel->create_time = time();
			return $messagePushModel->save();
		}else{
			$messageRelationModel = new MessageRelationModel();

			$messageContent = MessageContentModel::model()->findByPk($messageId);
			if($messageContent){
				$countField = $this->mapMessageTypeCounter($messageContent->category,$messageContent->sub_category);
				$this->updateMessageStatisticsCounters($uid,array($countField=>-1));
			}

			if($messageRelationModel->updateAll(array('is_read'=>1),'uid = :uid AND message_id = :messageId',array(':uid'=>$uid,':messageId'=>$messageId))){
				return true;
			}
		}
		return false;

	}

	/**
	 * 删除用户收件箱
	 *
	 * @param int $uid
	 * @param int $messageId
	 * @param string $type
	 * @return number
	 */
	public function delUserMessage($uid,$messageId,$type = NULL){
		if($messageId <=0 || $uid <= 0){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		$condition = array('uid'=>$uid,'message_id'=>$messageId);
		if($type == 'site'){
			$messagePushModel = new MessagePushReadModel();
			$orgMessagePushModel = $messagePushModel->findByAttributes($condition);
			if(!$orgMessagePushModel){
				$messagePushModel->uid = $uid;
				$messagePushModel->message_id = $messageId;
				$messagePushModel->is_del = 1;
				$messagePushModel->create_time = time();
				return $messagePushModel->save();
			}
			return $messagePushModel->updateAll(array('is_del'=>1),'uid = :uid AND message_id = :messageId',array(':uid'=>$uid,':messageId'=>$messageId));
		}else{
			$messageRelationModel = new MessageRelationModel();
			if($messageRelationModel->findByAttributes(array_merge($condition,array('is_read'=>0)))){
				$messageContent = MessageContentModel::model()->findByPk($messageId);
				if($messageContent){
					$countField = $this->mapMessageTypeCounter($messageContent->category,$messageContent->sub_category);
					$this->updateMessageStatisticsCounters($uid,array($countField=>-1));
				}
			}
			return $messageRelationModel->deleteAllByAttributes($condition);
		}
		return 0;
	}
	/**
	 * 删除用户关系的消息
	 *
	 * @param int $ids 关系ID
	 * @return array
	 */
	public function delMessageRelationByIds(array $ids){
		if(empty($ids)){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		return  MessageRelationModel::model()->delRelationByIds($ids);
	}

	/**
	 * 删除用户关系的消息
	 *
	 * @param array $messageIds 消息ID
	 * @return mix|number
	 */
	public function delMessageRelationByMessageIds(array $messageIds){
		if(empty($messageIds)){
			return $this->setError(Yii::t('common','Parameter is empty'),0);
		}
		return MessageRelationModel::model()->delRelationByMessageIds($messageIds);
	}

	/**
	 * 取得消息分类列表
	 *
	 * @param string $item 分类项
	 * @return string|array
	 */
	public function getMessageCateGoryList($item = NULL){
		$cateGoryList = array(
			MESSAGE_CATEGORY_FAMILY => '家族消息',
			MESSAGE_CATEGORY_SYSTEM=>'系统消息',
		);

		return !is_null($item) && isset($cateGoryList[$item]) ? $cateGoryList[$item] : $cateGoryList;
	}

	/**
	 * 获取消息分类
	 *
	 * @param string $item 消息分类
	 * @param string $subItem 消息分类子项
	 * @return  string | array
	 */
	public function getMessageSubCategoryList($item = null ,$subItem = null){
		$cateGoryList = array(
			MESSAGE_CATEGORY_FAMILY => array(
				'name'=>$this->getMessageCateGoryList(MESSAGE_CATEGORY_FAMILY),
				'child'=>array(
					MESSAGE_CATEGORY_FAMILY_JOIN=>'家族申请',
					MESSAGE_CATEGORY_FAMILY_MANAGE=>'家族管理',
					MESSAGE_CATEGORY_FAMILY_UPGRADE=>'家族升级',
				)
			),
			MESSAGE_CATEGORY_SYSTEM=>array(
				'name'=>$this->getMessageCateGoryList(MESSAGE_CATEGORY_SYSTEM),
				'child'=>array(
					MESSAGE_CATEGORY_SYSTEM_UPGRADE=>'用户升级',
					MESSAGE_CATEGORY_SYSTEM_PUSH=>'后台推送',
					MESSAGE_CATEGORY_SYSTEM_KAIBO=>'主播开播',
					MESSAGE_CATEGORY_SYSTEM_SITE=>'全站消息',
				)
			),

		);

		if( $item>=0 && isset($cateGoryList[$item])){
			if( $item>=0 && isset($cateGoryList[$item]['child'][$subItem])){
				return $cateGoryList[$item]['child'][$subItem];
			}else{
				return $cateGoryList[$item];
			}
		}
		return $cateGoryList;
	}

	/**
	 * 检查发送进是否被接收者加入黑名单
	 *
	 * @param int $senderUid
	 * @param mixed $receiveUids
	 * @return array
	 */
	private function checkBlackList($senderUid,$receiveUids){
		if(!$receiveUids){
			return array();
		}
		if(!is_array($receiveUids)){
			$receiveUids = explode(',',$receiveUids);
		}
		$_tempUids = array();
		foreach($receiveUids as $uid){
			$_tempUids[$uid] = $uid;
		}
		$userMessageConfigs = $this->getMessageConfigByUids($receiveUids);
		foreach ($userMessageConfigs as $uid=>$config){
			if($config['blacklist'] && in_array($senderUid,$config['blacklist'])){
				unset($_tempUids[$uid]);
				$this->setNotice('message.blacklist',Yii::t('message','{uid}:Shields you send message',array('{uid}'=>$uid)));
			}
		}
		return $_tempUids;
	}

	/**
	 * 是否屏蔽此消息接收类型
	 *
	 * @param int $uid 发送者用户
	 * @param string $category 消息类型
	 * @param string $subcategory 消息子类型
	 * @return array
	 */
	public function isShieldMessage($uid,$category,$subcategory){
		$meMessageConfig = $this->getMessageConfigByUid($uid);
		if($meMessageConfig){
			$sheildMesage = $meMessageConfig['sheildmessage'];
			if(isset($sheildMesage[$category]) && $sheildMesage[$category]['is_close']){
				return true;
			}
			$childCategory = $sheildMesage[$category]['child'];
			if(isset($childCategory[$subcategory]) && $childCategory[$subcategory]){
				return true;
			}
		}
		return false;
	}

	/**
	 * 存储用户消息关系
	 *
	 * @param array $relation
	 * @return int
	 */
	protected function saveMultiMessageRelation(array $relation){
		if(empty($relation)){
			return $this->setError(Yii::t('common','Parameter is empty'),array());
		}

		$relationModel = new MessageRelationModel();
		return $relationModel->batchInsert($relation);
	}

	protected function buildUserMessage(array $message){
		$userMessage = array();
		foreach($message as $_message){
			$_message['extra'] = json_decode($_message['extra'],true);
			$userMessage[$_message['message_id']] = $_message;
		}
		return $userMessage;
	}

	/**
	 * 更新用户未读消息数
	 * @param mixed $uid
	 * @param array $counters
	 * @return mix|number
	 */
	public function updateMessageStatisticsCounters($uid ,array $counters){
		if(!$counters || !$uid){
			return $this->setError(Yii::t('common','Parameter is empty'),false);
		}
		$uid = is_array($uid) ? $uid : array($uid);
		$messageStatisModel = new MessageStatisticsModel();
		$criteria = $messageStatisModel->getDbCriteria();
		$criteria->addInCondition('uid',$uid);
		$eUsers = $messageStatisModel->findAll($criteria);
		if($eUsers){
			$eUsers = $this->arToArray($eUsers);
			$eUsers = array_keys($this->buildDataByIndex($eUsers,'uid'));
			foreach($uid as $key=>$_uid){
				if(in_array($_uid,$eUsers)){
					unset($uid[$key]);
				}
			}
			$messageStatisModel->updateCounters($counters,'uid IN ('.implode(',',$eUsers).')');
		}
		if($uid){
			$newData = array();
			$i = 0;
			foreach($uid  as $_uid){
				foreach($counters as $key=>$value){
					$newData[$i]['uid'] = $_uid;
					$newData[$i][$key] = $value;
				}
				$i++;
			}
			return $messageStatisModel->batchInsert($newData);
		}

	}

	public function getUserMessageUnReads($uids){
		if(empty($uids)){
			return array();
		}
		$uids = is_array($uids) ? $uids : array($uids);
		$messageStatisModel = new MessageStatisticsModel();
		$dbCriteria = $messageStatisModel->getDbCriteria();
		$dbCriteria->addInCondition('uid',$uids);
		$unReads = $messageStatisModel->findAll($dbCriteria);
		if($unReads){
			$unReads = $this->arToArray($unReads);
			$unReads = $this->buildDataByIndex($unReads,'uid');
		}
		return $unReads;
	}
	public function mapMessageTypeCounter($item ,$subItem){
		$cateGoryList = array(
			MESSAGE_CATEGORY_FAMILY => array(
				'value'=>'family',
				'child'=>array(
					MESSAGE_CATEGORY_FAMILY_JOIN=>'family_join',
					MESSAGE_CATEGORY_FAMILY_MANAGE=>'family_manage',
					MESSAGE_CATEGORY_FAMILY_UPGRADE=>'family_upgrade',
				)
			),
			MESSAGE_CATEGORY_SYSTEM=>array(
				'value'=>'system',
				'child'=>array(
					MESSAGE_CATEGORY_SYSTEM_UPGRADE=>'system_upgrade',
					MESSAGE_CATEGORY_SYSTEM_PUSH=>'system_push',
					MESSAGE_CATEGORY_SYSTEM_KAIBO=>'system_kaibo',
					MESSAGE_CATEGORY_SYSTEM_SITE=>'system_site',
				)
			),
		);

		if( $item>=0 && isset($cateGoryList[$item])){
			if( $item>=0 && isset($cateGoryList[$item]['child'][$subItem])){
				return $cateGoryList[$item]['child'][$subItem];
			}else{
				return '';
			}
		}
		return '';
	}

	/**
	 * @author supeng
	 * @param array $condition
	 * @param unknown_type $offset
	 * @param unknown_type $pageSize
	 * @param unknown_type $isLimit
	 * @return Ambigous <multitype:, multitype:NULL , multitype:Ambigous <NULL, unknown, multitype:unknown Ambigous <unknown, NULL> , mixed, multitype:, multitype:unknown > Ambigous <string, unknown, mixed> >
	 */
	public function searchMessage(Array $condition = array(),$offset = 0,$pageSize=20,$isLimit=true){
		$model = new MessageContentModel();
		$data = $model->searchMessage($condition,$offset,$pageSize,$isLimit);
		if (!empty($data['list'])) {
			$data['list'] = $this->arToArray($data['list']);
		}
		return $data;
	}

	/**
	 * @author supeng
	 * @param array $condition
	 * @param unknown_type $offset
	 * @param unknown_type $pageSize
	 * @param unknown_type $isLimit
	 */
	public function searchPush(Array $condition = array(),$offset = 0,$pageSize=20,$isLimit=true){
		$model = new MessagePushModel();
		$data = $model->searchPush($condition,$offset,$pageSize,$isLimit);
		if (!empty($data['list'])) {
			$data['list'] = $this->arToArray($data['list']);
		}
		return $data;
	}

	/**
	 * @author supeng
	 * @param unknown_type $flag
	 */
	public function getExtraFlag($flag = null){
		$flags = array(
				'href'=>array('name'=>'链接','default'=>''),
				'from'=>array('name'=>'来源','default'=>'系统发送'),
			);
		return isset($flags[$flag])?$flags[$flag]:$flags;
	}

	/**
	 * @author supeng
	 * @param unknown_type $type
	 */
	public function getPushType($type = null){
		$types = array(
				MESSAGE_PUSH_TYPE_GLOBAL=>'全部所有人',
				MESSAGE_PUSH_TYPE_USER=>'指定用户',
				MESSAGE_PUSH_TYPE_LIVE=>'指定直播间',
				MESSAGE_PUSH_TYPE_DOTEY=>'指定主播'
			);
		return isset($types[$type])?$types[$type]:$types;
	}
}

?>


text:
/**
 * Config mocha
 */

mocha.timeout(60000);
mocha.globals(['jQuery*', '__auth0jp*']);

/**
 * Test User and Password
 */

describe('Auth0 - User And Passwords', function () {
  var auth0 = new Auth0({
    domain:      'mdocs.auth0.com',
    callbackURL: 'http://localhost:3000/',
    clientID:    'ptR6URmXef0OfBDHK0aCIy7iPKpdCG4t'
  });

  describe('Login', function () {

    describe('with resource owner', function () {

      it('should call the callback when user/pass is wrong', function (done) {
        auth0.login({
          connection: 'tests',
          username: 'testttt@wrong.com',
          password: '12345'
        }, function (err, profile) {
          expect(err.status).to.equal(401);
          expect(err.details.code).to.equal('invalid_user_password');
          done();
        });
      });

      // Fails on IE8. Some bug with errors on XMLHttpRequest handling
      // XXX: Fix it!
      it.skip('should call the callback with err when the connection doesn\'t exists', function (done) {
        auth0.login({
          connection: 'testsw3eeasdsadsa',
          username: 'testttt@wrong.com',
          password: '12345'
        }, function (err, profile) {
          expect(err.status).to.equal(400);
          expect(err.message).to.equal('invalid_connection');
          done();
        });
      });

      it('should return profile after successfull authentication', function (done) {
        auth0.login({
          connection: 'tests',
          username: 'johnfoo@gmail.com',
          password: '12345'
        }, function (err, profile, id_token, access_token) {
          expect(profile.name).to.eql('John Foo');
          expect(profile.foo).to.eql('bar');
          expect(profile.identities.length).to.eql(1);
          expect(id_token).to.exist;
          expect(access_token).to.exist;
          done();
        });
      });

      it('should return refresh_token after successfull authentication with offline_mode', function (done) {
        auth0.login({
          connection: 'tests',
          username: 'johnfoo@gmail.com',
          password: '12345',
          offline_mode: true
        }, function (err, profile, id_token, access_token, state, refresh_token) {
          expect(profile.name).to.eql('John Foo');
          expect(profile.foo).to.eql('bar');
          expect(profile.identities.length).to.eql(1);
          expect(id_token).to.exist;
          expect(refresh_token).to.exist;
          expect(access_token).to.exist;
          done();
        });
      });

    });

    describe('with wsfed', function () {

      it('should call the callback when user/pass is wrong', function (done) {
        auth0.login({
          connection: 'tests',
          username: 'testttt@wrong.com',
          password: '12345'
        }, function (err) {
          expect(err.status).to.equal(401);
          expect(err.details.code).to.equal('invalid_user_password');
          done();
        });
      });

      it('should call the callback with err when the connection doesn\'t exists', function (done) {
        auth0.login({
          connection: 'testsw3eeasdsadsa',
          username: 'testttt@wrong.com',
          password: '12345'
        }, function (err) {
          expect(err.status).to.equal(404);
          expect(err.message).to.match(/connection not found/ig);
          done();
        });
      });

      it('should render wsfed form after successfull authentication', function (done) {
        auth0._renderAndSubmitWSFedForm = function (options, htmlForm) {
          expect(htmlForm).to.match(/<form/);
          done();
        };

        auth0.login({
          connection: 'tests',
          username: 'johnfoo@gmail.com',
          password: '12345'
        });
      });

    });

    it('should trim username before login', function (done) {
      auth0.login({
        connection: 'tests',
        username: '    johnfoo@gmail.com     ',
        password: '12345'
      }, function (err, profile, id_token, access_token) {
        expect(profile.name).to.eql('John Foo');
        expect(profile.foo).to.eql('bar');
        expect(profile.identities.length).to.eql(1);
        expect(id_token).to.exist;
        expect(access_token).to.exist;
        done();
      });
    });
  });

  describe('Signup', function () {

    it('should fail when the username is null', function (done) {
      auth0.signup({
        connection: 'tests',
        username: null,
        password: '12345'
      }, function (err) {
        expect(err.status).to.equal(400);
        expect(err.message).to.exist;
        expect(err.details).to.exist;
        done();
      });
    });

    it('should handle server errors', function (done) {
      auth0.signup({
        connection: 'tests',
        username:   'pepo@example.com',
        password:   '12345'
      }, function (err) {
        expect(err.status).to.equal(500);
        expect(err.message).to.exist;
        expect(err.details).to.exist;
        done();
      });
    });

    describe('with resource owner authentication', function () {

      it('should return profile after successfull signup', function (done) {
        auth0.signup({
          connection: 'tests',
          username:   'johnfoo@gmail.com',
          password:   '12345'
        }, function (err, profile, id_token, access_token) {
          expect(profile.name).to.eql('John Foo');
          expect(profile.identities.length).to.eql(1);
          expect(id_token).to.exist;
          expect(access_token).to.exist;
          done();
        });
      });

      it('should not return profile after successfull signup if auto_login is false', function (done) {
        auth0._renderAndSubmitWSFedForm = function (options, htmlForm) {
          done(new Error('this should not be called'));
        };

        auth0.signup({
          connection: 'tests',
          username:   'johnfoo@gmail.com',
          password:   '12345',
          auto_login: false
        }, function (err, profile) {
          done(profile);
        });
      });

    });

    describe('with wsfed authentication', function () {

      it('should render wsfed form after successfull signup', function (done) {
        auth0._renderAndSubmitWSFedForm = function (options, htmlForm) {
          expect(htmlForm).to.match(/<form/);
          done();
        };

        auth0.signup({
          connection: 'tests',
          username: 'johnfoo@gmail.com',
          password: '12345'
        }, function (err) {
          done(err);
        });
      });

      it('should not render wsfed form after successfull signup if auto_login is false', function (done) {
        auth0._renderAndSubmitWSFedForm = function (options, htmlForm) {
          done(new Error('this should not be called'));
        };

        auth0.signup({
          connection: 'tests',
          username:   'johnfoo@gmail.com',
          password:   '12345',
          auto_login: false
        }, function (err) {
          done(err);
        });
      });

    });

    it('should trim username before signup', function (done) {
      auth0.signup({
        connection: 'tests',
        username:   'johnfoo@gmail.com',
        password:   '12345'
      }, function (err, profile) {
        expect(err).to.be(null);
        done();
      });
    });

    it('should handle username and email when requires_username enabled', function (done) {
      var username = makeUsername(15);

      auth0.signup({
        connection: 'requires-username',
        username:   username,
        email: username + '@gmail.com',
        password:   '12345'
      }, function (err, profile) {
        expect(err).to.be(null);
        expect(profile).to.have.property('username');
        expect(profile).to.have.property('email');
        expect(profile.username).to.be(username);
        expect(profile.email).to.be(username + '@gmail.com');
        done();
      });
    });

    it('should error when username is missing when requires_username enabled', function (done) {
      var username = makeUsername(15);

      auth0.signup({
        connection: 'requires-username',
        email: username + '@gmail.com',
        password:   '12345'
      }, function (err, profile) {
        expect(err).to.not.be(null);
        expect(err.status).to.be(400);
        expect(err).to.have.property('message');
        expect(err).to.have.property('details');
        expect(err.message).to.match(/missing username/ig);
        done();
      });
    });

  });

  describe('Change Password', function () {
    // TODO: add a test to check that the user can provide a username or email, when `requires_username` is enabled

    it('should fail when the username is null', function (done) {
      auth0.changePassword({
        connection: 'tests',
        username:   null,
        password:   '12345'
      }, function (err) {
        expect(err.status).to.equal(400);
        expect(err).to.have.property('message');
        expect(err).to.have.property('details');
        done();
      });
    });

    //this timeout sometimes. I need to improve.
    it('should return OK after successfull operation', function (done) {
      auth0.changePassword({
        connection: 'tests',
        username:   'johnfoo@contoso.com',
        password:   '12345'
      }, function (err) {
        expect(err).to.be(null);
        done();
      });
    });

    it('should trim username before operation', function (done) {
      auth0.changePassword({
        connection: 'tests',
        username:     '    johnfoo@gmail.com    ',
        password:   '12345'
      }, function (err) {
        expect(err).to.be(null);
        done();
      });
    });

  });

  describe('Validate User', function () {

    it('should return "true" if the credentials are valid', function (done) {
      auth0.validateUser({
        connection:   'tests',
        username:     'johnfoo@gmail.com',
        password:     '12345'
      }, function (err, valid) {
        expect(err).to.be(null);
        expect(valid).to.equal(true);
        done();
      });
    });

    it('should return "true" if the credentials with username and email are valid', function (done) {
      auth0.validateUser({
        connection:   'tests',
        username:     'johnfoo',
        email:        'johnfoo@gmail.com',
        password:     '12345'
      }, function (err, valid) {
        expect(err).to.be(null);
        expect(valid).to.equal(false);
        done();
      });
    });

    it('should return "false" if username is invalid', function (done) {
      auth0.validateUser({
        connection:   'tests',
        username:     'invalid-user@gmail.com',
        password:     '12345'
      }, function (err, valid) {
        expect(err).to.be(null);
        expect(valid).to.equal(false);
        done();
      });
    });

    it('should return "false" if email is valid and username is invalid', function (done) {
      auth0.validateUser({
        connection:   'tests',
        username:     'invalid-user',
        email:        'johnfoo@gmail.com',
        password:     '12345'
      }, function (err, valid) {
        expect(err).to.be(null);
        expect(valid).to.equal(false);
        done();
      });
    });

    it('should return "false" if email is invalid and username is valid', function (done) {
      auth0.validateUser({
        connection:   'tests',
        username:     'johnfoo',
        email:        'invalid#email@gmail.com',
        password:     '12345'
      }, function (err, valid) {
        expect(err).to.be(null);
        expect(valid).to.equal(false);
        done();
      });
    });

    it('should return "false" if connection is invalid', function (done) {
      auth0.validateUser({
        connection:   'invalid-conn',
        username:     'johnfoo@gmail.com',
        password:     '12345'
      }, function (err, valid) {
        expect(err).to.be(null);
        expect(valid).to.equal(false);
        done();
      });
    });

    it('should return error if connection is not specified', function (done) {
      auth0.validateUser({
        username:     'johnfoo@gmail.com',
        password:     '12345'
      }, function (err) {
        if (auth0._use)
        expect(err.message).to.equal('connection parameter is mandatory');
        done();
      });
    });

    it('should trim username before validation', function (done) {
      auth0.validateUser({
        connection:   'tests',
        username:     '    johnfoo@gmail.com    ',
        password:     '12345'
      }, function (err, valid) {
        expect(err).to.be(null);
        expect(valid).to.equal(true);
        done();
      });
    });

  });

});

function makeUsername(size) {
  var uname = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for( var i=0; i < size; i++ ) {
    uname += possible.charAt(Math.floor(Math.random() * possible.length));
  }

  return uname.toLowerCase();
}


text:
<?php
namespace packages\base;

class NoViewException extends Exception {
	/** @var string */
	private $viewName;

	/**
	 * @param string $viewName
	 * @param string $message
	 */
	public function __construct(string $viewName, string $message = "") {
		$this->viewName = $viewName;
		if (!$message) {
			$message = "Cannot find {$viewName} or any of its children";
		}
		return $viewName;
	}

	public function getViewName(): string {
		return $this->viewName;
	}
}


text:
#ifndef DT_ACCURACY_H
#define DT_ACCURACY_H

#include "MT_Scalar.h"

class DT_Accuracy {
public:
	static MT_Scalar rel_error2; // squared relative error in the computed distance
	static MT_Scalar depth_tolerance; // terminate EPA if upper_bound <= depth_tolerance * dist2
	static MT_Scalar tol_error; // error tolerance if the distance is almost zero

	static void setAccuracy(MT_Scalar rel_error)
	{
		rel_error2 = rel_error * rel_error;
		depth_tolerance = MT_Scalar(1.0) + MT_Scalar(2.0) * rel_error;
	}

	static void setTolerance(MT_Scalar epsilon)
	{
		tol_error = epsilon;
	}
};

#endif


text:
.class public final Landroid/content/pm/PackageParser$Service;
.super Landroid/content/pm/PackageParser$Component;
.source "PackageParser.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/content/pm/PackageParser;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Service"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/content/pm/PackageParser$Component",
        "<",
        "Landroid/content/pm/PackageParser$ServiceIntentInfo;",
        ">;"
    }
.end annotation

# instance fields
.field public final info:Landroid/content/pm/ServiceInfo;

# direct methods
.method public constructor <init>(Landroid/content/pm/PackageParser$ParseComponentArgs;Landroid/content/pm/ServiceInfo;)V
    .locals 2
    .param p1, "args"    # Landroid/content/pm/PackageParser$ParseComponentArgs;
    .param p2, "_info"    # Landroid/content/pm/ServiceInfo;

    .prologue
    .line 5046
    invoke-direct {p0, p1, p2}, Landroid/content/pm/PackageParser$Component;-><init>(Landroid/content/pm/PackageParser$ParseComponentArgs;Landroid/content/pm/ComponentInfo;)V

    .line 5047
    iput-object p2, p0, Landroid/content/pm/PackageParser$Service;->info:Landroid/content/pm/ServiceInfo;

    .line 5048
    iget-object v0, p0, Landroid/content/pm/PackageParser$Service;->info:Landroid/content/pm/ServiceInfo;

    iget-object v1, p1, Landroid/content/pm/PackageParser$ParseComponentArgs;->owner:Landroid/content/pm/PackageParser$Package;

    iget-object v1, v1, Landroid/content/pm/PackageParser$Package;->applicationInfo:Landroid/content/pm/ApplicationInfo;

    iput-object v1, v0, Landroid/content/pm/ServiceInfo;->applicationInfo:Landroid/content/pm/ApplicationInfo;

    .line 5049
    return-void
.end method

# virtual methods
.method public setPackageName(Ljava/lang/String;)V
    .locals 1
    .param p1, "packageName"    # Ljava/lang/String;

    .prologue
    .line 5052
    invoke-super {p0, p1}, Landroid/content/pm/PackageParser$Component;->setPackageName(Ljava/lang/String;)V

    .line 5053
    iget-object v0, p0, Landroid/content/pm/PackageParser$Service;->info:Landroid/content/pm/ServiceInfo;

    iput-object p1, v0, Landroid/content/pm/ServiceInfo;->packageName:Ljava/lang/String;

    .line 5054
    return-void
.end method

.method public toString()Ljava/lang/String;
    .locals 2

    .prologue
    .line 5057
    new-instance v0, Ljava/lang/StringBuilder;

    const/16 v1, 0x80

    invoke-direct {v0, v1}, Ljava/lang/StringBuilder;-><init>(I)V

    .line 5058
    .local v0, "sb":Ljava/lang/StringBuilder;
    const-string v1, "Service{"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 5059
    invoke-static {p0}, Ljava/lang/System;->identityHashCode(Ljava/lang/Object;)I

    move-result v1

    invoke-static {v1}, Ljava/lang/Integer;->toHexString(I)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 5060
    const/16 v1, 0x20

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    .line 5061
    invoke-virtual {p0, v0}, Landroid/content/pm/PackageParser$Service;->appendComponentShortName(Ljava/lang/StringBuilder;)V

    .line 5062
    const/16 v1, 0x7d

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    .line 5063
    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    return-object v1
.end method


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace P11_Odd_Number
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());

            while (n % 2 == 0)
            {
                Console.WriteLine("Please write an odd number.");
                n = int.Parse(Console.ReadLine());
            }

            if (n < 0)
            {
                n *= -1;
                Console.WriteLine($"The number is: {n}");
            }
            else
            {
                Console.WriteLine($"The number is: {n}");
            }

        }
    }
}


text:
<ns0:metadata xmlns:ns0="http://purl.org/ornl/schema/mercury/terms/v1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://purl.org/ornl/schema/mercury/terms/v1.0 mercury-ornl-v1.xsd">
  <idinfo>
    <citation>
      <citeinfo>
        <origin>Herman, Karl</origin>
        <origin>Hayden, Larry</origin>
        <title>Map ORR Land Cover LandsatTM SAMAB 30m 1992</title>
        <onlink>http://daac.ornl.gov/data/bluangel_harvest/WBW/gibbs/metadata/Map_ORR_Land_Cover_LandsatTM_SAMAB_30m_1992.xml</onlink>
        <onlink>ftp://ftp.esd.ornl.gov/pub/orr/Maps/Land_Cover/ORR/based_on_Landsat/1992_samab/Browse%20ORR%20Land%20Cover%201992%20SAMAB.html</onlink>
        <onlink>http://sunsite.utk.edu/samab/data/SAA_data.html</onlink>
        <onlink>http://samab.org/data/saa3/saa_rast/</onlink>
      </citeinfo>
    </citation>
    <descript>
      <abstract>This raster land cover map of theOak Ridge Reservation was produced through unsupervised classfication followed by post-classification refinement of LandsatTM data from the early 1990s.  This map is a subset of the land cover map produced as part of the SAMAB (Southern Appalachian Man and the Biosphere Program)SAA (Southern Appalachian Assessment).</abstract>
      <supplinf />
    </descript>
    <timeperd>
      <timeinfo>
        <rngdates>
          <begdate>19920101</begdate>
          <enddate>19920131</enddate>
        </rngdates>
      </timeinfo>
    </timeperd>
    <status>
      <progress>Final</progress>
      <update>As appropriate</update>
    </status>
    <spdom>
      <bounding>
        <westbc>-84.44</westbc>
        <eastbc>84.19</eastbc>
        <northbc>36</northbc>
        <southbc>-35.81</southbc>
      </bounding>
    </spdom>
    <keywords>
      <theme>
        <themekt>Parameter_Sensor_Source</themekt>
        <themekey>LAND CLASSES|LANDSAT TM(LANDSAT THEMATIC MAPPER)|LANDSAT-5</themekey>
        <themekt>Parameter</themekt>
        <themekey>LAND CLASSES</themekey>
        <themekt>Source</themekt>
        <themekey>LANDSAT-5</themekey>
        <themekt>Sensor</themekt>
        <themekey>LANDSAT TM(LANDSAT THEMATIC MAPPER)</themekey>
      </theme>
      <place>
        <placekt>Place Keywords</placekt>
        <placekey>Oak Ridge Reservation, TN, USA</placekey>
      </place>
    </keywords>
    <ptcontac>
      <cntinfo>
        <cntperp>
          <cntper>Herman, Karl</cntper>
        </cntperp>
        <cntfax>6.1.10.8 Contact Electronic Mail: INTERNET &gt; N/A</cntfax>
      </cntinfo>
    </ptcontac>
  </idinfo>
  <distinfo>
    <distrib>
      <cntinfo>
        <cntperp>
          <cntorg>Environmental Sciences Division, Oak Ridge National Laboratory</cntorg>
          <cntper>Gibbs, Holly K.</cntper>
        </cntperp>
        <cntvoice>(865) 574-7356</cntvoice>
        <cntfax>6.1.10.8 Contact Electronic Mail: INTERNET &gt; N/A</cntfax>
        <cntemail>gibbshk@ornl.gov</cntemail>
      </cntinfo>
    </distrib>
    <stdorder>
      <digform>
        <digtopt>
          <onlinopt>
            <computer>ftp://ftp.esd.ornl.gov/pub/orr/</computer>
            <accinstr>Public</accinstr>
          </onlinopt>
        </digtopt>
      </digform>
    </stdorder>
    <resdesc>Oak Ridge Reservation subset of the Hermann, K.A. (ed.). 1996.  The Southern Appalachian Assessment GIS Data Base CD ROM Set.  The Southern Appalachian Man and the Biosphere Program.  Norris, TN.  Available on-line at ftp://ftp.esd.ornl.gov/pub/orr/Maps/Land_Cover/ORR/based_on_Landsat/1992_samab/</resdesc>
  </distinfo>
  <metainfo>
    <metd>20020413 184305</metd>
    <metc>
      <cntinfo>
        <cntorgp>
          <cntper>Gibbs, Holly K.</cntper>
        </cntorgp>
        <cntperp>
          <cntper>Gibbs, Holly K.</cntper>
        </cntperp>
        <cntvoice>(865) 574-7356</cntvoice>
        <cntemail>gibbshk@ornl.gov</cntemail>
      </cntinfo>
    </metc>
    <metstdn>FGDC Content Standard for Digital Geospatial Metadata</metstdn>
  </metainfo>
  <mercury>
    <begdate>19920101</begdate>
    <enddate>19920131</enddate>
    <Site_Information>
      <Site>Oak Ridge Reservation, TN, USA</Site>
      <Westernmost_Longitude>-84.44</Westernmost_Longitude>
      <Easternmost_Longitude>84.19</Easternmost_Longitude>
      <Northernmost_Latitude>36</Northernmost_Latitude>
      <Southernmost_Latitude>-35.81</Southernmost_Latitude>
    </Site_Information>
    <Keywords>Oak Ridge Reservation</Keywords>
    <Keywords>Land use</Keywords>
    <Keywords>Settings</Keywords>
    <Keywords>Land cover</Keywords>
    <Keywords>Remote Sensing</Keywords>
    <Keywords>Landsat</Keywords>
    <Parameter_Description>
      <Parameter>LAND CLASSES</Parameter>
      <Sensor>LANDSAT TM(LANDSAT THEMATIC MAPPER)</Sensor>
      <Source>LANDSAT-5</Source>
      <Term>LAND USE/LAND COVER</Term>
      <Topic>LAND SURFACE</Topic>
    </Parameter_Description>
    <Project>The Oak Ridge Reservation Bioenergy and Carbon Sequestration Initiative; managed by Robin L. Graham</Project>
    <Navpath>LANDSAT-5|LANDSAT TM(LANDSAT THEMATIC MAPPER)|LAND CLASSES</Navpath>
    <Principal_Investigator>
      <Name>Herman, Karl</Name>
      <Email>N/A</Email>
    </Principal_Investigator>
    <Principal_Investigator>
      <Name>Hayden, Larry</Name>
      <Email>N/A</Email>
    </Principal_Investigator>
    <Data_Set_Link>
      <URL>ftp://ftp.esd.ornl.gov/pub/orr/Maps/Land_Cover/ORR/based_on_Landsat/1992_samab/</URL>
      Download 1992 SAMAB Land Cover Map
      <Link_Note />
    </Data_Set_Link>
    <Documentation_Link>
      <URL>ftp://ftp.esd.ornl.gov/pub/orr/Maps/Land_Cover/ORR/based_on_Landsat/1992_samab/Browse%20ORR%20Land%20Cover%201992%20SAMAB.html</URL>
      Browse image and metadata
      <Text />
    </Documentation_Link>
    <Documentation_Link>
      <URL>http://sunsite.utk.edu/samab/data/SAA_data.html</URL>
      Description of available spatial data sets of the Southern Appalachian region
    </Documentation_Link>
    <Documentation_Link>
      <URL>http://samab.org/data/saa3/saa_rast/</URL>
      Location of complete 'Settings for Southern Appalachia' data set
    </Documentation_Link>
    <OME_Software_Version>Version 2.4.04a, Revision Date: 19 Mar 2002</OME_Software_Version>
    <OME_DTD_Version>metadata20.dtd</OME_DTD_Version>
    <Contact_Person>
      <Email>gibbshk@ornl.gov</Email>
      <Name>Gibbs, Holly K.</Name>
      <Phone>(865) 574-7356</Phone>
    </Contact_Person>
    <Temporal_Resolution>N/A</Temporal_Resolution>
    <enddate_blank />
    <Harvest_Date>20140923</Harvest_Date>
    <File_ID>Created 20020413 184217 by 160.91.16.106</File_ID>
    <Spatial_Reference_Method>Raster</Spatial_Reference_Method>
    <Spatial_Extent>12109.3203</Spatial_Extent>
    <Search_Text_Link>
      <URL>ftp://ftp.esd.ornl.gov/pub/orr/Maps/Land_Cover/ORR/based_on_Landsat/1992_samab/Browse%20ORR%20Land%20Cover%201992%20SAMAB.html</URL>
      Browse image and metadata
    </Search_Text_Link>
    <Other_Link>
      <URL>http://sunsite.utk.edu/samab/data/SAA_data.html</URL>
      Description of available spatial data sets of the Southern Appalachian region
    </Other_Link>
    <Other_Link>
      <URL>http://samab.org/data/saa3/saa_rast/</URL>
      Location of complete 'Settings for Southern Appalachia' data set
    </Other_Link>
  </mercury>
</ns0:metadata>


text:
package jade.core.messaging;

//#J2ME_EXCLUDE_FILE

import jade.lang.acl.ACLMessage;

/**
   Ready made persistent delivery filter that makes whatever
   message always persistent.
   @author Giovanni Caire - TILAB
 */
public class MatchAllFilter implements PersistentDeliveryFilter {
  /**
     Match all possible messages
   */
  public long delayBeforeExpiration(ACLMessage msg) {
  	return NEVER;
  }
}


text: A project manager helping tool to visualize the projects by resources, projects and initiatives.


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Rabenh. Krypt. -Fl. , Edn 2 1(1): 215 (1882)

#### Original name
Puccinia silenes J. Schröt., 1882

### Remarks
null


text:
import org.jruby.runtime.EventHook;

public abstract class RcovHook extends EventHook {
  /** returns true if the hook is set */
  abstract boolean isActive();

  /** used to mark the hook set or unset */
  abstract void setActive(boolean active);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>

A ValueObject is an Object which Attributes could by retrived using
AttributesInfos.
A ValueObject could be used as Superclass, Wrapper oder as ReflectionHandler
for other classes to get their values.

</body>
</html>


text:
package com.getbase.exceptions;

public class ConnectionException extends RuntimeException {
    public ConnectionException(String message) {
        super(message);
    }

    public ConnectionException(Throwable cause) {
        super(cause);
    }
}


text:
classdef topsTreeNodeTask2AFCSwitch < topsTreeNodeTask
   % @class topsTreeNodeTask2AFCSwitch
   %
   % Simple 2AFC task with change-points.
   %
   % DEPENDENCIES: uses dotsPlayableTonePTB, which uses several
   %  Psychtoolbox files:
   %     PsychPortAudio.m
   %     PsychPortAudio.mexmaci64
   %     PsychPortAudioTimingTest.m
   %     Screen.m
   %     Screen.mexmaci64
   %
   % For standard configurations, call:
   %  topsTreeNodeTask2AFCSwitch.getStandardConfiguration
   %
   % Otherwise:
   %
   %  1. Create an instance directly:
   %        task = topsTreeNodeTask2AFCSwitch();
   %
   %  2. Set properties.
   %
   %  3. Add this as a child to another topsTreeNode
   %
   % 12/10/19 created by jig from topsTreeNodeTaskSimpleBandit

   properties % (SetObservable) % uncomment if adding listeners

      % Trial properties, put in a struct for convenience
      settings = struct( ...
         'blockMin',                   0,   ... % min hazard-block length (trials)
         'blockMax',                   0,   ... % max hazard-block length (trials)
         'blockHazard',                0.1, ... % p(block switch)
         'predictOrReport',            'Report', ... % duh
         'useDrawables',               true, ... % Use visual stimuli
         'usePlayables',               true, ... % Use auditory stimuli
         'checkFixation',              false, ... % Whether to use eye tracker to check
         'minimumRT',                  0.0, ...
         'fractionCongruent',          0.8);    % fraction of targets congurent with source

      % Task timing parameters, all in sec
      timing = struct( ...
         'waitFix',                    5.0, ...
         'waitNoFix',                  0.5, ...
         'waitBeforeStim',             0.1, ...
         'stimDuration',               1.0, ...
         'waitAfterStim',              0.1, ...
         'waitBeforeChoice',           0.1, ...
         'choiceTimeout',              5.0, ...
         'waitAfterChoice',            0.1, ...
         'minimumRT',                  0,   ...
         'interTrialInterval',         0.5);

      % Fields below are optional but if found with the given names
      %  will be used to automatically configure the task

      % independentVariables used by topsTreeNodeTask.makeTrials. Can
      % modify using setIndependentVariableByName and
      % setIndependentVariablesByName.
      %
      % Creates the array of trialData structures, using:
      %  name     ... list of independent variables
      %  values   ... array of values associated with each independent
      %                    variable
      %  priors   ... empty, or relative frequencies of each value for each
      %                    independent variable (automatically normalizes
      %                    to sum to 1).
      %
      %  Also uses:
      %     trialIterations property to determine the number
      %              of copies of each trial type to use
      %     trialIterationMethod property to determine the
      %              ordering of the trials (in trialIndices)
      independentVariables = struct( ...
         'hazard',   struct('values', [0.10 0.30 0.90]));

      % dataFieldNames is a cell array of string names used as trialData fields
      % state and stim are 1/2
      trialDataFields = {'fixationOn', 'drawOn', 'playOn', 'drawOff', ...
         'instructionOn', 'choice', 'choiceTime', 'RT', 'fixationOff', ...
         'stim', 'state', 'totalCorrect', 'totalChoices'};

      % Drawables settings
      drawable = struct( ...
         ...
         ...   % Stimulus ensemble and settings
         'stimulusEnsemble',           struct( ...
         ...
         ...   % Drawable A settings
         'stimulusA',                  struct(     ...
         'fevalable',                  @dotsDrawableImages, ...
         'settings',                   struct(     ...
         'fileNames',                  {{'bird.jpg'}}, ...
         'height',                     15)),  ...
         ...
         ...   % Drawable B settings
         'stimulusB',                  struct(     ...
         'fevalable',                  @dotsDrawableImages, ...
         'settings',                   struct(     ...
         'fileNames',                  {{'bird.jpg'}}, ...
         'height',                     8)), ...
         ...
         ...   % Fixation settings
         'fixation',                   struct( ...
         'fevalable',                  @dotsDrawableTargets, ...
         'settings',                   struct( ...
         'nSides',                     4,                ...
         'width',                      1.0.*[2.0 0.2],   ...
         'height',                     1.0.*[0.2 2.0],   ...
         'colors',                     [1 0 0]))));

      % Playable settings
      playable = struct( ...
         ...
         ...   % Playable A settings
         'stimulusA',                  struct(     ...
         'fevalable',                  @dotsPlayableTonePTB, ...
         'settings',                   struct(     ...
         'frequency',                  200,        ...
         'duration',                   1.0)),      ...
         ...
         ...   % Playable B settings
         'stimulusB',                  struct(     ...
         'fevalable',                  @dotsPlayableTonePTB, ...
         'settings',                   struct(     ...
         'frequency',                  1000,        ...
         'duration',                   1.0)));

      % Readable settings
      readable = struct( ...
         ...
         ...   % The readable object
         'reader',                     struct( ...
         ...
         'copySpecs',                  struct( ...
         ...
         ...    % Button box (this is actually a HIDKeyboard, so you should
         ...    %    list this before the keyboard to make sure the correct
         ...    %    class is mapped
         'dotsReadableHIDButtons',     struct( ...
         'start',                      {{@defineEventsFromStruct, struct( ...
         'name',                       {'choseA', 'choseB'}, ...
         'component',                  {'Button1', 'Button2'})}}), ...
         ...
         ...   % Keyboard events
         'dotsReadableHIDKeyboard',    struct( ...
         'start',                      {{@defineEventsFromStruct, struct( ...
         'name',                       {'choseA', 'choseB'}, ...
         'component',                  {'KeyboardF', 'KeyboardJ'})}}), ...
         ...
         ...   % Gamepad
         'dotsReadableHIDGamepad',   	struct( ...
         'start',                      {{@defineEventsFromStruct, struct( ...
         'name',                       {'choseA', 'choseB'}, ...
         'component',                  {'Trigger1', 'trigger2'})}}), ...
         ...
         ...   % Dummy to run in demo mode
         'dotsReadableDummy',          struct( ...
         'start',                      {{@defineEventsFromStruct, struct( ...
         'name',                       {'choseA', 'choseB'}, ...
         'component',                  {'Dummy1', 'Dummy2'})}}))), ...
         ...
         ...   % The eye tracker object, if being used
         'eye',                        struct( ...
         ...
         'copySpecs',                  struct( ...
         ...
         ...   % The gaze windows
         'dotsReadableEye',            struct( ...
         'bindingNames',               'stimulusEnsemble', ...
         'prepare',                    {{@updateGazeWindows}}, ...
         'start',                      {{@defineEventsFromStruct, struct( ...
         'name',                       {'holdFixation', 'brokeFixation'}, ...
         'ensemble',                   {'fixationEnsemble', 'fixationEnsemble'}, ... % ensemble object to bind to
         'ensembleIndices',            {[1 1], [1 1]}, ...
         'isInverted',                 {0, 1})}}))));

      % Feedback messages
      message = struct( ...
         ...
         'message',                    struct( ...
         ...
         ...   Instructions
         'Instructions',               struct( ...
         'text',                       'Instructions', ...
         'speakText',                  true, ...
         'duration',                   1.0, ...
         'pauseDuration',              0.5, ...
         'bgEnd',                      [0 0 0]), ...
         ...
         ...   Cue to predict
         'Predict',                    struct(  ...
         'text',                       'Predict'), ...
         ...
         ...   Cue to report
         'Report',                     struct(  ...
         'text',                       'Report')));
   end

   methods

      %% Constuct with name optional.
      % @param name optional name for this object
      % @details
      % If @a name is provided, assigns @a name to this object.
      function self = topsTreeNodeTask2AFCSwitch(varargin)

         % ---- Make it from the superclass
         %
         self = self@topsTreeNodeTask(mfilename, varargin{:});
      end

      %% Start task method
      function startTask(self)

         % ---- Initialize the state machine
         %
         self.initializeStateMachine();

         % ---- Set up block switches
         %
         self.incrementTrialMethod            = 'hazard';
         self.incrementTrial.hazard.rate      = self.settings.blockHazard;
         self.incrementTrial.hazard.minTrials = self.settings.blockMin;
         self.incrementTrial.hazard.maxTrials = self.settings.blockMax;

         % ---- Set up readables
         %
         % Check for eye helper
         if ~isfield(self.helpers, 'eye') || isempty(self.helpers.eye.theObject)
            self.settings.checkFixation = false;
         end

         % ---- Show task-specific instructions
         %
         if strcmpi(self.settings.predictOrReport, 'predict')
            self.settings.predictOrReport = 'Predict';
            self.helpers.message.setText('Instructions', ...
               {'Predict the identity of the next stimulus'});
         else
            self.settings.predictOrReport = 'Report';
            self.helpers.message.setText('Instructions', ...
               {'Report the identity of the previous stimulus'});
         end
         self.helpers.message.show('Instructions');
      end

      %% Overloaded finish task method
      function finishTask(self)
      end

      %% Overloaded start trial method
      %
      % Put stuff here that you want to do at the beginning of each
      %  trial
      function startTrial(self)

         % ---- Get the trial
         %
         trial = self.getTrial();

         %---- Set up trial struct
         %
         % Initialize just the first time we use this trial
         if ~isfinite(trial.totalCorrect)

            % We iterate through each "trial" several times, so at the
            % beginning we need to reset these counters
            trial.totalCorrect = 0;
            trial.totalChoices = 0;
            trial.state = randi(2);
         else

            % Clean up fields that get saved per trial
            for ii = 1:length(self.trialDataFields)-3
               trial.(self.trialDataFields{ii}) = nan;
            end
         end

         % Switch/keep state based on hazard
         if rand() <= trial.hazard
            trial.state = bitxor(trial.state, 3);
         end

         % Get stim location from state
         if rand() <= self.settings.fractionCongruent
            trial.stim = trial.state;
         else
            trial.stim = bitxor(trial.state, 3);
         end

         % Re-save the trial
         self.setTrial(trial);

         % ---- Prepare the playables
         %
         if self.settings.usePlayables
            self.helpers.stimulusA.theObject.prepareToPlay();
            self.helpers.stimulusB.theObject.prepareToPlay();
         end

         % ---- Set up readable isActive flags
         %
         if self.settings.checkFixation
            self.helpers.eye.theObject.setEventsActiveFlag({'holdFixation', 'brokeFixation'}, 'all');
         end
         self.helpers.reader.theObject.setEventsActiveFlag({'choseA', 'choseB'}, 'all');

         % ---- Use the task ITI
         %
         self.interTrialInterval = self.timing.interTrialInterval;

         % ---- Show information about the trial
         %
         % Task information
         taskString = sprintf('%s (ID=%d, task %d/%d)', self.name, ...
            self.taskID, self.taskIndex, length(self.caller.children));

         % Trial information
         trialString = sprintf('Trial %d(%d)/%d: Correct=%d/%d', ...
            self.trialCount, self.incrementTrial.counter, numel(self.trialData), ...
            trial.totalCorrect, trial.totalChoices);

         % Show the information
         self.updateStatus(taskString, trialString);
      end

      %% Finish Trial
      %
      % Could add stuff here
      function finishTrial(self)
      end

      %% Show stimulus
      %
      function showStimulus(self)

         % ---- Get the trial
         %
         trial = self.getTrial();

         % ---- Possibly show the visual stimulus
         %
         if self.settings.useDrawables
            self.helpers.stimulusEnsemble.draw({[trial.stim 3], []}, ...
               self, 'drawOn');
         end

         % ---- Possibly play the auditory stimulus
         %
         if self.settings.usePlayables
            self.helpers.(['stimulus' 64+trial.stim]).startPlaying( ...
               self, 'playOn');
         end
      end

      %% Hide stimulus
      %
      function hideStimulus(self)

         % ---- Possibly hide the visual stimulus
         %
         if self.settings.useDrawables
            self.helpers.stimulusEnsemble.draw({[], [1 2]}, ...
               self, 'drawOff');
         end
      end

      %% Check for choice
      %
      % Save choice/RT information and set up feedback for the dots task
      function nextState = checkForChoice(self, events, eventTag, nextStateAfterChoice)

         % ---- Check for event
         %
         eventName = self.helpers.reader.readEvent(events, self, eventTag);

         % Nothing... keep checking
         if isempty(eventName)
            nextState = [];
            return
         end

         % ---- Good choice!
         %
         % Override completedTrial flag
         self.completedTrial = true;

         % Jump to next state when done
         nextState = nextStateAfterChoice;

         % ---- Save trial info
         %
         % Get current task/trial and set/save RT, choice
         trial        = self.getTrial();
         trial.RT     = trial.choiceTime - trial.instructionOn;
         trial.choice = 1+double(strcmp(eventName, 'choseB'));

         % Mark as correct/error (with respect to largest reward side)
         trial.totalChoices = trial.totalChoices + 1;
         trial.totalCorrect = trial.totalCorrect + double( ...
            trial.choice == trial.stim);

         % Re-save the trial
         self.setTrial(trial);
      end
   end

   methods (Access = protected)

      %% configureStateMachine method
      %
      function initializeStateMachine(self)

         % ---- Fevalables for state list
         %
         % Draw
         blanks = {@dotsTheScreen.blankScreen};
         showfp = {@draw, self.helpers.stimulusEnsemble, {3, [1 2]}, self, 'fixationOn'};
         showst = {@showStimulus, self};
         hidest = {@hideStimulus, self};
         showi  = {@show, self.helpers.message, self.settings.predictOrReport, self, 'instructionOn'};

         % Read
         chkchc = {@checkForChoice, self, {'choseA' 'choseB'}, 'choiceTime', 'waitAfterChoice'};

         % ---- Conditional check for fixation
         %
         if self.settings.checkFixation
            chkeyef = {@getNextEvent, self.helpers.reader.theObject, false, {'holdFixation'}};
            chkeyeb = {@getNextEvent, self.helpers.reader.theObject, false, {'brokeFixation'}};
            nextFix = 'checkFixation';
         else
            chkeyef = {};
            chkeyeb = {};
            nextFix = 'noCheckFixation';
         end

         % ---- Timing variables, read directly from the timing property struct
         %
         t = self.timing;

         % ---- The Stimulus state machine
         %
         stimStates = {...
            'name'               'entry'  'input'  'timeout'            'exit'   'next'         ; ...
            'showFP'             showfp   {}       0                    {}       nextFix        ; ...
            'checkFixation'      {}       chkeyef  t.waitFix            {}       'retry'        ; ...
            'retry'              blanks   {}       t.interTrialInterval {}       'checkFixation'; ...
            'noCheckFixation'    {}       {}       t.waitNoFix          {}       'holdFixation' ; ...
            'holdFixation'       {}       chkeyeb  t.waitBeforeStim     {}       'showStim'     ; ...
            'showStim'           showst   chkeyeb  t.stimDuration       hidest   'waitAfterStim'; ...
            'waitAfterStim'      {}       chkeyeb  t.waitAfterStim      {}       'blank'        ; ...
            'blank'              blanks   {}       0                    {}       ''             ; ...
            };

         % ---- The Response state machine
         %
         responseStates = {...
            'name'               'entry'  'input'  'timeout'            'exit'   'next'         ; ...
            'waitBeforeChoice'   blanks   {}       t.waitBeforeChoice   {}       'getChoice'    ; ...
            'getChoice'          showi    chkchc   t.choiceTimeout      {}       'waitBeforeChoice' ; ...
            'waitAfterChoice'    {}       {}       t.waitAfterChoice    {}       ''             ; ...
            };

         % ---- Add state machines in appropriate order
         %
         if strcmp(self.settings.predictOrReport, 'predict')

            % Prediction task: first response, then stimulus
            self.addStateMachine(responseStates);
            self.addStateMachine(stimStates);
         else

            % Report task: first stimulus, then response
            self.addStateMachine(stimStates);
            self.addStateMachine(responseStates);
         end
      end
   end

   methods (Static)

      %% ---- Utility for defining standard configurations
      %
      function task = getStandardConfiguration(varargin)

         % ---- Get the task object, with optional property/value pairs
         task = topsTreeNodeTask2AFCSwitch(varargin{:});
      end

      %% ---- Utility for getting test configuration
      %
      function task = getTestConfiguration()

         task = topsTreeNodeTask2AFCSwitch();
         task.settings.blockMin = 2;
         task.settings.blockMax = 2;
         % task.independentVariables.hazard.values = 0.5;
         task.message.message.Instructions.text = {'Testing', 'topsTreeNodeTask2AFCSwitch'};
      end
   end
end


text:
package net.stevechaloner.intellijad.util;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;

import net.stevechaloner.intellijad.config.ApplicationConfigComponent;
import net.stevechaloner.intellijad.config.Config;
import net.stevechaloner.intellijad.config.ProjectConfigComponent;

import org.jetbrains.annotations.NotNull;

/**
 * Helper class for plugin interactions.
 *
 * @author Steve Chaloner
 */
public class PluginUtil
{
    /**
     * Static access only.
     */
    private PluginUtil()
    {
    }

    /**
     * Gets the component from the application context.
     *
     * @param clazz the class of the component
     * @return the component
     */
    public static <C> C getComponent(Class<C> clazz)
    {
        return ApplicationManager.getApplication().getComponent(clazz);
    }

    /**
     * Gets the application-level configuration.
     *
     * @return the application-level configuration
     */
    public static Config getApplicationConfig()
    {
        return getComponent(ApplicationConfigComponent.class).getConfig();
    }

    /**
     * Gets the plugin configuration.
     *
     * @param project the project to get the config from
     * @return the project configuration
     */
    public static Config getConfig(@NotNull Project project)
    {
        ProjectConfigComponent projectComponent = project.getComponent(ProjectConfigComponent.class);
        Config config = null;
        if (projectComponent != null)
        {
            config = projectComponent.getConfig();
        }
        if (config == null || !config.isUseProjectSpecificSettings())
        {
            config = getApplicationConfig();
        }
        return config;
    }
}


text:
namespace ml
{

void tsne(const std::vector<tIO>& originalData, f64 theta, f64 perplexity,
                std::vector<tIO>& reducedDimData)
{
    // Verify that the input is reasonable.
    if (originalData.size() == 0)
        throw eInvalidArgument("There must be at least one original data point.");
    for (size_t i = 1; i < originalData.size(); i++)
        if (originalData[i].size() != originalData[0].size())
            throw eInvalidArgument("All data points must have the same dimensionality.");
    if (originalData[0].size() == 0)
        throw eInvalidArgument("The dimensionality of the data points must be non-zero.");
    if (theta < 0.0 || theta > 1.0)
        throw eInvalidArgument("Theta must be in the range [0.0, 1.0].");

    // Setup the state that the t-SNE algo needs.
    int N = (int) originalData.size();
    int D = (int) originalData[0].size();
    int redDims = 2;
    double* data = (double*) malloc(N * D * sizeof(double));
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < D; j++)
            data[i*D + j] = originalData[i][j];
    }
    double* Y = (double*) malloc(N * redDims * sizeof(double));

    // Run t-SNE.
    TSNE tsneobj;
    tsneobj.run(data, N, D, Y, redDims, perplexity, theta);
    free(data); data = NULL;

    // Copy the results out.
    reducedDimData.resize(N);
    for (int i = 0; i < N; i++)
    {
        reducedDimData[i].resize(redDims);
        for (int j = 0; j < redDims; j++)
            reducedDimData[i][j] = Y[i*redDims + j];
    }
    free(Y); Y = NULL;
}

void plotImages(const std::vector<tIO>& images, bool color, u32 width,
                bool absolute, const std::vector<tIO>& locations,
                u32 destWidth, img::tImage* dest)
{
    // Verify the input.
    if (images.size() != locations.size())
        throw eInvalidArgument("There must be the same number of images as locations.");
    if (images.size() == 0)
        throw eInvalidArgument("There must be at least one image to plot.");
    for (size_t i = 1; i < images.size(); i++)
        if (images[i].size() != images[0].size())
            throw eInvalidArgument("Each image must have the same dimensionality.");
    if (images[0].size() == 0)
        throw eInvalidArgument("The image dimensionality must be non-zero.");
    for (size_t i = 0; i < locations.size(); i++)
        if (locations[i].size() != 2)
            throw eInvalidArgument("Each locations must specify a 2D point.");

    // Normalize the locations to the coordinate space we want.
    f64 xmin = locations[0][0];
    f64 xmax = locations[0][0];
    f64 ymin = locations[0][1];
    f64 ymax = locations[0][1];
    for (size_t i = 1; i < locations.size(); i++)
    {
        xmin = std::min(xmin, locations[i][0]);
        xmax = std::max(xmax, locations[i][0]);
        ymin = std::min(ymin, locations[i][1]);
        ymax = std::max(ymax, locations[i][1]);
    }
    f64 scale = ((f64)destWidth) / (xmax - xmin);
    std::vector<tIO> locs = locations;
    for (size_t i = 0; i < locs.size(); i++)
    {
        locs[i][0] = (locs[i][0] - xmin) * scale;
        locs[i][1] = (locs[i][1] - ymin) * scale;
    }

    // Plot each image onto a canvas.
    u8 bgColor[3] = { 255, 255, 255 };    // white
    img::tCanvas canvas(img::kRGB24, bgColor, 3);
    img::tImage image;
    for (size_t i = 0; i < locs.size(); i++)
    {
        ml::un_examplify(images[i], color, width, absolute, &image);
        canvas.drawImage(&image, (i32)round(locs[i][0]), (i32)round(locs[i][1]));
    }
    canvas.genImage(dest);
}

}  // namespace ml


text:
#include <mpi.h>

#ifndef IALLREDUCE_H
#define IALLREDUCE_H

#include "bench_nbc.h"

int bench_iallreduce_init(nbctest_params_t *params);
int bench_iallreduce_free();
int bench_iallreduce_printinfo();
int measure_iallreduce_blocking(nbctest_params_t *params,
                                nbctest_result_t *result);
int measure_iallreduce_overlap(nbctest_params_t *params,
                               nbctest_result_t *result);

#endif /* IALLREDUCE_H */


text:
using System.Collections.Generic;

namespace Quilt4.Service.Controllers.WebAPI.Web.DataTransfer
{
    public class VersionPageVersionResponse
    {
        public string VersionKey { get; set; }
        public string ProjectKey { get; set; }
        public string ApplicationKey { get; set; }
        public string VersionNumber { get; set; }
        public string ProjectName { get; set; }
        public string ApplicationName { get; set; }
        public IEnumerable<VersionPageIssueTypeResponse> IssueTypes { get; set; }
        public IEnumerable<VersionPageSessionResponse> Sessions { get; set; }
    }
}


text:
using System.Reflection;

[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Protocol Test Framework")]
[assembly: AssemblyVersion("1.0.0.0")]


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > First Time at Disneyland

						Expand All | Collapse All

First Time at Disneyland

 Sunny invited her closest friends to go to Disneyland with her. They went on a Thursday, so the lines were shorter. Sunny immediately fell in love with Disneyland. It was a dream that came true. It was everything her friends said it would be. Sunny went on almost all the rides and took pictures with all the Disney mascots. At the end of the day, she and her friends watched the fireworks.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>