text:
/******************************************************************************
 *
 *  This is the main implementation file for the BTA system manager.
 *
 ******************************************************************************/
#define LOG_TAG "bt_bta_sys_main"

// #include <assert.h>
#include <string.h>

#include "alarm.h"
#include "thread.h"
#include "btm_api.h"
#include "bta_api.h"
#include "bta_sys.h"
#include "bta_sys_int.h"

#include "fixed_queue.h"
#include "gki.h"
#include "hash_map.h"
#include "osi.h"
#include "hash_functions.h"
// #include "osi/include/log.h"
// #include "osi/include/thread.h"
#if( defined BTA_AR_INCLUDED ) && (BTA_AR_INCLUDED == TRUE)
#include "bta_ar_api.h"
#endif
#include "utl.h"

/* system manager control block definition */
#if BTA_DYNAMIC_MEMORY == FALSE
tBTA_SYS_CB bta_sys_cb;
#endif

static hash_map_t *bta_alarm_hash_map;
static const size_t BTA_ALARM_HASH_MAP_SIZE = 17;
static pthread_mutex_t bta_alarm_lock;
// extern thread_t *bt_workqueue_thread;

/* trace level */
/* TODO Bluedroid - Hard-coded trace levels -  Needs to be configurable */
UINT8 appl_trace_level = BT_TRACE_LEVEL_WARNING; //APPL_INITIAL_TRACE_LEVEL;
UINT8 btif_trace_level = BT_TRACE_LEVEL_WARNING;

void btu_bta_alarm_ready(fixed_queue_t *queue);

static const tBTA_SYS_REG bta_sys_hw_reg = {
    bta_sys_sm_execute,
    NULL
};

/* type for action functions */
typedef void (*tBTA_SYS_ACTION)(tBTA_SYS_HW_MSG *p_data);

/* action function list */
const tBTA_SYS_ACTION bta_sys_action[] = {
    /* device manager local device API events - cf bta_sys.h for events */
    bta_sys_hw_api_enable,             /* 0  BTA_SYS_HW_API_ENABLE_EVT    */
    bta_sys_hw_evt_enabled,           /* 1  BTA_SYS_HW_EVT_ENABLED_EVT */
    bta_sys_hw_evt_stack_enabled,       /* 2  BTA_SYS_HW_EVT_STACK_ENABLED_EVT */
    bta_sys_hw_api_disable,             /* 3  BTA_SYS_HW_API_DISABLE_EVT     */
    bta_sys_hw_evt_disabled,           /* 4  BTA_SYS_HW_EVT_DISABLED_EVT  */
    bta_sys_hw_error                        /* 5   BTA_SYS_HW_ERROR_EVT  */
};

/* state machine action enumeration list */
enum {
    /* device manager local device API events */
    BTA_SYS_HW_API_ENABLE,
    BTA_SYS_HW_EVT_ENABLED,
    BTA_SYS_HW_EVT_STACK_ENABLED,
    BTA_SYS_HW_API_DISABLE,
    BTA_SYS_HW_EVT_DISABLED,
    BTA_SYS_HW_ERROR
};

#define BTA_SYS_NUM_ACTIONS  (BTA_SYS_MAX_EVT & 0x00ff)
#define BTA_SYS_IGNORE       BTA_SYS_NUM_ACTIONS

/* state table information */
#define BTA_SYS_ACTIONS              2       /* number of actions */
#define BTA_SYS_NEXT_STATE           2       /* position of next state */
#define BTA_SYS_NUM_COLS             3       /* number of columns in state tables */

/* state table for OFF state */
const UINT8 bta_sys_hw_off[][BTA_SYS_NUM_COLS] = {
    /* Event                    Action 1               Action 2             Next State */
    /* API_ENABLE    */  {BTA_SYS_HW_API_ENABLE,    BTA_SYS_IGNORE,     BTA_SYS_HW_STARTING},
    /* EVT_ENABLED   */  {BTA_SYS_IGNORE,           BTA_SYS_IGNORE,     BTA_SYS_HW_STARTING},
    /* STACK_ENABLED */  {BTA_SYS_IGNORE,           BTA_SYS_IGNORE,     BTA_SYS_HW_ON},
    /* API_DISABLE   */  {BTA_SYS_HW_EVT_DISABLED,  BTA_SYS_IGNORE,     BTA_SYS_HW_OFF},
    /* EVT_DISABLED  */  {BTA_SYS_IGNORE,           BTA_SYS_IGNORE,     BTA_SYS_HW_OFF},
    /* EVT_ERROR     */  {BTA_SYS_IGNORE,           BTA_SYS_IGNORE,     BTA_SYS_HW_OFF}
};

const UINT8 bta_sys_hw_starting[][BTA_SYS_NUM_COLS] = {
    /* Event                    Action 1                   Action 2               Next State */
    /* API_ENABLE    */  {BTA_SYS_IGNORE,               BTA_SYS_IGNORE,         BTA_SYS_HW_STARTING}, /* wait for completion event */
    /* EVT_ENABLED   */  {BTA_SYS_HW_EVT_ENABLED,       BTA_SYS_IGNORE,         BTA_SYS_HW_STARTING},
    /* STACK_ENABLED */  {BTA_SYS_HW_EVT_STACK_ENABLED, BTA_SYS_IGNORE,         BTA_SYS_HW_ON},
    /* API_DISABLE   */  {BTA_SYS_IGNORE,               BTA_SYS_IGNORE,         BTA_SYS_HW_STOPPING}, /* successive disable/enable: change state wait for completion to disable */
    /* EVT_DISABLED  */  {BTA_SYS_HW_EVT_DISABLED,      BTA_SYS_HW_API_ENABLE,  BTA_SYS_HW_STARTING}, /* successive enable/disable: notify, then restart HW */
    /* EVT_ERROR */      {BTA_SYS_HW_ERROR,             BTA_SYS_IGNORE,         BTA_SYS_HW_ON}
};

const UINT8 bta_sys_hw_on[][BTA_SYS_NUM_COLS] = {
    /* Event                    Action 1                   Action 2               Next State */
    /* API_ENABLE    */  {BTA_SYS_HW_API_ENABLE,        BTA_SYS_IGNORE,         BTA_SYS_HW_ON},
    /* EVT_ENABLED   */  {BTA_SYS_IGNORE,               BTA_SYS_IGNORE,         BTA_SYS_HW_ON},
    /* STACK_ENABLED */  {BTA_SYS_IGNORE,               BTA_SYS_IGNORE,         BTA_SYS_HW_ON},
    /* API_DISABLE   */  {BTA_SYS_HW_API_DISABLE,       BTA_SYS_IGNORE,         BTA_SYS_HW_ON}, /* don't change the state here, as some other modules might be active */
    /* EVT_DISABLED */   {BTA_SYS_HW_ERROR,             BTA_SYS_IGNORE,         BTA_SYS_HW_ON},
    /* EVT_ERROR */      {BTA_SYS_HW_ERROR,             BTA_SYS_IGNORE,         BTA_SYS_HW_ON}
};

const UINT8 bta_sys_hw_stopping[][BTA_SYS_NUM_COLS] = {
    /* Event                    Action 1                   Action 2               Next State */
    /* API_ENABLE    */  {BTA_SYS_IGNORE,               BTA_SYS_IGNORE,         BTA_SYS_HW_STARTING}, /* change state, and wait for completion event to enable */
    /* EVT_ENABLED   */  {BTA_SYS_HW_EVT_ENABLED,       BTA_SYS_IGNORE,         BTA_SYS_HW_STOPPING}, /* successive enable/disable: finish the enable before disabling */
    /* STACK_ENABLED */  {BTA_SYS_HW_EVT_STACK_ENABLED, BTA_SYS_HW_API_DISABLE, BTA_SYS_HW_STOPPING}, /* successive enable/disable: notify, then stop */
    /* API_DISABLE   */  {BTA_SYS_IGNORE,               BTA_SYS_IGNORE,         BTA_SYS_HW_STOPPING}, /* wait for completion event */
    /* EVT_DISABLED  */  {BTA_SYS_HW_EVT_DISABLED,      BTA_SYS_IGNORE,         BTA_SYS_HW_OFF},
    /* EVT_ERROR     */  {BTA_SYS_HW_API_DISABLE,       BTA_SYS_IGNORE,         BTA_SYS_HW_STOPPING}
};

typedef const UINT8 (*tBTA_SYS_ST_TBL)[BTA_SYS_NUM_COLS];

/* state table */
const tBTA_SYS_ST_TBL bta_sys_st_tbl[] = {
    bta_sys_hw_off,
    bta_sys_hw_starting,
    bta_sys_hw_on,
    bta_sys_hw_stopping
};

/*******************************************************************************
**
** Function         bta_sys_init
**
** Description      BTA initialization; called from task initialization.
**
**
** Returns          void
**
*******************************************************************************/
void bta_sys_init(void)
{
    memset(&bta_sys_cb, 0, sizeof(tBTA_SYS_CB));

    pthread_mutex_init(&bta_alarm_lock, NULL);

    bta_alarm_hash_map = hash_map_new(BTA_ALARM_HASH_MAP_SIZE,
                                      hash_function_pointer, NULL, (data_free_fn)osi_alarm_free, NULL);

    appl_trace_level = APPL_INITIAL_TRACE_LEVEL;

    /* register BTA SYS message handler */
    bta_sys_register( BTA_ID_SYS,  &bta_sys_hw_reg);

    /* register for BTM notifications */
    BTM_RegisterForDeviceStatusNotif ((tBTM_DEV_STATUS_CB *)&bta_sys_hw_btm_cback );

#if( defined BTA_AR_INCLUDED ) && (BTA_AR_INCLUDED == TRUE)
    bta_ar_init();
#endif

}

void bta_sys_free(void)
{
    hash_map_free(bta_alarm_hash_map);
    pthread_mutex_destroy(&bta_alarm_lock);
}

/*******************************************************************************
**
** Function         bta_dm_sm_execute
**
** Description      State machine event handling function for DM
**
**
** Returns          void
**
*******************************************************************************/
BOOLEAN bta_sys_sm_execute(BT_HDR *p_msg)
{
    BOOLEAN freebuf = TRUE;
    tBTA_SYS_ST_TBL      state_table;
    UINT8               action;
    int                 i;

    APPL_TRACE_EVENT("bta_sys_sm_execute state:%d, event:0x%x\n",  bta_sys_cb.state, p_msg->event);

    /* look up the state table for the current state */
    state_table = bta_sys_st_tbl[bta_sys_cb.state];
    /* update state */
    bta_sys_cb.state = state_table[p_msg->event & 0x00ff][BTA_SYS_NEXT_STATE];

    /* execute action functions */
    for (i = 0; i < BTA_SYS_ACTIONS; i++) {
        if ((action = state_table[p_msg->event & 0x00ff][i]) != BTA_SYS_IGNORE) {
            (*bta_sys_action[action])( (tBTA_SYS_HW_MSG *) p_msg);
        } else {
            break;
        }
    }
    return freebuf;

}

void bta_sys_hw_register( tBTA_SYS_HW_MODULE module, tBTA_SYS_HW_CBACK *cback)
{
    bta_sys_cb.sys_hw_cback[module] = cback;
}

void bta_sys_hw_unregister( tBTA_SYS_HW_MODULE module )
{
    bta_sys_cb.sys_hw_cback[module] = NULL;
}

/*******************************************************************************
**
** Function         bta_sys_hw_btm_cback
**
** Description     This function is registered by BTA SYS to BTM in order to get status notifications
**
**
** Returns
**
*******************************************************************************/
void bta_sys_hw_btm_cback( tBTM_DEV_STATUS status )
{

    tBTA_SYS_HW_MSG *sys_event;

    APPL_TRACE_DEBUG(" bta_sys_hw_btm_cback was called with parameter: %i" , status );

    /* send a message to BTA SYS */
    if ((sys_event = (tBTA_SYS_HW_MSG *) GKI_getbuf(sizeof(tBTA_SYS_HW_MSG))) != NULL) {
        if (status == BTM_DEV_STATUS_UP) {
            sys_event->hdr.event = BTA_SYS_EVT_STACK_ENABLED_EVT;
        } else if (status == BTM_DEV_STATUS_DOWN) {
            sys_event->hdr.event = BTA_SYS_ERROR_EVT;
        } else {
            /* BTM_DEV_STATUS_CMD_TOUT is ignored for now. */
            GKI_freebuf (sys_event);
            sys_event = NULL;
        }

        if (sys_event) {
            bta_sys_sendmsg(sys_event);
        }
    } else {
        APPL_TRACE_DEBUG("ERROR bta_sys_hw_btm_cback couldn't send msg" );
    }
}

/*******************************************************************************
**
** Function         bta_sys_hw_error
**
** Description     In case the HW device stops answering... Try to turn it off, then re-enable all
**                      previously active SW modules.
**
** Returns          success or failure
**
*******************************************************************************/
void bta_sys_hw_error(tBTA_SYS_HW_MSG *p_sys_hw_msg)
{
    UINT8 module_index;
    UNUSED(p_sys_hw_msg);

    APPL_TRACE_DEBUG("%s\n", __FUNCTION__);

    for (module_index = 0; module_index < BTA_SYS_MAX_HW_MODULES; module_index++) {
        if ( bta_sys_cb.sys_hw_module_active &  ((UINT32)1 << module_index )) {
            switch ( module_index) {
            case BTA_SYS_HW_BLUETOOTH:
                /* Send BTA_SYS_HW_ERROR_EVT to DM */
                if (bta_sys_cb.sys_hw_cback[module_index] != NULL) {
                    bta_sys_cb.sys_hw_cback[module_index] (BTA_SYS_HW_ERROR_EVT);
                }
                break;
            default:
                /* not yet supported */
                break;
            }
        }
    }
}

/*******************************************************************************
**
** Function         bta_sys_hw_enable
**
** Description     this function is called after API enable and HW has been turned on
**
**
** Returns          success or failure
**
*******************************************************************************/

void bta_sys_hw_api_enable( tBTA_SYS_HW_MSG *p_sys_hw_msg )
{
    if ((!bta_sys_cb.sys_hw_module_active) && (bta_sys_cb.state != BTA_SYS_HW_ON)) {
        /* register which HW module was turned on */
        bta_sys_cb.sys_hw_module_active |=  ((UINT32)1 << p_sys_hw_msg->hw_module );

        tBTA_SYS_HW_MSG *p_msg;
        if ((p_msg = (tBTA_SYS_HW_MSG *) GKI_getbuf(sizeof(tBTA_SYS_HW_MSG))) != NULL) {
            p_msg->hdr.event = BTA_SYS_EVT_ENABLED_EVT;
            p_msg->hw_module = p_sys_hw_msg->hw_module;

            bta_sys_sendmsg(p_msg);
        }
    } else {
        /* register which HW module was turned on */
        bta_sys_cb.sys_hw_module_active |=  ((UINT32)1 << p_sys_hw_msg->hw_module );

        /* HW already in use, so directly notify the caller */
        if (bta_sys_cb.sys_hw_cback[p_sys_hw_msg->hw_module ] != NULL ) {
            bta_sys_cb.sys_hw_cback[p_sys_hw_msg->hw_module ](  BTA_SYS_HW_ON_EVT   );
        }
    }

    APPL_TRACE_EVENT ("bta_sys_hw_api_enable for %d, active modules 0x%04X\n",
                      p_sys_hw_msg->hw_module, bta_sys_cb.sys_hw_module_active);

}

/*******************************************************************************
**
** Function         bta_sys_hw_disable
**
** Description     if no other module is using the HW, this function will call ( if defined ) a user-macro to turn off the HW
**
**
** Returns          success or failure
**
*******************************************************************************/
void bta_sys_hw_api_disable(tBTA_SYS_HW_MSG *p_sys_hw_msg)
{
    APPL_TRACE_DEBUG("bta_sys_hw_api_disable for %d, active modules: 0x%04X\n",
                     p_sys_hw_msg->hw_module, bta_sys_cb.sys_hw_module_active );

    /* make sure the related SW blocks were stopped */
    bta_sys_disable( p_sys_hw_msg->hw_module );

    /* register which module we turn off */
    bta_sys_cb.sys_hw_module_active &=  ~((UINT32)1 << p_sys_hw_msg->hw_module );

    /* if there are still some SW modules using the HW, just provide an answer to the calling */
    if ( bta_sys_cb.sys_hw_module_active != 0  ) {
        /*  if there are still some SW modules using the HW,  directly notify the caller */
        if ( bta_sys_cb.sys_hw_cback[p_sys_hw_msg->hw_module ] != NULL ) {
            bta_sys_cb.sys_hw_cback[p_sys_hw_msg->hw_module ](  BTA_SYS_HW_OFF_EVT   );
        }
    } else {
        /* manually update the state of our system */
        bta_sys_cb.state = BTA_SYS_HW_STOPPING;

        tBTA_SYS_HW_MSG *p_msg;
        if ((p_msg = (tBTA_SYS_HW_MSG *) GKI_getbuf(sizeof(tBTA_SYS_HW_MSG))) != NULL) {
            p_msg->hdr.event = BTA_SYS_EVT_DISABLED_EVT;
            p_msg->hw_module = p_sys_hw_msg->hw_module;

            bta_sys_sendmsg(p_msg);
        }
    }

}

/*******************************************************************************
**
** Function         bta_sys_hw_event_enabled
**
** Description
**
**
** Returns          success or failure
**
*******************************************************************************/
void bta_sys_hw_evt_enabled(tBTA_SYS_HW_MSG *p_sys_hw_msg)
{
    APPL_TRACE_EVENT("bta_sys_hw_evt_enabled for %i\n", p_sys_hw_msg->hw_module);
    BTM_DeviceReset( NULL );
}

/*******************************************************************************
**
** Function         bta_sys_hw_event_disabled
**
** Description
**
**
** Returns          success or failure
**
*******************************************************************************/
void bta_sys_hw_evt_disabled(tBTA_SYS_HW_MSG *p_sys_hw_msg)
{
    UINT8 hw_module_index;

    APPL_TRACE_DEBUG("bta_sys_hw_evt_disabled - module 0x%X\n", p_sys_hw_msg->hw_module);

    for (hw_module_index = 0; hw_module_index < BTA_SYS_MAX_HW_MODULES; hw_module_index++) {
        if (bta_sys_cb.sys_hw_cback[hw_module_index] != NULL) {
            bta_sys_cb.sys_hw_cback[hw_module_index] (BTA_SYS_HW_OFF_EVT);
        }
    }
}

/*******************************************************************************
**
** Function         bta_sys_hw_event_stack_enabled
**
** Description     we receive this event once the SW side is ready ( stack, FW download,... ),
**                       i.e. we can really start using the device. So notify the app.
**
** Returns          success or failure
**
*******************************************************************************/
void bta_sys_hw_evt_stack_enabled(tBTA_SYS_HW_MSG *p_sys_hw_msg)
{
    UINT8 hw_module_index;
    UNUSED(p_sys_hw_msg);

    APPL_TRACE_DEBUG(" bta_sys_hw_evt_stack_enabled!notify the callers\n");

    for (hw_module_index = 0; hw_module_index < BTA_SYS_MAX_HW_MODULES; hw_module_index++ ) {
        if (bta_sys_cb.sys_hw_cback[hw_module_index] != NULL) {
            bta_sys_cb.sys_hw_cback[hw_module_index] (BTA_SYS_HW_ON_EVT);
        }
    }
}

/*******************************************************************************
**
** Function         bta_sys_event
**
** Description      BTA event handler; called from task event handler.
**
**
** Returns          void
**
*******************************************************************************/
void bta_sys_event(BT_HDR *p_msg)
{
    UINT8       id;
    BOOLEAN     freebuf = TRUE;

    APPL_TRACE_EVENT("BTA got event 0x%x\n", p_msg->event);

    /* get subsystem id from event */
    id = (UINT8) (p_msg->event >> 8);

    /* verify id and call subsystem event handler */
    if ((id < BTA_ID_MAX) && (bta_sys_cb.reg[id] != NULL)) {
        freebuf = (*bta_sys_cb.reg[id]->evt_hdlr)(p_msg);
    } else {
        APPL_TRACE_WARNING("BTA got unregistered event id %d\n", id);
    }

    if (freebuf) {
        GKI_freebuf(p_msg);
    }

}

/*******************************************************************************
**
** Function         bta_sys_register
**
** Description      Called by other BTA subsystems to register their event
**                  handler.
**
**
** Returns          void
**
*******************************************************************************/
void bta_sys_register(UINT8 id, const tBTA_SYS_REG *p_reg)
{
    bta_sys_cb.reg[id] = (tBTA_SYS_REG *) p_reg;
    bta_sys_cb.is_reg[id] = TRUE;
}

/*******************************************************************************
**
** Function         bta_sys_deregister
**
** Description      Called by other BTA subsystems to de-register
**                  handler.
**
**
** Returns          void
**
*******************************************************************************/
void bta_sys_deregister(UINT8 id)
{
    bta_sys_cb.is_reg[id] = FALSE;
}

/*******************************************************************************
**
** Function         bta_sys_is_register
**
** Description      Called by other BTA subsystems to get registeration
**                  status.
**
**
** Returns          void
**
*******************************************************************************/
BOOLEAN bta_sys_is_register(UINT8 id)
{
    return bta_sys_cb.is_reg[id];
}

/*******************************************************************************
**
** Function         bta_sys_sendmsg
**
** Description      Send a GKI message to BTA.  This function is designed to
**                  optimize sending of messages to BTA.  It is called by BTA
**                  API functions and call-in functions.
**
**
** Returns          void
**
*******************************************************************************/
void bta_sys_sendmsg(void *p_msg)
{
    // There is a race condition that occurs if the stack is shut down while
    // there is a procedure in progress that can schedule a task via this
    // message queue. This causes |btu_bta_msg_queue| to get cleaned up before
    // it gets used here; hence we check for NULL before using it.
    if (btu_task_post(SIG_BTU_BTA_MSG, p_msg,  TASK_POST_BLOCKING) != TASK_POST_SUCCESS) {
        GKI_freebuf(p_msg);
    }
}

/*******************************************************************************
**
** Function         bta_sys_start_timer
**
** Description      Start a protocol timer for the specified amount
**                  of time in milliseconds.
**
** Returns          void
**
*******************************************************************************/
void bta_alarm_cb(void *data)
{
    assert(data != NULL);
    TIMER_LIST_ENT *p_tle = (TIMER_LIST_ENT *)data;

    btu_task_post(SIG_BTU_BTA_ALARM, p_tle, TASK_POST_BLOCKING);
}

void bta_sys_start_timer(TIMER_LIST_ENT *p_tle, UINT16 type, INT32 timeout_ms)
{
    assert(p_tle != NULL);

    // Get the alarm for this p_tle.
    pthread_mutex_lock(&bta_alarm_lock);
    if (!hash_map_has_key(bta_alarm_hash_map, p_tle)) {
        hash_map_set(bta_alarm_hash_map, p_tle, osi_alarm_new("bta_sys", bta_alarm_cb, p_tle, 0));
    }
    pthread_mutex_unlock(&bta_alarm_lock);

    osi_alarm_t *alarm = hash_map_get(bta_alarm_hash_map, p_tle);
    if (alarm == NULL) {
        LOG_ERROR("%s unable to create alarm.", __func__);
        return;
    }

    p_tle->event = type;
    p_tle->ticks = timeout_ms;
    //osi_alarm_set(alarm, (period_ms_t)timeout_ms, bta_alarm_cb, p_tle);
    osi_alarm_set(alarm, (period_ms_t)timeout_ms);
}

bool hash_iter_ro_cb(hash_map_entry_t *hash_map_entry, void *context)
{
    osi_alarm_t *alarm = (osi_alarm_t *)hash_map_entry->data;
    period_ms_t *p_remaining_ms = (period_ms_t *)context;
    *p_remaining_ms += osi_alarm_get_remaining_ms(alarm);
    return true;
}

UINT32 bta_sys_get_remaining_ticks(TIMER_LIST_ENT *p_target_tle)
{
    period_ms_t remaining_ms = 0;
    pthread_mutex_lock(&bta_alarm_lock);
    // Get the alarm for this p_tle
    hash_map_foreach(bta_alarm_hash_map, hash_iter_ro_cb, &remaining_ms);
    pthread_mutex_unlock(&bta_alarm_lock);
    return remaining_ms;
}

/*******************************************************************************
**
** Function         bta_sys_stop_timer
**
** Description      Stop a BTA timer.
**
** Returns          void
**
*******************************************************************************/
void bta_sys_stop_timer(TIMER_LIST_ENT *p_tle)
{
    assert(p_tle != NULL);

    osi_alarm_t *alarm = hash_map_get(bta_alarm_hash_map, p_tle);
    if (alarm == NULL) {
        LOG_DEBUG("%s expected alarm was not in bta alarm hash map.", __func__);
        return;
    }
    osi_alarm_cancel(alarm);
}

/*******************************************************************************
**
** Function         bta_sys_disable
**
** Description      For each registered subsystem execute its disable function.
**
** Returns          void
**
*******************************************************************************/
void bta_sys_disable(tBTA_SYS_HW_MODULE module)
{
    int bta_id = 0;
    int bta_id_max = 0;

    APPL_TRACE_DEBUG("bta_sys_disable: module %i", module);

    switch ( module ) {
    case BTA_SYS_HW_BLUETOOTH:
        bta_id = BTA_ID_DM;
        bta_id_max = BTA_ID_BLUETOOTH_MAX;
        break;
    default:
        APPL_TRACE_WARNING("bta_sys_disable: unkown module");
        return;
    }

    for ( ; bta_id <= bta_id_max; bta_id++) {
        if (bta_sys_cb.reg[bta_id] != NULL) {
            if (bta_sys_cb.is_reg[bta_id] == TRUE  &&  bta_sys_cb.reg[bta_id]->disable != NULL) {
                (*bta_sys_cb.reg[bta_id]->disable)();
            }
        }
    }
}

/*******************************************************************************
**
** Function         bta_sys_set_trace_level
**
** Description      Set trace level for BTA
**
** Returns          void
**
*******************************************************************************/
void bta_sys_set_trace_level(UINT8 level)
{
    appl_trace_level = level;
}

/*******************************************************************************
**
** Function         bta_sys_get_sys_features
**
** Description      Returns sys_features to other BTA modules.
**
** Returns          sys_features
**
*******************************************************************************/
UINT16 bta_sys_get_sys_features (void)
{
    return bta_sys_cb.sys_features;
}


text:
Capistrano::Configuration.instance(:must_exist).load do
  namespace :dwell do
    namespace :ruby_enterprise do

      desc "Install Ruby Enterprise 1.8.6 for Ubuntu 8.04"
      task :install do
        run "wget -c http://rubyforge.org/frs/download.php/41041/ruby-enterprise_1.8.6-20080810-i386.deb"
        sudo "dpkg -i ruby-enterprise_1.8.6-20080810-i386.deb"
        dwell1.record_install "enterprise_ruby"
      end
    end

    namespace :ruby do

      desc "Install Ruby 1.8.6"
      task :install do
        sudo "apt-get install ruby rdoc ri irb libopenssl-ruby1.8 ruby1.8-dev -y"
        dwell1.record_install "ruby"
      end

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
layout: default

theme: ribbon

---

{{ content }}


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Fernando Iglesias, Sergey Lisitsyn, Thoralf Klein, Shell Hu,
 *          Soeren Sonnenburg, Viktor Gal, Abinash Panda, Michal Uricar
 */

#include <shogun/structure/StructuredModel.h>

#include <utility>

using namespace shogun;

ResultSet::ResultSet()
: SGObject(), argmax(NULL),
	psi_computed_sparse(false),
	psi_computed(false),
	psi_truth(SGVector<float64_t>(0)),
	psi_pred(SGVector<float64_t>(0)),
	psi_truth_sparse(SGSparseVector<float64_t>(0)),
	psi_pred_sparse(SGSparseVector<float64_t>(0)),
	score(0),
	delta(0)
{
}

ResultSet::~ResultSet()
{

}

std::shared_ptr<StructuredLabels> StructuredModel::structured_labels_factory(int32_t num_labels)
{
	return std::make_shared<StructuredLabels>(num_labels);
}

const char* ResultSet::get_name() const
{
	return "ResultSet";
}

StructuredModel::StructuredModel() : SGObject()
{
	init();
}

StructuredModel::StructuredModel(
		std::shared_ptr<Features>         features,
		std::shared_ptr<StructuredLabels> labels)
: SGObject()
{
	init();

	set_labels(std::move(labels));
	set_features(std::move(features));
}

StructuredModel::~StructuredModel()
{

}

void StructuredModel::init_primal_opt(
		float64_t regularization,
		SGMatrix< float64_t > & A,
		SGVector< float64_t > a,
		SGMatrix< float64_t > B,
		SGVector< float64_t > & b,
		SGVector< float64_t > & lb,
		SGVector< float64_t > & ub,
		SGMatrix< float64_t > & C)
{
	error("init_primal_opt is not implemented for {}!", get_name());
}

void StructuredModel::set_labels(std::shared_ptr<StructuredLabels> labels)
{

	m_labels = std::move(labels);
}

std::shared_ptr<StructuredLabels> StructuredModel::get_labels()
{

	return m_labels;
}

void StructuredModel::set_features(std::shared_ptr<Features> features)
{

	m_features = std::move(features);
}

std::shared_ptr<Features> StructuredModel::get_features()
{

	return m_features;
}

SGVector< float64_t > StructuredModel::get_joint_feature_vector(
		int32_t feat_idx,
		int32_t lab_idx)
{
	auto label = m_labels->get_label(lab_idx);
	SGVector< float64_t > ret = get_joint_feature_vector(feat_idx, label);

	return ret;
}

SGVector< float64_t > StructuredModel::get_joint_feature_vector(
		int32_t feat_idx,
		std::shared_ptr<StructuredData> y)
{
	error("compute_joint_feature(int32_t, StructuredData*) is not "
			"implemented for {}!", get_name());

	return SGVector< float64_t >();
}

SGSparseVector< float64_t > StructuredModel::get_sparse_joint_feature_vector(
		int32_t feat_idx,
		int32_t lab_idx)
{
	auto label = m_labels->get_label(lab_idx);
	SGSparseVector< float64_t > ret = get_sparse_joint_feature_vector(feat_idx, label);

	return ret;
}

SGSparseVector< float64_t > StructuredModel::get_sparse_joint_feature_vector(
		int32_t feat_idx,
		std::shared_ptr<StructuredData> y)
{
	error("compute_sparse_joint_feature(int32_t, StructuredData*) is not "
			"implemented for {}!", get_name());

	return SGSparseVector< float64_t >();
}

float64_t StructuredModel::delta_loss(int32_t ytrue_idx, std::shared_ptr<StructuredData> ypred)
{
	require(ytrue_idx >= 0 || ytrue_idx < m_labels->get_num_labels(),
			"The label index must be inside [0, num_labels-1]");

	auto ytrue = m_labels->get_label(ytrue_idx);
	float64_t ret = delta_loss(ytrue, std::move(ypred));

	return ret;
}

float64_t StructuredModel::delta_loss(std::shared_ptr<StructuredData> y1, std::shared_ptr<StructuredData> y2)
{
	error("delta_loss(StructuredData*, StructuredData*) is not "
			"implemented for {}!", get_name());

	return 0.0;
}

void StructuredModel::init()
{
	SG_ADD((std::shared_ptr<Labels>*) &m_labels, "m_labels", "Structured labels");
	SG_ADD((std::shared_ptr<Features>*) &m_features, "m_features", "Feature vectors");

	m_features = NULL;
	m_labels   = NULL;
}

void StructuredModel::init_training()
{
	// Nothing to do here
}

bool StructuredModel::check_training_setup() const
{
	// Nothing to do here
	return true;
}

int32_t StructuredModel::get_num_aux() const
{
	return 0;
}

int32_t StructuredModel::get_num_aux_con() const
{
	return 0;
}


text:
typedef NSString DKThemeVersion;

typedef UIColor *(^DKColorPicker)(DKThemeVersion *themeVersion);

DKColorPicker DKColorPickerWithRGB(NSUInteger normal, NSUInteger night);
DKColorPicker DKColorPickerWithColors(UIColor *normalColor, UIColor *nightColor);

@interface DKColor : NSObject

+ (DKColorPicker)colorPickerWithUIColor:(UIColor *)color;

+ (DKColorPicker)colorPickerWithWhite:(CGFloat)white alpha:(CGFloat)alpha;
+ (DKColorPicker)colorPickerWithHue:(CGFloat)hue saturation:(CGFloat)saturation brightness:(CGFloat)brightness alpha:(CGFloat)alpha;
+ (DKColorPicker)colorPickerWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha;
+ (DKColorPicker)colorPickerWithCGColor:(CGColorRef)cgColor;
+ (DKColorPicker)colorPickerWithPatternImage:(UIImage *)image;
#if __has_include(<CoreImage/CoreImage.h>)
+ (DKColorPicker)colorPickerWithCIColor:(CIColor *)ciColor NS_AVAILABLE_IOS(5_0);
#endif

+ (DKColorPicker)blackColor;
+ (DKColorPicker)darkGrayColor;
+ (DKColorPicker)lightGrayColor;
+ (DKColorPicker)whiteColor;
+ (DKColorPicker)grayColor;
+ (DKColorPicker)redColor;
+ (DKColorPicker)greenColor;
+ (DKColorPicker)blueColor;
+ (DKColorPicker)cyanColor;
+ (DKColorPicker)yellowColor;
+ (DKColorPicker)magentaColor;
+ (DKColorPicker)orangeColor;
+ (DKColorPicker)purpleColor;
+ (DKColorPicker)brownColor;
+ (DKColorPicker)clearColor;

@end


text:
import React from 'react';

import {
	FloatingActionButton,
	ActionGrade
} from 'material-ui';

var Canvas = React.createClass({
	componentDidMount() {
		var self = this;

		$('#canvas').attr('width', $('.canvas-wrapper').width());

		$(window).resize(function() {
			$('#canvas').attr('width', $('.canvas-wrapper').width());
		});

		this.props.socket.on('update_canvas', function(action) {
			// get scketch and redraw
			var sketch = $("#canvas").sketch();
			sketch.actions.push(action);
			sketch.redraw();
		});

		this.props.socket.on('clear_canvas', function(action) {
			// get scketch and redraw
			var sketch = $("#canvas").sketch();
			sketch.actions = [];
			sketch.redraw();
		});

		$('#canvas').sketch();

		// limit canvas update to 24 fps
		var canCall = true;
		setInterval(function(){
            canCall = true;
        }, 42);

		$('.canvas-wrapper canvas').on('mouseup touchmove mousemove touchend touchcancel', function() {
			var action = $(this).sketch().action;

			if (canCall && action) {
				self.props.socket.emit('server_update_canvas', action);
				canCall = false;
			}
		});
	},
	clearCanvas() {
		var self = this;
		var sketch = $("#canvas").sketch();

		sketch.actions = [];
		sketch.redraw();
		self.props.socket.emit('server_clear_canvas');
	},
	render() {
		return (

				<canvas id="canvas" width="450" height="400"></canvas>

						<FloatingActionButton onClick={this.clearCanvas} mini={true}>

						</FloatingActionButton>

		)
	}
});

export default Canvas;


text:
class Person < ActiveRecord::Base
  belongs_to :employer, class_name: 'Company', optional: true

  def full_name
    [first_name, last_name].compact.join ' '
  end

  def full_name=(name)
    first_name, last_name = name.split
    self.first_name = first_name
    self.last_name = last_name
  end
end


text:
<Record>
<Term>Lorcainide</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Antiarrhythmic Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Cardiovascular Agent/Antiarrhythmic Agent/Lorcainide Hydrochloride</ClassificationPath>
<BroaderTerm>Lorcainide Hydrochloride</BroaderTerm>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Cardiovascular Agent</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<BroaderTerm>Antiarrhythmic Agent</BroaderTerm>
<Synonym>LORCAINIDE HYDROCHLORIDE</Synonym>
<Synonym>Lorcainide Hydrochloride</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
require 'rformspec'

class CalcTest < RFormSpec::FormTestCase
  include RFormSpec::Driver

  def setup
    RFormSpec::AutoIt.init

    if window_exists?("Calculator")
      focus_window('Calculator')
      RFormSpec::Window.new('Calculator')
    else
    RFormSpec::Process.run("calc.exe")
    end

    @calc_win = RFormSpec::Window.new('Calculator', "", :wait_timeout => 2)
  end

  def teardown
    # @calc_win.close
  end

  def test_multiple
    @calc_win.click_button('127')  #3
    @calc_win.click_button('91')   #*
    @calc_win.click_button('131')  #7
    @calc_win.click_button('112')  #=
    sleep 1
    assert_equal "21. ", @calc_win.get_control_text('403')

  end

end


text:
package org.waveprotocol.wave.client.editor.content;

import org.waveprotocol.wave.client.editor.testing.TestEditors;
import org.waveprotocol.wave.model.document.ReadableDocument;
import org.waveprotocol.wave.model.document.operation.DocOp;
import org.waveprotocol.wave.model.document.operation.impl.DocOpBuffer;
import org.waveprotocol.wave.model.document.operation.impl.DocOpUtil;
import org.waveprotocol.wave.model.document.util.DocHelper;
import org.waveprotocol.wave.model.document.util.DocProviders;
import org.waveprotocol.wave.model.document.util.DomOperationUtil;
import org.waveprotocol.wave.model.document.util.LocalDocument;
import org.waveprotocol.wave.model.document.util.Point;
import org.waveprotocol.wave.model.document.util.ReadableTreeWalker;
import org.waveprotocol.wave.model.operation.SilentOperationSink;

import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * Tests some transparent/persistent operations on a ContentDocument
 *
 * @author patcoleman@google.com (Pat Coleman)
 */

public class LazyPersistentContentDocumentGwtTest extends EditorGwtTestCase {
  /** Simplest use of persistence, creating a node locally then persisting it. */
  public void testSimpleForcedPersist() {
    // set up document, with queue for outgoing messages.
    final Queue<DocOp> opMessageQueue = new LinkedList<DocOp>();
    ContentDocument doc = TestEditors.createTestDocument();
    // Note: this replaces the output sink that the editor has injected into the
    // document, breaking an editor assumption.
    doc.replaceOutgoingSink(new SilentOperationSink<DocOp>(){
      @Override
      public void consume(DocOp op) {
        opMessageQueue.add(op);
      }
    });

    // initial document, with simple content:
    doc.consume(DocProviders.POJO.parse("<root></root>").asOperation());
    assertTrue(opMessageQueue.isEmpty()); // came from server, nothing sent out
    LocalDocument<ContentNode, ContentElement, ContentTextNode> local
        = doc.getContext().annotatableContent();
    ContentElement root = local.getFirstChild(local.getDocumentElement()).asElement();

    // create local text node:
    ContentElement child = local.transparentCreate("child",
        Collections.<String, String>emptyMap(), root, null);
    assertTrue(opMessageQueue.isEmpty()); // local, nothing used.
    assertFalse(checkDomEqual(doc.getMutableDoc(), local));

    // forcibly persist:
    local.markNodeForPersistence(child, false);
    popServerOp(opMessageQueue, "__1; << child {}; >>; __1; "); // sent
    assertTrue(checkDomEqual(doc.getMutableDoc(), local));
    ContentElement mutableChild = doc.getMutableDoc().getFirstChild(root).asElement();
    assertTrue(child == mutableChild); // exact same object

    // persist again, just to make sure it's fine
    local.markNodeForPersistence(child, false);
    assertTrue(opMessageQueue.isEmpty()); // nothing new to send
    assertTrue(checkDomEqual(doc.getMutableDoc(), local));
  }

  /**
   * Simple use of lazy persistence, creating a node locally, marking to persist,
   * then persisting due to (say) a user action.
   */
  public void testSimpleLazyPersist() {
    // set up document, with queue for outgoing messages.
    final Queue<DocOp> opMessageQueue = new LinkedList<DocOp>();
    ContentDocument doc = TestEditors.createTestDocument();
    // Note: this replaces the output sink that the editor has injected into the
    // document, breaking an editor assumption.
    doc.replaceOutgoingSink(new SilentOperationSink<DocOp>(){
      @Override
      public void consume(DocOp op) {
        opMessageQueue.add(op);
      }
    });

    // initial document, with simple content:
    doc.consume(DocProviders.POJO.parse("<root></root>").asOperation());
    assertTrue(opMessageQueue.isEmpty()); // came from server, nothing sent out
    LocalDocument<ContentNode, ContentElement, ContentTextNode> local
        = doc.getContext().annotatableContent();
    ContentElement root = local.getFirstChild(local.getDocumentElement()).asElement();

    // create local text node:
    ContentElement child = local.transparentCreate("child",
        Collections.<String, String>emptyMap(), root, null);
    assertTrue(opMessageQueue.isEmpty()); // local, nothing used.
    assertFalse(checkDomEqual(doc.getMutableDoc(), local));

    // Make sure it doesn't get included in a filter:
    Point<ContentNode> filtered = DocHelper.getFilteredPoint(
        doc.getPersistentView(), Point.start(doc.getFullContentView(), child));
    // filter container to be the root persisted node
    assertTrue(filtered.getContainer() == root);

    // mark to lazily persist:
    local.markNodeForPersistence(child, true);
    assertTrue(opMessageQueue.isEmpty()); // still local, nothing used.
    assertFalse(checkDomEqual(doc.getMutableDoc(), local));

    // now require it to be persisted:
    filtered = DocHelper.getFilteredPoint(
        doc.getPersistentView(), Point.start(doc.getFullContentView(), child));

    popServerOp(opMessageQueue, "__1; << child {}; >>; __1; "); // sent
    assertTrue(checkDomEqual(doc.getMutableDoc(), local));
    ContentElement mutableChild = doc.getMutableDoc().getFirstChild(root).asElement();
    assertTrue(child == mutableChild); // exact same object
    assertTrue(filtered.getContainer() == child); // different container now.

    // persist again, just to make sure it's fine
    local.markNodeForPersistence(child, false);
    assertTrue(opMessageQueue.isEmpty()); // nothing new to send
    assertTrue(checkDomEqual(doc.getMutableDoc(), local));
  }

  /** Using a complex tree, make sure state is correct before and after an opaque persist call. */
  public void testComplexSingleOpaquePersist() {
    // set up document, with queue for outgoing messages.
    final Queue<DocOp> opMessageQueue = new LinkedList<DocOp>();
    ContentDocument doc = TestEditors.createTestDocument();
    // Note: this replaces the output sink that the editor has injected into the
    // document, breaking an editor assumption.
    doc.replaceOutgoingSink(new SilentOperationSink<DocOp>(){
      @Override
      public void consume(DocOp op) {
        opMessageQueue.add(op);
      }
    });

    // initial document, with content and annotation:
    doc.consume(DocProviders.POJO.parse("hi world").asOperation());
    assertTrue(opMessageQueue.isEmpty()); // came from server, nothing sent out
    doc.getMutableDoc().setAnnotation(1, 5, "a", "b");
    popServerOp(opMessageQueue, "__1; || { \"a\": null -> \"b\" }; __4; || { \"a\" }; __7; ");

    // save some places:
    LocalDocument<ContentNode, ContentElement, ContentTextNode> local
      = doc.getContext().annotatableContent();
    ContentElement A = local.getDocumentElement().getFirstChild().asElement();
    ContentNode B = local.getFirstChild(A);

    // writing to mutable sends to server:
    doc.getMutableDoc().insertText(2, "!");
    popServerOp(opMessageQueue, "__2; ++\"!\"; __10; ");

    // local mutations, nothing sent to server:
    ContentNode afterB = local.getNextSibling(B);
    ContentElement X = local.transparentCreate("c", Collections.singletonMap("K", "V"), A, afterB);
    ContentTextNode T = local.transparentCreate(":)", X, null);
    assertTrue(opMessageQueue.isEmpty());

    // documents are different:
    assertFalse(checkDomEqual(doc.getMutableDoc(), local));

    // persist the local subtree
    local.markNodeForPersistence(X, true);
    assertTrue(opMessageQueue.isEmpty()); // marked for persistence, not actually used yet.
    doc.getPersistentView().onBeforeFilter(Point.inElement((ContentNode) X, null));
    popServerOp(opMessageQueue, "__6; << c { K=\"V\" }; ++\":)\"; >>; __7; ");
    assertTrue(checkDomEqual(doc.getMutableDoc(), local));

    // change attribute on newly persisted doc:
    doc.getMutableDoc().setElementAttribute(X, "K", "V2");
    popServerOp(opMessageQueue, "__6; u@ { K: \"V\" -> \"V2\" }; __10; ");

    // check annotations moved correctly:
    int sz = doc.getMutableDoc().size();
    assertEquals( 1, doc.getMutableDoc().firstAnnotationChange(0, sz, "a", null));
    assertEquals(10, doc.getMutableDoc().firstAnnotationChange(3, sz, "a", "b"));

    // check *exact* equality
    ContentElement mA = doc.getMutableDoc().getDocumentElement().getFirstChild().asElement();
    ContentNode mB = doc.getMutableDoc().getFirstChild(mA);
    ContentNode mX = doc.getMutableDoc().getNextSibling(mB);
    ContentNode mT = doc.getMutableDoc().getFirstChild(mX);
    assertTrue(mA == A);
    assertTrue(mB == B);
    assertTrue(mX == X);
    assertTrue(mT == T);

    // try inserting text through mutable document too:
    int at = doc.getMutableDoc().getLocation(X);
    doc.getMutableDoc().insertText(at + 1, "#");
    popServerOp(opMessageQueue, "__7; ++\"#\"; __10; ");
    assertTrue(checkDomEqual(doc.getMutableDoc(), local));
  }

  /** Checks multiple calls to opaque persist with related nodes. */
  public void testMultipleChildOpaquePersists() {
    // set up document, with queue for outgoing messages.
    final Queue<DocOp> opMessageQueue = new LinkedList<DocOp>();
    ContentDocument doc = TestEditors.createTestDocument();
    // Note: this replaces the output sink that the editor has injected into the
    // document, breaking an editor assumption.
    doc.replaceOutgoingSink(new SilentOperationSink<DocOp>(){
      @Override
      public void consume(DocOp op) {
        opMessageQueue.add(op);
      }
    });
    Map<String, String> empty = Collections.<String, String>emptyMap();

    // initial document, many child nodes
    doc.consume(DocProviders.POJO.parse("

").asOperation()); // just parent
    assertTrue(opMessageQueue.isEmpty()); // came from server, nothing sent out
    LocalDocument<ContentNode, ContentElement, ContentTextNode> local
        = doc.getContext().annotatableContent();
    CMutableDocument mutable = doc.getMutableDoc();
    ContentElement P = local.getDocumentElement().getFirstChild().asElement(); // parent

    // create four children locally, one after the other.
    final ContentElement C1 = local.transparentCreate("C1", empty, P, null);
    ContentElement C2 = local.transparentCreate("C2", Collections.singletonMap("K", "V"), P, null);
    ContentElement C3 = local.transparentCreate("C3", empty, P, null);
    ContentElement C4 = local.transparentCreate("C4", Collections.singletonMap("X", "Y"), P, null);
    local.transparentCreate("a", C1, null);
    local.transparentCreate("b", C4, null);
    String localDom = "<doc>
<C1>a</C1><C2 K=\"V\"/><C3/><C4 X=\"Y\">b</C4>
</doc>";

    assertEquals(localDom, toSimpleString(local));
    assertEquals("<doc>
</doc>", toSimpleString(mutable));

    // persist C4
    local.markNodeForPersistence(C4, false);
    assertEquals(localDom, toSimpleString(local));
    assertEquals("<doc>
<C4 X=\"Y\">b</C4>
</doc>", toSimpleString(mutable));
    assertTrue(mutable.getFirstChild(mutable.getFirstChild(mutable.getDocumentElement())) == C4);
    popServerOp(opMessageQueue, "__1; << C4 { X=\"Y\" }; ++\"b\"; >>; __1; ");

    // persist C1's child
    local.markNodeForPersistence(C1.getFirstChild(), false);
    assertEquals(localDom, toSimpleString(local));
    assertEquals("<doc>
a<C4 X=\"Y\">b</C4>
</doc>", toSimpleString(mutable));
    assertTrue(mutable.getFirstChild(mutable.getFirstChild(mutable.getDocumentElement())) ==
        C1.getFirstChild());
    popServerOp(opMessageQueue, "__1; ++\"a\"; __4; ");

    // forcibly persist C3
    local.markNodeForPersistence(C3, false);
    assertEquals(localDom, toSimpleString(local));
    assertEquals("<doc>
a<C3/><C4 X=\"Y\">b</C4>
</doc>", toSimpleString(mutable));
    popServerOp(opMessageQueue, "__2; << C3 {}; >>; __4; ");

    // forcibly persist C2
    local.markNodeForPersistence(C2, false);
    assertEquals(localDom, toSimpleString(local));
    assertEquals("<doc>
a<C2 K=\"V\"/><C3/><C4 X=\"Y\">b</C4>
</doc>",
        toSimpleString(mutable));
    popServerOp(opMessageQueue, "__2; << C2 { K=\"V\" }; >>; __6; ");

    // check that they're different by the C1 tag:
    assertTrue(new ReadableTreeWalker<ContentNode, ContentElement, ContentTextNode>(
        local, local.getDocumentElement()) {
          @Override
          protected void progress() {
            super.progress();
            if (currentNode == C1) {
              super.progress(); // skip C1
            }
          }
        }.checkWalk(mutable, mutable.getDocumentElement()));
  }

  //
  // Utilities
  //

  // removes serialized op from the server queue and checks against expected string.
  private static void popServerOp(Queue<DocOp> queue, String op) {
    assertTrue("Empty queue, " + op + " expected", !queue.isEmpty());
    String next = DocOpUtil.toConciseString(queue.poll());
    assertEquals(next + " sent, " + op + " expected", next, op);
  }

  // makes sure the two given documents have identical DOM structure.
  private static boolean checkDomEqual(
      ReadableDocument<ContentNode, ContentElement, ContentTextNode> A,
      ReadableDocument<ContentNode, ContentElement, ContentTextNode> B) {
    return new ReadableTreeWalker<ContentNode, ContentElement, ContentTextNode>(
        A, A.getDocumentElement()).checkWalk(B, B.getDocumentElement());
  }

  // converts the DOM to a string.
  private static String toSimpleString(ReadableDocument<ContentNode, ?, ?> doc) {
    DocOpBuffer opBuffer = new DocOpBuffer();
    DomOperationUtil.buildDomInitializationFromSubtree(doc, doc.getDocumentElement(), opBuffer);
    return DocOpUtil.toXmlString(DocOpUtil.asInitialization(opBuffer.finish()));
  }
}


text:
from TOSSIM import *
import sys

t = Tossim([])
r = t.radio()

print("Reading network topology...")
f = open("../topology.txt", "r")
for line in f:
    s = line.split()
    if s:
        print " ", s[0], " ", s[1], " ", s[2]
        r.add(int(s[0]), int(s[1]), float(s[2]))

print("Configuring debug output channels...")
t.addChannel("Boot", sys.stdout)
t.addChannel("Timer", sys.stdout)

print("Creating noise model for all nodes...")
noise = open("/opt/tinyos-2.1.2/tos/lib/tossim/noise/meyer-heavy.txt", "r")
lines = noise.readlines()
for line in lines:
    str1 = line.strip()
    if str1:
        val = int(str1)
        for i in range(1, 4):
            t.getNode(i).addNoiseTraceReading(val)

for i in range(1, 4):
    print "\tCreating noise model for node ", i
    t.getNode(i).createNoiseModel()

print("Configuring boot times")
t.getNode(1).bootAtTime(100000)
t.getNode(2).bootAtTime(200001)
t.getNode(3).bootAtTime(300002)

print("Done!")

for i in range(2000):
    t.runNextEvent()

# Simulates 5 seconds from first boot event.
#
# t.runNextEvent()
# time = t.time()
# while time + 50000000000 > t.time():
#     t.runNextEvent()


text:
@interface CityModel : BaseModel
@property(nonatomic,strong)NSString *city;

@end


text:
namespace asio {
namespace detail {

// Helper function to create thread-specific storage.
ASIO_DECL DWORD win_tss_ptr_create();

template <typename T>
class win_tss_ptr
  : private noncopyable
{
public:
  // Constructor.
  win_tss_ptr()
    : tss_key_(win_tss_ptr_create())
  {
  }

  // Destructor.
  ~win_tss_ptr()
  {
    ::TlsFree(tss_key_);
  }

  // Get the value.
  operator T*() const
  {
    return static_cast<T*>(::TlsGetValue(tss_key_));
  }

  // Set the value.
  void operator=(T* value)
  {
    ::TlsSetValue(tss_key_, value);
  }

private:
  // Thread-specific storage to allow unlocked access to determine whether a
  // thread is a member of the pool.
  DWORD tss_key_;
};

} // namespace detail
} // namespace asio

#include "asio/detail/pop_options.hpp"

#if defined(ASIO_HEADER_ONLY)
# include "asio/detail/impl/win_tss_ptr.ipp"
#endif // defined(ASIO_HEADER_ONLY)

#endif // defined(ASIO_WINDOWS)

#endif // ASIO_DETAIL_WIN_TSS_PTR_HPP


text:
<property name="balance" type="float">
    <column name="balance" sql-type="decimal(13,3)"/>
</property>


text:
package net.floodlightcontroller.core.internal;

import org.openflow.protocol.statistics.OFDescriptionStatistics;

import net.floodlightcontroller.core.IOFSwitch;

public interface IOFSwitchFeatures {
    public void setFromDescription(IOFSwitch sw, OFDescriptionStatistics description);
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">

<TITLE>Jikes RVM Userguide</TITLE>

The online
version of the Jikes RVM userguide tracks the svn head of the
project.

For releases of Jikes RVM, we export this userguide as a pdf file and as standalone html


text:
FROM maven:3.5.2-jdk-8-slim

# rsync is required to prevent the contamination of arrow directory
# (mounted from the host)
RUN apt-get update -y \
    && apt-get install -y --no-install-recommends rsync \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

CMD ["/bin/bash", "-c", "arrow/ci/docker_build_java.sh && \
    cd /build/java/arrow/java && \
    mvn test"]


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLikesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('likes', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('location_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->boolean('like');
            $table->timestamps();

            $table->foreign('location_id')->references('id')->on('locations');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('likes');
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>sizeTest100x100percent</title>

sizeTest100x100percent

	open
	/run/com.vaadin.tests.components.calendar.CalendarTest?testBench&restartApplication&width=100%25&height=100%25

	assertText
	vaadin=runcomvaadintestscomponentscalendarCalendarTest::/VGridLayout[0]/VHorizontalLayout[1]/Slot[1]/VLabel[0]
	Jan 2000

	screenCapture

	month

	mouseClick
	vaadin=runcomvaadintestscomponentscalendarCalendarTest::/VGridLayout[0]/VCalendar[0]/domChild[0]/domChild[1]/domChild[0]/domChild[0]/domChild[1]/domChild[2]/domChild[0]/domChild[0]
	12,54

	screenCapture

	week


text:
package appeng.api.storage;

import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;

public interface IMEMonitor<T extends IAEStack> extends IMEInventoryHandler<T>, IBaseMonitor<T> {

    @Override
    @Deprecated
    /**
     * This method is discouraged when accessing data via a IMEMonitor
     */
    public IItemList<T> getAvailableItems(IItemList out);

    /**
     * Get access to the full item list of the network, preferred over {@link IMEInventory} .getAvaialbleItems(...)
     *
     * @return full storage list.
     */
    IItemList<T> getStorageList();

}


text:
<!doctype html>

  <link rel="stylesheet" type="text/css" href="https://s3-s.licdn.com/scds/concat/common/css?h=3bifs78lai5i0ndyj1ew7316e-c8kkvmvykvq2ncgxoqb13d2by-4cff62fozoxsbiyfz40j584kw-c5839km74lqu75dnankln5rgt-4uu2pkz5u0jch61r2nhpyyrn8-bf0i9bv8oqeq4shjzvzhms72i-4om4nn3a2z730xs82d78xj3be-4newiqesz8x3qjgqezmhywsri-ct4kfyj4tquup0bvqhttvymms-8s9la6qzt782vxdcgwzy2mbpn-btde8he824yz2feemk13vlls3-9zbbsrdszts09by60it4vuo3q-6ar98u770i0clgj9lu8zxe6dx-901u057v2k19l3bz80xj15yhf-34ohz9lv9h6cjd8zhbmfk3tbw-5pnxeosk9ql3alz2yvw5hhirb-6ceg763nywwe227qy2g9w2q4u-4z5x4qkl5qhtmn810nwa1hmnd"/>

  <link rel="stylesheet" type="text/css" href="https://s3-s.licdn.com/scds/concat/common/css?h=dbcxcwzgraa6yv9hqn4z5oxa8-aw0kahdybem6ne4oztq7x7gk7-7rflve27c4osbf7mxegpfv8wu-e1j8a4dr5u8cb7wm4sz84tom6-caxjw3htjf4qg5f0wd65k1ttm-afoc3swru33ae6usa0wj75o71-9uegbhuyb09xbg73v34d8cayb-3x2uta0fo028jpw2bd6ti5wfe"/>

  <link rel="stylesheet" type="text/css" href="plus-card.css"/>

        Jul
        26

LinkedIn Today


text:
namespace atom {

namespace api {

MenuViews::MenuViews(v8::Isolate* isolate) : Menu(isolate) {
}

void MenuViews::PopupAt(Window* window, int x, int y, int positioning_item) {
  NativeWindow* native_window = static_cast<NativeWindow*>(window->window());
  if (!native_window)
    return;
  content::WebContents* web_contents = native_window->web_contents();
  if (!web_contents)
    return;
  content::RenderWidgetHostView* view = web_contents->GetRenderWidgetHostView();
  if (!view)
    return;

  // (-1, -1) means showing on mouse location.
  gfx::Point location;
  if (x == -1 || y == -1) {
    location = gfx::Screen::GetScreen()->GetCursorScreenPoint();
  } else {
    gfx::Point origin = view->GetViewBounds().origin();
    location = gfx::Point(origin.x() + x, origin.y() + y);
  }

  // Show the menu.
  views::MenuRunner menu_runner(
      model(),
      views::MenuRunner::CONTEXT_MENU | views::MenuRunner::HAS_MNEMONICS);
  ignore_result(menu_runner.RunMenuAt(
      static_cast<NativeWindowViews*>(window->window())->widget(),
      NULL,
      gfx::Rect(location, gfx::Size()),
      views::MENU_ANCHOR_TOPLEFT,
      ui::MENU_SOURCE_MOUSE));
}

// static
mate::WrappableBase* Menu::Create(v8::Isolate* isolate) {
  return new MenuViews(isolate);
}

}  // namespace api

}  // namespace atom


text:
require 'spec_helper'

describe 'layouts/application.html.erb' do
  before do
    @user = FactoryGirl.create(:user)
    view.stub(:current_user).and_return(@user)
  end

  context 'meta tags' do
    all_selectors = %w(
      meta[charset="utf-8"]
      meta[http-equiv=X-UA-Compatible][content="IE=edge"]
      meta[name="viewport"]
      meta[name="keywords"]
      meta[name="description"]
      meta[name="author"]
      meta[property="og:title"]
      meta[property="og:type"]
      meta[property="og:url"]
      meta[property="og:description"]
      meta[property="og:image"]
      meta[name="twitter:card"]
      meta[name="twitter:title"]
      meta[name="twitter:description"]
      meta[name="twitter:url"]
    )
    all_selectors.each do |css_selector|
      it "should have selector #{css_selector}" do
        render
        rendered.should have_css css_selector, visible: false
      end
    end
  end

  it 'should include css & js files' do
    render
    rendered.should have_tag('link', href: /\.css/)
    rendered.should have_tag('script', href: /\.js/)
  end

  it 'should not have div nested inside p' do
    should_not have_selector('p>div')
  end

  it 'should not have extra escaped html' do
    should_not =~ /</
    should_not =~ />/
    should_not =~ /&/
  end

  it 'should render a navbar' do
    render
    rendered.should have_selector('div.navbar')
  end

  it 'should render a search toggle' do
    render
    expect(rendered).to have_selector('a#google_search')
  end

  it 'should render links to site features' do
    render
    #TODO Y replace href with project_path helper
    rendered.should have_link 'Projects', :href => projects_path
  end

  it 'should render a footer' do
    render
    rendered.should have_selector('footer')
    rendered.should have_text ('AgileVentures - Crowdsourced Learning')
  end

  it 'should return 200 for all link visits' do
    StaticPage.stub_chain(:friendly, :find).and_return(stub_model(StaticPage, title: 'A static page'))
    render
    rendered.within('div.navbar') do |header|
      links = header.all('a').map { |el| el[:href] }
      links.each do |link|
        visit link
        page.status_code.should == 200
      end
    end
  end

  context 'not signed in as registered user' do
    before :each do
      view.stub(:user_signed_in?).and_return(false)
    end

    it 'should render login & sign-up links' do
      render
      rendered.within('header#main_header') do |header|
        header.should have_link 'Log in', :href => new_user_session_path
        header.should have_link 'Sign up', :href => new_user_registration_path
      end
    end
  end

  context 'user is signed in' do
    before :each do
      view.stub(:user_signed_in?).and_return(true)
    end

    it 'should render navigation links' do
      render
      rendered.should have_css('#user-gravatar', :visible => true)
      rendered.should have_link 'My account', :href => user_path(@user), :visible => false
      rendered.within('div.navbar') do |header|
        header.should_not have_link 'Log in', :href => new_user_session_path
        header.should_not have_link 'Sign up', :href => new_user_registration_path
      end
    end

    it 'should return 200 on link visit' do
      visit edit_user_registration_path
      page.status_code.should == 200
    end

  end

  context 'within the site footer' do
    before(:each) { render }

    it 'should render a link to the "About Us" page' do
      rendered.within('#footer') do |footer|
        footer.should have_link 'About Us', :href => static_page_path('About Us')
      end
    end

    it 'should render a link to the "Getting Started" page' do
      rendered.within('#footer') do |footer|
        footer.should have_link 'Getting Started', :href => static_page_path('Getting Started')
      end
    end

    it 'should render a link to the AgileVentures Facebook page' do
      rendered.within('#footer') do |footer|
        footer.should have_link 'Facebook', href: 'https://www.facebook.com/agileventures'
      end
    end

    it 'should render a link to the AgileVentures Twitter page' do
      rendered.within('#footer') do |footer|
        footer.should have_link 'Twitter', href: 'https://twitter.com/AgileVentures'
      end
    end
  end
end


text:
package org.huxizhijian.hhcomicviewer.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.widget.ListView;

/**
 * Created by wei on 2017/1/21.
 */

public class ZoomableListView extends ListView {

    private ScaleGestureDetector mScaleDetector;
    private float mScaleFactor = 1.f;
    private boolean isPagerEnabled;
    private static final int INVALID_POINTER_ID = -1;

    // The 'active pointer' is the one currently moving our object.
    private int mActivePointerId = INVALID_POINTER_ID;

    private float mPosX;
    private float mPosY;

    private float mLastTouchX;
    private float mLastTouchY;

    // Pivot point for Scaling
    static float gx = 0, gy = 0;

    public ZoomableListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScaleDetector = new ScaleGestureDetector(getContext(),
                new ScaleListener());
    }

    public ZoomableListView(Context context) {
        super(context);
        mScaleDetector = new ScaleGestureDetector(getContext(),
                new ScaleListener());
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        // Save the canvas to set the scaling factor returned from detector
        canvas.save();
        if (mScaleFactor == 1.0f) {
            isPagerEnabled = true;
        } else {
            isPagerEnabled = false;
        }

        if (mScaleFactor == 1.0f) {
            mPosX = 0.0f;
            mPosY = 0.0f;
        }
        canvas.translate(mPosX, mPosY);
        canvas.scale(mScaleFactor, mScaleFactor);
        super.dispatchDraw(canvas);
        canvas.restore();
        invalidate();
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        super.onTouchEvent(ev);
        final int action = ev.getAction();
        mScaleDetector.onTouchEvent(ev);
        switch (action & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN: {
                final float x = ev.getX();
                final float y = ev.getY();

                mLastTouchX = x;
                mLastTouchY = y;

                // Save the ID of this pointer
                mActivePointerId = ev.getPointerId(0);
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                // Find the index of the active pointer and fetch its position
                final int pointerIndex = ev.findPointerIndex(mActivePointerId);
                final float x = ev.getX(pointerIndex);
                final float y = ev.getY(pointerIndex);

                final float dx = x - mLastTouchX;
                final float dy = y - mLastTouchY;

                mPosX += dx;
                mPosY += dy;

                mLastTouchX = x;
                mLastTouchY = y;

                invalidate();
                break;
            }

            case MotionEvent.ACTION_UP: {
                mActivePointerId = INVALID_POINTER_ID;
                break;
            }

            case MotionEvent.ACTION_CANCEL: {
                mActivePointerId = INVALID_POINTER_ID;
                break;
            }

            case MotionEvent.ACTION_POINTER_UP: {
                // Extract the index of the pointer that left the touch sensor
                final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
                final int pointerId = ev.getPointerId(pointerIndex);
                if (pointerId == mActivePointerId) {
                    // This was our active pointer going up. Choose a new
                    // active pointer and adjust accordingly.
                    final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                    mLastTouchX = ev.getX(newPointerIndex);
                    mLastTouchY = ev.getY(newPointerIndex);
                    mActivePointerId = ev.getPointerId(newPointerIndex);
                }
                break;
            }
        }

        return true;
    }

    private class ScaleListener extends
            ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor();

            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(1.0f, Math.min(mScaleFactor, 3.0f));

            invalidate();
            return true;
        }
    }
}


text:
package au.org.aurin.wif.impl.suitability;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.filter.text.cql2.CQLException;
import org.opengis.geometry.MismatchedDimensionException;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.operation.TransformException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.vividsolutions.jts.io.ParseException;

import au.org.aurin.wif.config.GeoServerConfig;
import au.org.aurin.wif.config.WifConfig;
import au.org.aurin.wif.exception.config.InvalidEntityIdException;
import au.org.aurin.wif.exception.config.ParsingException;
import au.org.aurin.wif.exception.config.WifInvalidConfigException;
import au.org.aurin.wif.exception.io.DatabaseFailedException;
import au.org.aurin.wif.exception.validate.SuitabilityAnalysisFailedException;
import au.org.aurin.wif.exception.validate.WifInvalidInputException;
import au.org.aurin.wif.impl.lsa.SuitabilityAnalyzer;
import au.org.aurin.wif.io.CouchMapper;
import au.org.aurin.wif.io.parsers.SuitabilityCouchParser;
import au.org.aurin.wif.model.WifProject;
import au.org.aurin.wif.model.allocation.AllocationLU;
import au.org.aurin.wif.model.suitability.Factor;
import au.org.aurin.wif.model.suitability.FactorImportance;
import au.org.aurin.wif.model.suitability.FactorType;
import au.org.aurin.wif.model.suitability.FactorTypeRating;
import au.org.aurin.wif.model.suitability.SuitabilityLU;
import au.org.aurin.wif.model.suitability.SuitabilityRule;
import au.org.aurin.wif.model.suitability.SuitabilityScenario;
import au.org.aurin.wif.repo.impl.CouchWifProjectDao;
import au.org.aurin.wif.repo.suitability.SuitabilityRuleDao;
import au.org.aurin.wif.repo.suitability.SuitabilityScenarioDao;
import au.org.aurin.wif.svc.AllocationLUService;
import au.org.aurin.wif.svc.ProjectService;
import au.org.aurin.wif.svc.WifKeys;
import au.org.aurin.wif.svc.suitability.SuitabilityScenarioService;

/**
 * The Class SuitabilityScenarioServiceImpl.
 */
@Service
@Qualifier("suitabilityScenarioService")
public class SuitabilityScenarioServiceImpl implements
SuitabilityScenarioService {

  /** The Constant serialVersionUID. */
  @SuppressWarnings("unused")
  private static final long serialVersionUID = 79823546576734533L;

  /** The Constant LOGGER. */
  private static final Logger LOGGER = LoggerFactory
      .getLogger(SuitabilityScenarioServiceImpl.class);

  /** The suitability scenario dao. */
  @Autowired
  private SuitabilityScenarioDao suitabilityScenarioDao;

  /** The geoserver config. */
  @Autowired
  private GeoServerConfig geoserverConfig;

  /** The wif config. */
  @Autowired
  private WifConfig wifConfig;

  /** The mapper. */
  @Autowired
  private CouchMapper mapper;

  /** The wif project dao. */
  @Autowired
  private CouchWifProjectDao wifProjectDao;

  /** The project service. */
  @Resource
  private ProjectService projectService;

  /** The allocation lu service. */
  @Resource
  private AllocationLUService allocationLUService;

  /** The suitability analyzer. */
  @Autowired
  private SuitabilityAnalyzer suitabilityAnalyzer;

  /** The suitability rule dao. */
  @Autowired
  private SuitabilityRuleDao suitabilityRuleDao;

  /** The parser. */
  @Autowired
  private SuitabilityCouchParser suitabilityParser;

  /**
   * Inits the.
   */
  @PostConstruct
  public void init() {
    LOGGER.trace("Initializing version: " + WifKeys.WIF_KEY_VERSION);
  }

  /**
   * Cleanup.
   */

  @PreDestroy
  public void cleanup() {
    LOGGER.trace("SuitabilityScenario Service succesfully cleared! ");
  }

  /*
   * (non-Javadoc)
   * @see au.org.aurin.wif.svc.suitability.SuitabilityScenarioService#
   * createSuitabilityScenario
   * (au.org.aurin.wif.model.suitability.SuitabilityScenario, java.lang.String)
   */
  @Override
  public SuitabilityScenario createSuitabilityScenario(
      SuitabilityScenario suitabilityScenario, final String projectId)
          throws WifInvalidInputException, WifInvalidConfigException,
          ParsingException {
    if (suitabilityScenario == null) {
      LOGGER
      .error("createSuitabilityScenario failed: suitabilityScenario is null or invalid");
      throw new WifInvalidInputException(
          "createSuitabilityScenario failed: suitabilityScenario is null or invalid");
    }
    final WifProject project = projectService.getProject(projectId);
    suitabilityScenario = suitabilityParser.parseSuitabilityScenario(
        suitabilityScenario, project);
    suitabilityScenario.setProjectId(projectId);
    project.getSuitabilityConfig().setNotConvertableScore(
        WifKeys.NOT_CONVERTABLE_SCORE);
    project.getSuitabilityConfig().setNotSuitableScore(
        WifKeys.NOT_SUITABLE_SCORE);
    project.getSuitabilityConfig().setNotDevelopableScore(
        WifKeys.NOT_DEVELOPABLE_SCORE);
    project.getSuitabilityConfig().setUndefinedScore(WifKeys.UNDEFINED_SCORE);
    LOGGER.debug("persisting the suitabilityScenario={}",
        suitabilityScenario.getLabel());
    suitabilityScenario.setReady(true);

    final SuitabilityScenario savedSuitabilityScenario = suitabilityScenarioDao
        .persistSuitabilityScenario(suitabilityScenario);

    LOGGER.debug("returning the suitabilityScenario with id={}",
        savedSuitabilityScenario.getId());

    final Collection<SuitabilityRule> suitabilityRules = suitabilityScenario
        .getSuitabilityRules();
    LOGGER.debug("{} has {} suitability rules associated",
        suitabilityScenario.getLabel(), suitabilityRules.size());
    for (final SuitabilityRule rule : suitabilityRules) {
      rule.setScenarioId(savedSuitabilityScenario.getId());
      suitabilityRuleDao.persistSuitabilityRule(rule);
    }

    suitabilityScenarioDao.updateSuitabilityScenario(savedSuitabilityScenario);
    project.getSuitabilityScenariosMap().put(savedSuitabilityScenario.getId(),
        savedSuitabilityScenario.getLabel());
    // TODO It would be more efficient if we use the dao here
    // projectService.updateProject(project);
    project.getSuitabilityScenariosMap().put(savedSuitabilityScenario.getId(),
        savedSuitabilityScenario.getLabel());
    wifProjectDao.updateProject(project);
    return savedSuitabilityScenario;
  }

  /*
   * (non-Javadoc)
   * @see au.org.aurin.wif.svc.suitability.SuitabilityScenarioService#
   * getSuitabilityScenario(java.lang.String)
   */
  @Override
  public SuitabilityScenario getSuitabilityScenario(final String id)
      throws WifInvalidInputException, WifInvalidConfigException,
      ParsingException {

    LOGGER.debug("getting the suitabilityScenario with ID={}", id);
    try {
      SuitabilityScenario suitabilityScenario = suitabilityScenarioDao
          .findSuitabilityScenarioById(id);
      if (suitabilityScenario == null) {
        LOGGER.error("illegal argument, the suitabilityScenario with the ID "
            + id + " supplied was not found ");
        throw new InvalidEntityIdException(
            "illegal argument, the suitabilityScenario with the ID " + id
            + " supplied was not found ");
      }

      final WifProject project = projectService
          .getProjectConfiguration(suitabilityScenario.getProjectId());

      suitabilityScenario = suitabilityParser.parseSuitabilityScenario(
          suitabilityScenario, project);

      suitabilityScenario.setWifProject(project);
      return suitabilityScenario;

    } catch (final IllegalArgumentException e) {

      LOGGER.error("illegal argument, the ID " + id
          + " supplied doesn't identify a valid suitabilityScenario ");
      throw new WifInvalidInputException("illegal argument, the ID " + id
          + " supplied doesn't identify a valid suitabilityScenario ", e);
    }
  }

  /*
   * (non-Javadoc)
   * @see au.org.aurin.wif.svc.suitability.SuitabilityScenarioService#
   * getSuitabilityScenarioNoMapping(java.lang.String)
   */
  @Override
  public SuitabilityScenario getSuitabilityScenarioNoMapping(final String id)
      throws WifInvalidInputException, WifInvalidConfigException {

    LOGGER.debug("getting the suitabilityScenario with ID={}", id);
    try {
      final SuitabilityScenario suitabilityScenario = suitabilityScenarioDao
          .findSuitabilityScenarioById(id);
      if (suitabilityScenario == null) {
        LOGGER.error("illegal argument, the suitabilityScenario with the ID "
            + id + " supplied was not found ");
        throw new InvalidEntityIdException(
            "illegal argument, the suitabilityScenario with the ID " + id
            + " supplied was not found ");
      }

      return suitabilityScenario;

    } catch (final IllegalArgumentException e) {

      LOGGER.error("illegal argument, the ID " + id
          + " supplied doesn't identify a valid suitabilityScenario ");
      throw new WifInvalidInputException("illegal argument, the ID " + id
          + " supplied doesn't identify a valid suitabilityScenario ", e);
    }
  }

  /*
   * (non-Javadoc)
   * @see
   * au.org.aurin.wif.svc.SuitabilityScenarioService#getSuitabilityScenario(
   * java.lang.String)
   */
  @Override
  public SuitabilityScenario getSuitabilityScenario(final String id, final String projectId)
      throws WifInvalidInputException, WifInvalidConfigException,
      ParsingException {
    final SuitabilityScenario suitabilityScenario = getSuitabilityScenario(id);
    if (suitabilityScenario.getProjectId().equals(projectId)) {
      return suitabilityScenario;
    } else {
      LOGGER
      .error("illegal argument, the suitabilityScenario supplied doesn't belong to project: "
          + projectId);
      throw new WifInvalidInputException(
          "illegal argument, the suitabilityScenario supplied doesn't belong to this  project: "
              + projectId);
    }
  }

  /*
   * (non-Javadoc)
   * @see
   * au.org.aurin.wif.svc.SuitabilityScenarioService#updateSuitabilityScenario
   * (au.org.aurin.wif.model.allocation.SuitabilityScenario, java.lang.String)
   */
  @Override
  public synchronized void updateSuitabilityScenario(
      final SuitabilityScenario suitabilityScenario, final String projectId)
          throws WifInvalidInputException, WifInvalidConfigException {
    LOGGER.info("updating suitabilityScenario: {}, with id: {}",
        suitabilityScenario.getLabel(), suitabilityScenario.getId());
    try {
      final Collection<SuitabilityRule> suitabilityRules = suitabilityScenario
          .getSuitabilityRules();
      LOGGER.debug("{} has {} suitability rules associated",
          suitabilityScenario.getLabel(), suitabilityRules.size());
      for (final SuitabilityRule rule : suitabilityRules) {
        rule.setRevision(suitabilityRuleDao.findSuitabilityRuleById(
            rule.getId()).getRevision());
        LOGGER.debug("updating the rule with Rev={}", rule.getRevision());
        suitabilityRuleDao.updateSuitabilityRule(rule);
      }
      suitabilityScenario.setRevision(suitabilityScenarioDao
          .findSuitabilityScenarioById(suitabilityScenario.getId())
          .getRevision());
      LOGGER.debug("updating the suitabilityScenario with Rev={}",
          suitabilityScenario.getRevision());
      suitabilityScenarioDao.updateSuitabilityScenario(suitabilityScenario);
    } catch (final IllegalArgumentException e) {

      LOGGER
      .error("illegal argument, the suitabilityScenario supplied is invalid ");
      throw new WifInvalidInputException(
          "illegal argument, the suitabilityScenario supplied is invalid ", e);
    }
  }

  /*
   * (non-Javadoc)
   * @see
   * au.org.aurin.wif.svc.SuitabilityScenarioService#deleteSuitabilityScenario
   * (java.lang.String, java.lang.String)
   */
  @Override
  public void deleteSuitabilityScenario(final String id, final String projectId)
      throws WifInvalidInputException, WifInvalidConfigException {
    LOGGER.info("deleting the suitabilityScenario with ID={}", id);
    try {
      final SuitabilityScenario suitabilityScenario = suitabilityScenarioDao
          .findSuitabilityScenarioById(id);
      if (suitabilityScenario == null) {
        LOGGER.error("illegal argument, the suitabilityScenario with the ID "
            + id + " supplied was not found ");
        throw new InvalidEntityIdException(
            "illegal argument, the suitabilityScenario with the ID " + id
            + " supplied was not found ");
      }
      if (suitabilityScenario.getProjectId().equals(projectId)) {
        final Collection<SuitabilityRule> suitabilityRules = suitabilityScenario
            .getSuitabilityRules();
        LOGGER.debug("{} has {} suitability rules associated",
            suitabilityScenario.getLabel(), suitabilityRules.size());
        for (final SuitabilityRule rule : suitabilityRules) {
          suitabilityRuleDao.deleteSuitabilityRule(rule);
        }
        suitabilityScenarioDao.deleteSuitabilityScenario(suitabilityScenario);
        final WifProject project = projectService.getProject(projectId);
        project.getSuitabilityScenariosMap().remove(id);
        wifProjectDao.updateProject(project);
      } else {
        LOGGER
        .error("illegal argument, the suitabilityScenario supplied doesn't belong to project: "
            + projectId);
        throw new WifInvalidInputException(
            "illegal argument, the suitabilityScenario supplied doesn't belong to project: "
                + projectId);
      }

    } catch (final IllegalArgumentException e) {

      LOGGER.error("illegal argument, the ID " + id
          + " supplied doesn't identify a valid suitabilityScenario ");
      throw new InvalidEntityIdException("illegal argument, the ID " + id
          + " supplied doesn't identify a valid suitabilityScenario ", e);
    }
  }

  /*
   * (non-Javadoc)
   * @see
   * au.org.aurin.wif.svc.SuitabilityScenarioService#getSuitabilityScenarios
   * (java.lang.String)
   */
  @Override
  public List<SuitabilityScenario> getSuitabilityScenarios(final String projectID)
      throws WifInvalidInputException {
    LOGGER.info("getting all suitabilityScenarios for projectID: {} ",
        projectID);

    return suitabilityScenarioDao.getSuitabilityScenarios(projectID);
  }

  /*
   * (non-Javadoc)
   * @see
   * au.org.aurin.wif.svc.suitability.SuitabilityScenarioService#getWMSOutcome
   * (java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  public Boolean getWMSOutcome(final String id, final String areaAnalyzed, final String crsArea)
      throws WifInvalidInputException, WifInvalidConfigException,
      MismatchedDimensionException, NoSuchAuthorityCodeException,
      FactoryException, TransformException, ParseException, IOException,
      CQLException, SuitabilityAnalysisFailedException, ParsingException {
    final SuitabilityScenario suitabilityScenario = getSuitabilityScenario(id);
    return suitabilityAnalyzer.doSuitabilityAnalysisWMS(suitabilityScenario,
        areaAnalyzed, crsArea);
  }

  /*
   * (non-Javadoc)
   * @see
   * au.org.aurin.wif.svc.suitability.SuitabilityScenarioService#getOutcome(
   * java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  public SimpleFeatureCollection getOutcome(final String id, final String areaAnalyzed,
      final String crsArea) throws WifInvalidInputException,
  WifInvalidConfigException, MismatchedDimensionException,
  NoSuchAuthorityCodeException, CQLException, FactoryException,
  TransformException, ParseException, ParsingException,
  DatabaseFailedException {
    final SuitabilityScenario suitabilityScenario = getSuitabilityScenario(id);
    return suitabilityAnalyzer.doSuitabilityAnalysis(suitabilityScenario,
        areaAnalyzed, crsArea);
  }

  /*
   * (non-Javadoc)
   * @see
   * au.org.aurin.wif.svc.ProjectService#getWMS(au.org.aurin.wif.model.WifProject
   * )
   */
  @Override
  public WMSOutcome getWMS(final String id) throws WifInvalidInputException,
  WifInvalidConfigException, ParsingException {

    final SuitabilityScenario suitabilityScenario = getSuitabilityScenario(id);
    LOGGER
    .info(
        "creating the information for WMS outcome of wif suitabilityScenario={}",
        suitabilityScenario.getLabel());
    final WMSOutcome outcome = new WMSOutcome();
    outcome.setStoreName(geoserverConfig.getStoreName());
    outcome.setWorkspaceName(geoserverConfig.getWorkspace());
    LOGGER.debug("using the following Geoserver store: {} workspace name:  {}",
        outcome.getStoreName(), outcome.getWorkspaceName());
    final WifProject project = wifProjectDao.findProjectById(suitabilityScenario
        .getProjectId());
    outcome.setScoreColumns(suitabilityAnalyzer
        .generateScoreRanges(suitabilityScenario));
    outcome.setAvailableStyles(wifConfig.getSuitabilityStyles());
    LOGGER.debug(
        "using the following {} suitability columns for the outcome layers",
        outcome.getScoreColumns().size());
    for (final String column : outcome.getScoreColumns().keySet()) {
      LOGGER.debug("={}", column);
    }
    final String uazDBTable = project.getSuitabilityConfig().getUnifiedAreaZone();
    LOGGER.info(
        "creating a suitability outcome for WMS Layer ={}, geo WMS  URL ={}",
        uazDBTable, wifConfig.getServerWMSURL());
    outcome.setLayerName(uazDBTable);
    final String serverWMSURL = wifConfig.getServerWMSURL();
    outcome.setServerURL(serverWMSURL);
    return outcome;
  }

  /*
   * (non-Javadoc)
   * @see au.org.aurin.wif.svc.suitability.SuitabilityScenarioService#
   * restoreSuitabilityScenario
   * (au.org.aurin.wif.model.suitability.SuitabilityScenario)
   */
  @Override
  public SuitabilityScenario restoreSuitabilityScenario(
      final SuitabilityScenario oldSuitabilityScenario, final WifProject restoreProject)
          throws WifInvalidInputException {
    LOGGER.info("Restoring {} suitability scenario...",
        oldSuitabilityScenario.getLabel());
    SuitabilityScenario restoreSuitabilityScenario = new SuitabilityScenario();
    restoreSuitabilityScenario.setLabel(oldSuitabilityScenario.getLabel());
    restoreSuitabilityScenario.setFeatureFieldName(oldSuitabilityScenario
        .getFeatureFieldName());
    restoreSuitabilityScenario.setProjectId(restoreProject.getId());
    restoreSuitabilityScenario = suitabilityScenarioDao
        .persistSuitabilityScenario(restoreSuitabilityScenario);
    final Set<SuitabilityRule> suitabilityRules = oldSuitabilityScenario
        .getSuitabilityRules();
    for (final SuitabilityRule oldRule : suitabilityRules) {
      final SuitabilityRule newRule = new SuitabilityRule();
      final String suitabilityLULabel = oldRule.getSuitabilityLUMap().values()
          .iterator().next();
      LOGGER.debug("Restoring {} suitabilityLU...", suitabilityLULabel);
      final SuitabilityLU suitabilityLU = restoreProject
          .getSuitabilityLUByName(suitabilityLULabel);
      newRule.getSuitabilityLUMap().put(suitabilityLU.getId(),
          suitabilityLU.getLabel());
      final Collection<String> convertibleLUsLabels = oldRule.getConvertibleLUsMap()
          .values();
      for (final String luLabel : convertibleLUsLabels) {
        LOGGER.debug("Restoring {} convertibleLU...", luLabel);
        final AllocationLU allocationLU = restoreProject
            .getExistingLandUseByLabel(luLabel);
        newRule.getConvertibleLUsMap().put(allocationLU.getId(),
            allocationLU.getLabel());
      }
      final Set<FactorImportance> factorImportances = oldRule.getFactorImportances();
      for (final FactorImportance oldImportance : factorImportances) {
        final FactorImportance importance = new FactorImportance();
        importance.setImportance(oldImportance.getImportance());
        final String factorLabel = oldImportance.getFactorMap().values().iterator()
            .next();
        LOGGER.debug("Restoring factorImportance for {}...", factorLabel);
        final Factor factor = restoreProject.getFactorByLabel(factorLabel);
        importance.getFactorMap().put(factor.getId(), factor.getLabel());

        final Set<FactorTypeRating> factorTypeRatings = oldImportance
            .getFactorTypeRatings();
        for (final FactorTypeRating oldRating : factorTypeRatings) {
          final FactorTypeRating rating = new FactorTypeRating();
          final String ftLabel = oldRating.getFactorTypeMap().values().iterator()
              .next();
          rating.setScore(oldRating.getScore());
          LOGGER.debug(
              "Restoring factor type importance for {} with score {}...",
              ftLabel, rating.getScore());
          final FactorType factorType = factor.getFactorTypeByLabel(ftLabel);
          rating.getFactorTypeMap().put(factorType.getId(),
              factorType.getLabel());
          importance.getFactorTypeRatings().add(rating);
        }
        newRule.getFactorImportances().add(importance);
      }
      final SuitabilityRule savedRule = suitabilityRuleDao
          .persistSuitabilityRule(newRule);
      restoreSuitabilityScenario.getSuitabilityRules().add(savedRule);
    }
    suitabilityScenarioDao
    .updateSuitabilityScenario(restoreSuitabilityScenario);
    return restoreSuitabilityScenario;
  }

  @Override
  public String duplicateSuitabiliyScenario(final String projectID, final String scenarioID, final String name)
      throws WifInvalidInputException, WifInvalidConfigException, ParsingException
  {
    LOGGER.info("duplicateSuitabiliyScenario");
    String out="";
    try
    {

      final SuitabilityScenario suitabilityScenario = getSuitabilityScenario(scenarioID);
      suitabilityScenario.setLabel(name);

      final WifProject project = projectService
          .getProjectConfiguration(suitabilityScenario.getProjectId());

      final SuitabilityScenario restoredSuitabilityScenario = restoreSuitabilityScenario(suitabilityScenario, project);
      project.getSuitabilityScenariosMap().put(
          restoredSuitabilityScenario.getId(),
          restoredSuitabilityScenario.getLabel());

      wifProjectDao.updateProject(project);
      out= "Success";

    } catch (final IllegalArgumentException e) {

      LOGGER.error("illegal argument, the suitabilityScenario supplied is invalid ");
      out ="Error:"+ e.getMessage();
    }

    return out;

  }

  @Override
  public String uploadXlsFactors(final String projectID, final String scenarioID, final InputStream inputStream)
      throws WifInvalidInputException, WifInvalidConfigException, ParsingException, IOException {
    LOGGER.info("uploadXlsFactors");
    String out="";
    try
    {

      final HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
      final HSSFSheet sheet = workbook.getSheetAt(0);
      HSSFRow row6;
      HSSFRow row;
      HSSFCell cell;
      HSSFCell factorName;

      LOGGER.info("hii");

      final Map<String, Double> map = new HashMap<String, Double>();

      int rows; // No of rows
      rows = sheet.getPhysicalNumberOfRows();

      final SuitabilityScenario rawSuitabilityScenario =
          getSuitabilityScenario(scenarioID);
      if (!rawSuitabilityScenario.getLabel().equals(sheet.getRow(2).getCell(0).getStringCellValue()))
      {
        out = "{\"result\" : \"" +"The scenario name is not match!" +"\"}";
        return out;
      }
      final WifProject rawProject = projectService
          .getProjectConfiguration(rawSuitabilityScenario.getProjectId());
      if (!rawProject.getLabel().equals(sheet.getRow(4).getCell(0).getStringCellValue()))
      {
        out = "{\"result\" : \"" +"The project name is not match!" +"\"}";
        return out;
      }

      int cols = 0; // No of columns
      int tmp = 0;
      // This trick ensures that we get the data properly even if it doesn't start from first few rows
      for(int i = 6;  i < rows; i++) {
        row = sheet.getRow(i);
        if(row != null) {
          tmp = sheet.getRow(i).getPhysicalNumberOfCells();
          if(tmp > cols) {
            cols = tmp;
          }
        }
      }

      for(int c = 1; c < cols; c++) {

        row6 = sheet.getRow(6);
        cell = row6.getCell(c);

        final String headerLU = cell.getStringCellValue();
        LOGGER.info(headerLU);

        LOGGER.info("********");

        String lbl="";
        String lbluse="";
        for(int r = 8; r < rows; r++) {

          Boolean lswHeader = false;

          row = sheet.getRow(r);
          if(row != null)
          {

            cell = row.getCell((short)c);
            factorName = row.getCell(0);
            lbluse= factorName.getStringCellValue();
            if (!factorName.getStringCellValue().equals(lbl))
            {
              if (lbl.equals(""))
              {
                lbl =  factorName.getStringCellValue();
                lbluse= "Header:" + lbl;
                lswHeader= true;
              }
              else
              {
                if (factorName.getStringCellValue().length() <= lbl.length())
                {
                  lbl =  factorName.getStringCellValue();
                  lbluse= "Header:" + lbl;
                  lswHeader= true;
                }
                else
                {
                  if (factorName.getStringCellValue().substring(0, lbl.length()).equals(lbl))
                  {
                    int k = lbl.length();
                    final String str = factorName.getStringCellValue();
                    if (str.substring(k, k+1).equals("_"))
                    {
                      k = factorName.getStringCellValue().length();

                      String lname=str.substring(lbl.length()+1,k);
                      lname = lname.replaceAll(",", "");
                      lname = lname.replaceAll("'Greater ", ">");
                      lname = lname.replaceAll("'Lower ", "<");

                      //lbluse= "Header:" + lbl + ":Child:" +str.substring(lbl.length()+1,k);
                      lbluse= "Header:" + lbl + ":Child:" +lname;
                      lswHeader= false;

                      Double newvalue=0.0;
                      if (cell.getCellType() == 1)
                      {

                        newvalue= Double.parseDouble(cell.getStringCellValue());
                      }
                      else if (cell.getCellType() == 0)
                      {

                        newvalue= cell.getNumericCellValue();
                      }

                    }
                    else
                    {
                      lbl =  factorName.getStringCellValue();
                      lbluse= "Header:" + lbl;
                      lswHeader= true;
                    }
                  }
                  else
                  {
                    lbl =  factorName.getStringCellValue();
                    lbluse= "Header:" + lbl;
                    lswHeader= true;
                  }
                }
              }
            }//end for

            if (lswHeader== true)
            {

            }
            else
            {

            }

            if(cell != null) {
              // Your code here
              //LOGGER.info(lbluse + " : "+cell.getCellType());
              if (cell.getCellType() == 1)
              {

                LOGGER.info(headerLU+":"+lbluse + ":"+cell.getStringCellValue());
                map.put(headerLU+":"+lbluse, Double.valueOf(cell.getStringCellValue()));
              }
              else
              {
                LOGGER.info(headerLU+":"+lbluse + ":"+cell.getNumericCellValue());
                map.put(headerLU+":"+lbluse, cell.getNumericCellValue());
              }
            }

          }
        }
      }//end for c

      for (final Map.Entry<String, Double> entry : map.entrySet()) {
        LOGGER.info("Key : " + entry.getKey() + " Value : " + entry.getValue());
        //LOGGER.info("Key : " + entry.getKey().split(":").length);
      }

      //////////////////////////////////////////////////////////////////////////////

      final SuitabilityScenario oldSuitabilityScenario =
          getSuitabilityScenario(scenarioID);
      //          final SuitabilityScenario oldSuitabilityScenario = suitabilityScenarioService
      //              .getSuitabilityScenario("d2ee05b32886f857ef1dd7272211b38d");

      final WifProject project = projectService
          .getProjectConfiguration(oldSuitabilityScenario.getProjectId());

      final Set<SuitabilityRule> setRules =  new HashSet<SuitabilityRule>();
      final Set<SuitabilityRule> suitabilityRules = oldSuitabilityScenario
          .getSuitabilityRules();
      for (final SuitabilityRule oldRule : suitabilityRules) {

        final SuitabilityRule newRule = new SuitabilityRule();

        newRule.setId(oldRule.getId());
        final String suitabilityLULabel = oldRule.getSuitabilityLUMap().values()
            .iterator().next();
        // LOGGER.debug("Restoring {} suitabilityLU...", suitabilityLULabel);
        final SuitabilityLU suitabilityLU = project
            .getSuitabilityLUByName(suitabilityLULabel);
        newRule.getSuitabilityLUMap().put(suitabilityLU.getId(),
            suitabilityLU.getLabel());
        final Collection<String> convertibleLUsLabels = oldRule.getConvertibleLUsMap()
            .values();
        for (final String luLabel : convertibleLUsLabels) {
          //LOGGER.debug("Restoring {} convertibleLU...", luLabel);
          final AllocationLU allocationLU = project
              .getExistingLandUseByLabel(luLabel);
          newRule.getConvertibleLUsMap().put(allocationLU.getId(),
              allocationLU.getLabel());
        }
        final Set<FactorImportance> factorImportances = oldRule.getFactorImportances();
        for (final FactorImportance oldImportance : factorImportances) {
          final Double newvalue=oldImportance.getImportance();

          final FactorImportance importance = new FactorImportance();

          final String factorLabel = oldImportance.getFactorMap().values().iterator()
              .next();
          //LOGGER.debug("Restoring factorImportance for {}...", factorLabel);
          final Factor factor = project.getFactorByLabel(factorLabel);
          importance.getFactorMap().put(factor.getId(), factor.getLabel());

          for (final Map.Entry<String, Double> entry : map.entrySet()) {
            //
            //System.out.println("Key : " + entry.getKey().split(":").length);
            if (entry.getKey().split(":").length==3)
            {
              final String[] str = entry.getKey().split(":");
              if (str[0].equals(suitabilityLULabel))
              {
                if (str[2].equals(factorLabel))
                {
                  //importance.setImportance(2.0);
                  importance.setImportance(entry.getValue());
                  //LOGGER.info("Key : " + entry.getKey() + " Value : " + entry.getValue());
                }
              }
            }
          }

          final Set<FactorTypeRating> factorTypeRatings = oldImportance
              .getFactorTypeRatings();
          for (final FactorTypeRating oldRating : factorTypeRatings) {
            final FactorTypeRating rating = new FactorTypeRating();
            final String ftLabel = oldRating.getFactorTypeMap().values().iterator()
                .next();

            for (final Map.Entry<String, Double> entry : map.entrySet()) {
              if (entry.getKey().split(":").length==5)
              {
                final String[] str = entry.getKey().split(":");
                if (str[0].equals(suitabilityLULabel))
                {
                  if (str[2].equals(factorLabel))
                  {

                    if (str[4].equals(ftLabel))
                    {
                      //rating.setScore(2.0);
                      rating.setScore(entry.getValue());
                      //LOGGER.info("Key : " + entry.getKey() + " Value : " + entry.getValue());
                      if (suitabilityLULabel.equals("Retail"))
                      {
                        if (factorLabel.equals("streams"))
                        {
                          int cc=0;
                          cc=2;
                          if (ftLabel.equals("Outside buffers"))
                          {

                          }
                        }
                      }

                    }

                  }
                }
              }
            }

            final FactorType factorType = factor.getFactorTypeByLabel(ftLabel);
            rating.getFactorTypeMap().put(factorType.getId(),
                factorType.getLabel());
            importance.getFactorTypeRatings().add(rating);
          }
          newRule.getFactorImportances().add(importance);

          newRule.setRevision(suitabilityRuleDao.findSuitabilityRuleById(
              oldRule.getId()).getRevision());
          LOGGER.info("updating the newrule with Rev={}", newRule.getRevision());
          suitabilityRuleDao.updateSuitabilityRule(newRule);

          newRule.setRevision(suitabilityRuleDao.findSuitabilityRuleById(
              oldRule.getId()).getRevision());
          setRules.add(newRule);

        }

      }

      oldSuitabilityScenario.setSuitabilityRules(setRules);
      oldSuitabilityScenario.setRevision(suitabilityScenarioDao
          .findSuitabilityScenarioById(oldSuitabilityScenario.getId())
          .getRevision());
      LOGGER.info("updating the suitabilityScenario with Rev={}",
          oldSuitabilityScenario.getRevision());
      updateSuitabilityScenario(oldSuitabilityScenario,
          project.getId());

      //////////////////////////////////////////////////////////////////////////////

      inputStream.close();

      out = "{\"result\" : \"" +"success" +"\"}";

    } catch (final IllegalArgumentException e) {

      LOGGER.error("illegal argument, the suitabilityScenario supplied is invalid ");
      out ="Error: " + e.getMessage();
      out = "{\"result\" : \"" + out +"\"}";
    }

    return out;
  }

}


text:
======================================

Requirements for Cordova
--------------------

* Node.js
* Ant
* `sudo npm install -g cordova`

###For iOS
* XCode
* `sudo npm install -g ios-deploy`
* `sudo npm install -g ios-sim`

**Don't forget to set your environment variables !**

###Add android platform to project :
`cordova platform add android`

###Compile to apk :
`cordova build android`

###Run
`cordova run android`

###Add iOS platform to project :
`cordova platform add ios`

###Compile iOS project:
`cordova build ios`

###Run (in iPhone Simulator)
`cordova run ios`

# License
======================================
Copyright 2014 eBusiness Information

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.