text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwpf/hwp/activate_powerbus/proc_build_smp/proc_build_smp_adu.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2015                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
// $Id: proc_build_smp_adu.C,v 1.11 2014/11/18 17:41:03 jmcgill Exp $
// $Source: /afs/awd/projects/eclipz/KnowledgeBase/.cvsroot/eclipz/chips/p8/working/procedures/ipl/fapi/proc_build_smp_adu.C,v $
//------------------------------------------------------------------------------
// *|
// *! (C) Copyright International Business Machines Corp. 2011
// *! All Rights Reserved -- Property of IBM
// *! ***  ***
// *|
// *! TITLE       : proc_build_smp_adu.C
// *! DESCRIPTION : Interface for ADU operations required to support fabric
// *!               configuration actions (FAPI)
// *!
// *! OWNER NAME  : Joe McGill    Email: jmcgill@us.ibm.com
// *!
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <proc_build_smp_adu.H>
#include <proc_adu_utils.H>

//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------

const uint32_t PROC_BUILD_SMP_MAX_STATUS_POLLS = 5;

const uint32_t PROC_BUILD_SMP_PHASE1_ADU_LOCK_ATTEMPTS = 1;
const bool PROC_BUILD_SMP_PHASE1_ADU_PICK_LOCK = false;
const uint32_t PROC_BUILD_SMP_PHASE1_POST_QUIESCE_DELAY = 128;
const uint32_t PROC_BUILD_SMP_PHASE1_PRE_INIT_DELAY = 128;

const uint32_t PROC_BUILD_SMP_PHASE2_ADU_LOCK_ATTEMPTS = 5;
const bool PROC_BUILD_SMP_PHASE2_ADU_PICK_LOCK = true;
const uint32_t PROC_BUILD_SMP_PHASE2_POST_QUIESCE_DELAY = 4096;
const uint32_t PROC_BUILD_SMP_PHASE2_PRE_INIT_DELAY = 512;

// ADU pMISC Mode register field/bit definitions
const uint32_t ADU_PMISC_MODE_ENABLE_PB_SWITCH_AB_BIT = 30;
const uint32_t ADU_PMISC_MODE_ENABLE_PB_SWITCH_CD_BIT = 31;

// FFDC logging on ADU switch fails
const uint8_t PROC_BUILD_SMP_FFDC_NUM_REGS = 11;
const uint32_t PROC_BUILD_SMP_FFDC_REGS[PROC_BUILD_SMP_FFDC_NUM_REGS] =
{
    PB_MODE_CENT_0x02010C4A,
    PB_HP_MODE_NEXT_CENT_0x02010C4B,
    PB_HP_MODE_CURR_CENT_0x02010C4C,
    PB_HPX_MODE_NEXT_CENT_0x02010C4D,
    PB_HPX_MODE_CURR_CENT_0x02010C4E,
    X_GP0_0x04000000,
    PB_X_MODE_0x04010C0A,
    A_GP0_0x08000000,
    ADU_IOS_LINK_EN_0x02020019,
    PB_A_MODE_0x0801080A,
    ADU_PMISC_MODE_0x0202000B
};
enum proc_build_smp_ffdc_reg_index
{
    PB_MODE_CENT_DATA_INDEX = 0,
    PB_HP_MODE_NEXT_CENT_DATA_INDEX = 1,
    PB_HP_MODE_CURR_CENT_DATA_INDEX = 2,
    PB_HPX_MODE_NEXT_CENT_DATA_INDEX = 3,
    PB_HPX_MODE_CURR_CENT_DATA_INDEX = 4,
    X_GP0_DATA_INDEX = 5,
    PB_X_MODE_DATA_INDEX = 6,
    A_GP0_DATA_INDEX = 7,
    ADU_IOS_LINK_EN_DATA_INDEX = 8,
    PB_A_MODE_DATA_INDEX = 9,
    ADU_PMISC_MODE_DATA_INDEX = 10
};

extern "C"
{

//------------------------------------------------------------------------------
// Function definitions
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// function: set action which will occur on fabric pmisc switch command
// parameters: i_target    => P8 chip target
//             i_switch_ab => perform switch AB operation?
//             i_switch_cd => perform switch CD operation?
// returns: FAPI_RC_SUCCESS if action is configured successfully,
//          else error
//------------------------------------------------------------------------------
fapi::ReturnCode proc_build_smp_adu_set_switch_action(
    const fapi::Target& i_target,
    const bool i_switch_ab,
    const bool i_switch_cd)
{
    fapi::ReturnCode rc;
    uint32_t rc_ecmd = 0;
    ecmdDataBufferBase pmisc_data(64), pmisc_mask(64);

    FAPI_DBG("proc_build_smp_adu_set_switch_action: Start");
    do
    {
        // build ADU pMisc Mode register content
        FAPI_DBG("proc_build_smp_adu_set_switch_action: Writing ADU pMisc Mode register");
        // switch AB bit
        rc_ecmd |= pmisc_data.writeBit(
            ADU_PMISC_MODE_ENABLE_PB_SWITCH_AB_BIT,
            i_switch_ab);
        rc_ecmd |= pmisc_mask.setBit(
            ADU_PMISC_MODE_ENABLE_PB_SWITCH_AB_BIT);
        // switch CD bit
        rc_ecmd |= pmisc_data.writeBit(
            ADU_PMISC_MODE_ENABLE_PB_SWITCH_CD_BIT,
            i_switch_cd);
        rc_ecmd |= pmisc_mask.setBit(
            ADU_PMISC_MODE_ENABLE_PB_SWITCH_CD_BIT);

        if (rc_ecmd)
        {
            FAPI_ERR("proc_build_smp_adu_set_switch_action: Error 0x%x setting up ADU pMisc Mode register data buffer",
                     rc_ecmd);
            rc.setEcmdError(rc_ecmd);
            break;
        }
        // write ADU pMisc Mode register content
        rc = fapiPutScomUnderMask(i_target,
                                  ADU_PMISC_MODE_0x0202000B,
                                  pmisc_data,
                                  pmisc_mask);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_adu_set_switch_action: fapiPutScomUnderMask error (ADU_PMISC_MODE_0x0202000B)");
            break;
        }
    } while(0);

    FAPI_DBG("proc_build_smp_adu_set_switch_action: End");
    return rc;
}

//------------------------------------------------------------------------------
// function: acquire ADU atomic lock to guarantee exclusive use of its
//           resources
// parameters: i_target         => P8 chip target
//             i_adu_lock_tries => number of lock acquisistions to attempt
//             i_adu_pick_lock  => attempt lock pick if lock acquisition
//                                 is unsuccessful after i_adu_lock_tries?
// returns: FAPI_RC_SUCCESS if lock is successfully acquired,
//          FAPI_RC_PLAT_ERR_ADU_LOCKED if operation failed due to state of
//              ADU atomic lock,
//          RC_PROC_ADU_UTILS_INVALID_LOCK_OPERATION if an unsupported operation
//              is specified,
//          RC_PROC_ADU_UTILS_INVALID_LOCK_ATTEMPTS if invalid number of attempts
//              is specified,
//          else error
//------------------------------------------------------------------------------
fapi::ReturnCode proc_build_smp_adu_acquire_lock(
    const fapi::Target& i_target,
    const uint32_t& i_adu_lock_tries,
    const bool& i_adu_pick_lock)
{
    fapi::ReturnCode rc;
    proc_adu_utils_adu_lock_operation lock_op = ADU_LOCK_ACQUIRE;

    FAPI_DBG("proc_build_smp_adu_acquire_lock: Start");

    do
    {
        // attempt ADU lock acquisition
        FAPI_DBG("proc_build_smp_adu_acquire_lock: Calling library to acquire ADU lock");
        rc = proc_adu_utils_manage_adu_lock(i_target,
                                            lock_op,
                                            i_adu_lock_tries);

        // return code specifically indicates lock acquisition was not
        // successful because ADU lock is held by another entity
        if (rc == fapi::FAPI_RC_PLAT_ERR_ADU_LOCKED)
        {
            FAPI_INF("proc_build_smp_adu_acquire_lock: Unable to acquire ADU lock after %d tries",
                     i_adu_lock_tries);

            // give up if lock pick is not specified
            if (!i_adu_pick_lock)
            {
                FAPI_ERR("proc_build_smp_adu_acquire_lock: ADU lock acquisition unsuccessful, giving up without attempting to pick lock");
                break;
            }
            // otherwise make single lock pick attempt
            else
            {
                FAPI_DBG("proc_build_smp_adu_acquire_lock: Calling library to pick ADU lock");
                lock_op = ADU_LOCK_FORCE_ACQUIRE;
                rc = proc_adu_utils_manage_adu_lock(i_target,
                                                    lock_op,
                                                    1);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_build_smp_adu_acquire_lock: Error from proc_adu_utils_manage_adu_lock");
                    break;
                }
            }
        }
        // flag error on any other return code that is not OK
        else if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_adu_acquire_lock: Error from proc_adu_utils_manage_adu_lock");
            break;
        }
    } while(0);

    FAPI_DBG("proc_build_smp_adu_acquire_lock: End");
    return rc;
}

//------------------------------------------------------------------------------
// function: reset ADU state machines and status register
//           NOTE: intended to be run while holding ADU lock
// parameters: i_target => P8 chip target
// returns: FAPI_RC_SUCCESS if fabric is not stopped,
//          FAPI_RC_PLAT_ERR_ADU_LOCKED if operation failed due to state of
//              ADU atomic lock,
//          else error
//------------------------------------------------------------------------------
fapi::ReturnCode proc_build_smp_adu_reset(
    const fapi::Target& i_target)
{
    fapi::ReturnCode rc;

    FAPI_DBG("proc_build_smp_adu_reset: Start");
    do
    {
        // call ADU library function
        FAPI_DBG("proc_build_smp_adu_reset: Calling library to reset ADU");
        rc = proc_adu_utils_reset_adu(i_target);
        if (!rc.ok()) {
            FAPI_ERR("proc_build_smp_adu_reset: Error from proc_adu_utils_reset_adu");
        }
    } while(0);

    FAPI_DBG("proc_build_smp_adu_reset: End");
    return rc;
}

//------------------------------------------------------------------------------
// function: release ADU atomic lock
//           NOTE: intended to be run while holding ADU lock
// parameters: i_target           => P8 chip target
//             i_adu_unlock_tries => number of lock releases to attempt
// returns: FAPI_RC_SUCCESS if lock is successfully released,
//          FAPI_RC_PLAT_ERR_ADU_LOCKED if operation failed due to state of
//              ADU atomic lock,
//          RC_PROC_ADU_UTILS_INVALID_LOCK_OPERATION if an unsupported operation
//              is specified,
//          RC_PROC_ADU_UTILS_INVALID_LOCK_ATTEMPTS if invalid number of attempts
//              is specified,
//          else error
//------------------------------------------------------------------------------
fapi::ReturnCode proc_build_smp_adu_release_lock(
    const fapi::Target& i_target,
    const uint32_t& i_adu_unlock_tries)
{
    fapi::ReturnCode rc;

    FAPI_DBG("proc_build_smp_adu_release_lock: Start");

    do
    {
        // attempt ADU lock acquisition
        FAPI_DBG("proc_build_smp_adu_release_lock: Calling library to release ADU lock");
        rc = proc_adu_utils_manage_adu_lock(i_target,
                                            ADU_LOCK_RELEASE,
                                            i_adu_unlock_tries);

        // return code specifically indicates lock release was not
        // successful because ADU lock is held by another entity
        if (rc == fapi::FAPI_RC_PLAT_ERR_ADU_LOCKED)
        {
            FAPI_INF("proc_build_smp_adu_release_lock: Unable to release ADU lock after %d tries",
                     i_adu_unlock_tries);
            FAPI_ERR("proc_build_smp_adu_release_lock: ADU lock release unsuccessful");
            break;
        }
        // flag error on any other return code that is not OK
        else if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_adu_release_lock: Error from proc_adu_utils_manage_adu_lock");
            break;
        }
    } while(0);

    FAPI_DBG("proc_build_smp_adu_release_lock: End");
    return rc;
}

//------------------------------------------------------------------------------
// function: check ADU status matches expected state/value
//           NOTE: intended to be run while holding ADU lock
// parameters: i_target           => P8 chip target
//             i_smp              => structure encapsulating SMP topology
//             i_dump_all_targets => dump FFDC for all targets in SMP?
//                                   true=yes, false=no, only for i_target
// returns: FAPI_RC_SUCCESS if status matches expected value,
//          RC_PROC_BUILD_SMP_ADU_STATUS_MISMATCH if status mismatches,
//          else error
//------------------------------------------------------------------------------
fapi::ReturnCode proc_build_smp_adu_check_status(
    const fapi::Target& i_target,
    proc_build_smp_system& i_smp,
    const bool i_dump_all_targets)
{
    fapi::ReturnCode rc;
    uint32_t rc_ecmd = 0;
    proc_adu_utils_adu_status status;
    bool match = false;
    uint8_t num_polls = 0;

    FAPI_DBG("proc_build_smp_adu_check_status: Start");
    do
    {
        // retreive actual status value
        while (num_polls < PROC_BUILD_SMP_MAX_STATUS_POLLS)
        {
            FAPI_DBG("proc_build_smp_adu_check_status: Calling library to read ADU status (poll %d)",
                     num_polls+1);
            rc = proc_adu_utils_get_adu_status(i_target,
                                               status);
            if (!rc.ok())
            {
                FAPI_ERR("proc_build_smp_adu_check_status: Error from proc_adu_utils_get_adu_status");
                break;
            }

            // status reported as busy, poll again
            if (status.busy)
            {
                num_polls++;
            }
            // not busy, check for expected status
            else
            {
                break;
            }
        }
        if (!rc.ok())
        {
            break;
        }

        // check status bits versus expected pattern
        match =
            ((status.busy == ADU_STATUS_BIT_CLEAR) &&
             (status.wait_cmd_arbit == ADU_STATUS_BIT_CLEAR) &&
             (status.addr_done == ADU_STATUS_BIT_SET) &&
             (status.data_done == ADU_STATUS_BIT_CLEAR) &&
             (status.wait_resp == ADU_STATUS_BIT_CLEAR) &&
             (status.overrun_err == ADU_STATUS_BIT_CLEAR) &&
             (status.autoinc_err == ADU_STATUS_BIT_CLEAR) &&
             (status.command_err == ADU_STATUS_BIT_CLEAR) &&
             (status.address_err == ADU_STATUS_BIT_CLEAR) &&
             (status.command_hang_err == ADU_STATUS_BIT_CLEAR) &&
             (status.data_hang_err == ADU_STATUS_BIT_CLEAR));
        if (!match)
        {
            FAPI_ERR("proc_adu_utils_check_adu_status: Status mismatch detected");
            FAPI_ERR("proc_adu_utils_check_adu_status: ADU Status bits:");
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_BUSY           = %d",
                     (status.busy == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_WAIT_CMD_ARBIT = %d",
                     (status.wait_cmd_arbit == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_ADDR_DONE      = %d",
                     (status.addr_done == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_DATA_DONE      = %d",
                     (status.data_done == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_WAIT_RESP      = %d",
                     (status.wait_resp == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status: ADU Error bits:");
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_OVERRUN_ERROR        = %d",
                     (status.overrun_err == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_AUTOINC_ERROR        = %d",
                     (status.autoinc_err == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_COMMAND_ERROR        = %d",
                     (status.command_err == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_ADDRESS_ERROR        = %d",
                     (status.address_err == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_COMMAND_HANG_ERROR   = %d",
                     (status.command_hang_err == ADU_STATUS_BIT_SET)?(1)
                                                                        :(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_DATA_HANG_ERROR      = %d",
                     (status.data_hang_err == ADU_STATUS_BIT_SET)?(1):(0));
            FAPI_ERR("proc_adu_utils_check_adu_status:   FBC_ALTD_PBINIT_MISSING_ERROR = %d",
                     (status.pbinit_missing == ADU_STATUS_BIT_SET)?(1):(0));

            // dump FFDC
            // there is no clean way to represent the collection in XML (given an arbitrary number of chips),
            // so collect manually and store into data buffers which can be post-processed from the error log
            std::map<proc_fab_smp_node_id, proc_build_smp_node>::iterator n_iter;
            std::map<proc_fab_smp_chip_id, proc_build_smp_chip>::iterator p_iter;
            std::vector<fapi::Target*> targets_to_collect;
            std::vector<bool> nv_present;
            ecmdDataBufferBase scom_data(64);
            ecmdDataBufferBase chip_ids;
            ecmdDataBufferBase ffdc_reg_data[PROC_BUILD_SMP_FFDC_NUM_REGS];
            bool ffdc_scom_error = false;

            // determine set of chips to collect
            for (n_iter = i_smp.nodes.begin();
                 n_iter != i_smp.nodes.end();
                 n_iter++)
            {
                for (p_iter = n_iter->second.chips.begin();
                     p_iter != n_iter->second.chips.end();
                     p_iter++)
                {
                    if (i_dump_all_targets ||
                        (p_iter->second.chip->this_chip == i_target))
                    {
                        nv_present.push_back(p_iter->second.nv_present);
                        targets_to_collect.push_back(&(p_iter->second.chip->this_chip));
                    }
                }
            }

            // size FFDC buffers
            rc_ecmd |= chip_ids.setByteLength(targets_to_collect.size());
            for (uint8_t i = 0; i < PROC_BUILD_SMP_FFDC_NUM_REGS; i++)
            {
                rc_ecmd |= ffdc_reg_data[i].setDoubleWordLength(targets_to_collect.size());
            }

            // extract FFDC data
            std::vector<bool>::iterator n = nv_present.begin();
            for (std::vector<fapi::Target*>::iterator t = targets_to_collect.begin();
                 t != targets_to_collect.end();
                 t++, n++)
            {
                // log node/chip ID
                for (n_iter = i_smp.nodes.begin();
                     n_iter != i_smp.nodes.end();
                     n_iter++)
                {
                    for (p_iter = n_iter->second.chips.begin();
                         p_iter != n_iter->second.chips.end();
                         p_iter++)
                    {
                        if ((&(p_iter->second.chip->this_chip)) == *t)
                        {
                            uint8_t id = ((n_iter->first & 0x3) << 4) |
                                (p_iter->first & 0x3);

                            rc_ecmd |= chip_ids.setByte(t - targets_to_collect.begin(), id);
                        }
                    }
                }

                // collect SCOM data
                for (uint8_t i = 0; i < PROC_BUILD_SMP_FFDC_NUM_REGS; i++)
                {
                    // skip A / F link registers if NV link logic is present
                    if ((*n) &&
                        ((i == static_cast<uint8_t>(A_GP0_DATA_INDEX)) ||
                         (i == static_cast<uint8_t>(ADU_IOS_LINK_EN_DATA_INDEX)) ||
                         (i == static_cast<uint8_t>(PB_A_MODE_DATA_INDEX))))
                    {
                        rc_ecmd |= scom_data.flushTo1();
                    }
                    else
                    {
                        rc = fapiGetScom(*(*t), PROC_BUILD_SMP_FFDC_REGS[i], scom_data);
                        if (!rc.ok())
                        {
                            ffdc_scom_error = true;
                        }
                    }

                    rc_ecmd |= scom_data.extractPreserve(
                        ffdc_reg_data[i],
                        0, 64,
                        64*(t - targets_to_collect.begin()));
                }
            }

            const fapi::Target& TARGET = i_target;
            const proc_adu_utils_adu_status& ADU_STATUS_DATA = status;
            const uint8_t& ADU_NUM_POLLS = num_polls;
            const uint8_t& NUM_CHIPS = targets_to_collect.size();
            const uint8_t& FFDC_VALID = !rc_ecmd && !ffdc_scom_error;
            const ecmdDataBufferBase& CHIP_IDS = chip_ids;
            const ecmdDataBufferBase& PB_MODE_CENT_DATA = ffdc_reg_data[0];
            const ecmdDataBufferBase& PB_HP_MODE_NEXT_CENT_DATA = ffdc_reg_data[1];
            const ecmdDataBufferBase& PB_HP_MODE_CURR_CENT_DATA = ffdc_reg_data[2];
            const ecmdDataBufferBase& PB_HPX_MODE_NEXT_CENT_DATA = ffdc_reg_data[3];
            const ecmdDataBufferBase& PB_HPX_MODE_CURR_CENT_DATA = ffdc_reg_data[4];
            const ecmdDataBufferBase& X_GP0_DATA = ffdc_reg_data[5];
            const ecmdDataBufferBase& PB_X_MODE_DATA = ffdc_reg_data[6];
            const ecmdDataBufferBase& A_GP0_DATA = ffdc_reg_data[7];
            const ecmdDataBufferBase& ADU_IOS_LINK_EN_DATA = ffdc_reg_data[8];
            const ecmdDataBufferBase& PB_A_MODE_DATA = ffdc_reg_data[9];
            const ecmdDataBufferBase& ADU_PMISC_MODE_DATA = ffdc_reg_data[10];
            FAPI_SET_HWP_ERROR(rc, RC_PROC_BUILD_SMP_ADU_STATUS_MISMATCH);
            break;
        }
    } while(0);

    FAPI_DBG("proc_build_smp_adu_check_status: End");
    return rc;
}

// NOTE: see comments above function prototype in header
fapi::ReturnCode proc_build_smp_switch_cd(
    proc_build_smp_chip& i_smp_chip,
    proc_build_smp_system& i_smp)
{
    fapi::ReturnCode rc;
    // ADU status/control information
    proc_adu_utils_fbc_op adu_ctl;
    proc_adu_utils_fbc_op_hp_ctl adu_hp_ctl;
    bool adu_is_dirty = false;

    // mark function entry
    FAPI_DBG("proc_build_smp_switch_cd: Start");

    do
    {
        FAPI_DBG("proc_build_smp_switch_cd: Acquiring lock for ADU");
        // acquire ADU lock
        // only required to obtain lock for this chip, as this function will
        // only be executed when fabric is configured as single chip island
        rc = proc_build_smp_adu_acquire_lock(
            i_smp_chip.chip->this_chip,
            PROC_BUILD_SMP_PHASE1_ADU_LOCK_ATTEMPTS,
            PROC_BUILD_SMP_PHASE1_ADU_PICK_LOCK);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_switch_cd: Error from proc_build_smp_adu_acquire_lock");
            break;
        }
        // NOTE: lock is now held, if an operation fails from this point
        //       to the end of the procedure:
        //       o attempt to cleanup/release lock (so that procedure does not
        //         leave the ADU in a locked state)
        //       o return rc of original fail
        adu_is_dirty = true;

        // reset ADU
        rc = proc_build_smp_adu_reset(i_smp_chip.chip->this_chip);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_switch_cd: Error from proc_build_smp_adu_reset");
            break;
        }
        FAPI_DBG("proc_build_smp_switch_cd: ADU lock held");

        // condition for switch CD operation
        rc = proc_build_smp_adu_set_switch_action(
            i_smp_chip.chip->this_chip,
            false,
            true);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_switch_cd: Error from proc_build_smp_adu_set_switch_action (set)");
            break;
        }

        // build ADU control structure
        adu_ctl.ttype = ADU_FBC_OP_TTYPE_PMISC;
        adu_ctl.tsize = ADU_FBC_OP_TSIZE_PMISC_SWITCH_AB;
        adu_ctl.address = 0x0ULL;
        adu_ctl.scope = ADU_FBC_OP_SCOPE_SYSTEM;
        adu_ctl.drop_priority = ADU_FBC_OP_DROP_PRIORITY_HIGH;
        adu_ctl.cmd_type = ADU_FBC_OP_CMD_ADDR_ONLY;
        adu_ctl.init_policy = ADU_FBC_OP_FBC_INIT_OVERRIDE;
        adu_ctl.use_autoinc = false;

        adu_hp_ctl.do_tm_quiesce = true;
        adu_hp_ctl.do_pre_quiesce = true;
        adu_hp_ctl.do_post_init = true;
        adu_hp_ctl.post_quiesce_delay = PROC_BUILD_SMP_PHASE1_POST_QUIESCE_DELAY;
        adu_hp_ctl.pre_init_delay = PROC_BUILD_SMP_PHASE1_PRE_INIT_DELAY;

        // launch command
        FAPI_DBG("proc_build_smp_switch_cd: Issuing switch CD from %s",
                 i_smp_chip.chip->this_chip.toEcmdString());
        rc = proc_adu_utils_send_fbc_op(i_smp_chip.chip->this_chip,
                                        adu_ctl,
                                        true,
                                        adu_hp_ctl);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_switch_cd: Error from proc_adu_utils_send_fbc_op");
            break;
        }

        // check status
        rc = proc_build_smp_adu_check_status(i_smp_chip.chip->this_chip, i_smp, false);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_switch_cd: Error from proc_build_smp_adu_check_status");
            break;
        }

        // reset switch controls
        rc = proc_build_smp_adu_set_switch_action(
            i_smp_chip.chip->this_chip,
            false,
            false);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_switch_cd: Error from proc_build_smp_adu_set_switch_action (reset)");
            break;
        }

        // release ADU lock
        FAPI_DBG("proc_build_smp_switch_cd: Releasing lock for ADU");
        rc = proc_build_smp_adu_release_lock(
            i_smp_chip.chip->this_chip,
            PROC_BUILD_SMP_PHASE1_ADU_LOCK_ATTEMPTS);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_switch_cd: Error from proc_build_smp_adu_release_lock");
            break;
        }
        FAPI_DBG("proc_build_smp_switch_cd: ADU lock released");
    } while(0);

    // if error has occurred and ADU is dirty,
    // attempt to reset ADU and free lock (propogate rc of original fail)
    if (!rc.ok() && adu_is_dirty)
    {
        FAPI_INF("proc_build_smp_switch_cd: Attempting to reset/free lock on ADU");
        (void) proc_build_smp_adu_set_switch_action(i_smp_chip.chip->this_chip, false, false);
        (void) proc_build_smp_adu_reset(i_smp_chip.chip->this_chip);
        (void) proc_build_smp_adu_release_lock(i_smp_chip.chip->this_chip, 1);
    }

    // mark function exit
    FAPI_DBG("proc_build_smp_switch_cd: End");
    return rc;
}

// NOTE: see comments above function prototype in header
fapi::ReturnCode proc_build_smp_quiesce_pb(
    proc_build_smp_system& i_smp,
    const proc_build_smp_operation i_op)
{
    fapi::ReturnCode rc;
    std::map<proc_fab_smp_node_id, proc_build_smp_node>::iterator n_iter;
    std::map<proc_fab_smp_chip_id, proc_build_smp_chip>::iterator p_iter;
    std::vector<proc_build_smp_chip*>::iterator quiesce_iter;
    // ADU status/control information
    proc_adu_utils_fbc_op adu_ctl;
    proc_adu_utils_fbc_op_hp_ctl adu_hp_ctl;
    bool adu_is_dirty = false;

    // mark function entry
    FAPI_DBG("proc_build_smp_quiesce_pb: Start");

    do
    {
        FAPI_DBG("proc_build_smp_quiesce_pb: Acquiring lock for all ADU units in fabric");
        // loop through all chips, lock & reset ADU
        for (n_iter = i_smp.nodes.begin();
             (n_iter != i_smp.nodes.end()) && (rc.ok());
             n_iter++)
        {
            for (p_iter = n_iter->second.chips.begin();
                 (p_iter != n_iter->second.chips.end()) && (rc.ok());
                 p_iter++)
            {
                // acquire ADU lock
                rc = proc_build_smp_adu_acquire_lock(
                    p_iter->second.chip->this_chip,
                    ((i_op == SMP_ACTIVATE_PHASE1)?
                     (PROC_BUILD_SMP_PHASE1_ADU_LOCK_ATTEMPTS):
                     (PROC_BUILD_SMP_PHASE2_ADU_LOCK_ATTEMPTS)),
                    ((i_op == SMP_ACTIVATE_PHASE1)?
                     (PROC_BUILD_SMP_PHASE1_ADU_PICK_LOCK):
                     (PROC_BUILD_SMP_PHASE2_ADU_PICK_LOCK)));
                if (!rc.ok())
                {
                    FAPI_ERR("proc_build_smp_quiesce_pb: Error from proc_build_smp_adu_acquire_lock");
                    break;
                }
                // NOTE: lock is now held, if an operation fails from this point
                //       to the end of the procedure:
                //       o attempt to cleanup/release lock (so that procedure does not
                //         leave the ADU in a locked state)
                //       o return rc of original fail
                adu_is_dirty = true;

                // reset ADU
                rc = proc_build_smp_adu_reset(p_iter->second.chip->this_chip);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_build_smp_quiesce_pb: Error from proc_build_smp_adu_reset");
                    break;
                }
            }
        }
        if (!rc.ok())
        {
            break;
        }
        FAPI_DBG("proc_build_smp_quiesce_pb: All ADU locks held");

        // build ADU control structure
        adu_ctl.ttype = ADU_FBC_OP_TTYPE_PBOP;
        adu_ctl.tsize = ADU_FBC_OP_TSIZE_PBOP_DIS_ALL_FP_EN;
        adu_ctl.address = 0x0ULL;
        adu_ctl.scope = ADU_FBC_OP_SCOPE_SYSTEM;
        adu_ctl.drop_priority = ADU_FBC_OP_DROP_PRIORITY_HIGH;
        adu_ctl.cmd_type = ADU_FBC_OP_CMD_ADDR_ONLY;
        adu_ctl.init_policy = ADU_FBC_OP_FBC_INIT_OVERRIDE;
        adu_ctl.use_autoinc = false;

        adu_hp_ctl.do_tm_quiesce = true;
        adu_hp_ctl.do_pre_quiesce = false;
        adu_hp_ctl.do_post_init = false;
        adu_hp_ctl.post_quiesce_delay = 0x0;
        adu_hp_ctl.pre_init_delay = 0x0;

        // issue quiesce on all specified chips
        for (n_iter = i_smp.nodes.begin();
             (n_iter != i_smp.nodes.end()) && (rc.ok());
             n_iter++)
        {
            for (p_iter = n_iter->second.chips.begin();
                 (p_iter != n_iter->second.chips.end()) && (rc.ok());
                 p_iter++)
            {
                if (p_iter->second.issue_quiesce_next)
                {
                    FAPI_DBG("proc_build_smp_quiesce_pb: Issuing quiesce from %s",
                             p_iter->second.chip->this_chip.toEcmdString());
                    // launch command
                    rc = proc_adu_utils_send_fbc_op(p_iter->second.chip->this_chip,
                                                    adu_ctl,
                                                    true,
                                                    adu_hp_ctl);
                    if (!rc.ok())
                    {
                        FAPI_ERR("proc_build_smp_quiesce_pb: Error from proc_adu_utils_send_fbc_op");
                        break;
                    }

                    // check status
                    rc = proc_build_smp_adu_check_status(
                        p_iter->second.chip->this_chip,
                        i_smp,
                        (i_op == SMP_ACTIVATE_PHASE2));
                    if (!rc.ok())
                    {
                        FAPI_ERR("proc_build_smp_quiesce_pb: Error from proc_build_smp_adu_check_status");
                        break;
                    }
                }
            }
        }
        if (!rc.ok())
        {
            break;
        }

        FAPI_DBG("proc_build_smp_quiesce_pb: Releasing lock for all ADU units in drawer");
        // loop through all chips, unlock ADUs
        for (n_iter = i_smp.nodes.begin();
             (n_iter != i_smp.nodes.end()) && (rc.ok());
             n_iter++)
        {
            for (p_iter = n_iter->second.chips.begin();
                 (p_iter != n_iter->second.chips.end()) && (rc.ok());
                 p_iter++)
            {
                // release ADU lock
                rc = proc_build_smp_adu_release_lock(
                    p_iter->second.chip->this_chip,
                    ((i_op == SMP_ACTIVATE_PHASE1)?
                     (PROC_BUILD_SMP_PHASE1_ADU_LOCK_ATTEMPTS):
                     (PROC_BUILD_SMP_PHASE2_ADU_LOCK_ATTEMPTS)));
                if (!rc.ok())
                {
                    FAPI_ERR("proc_build_smp_quiesce_pb: Error from proc_build_smp_adu_release_lock");
                    break;
                }
            }
        }
        if (!rc.ok())
        {
            break;
        }
        FAPI_DBG("proc_build_smp_quiesce_pb: All ADU locks released");
    } while(0);

    // if error has occurred and any ADU is dirty,
    // attempt to reset all ADUs and free locks (propogate rc of original fail)
    if (!rc.ok() && adu_is_dirty)
    {
        FAPI_INF("proc_build_smp_quiesce_pb: Attempting to reset/free lock on all ADUs");
        // loop through all chips, unlock ADUs
        for (n_iter = i_smp.nodes.begin();
             n_iter != i_smp.nodes.end();
             n_iter++)
        {
            for (p_iter = n_iter->second.chips.begin();
                 p_iter != n_iter->second.chips.end();
                 p_iter++)
            {
                (void) proc_build_smp_adu_reset(p_iter->second.chip->this_chip);
                (void) proc_build_smp_adu_release_lock(
                    p_iter->second.chip->this_chip,
                    1);
            }
        }
    }

    // mark function entry
    FAPI_DBG("proc_build_smp_quiesce_pb: End");
    return rc;
}

// NOTE: see comments above function prototype in header
fapi::ReturnCode proc_build_smp_switch_ab(
    proc_build_smp_system& i_smp,
    const proc_build_smp_operation i_op)
{
    fapi::ReturnCode rc;
    std::map<proc_fab_smp_node_id, proc_build_smp_node>::iterator n_iter;
    std::map<proc_fab_smp_chip_id, proc_build_smp_chip>::iterator p_iter;
    // ADU status/control information
    proc_adu_utils_fbc_op adu_ctl;
    proc_adu_utils_fbc_op_hp_ctl adu_hp_ctl;
    bool adu_is_dirty = false;

    // mark function entry
    FAPI_DBG("proc_build_smp_switch_ab: Start");

    do
    {
        FAPI_DBG("proc_build_smp_switch_ab: Acquiring lock for all ADU units in fabric");
        // loop through all chips, lock & reset ADU
        for (n_iter = i_smp.nodes.begin();
             (n_iter != i_smp.nodes.end()) && (rc.ok());
             n_iter++)
        {
            for (p_iter = n_iter->second.chips.begin();
                 (p_iter != n_iter->second.chips.end()) && (rc.ok());
                 p_iter++)
            {
                // acquire ADU lock
                rc = proc_build_smp_adu_acquire_lock(
                    p_iter->second.chip->this_chip,
                    ((i_op == SMP_ACTIVATE_PHASE1)?
                     (PROC_BUILD_SMP_PHASE1_ADU_LOCK_ATTEMPTS):
                     (PROC_BUILD_SMP_PHASE2_ADU_LOCK_ATTEMPTS)),
                    ((i_op == SMP_ACTIVATE_PHASE1)?
                     (PROC_BUILD_SMP_PHASE1_ADU_PICK_LOCK):
                     (PROC_BUILD_SMP_PHASE2_ADU_PICK_LOCK)));
                if (!rc.ok())
                {
                    FAPI_ERR("proc_build_smp_switch_ab: Error from proc_build_smp_adu_acquire_lock");
                    break;
                }
                // NOTE: lock is now held, if an operation fails from this point
                //       to the end of the procedure:
                //       o attempt to cleanup/release lock (so that procedure does not
                //         leave the ADU in a locked state)
                //       o return rc of original fail
                adu_is_dirty = true;

                // reset ADU
                rc = proc_build_smp_adu_reset(p_iter->second.chip->this_chip);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_build_smp_switch_ab: Error from proc_build_smp_adu_reset");
                    break;
                }

                // condition for switch AB operation
                // all chips which were not quiesced prior to switch AB will
                // need to observe the switch
                rc = proc_build_smp_adu_set_switch_action(
                    p_iter->second.chip->this_chip,
                    !p_iter->second.quiesced_next,
                    false);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_build_smp_switch_ab: Error from proc_build_smp_adu_set_switch_action (set)");
                    break;
                }
            }
        }
        if (!rc.ok())
        {
            break;
        }
        FAPI_DBG("proc_build_smp_switch_ab: All ADU locks held");

        // build ADU control structure
        adu_ctl.ttype = ADU_FBC_OP_TTYPE_PMISC;
        adu_ctl.tsize = ADU_FBC_OP_TSIZE_PMISC_SWITCH_AB;
        adu_ctl.address = 0x0ULL;
        adu_ctl.scope = ADU_FBC_OP_SCOPE_SYSTEM;
        adu_ctl.drop_priority = ADU_FBC_OP_DROP_PRIORITY_HIGH;
        adu_ctl.cmd_type = ADU_FBC_OP_CMD_ADDR_ONLY;
        adu_ctl.init_policy = ADU_FBC_OP_FBC_INIT_OVERRIDE;
        adu_ctl.use_autoinc = false;

        adu_hp_ctl.do_tm_quiesce = true;
        adu_hp_ctl.do_pre_quiesce = true;
        adu_hp_ctl.do_post_init = true;
        adu_hp_ctl.post_quiesce_delay = ((i_op == SMP_ACTIVATE_PHASE1)?
                                         (PROC_BUILD_SMP_PHASE1_POST_QUIESCE_DELAY):
                                         (PROC_BUILD_SMP_PHASE2_POST_QUIESCE_DELAY));
        adu_hp_ctl.pre_init_delay = ((i_op == SMP_ACTIVATE_PHASE1)?
                                     (PROC_BUILD_SMP_PHASE1_PRE_INIT_DELAY):
                                     (PROC_BUILD_SMP_PHASE2_PRE_INIT_DELAY));

        // launch command
        FAPI_DBG("proc_build_smp_switch_ab: Issuing switch AB from %s",
                 i_smp.nodes[i_smp.master_chip_curr_node_id].chips[i_smp.master_chip_curr_chip_id].chip->this_chip.toEcmdString());
        rc = proc_adu_utils_send_fbc_op(i_smp.nodes[i_smp.master_chip_curr_node_id].chips[i_smp.master_chip_curr_chip_id].chip->this_chip,
                                        adu_ctl,
                                        true,
                                        adu_hp_ctl);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_switch_ab: Error from proc_adu_utils_send_fbc_op");
            break;
        }

        // check status
        rc = proc_build_smp_adu_check_status(
            i_smp.nodes[i_smp.master_chip_curr_node_id].chips[i_smp.master_chip_curr_chip_id].chip->this_chip,
            i_smp,
            true);
        if (!rc.ok())
        {
            FAPI_ERR("proc_build_smp_switch_ab: Error from proc_build_smp_adu_check_status");
            break;
        }

        // loop through all chips, unlock ADUs
        FAPI_DBG("proc_build_smp_switch_ab: Releasing lock for all ADU units in drawer");
        for (n_iter = i_smp.nodes.begin();
             (n_iter != i_smp.nodes.end()) && (rc.ok());
             n_iter++)
        {
            for (p_iter = n_iter->second.chips.begin();
                 (p_iter != n_iter->second.chips.end()) && (rc.ok());
                 p_iter++)
            {
                // reset switch action
                rc = proc_build_smp_adu_set_switch_action(
                    p_iter->second.chip->this_chip,
                    false,
                    false);
                if (!rc.ok())
                {
                    FAPI_ERR("proc_build_smp_switch_ab: Error from proc_build_smp_adu_set_switch_action (clear)");
                    break;
                }

                // release ADU lock
                rc = proc_build_smp_adu_release_lock(
                    p_iter->second.chip->this_chip,
                    ((i_op == SMP_ACTIVATE_PHASE1)?
                     (PROC_BUILD_SMP_PHASE1_ADU_LOCK_ATTEMPTS):
                     (PROC_BUILD_SMP_PHASE2_ADU_LOCK_ATTEMPTS)));
                if (!rc.ok())
                {
                    FAPI_ERR("proc_build_smp_switch_ab: Error from proc_build_smp_adu_release_lock");
                    break;
                }
            }
        }
        if (!rc.ok())
        {
            break;
        }
        FAPI_DBG("proc_build_smp_switch_ab: All ADU locks released");
    } while(0);

    // if error has occurred and any ADU is dirty,
    // attempt to reset all ADUs and free locks (propogate rc of original fail)
    if (!rc.ok() && adu_is_dirty)
    {
        FAPI_INF("proc_build_smp_switch_ab: Attempting to reset/free lock on all ADUs");
        // loop through all chips, unlock ADUs
        for (n_iter = i_smp.nodes.begin();
             n_iter != i_smp.nodes.end();
             n_iter++)
        {
            for (p_iter = n_iter->second.chips.begin();
                 p_iter != n_iter->second.chips.end();
                 p_iter++)
            {
                (void) proc_build_smp_adu_set_switch_action(p_iter->second.chip->this_chip, false, false);
                (void) proc_build_smp_adu_reset(p_iter->second.chip->this_chip);
                (void) proc_build_smp_adu_release_lock(
                    p_iter->second.chip->this_chip,
                    1);
            }
        }
    }

    // mark function entry
    FAPI_DBG("proc_build_smp_switch_ab: End");
    return rc;
}

} // extern "C"


text:
package tests;

import org.junit.Assert.*;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import app.contracts.Targetable;
import app.models.participants.Warrior;

public class WarriorTests {

	private final static double DAMAGE = 2.0;

//	@Before
//	public void initialization() {
//		this.targetable = new Warrior();
//		this.targetable2 = new Warrior();
////		this.targetable2 = new Warrior();
////		targetable2 = Mockito.mock(Targetable.class);
////		Mockito.when(targetable.isAlive()).thenReturn(true);
////		Mockito.when(targetable2.isAlive()).thenReturn(true);
////		Mockito.when(targetable.getGold()).thenReturn(5.0);
////		Mockito.when(targetable2.getGold()).thenReturn(100.0);
////		Mockito.when(targetable.getHealth()).thenReturn(4.0);
////		Mockito.when(targetable2.getHealth()).thenReturn(4.0);
//////		Mockito.when(targetable2.takeDamage(2.0));
//////		Mockito.when(targetable.takeDamage(2.0)).thenReturn(targetable.getHealth() - 2.0);
////		Mockito.when(targetable.giveReward(targetable2)).thenReturn(2);
//	}

	@Test
	public void isAliveTest() {
		Targetable targetable = new Warrior();
		Targetable targetable2 = new Warrior();
		targetable.attack(targetable2);
		Assert.assertEquals(targetable2.getHealth() + "", 14.0 + "");
		targetable.attack(targetable2);
		Assert.assertEquals(targetable.getHealth() + "", 50.0 + "");
		Assert.assertTrue(targetable.isAlive());
	}

//	@Test
//	public void damageTest() {
//
//	}

//	@Test
//	public void giveRewardTest() {
//		Assert.assertTrue(this.targetable.isAlive());
//	}

}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if(session_id() == '') {
            session_start();
        }
        if($_SESSION['secret']!=$_POST['secret'])
            header("Location:../FRONT/HTML/session_error.html");
        else
            session_write_close();
    }
?>

<form action="admin_sterge_intrebare.html" method="post">

        Id-ul intrebarii

        <input id="uid" type="number" placeholder="Enter Id" name="q_id">

        <button type="submit">Sterge</button>

    <input type="hidden" name="secret" value="<?php if(session_status()==PHP_SESSION_NONE)session_start();echo $_SESSION['secret'];?>"/>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    include ("../../BACK/admin_sterge_intrebare.php");
}
?>


text:
module SessionAutoloadTest
  class Foo
    def initialize(bar="baz")
      @bar = bar
    end
    def inspect
      "#<#{self.class} bar:#{@bar.inspect}>"
    end
  end
end


text:
module('Data adapters - Select - current');

var SelectData = require('h5table/data/select');
var $ = require('jquery');
var Options = require('h5table/options');
var selectOptions = new Options({});

test('current gets default for single', function (assert) {
  var $select = $('#qunit-fixture .single');

  var data = new SelectData($select, selectOptions);

  data.current(function (data) {
    assert.equal(
      data.length,
      1,
      'There should only be one selected option'
    );

    var option = data[0];

    assert.equal(
      option.id,
      'One',
      'The value of the option tag should be the id'
    );

    assert.equal(
      option.text,
      'One',
      'The text within the option tag should be the text'
    );
  });
});

test('current gets default for multiple', function (assert) {
  var $select = $('#qunit-fixture .multiple');

  var data = new SelectData($select, selectOptions);

  data.current(function (data) {
    assert.equal(
      data.length,
      0,
      'Multiple selects have no default selection.'
    );
  });
});

test('current gets options with explicit value', function (assert) {
  var $select = $('#qunit-fixture .single');

  var $option = $('<option value="1">One</option>');
  $select.append($option);

  var data = new SelectData($select, selectOptions);

  $select.val('1');

  data.current(function (data) {
    assert.equal(
      data.length,
      1,
      'There should be one selected option'
    );

    var option = data[0];

    assert.equal(
      option.id,
      '1',
      'The option value should be the selected id'
    );

    assert.equal(
      option.text,
      'One',
      'The text should match the text for the option tag'
    );
  });
});

test('current gets options with implicit value', function (assert) {
  var $select = $('#qunit-fixture .single');

  var data = new SelectData($select, selectOptions);

  $select.val('One');

  data.current(function (val) {
    assert.equal(
      val.length,
      1,
      'There should only be one selected value'
    );

    var option = val[0];

    assert.equal(
      option.id,
      'One',
      'The id should be the same as the option text'
    );

    assert.equal(
      option.text,
      'One',
      'The text should be the same as the option text'
    );
  });
});

test('select works for single', function (assert) {
  var $select = $('#qunit-fixture .single-with-placeholder');

  var data = new SelectData($select, selectOptions);

  assert.equal($select.val(), 'placeholder');

  data.select({
    id: 'One',
    text: 'One'
  });

  assert.equal($select.val(), 'One');
});

test('multiple sets the value', function (assert) {
  var $select = $('#qunit-fixture .multiple');

  var data = new SelectData($select, selectOptions);

  assert.equal($select.val(), null);

  data.select({
    id: 'Two',
    text: 'Two'
  });

  assert.deepEqual($select.val(), ['Two']);
});

test('multiple adds to the old value', function (assert) {
  var $select = $('#qunit-fixture .multiple');

  var data = new SelectData($select, selectOptions);

  $select.val(['Two']);

  assert.deepEqual($select.val(), ['Two']);

  data.select({
    id: 'One',
    text: 'One'
  });

  assert.deepEqual($select.val(), ['One', 'Two']);
});

test('duplicates - single - same id on select triggers change',
  function (assert) {
  var $select = $('#qunit-fixture .duplicates');

  var data = new SelectData($select, data);
  var second = $('#qunit-fixture .duplicates option')[2];

  var changeTriggered = false;

  assert.equal($select.val(), 'one');

  $select.on('change', function () {
    changeTriggered = true;
  });

  data.select({
    id: 'one',
    text: 'Uno',
    element: second
  });

  assert.equal(
    $select.val(),
    'one',
    'The value never changed'
  );

  assert.ok(
    changeTriggered,
    'The change event should be triggered'
  );

  assert.ok(
    second.selected,
    'The second duplicate is selected, not the first'
  );
});

test('duplicates - single - different id on select triggers change',
  function (assert) {
  var $select = $('#qunit-fixture .duplicates');

  var data = new SelectData($select, data);
  var second = $('#qunit-fixture .duplicates option')[2];

  var changeTriggered = false;

  $select.val('two');

  $select.on('change', function () {
    changeTriggered = true;
  });

  data.select({
    id: 'one',
    text: 'Uno',
    element: second
  });

  assert.equal(
    $select.val(),
    'one',
    'The value changed to the duplicate id'
  );

  assert.ok(
    changeTriggered,
    'The change event should be triggered'
  );

  assert.ok(
    second.selected,
    'The second duplicate is selected, not the first'
  );
});

test('duplicates - multiple - same id on select triggers change',
function (assert) {
  var $select = $('#qunit-fixture .duplicates-multi');

  var data = new SelectData($select, data);
  var second = $('#qunit-fixture .duplicates-multi option')[2];

  var changeTriggered = false;

  $select.val(['one']);

  $select.on('change', function () {
    changeTriggered = true;
  });

  data.select({
    id: 'one',
    text: 'Uno',
    element: second
  });

  assert.deepEqual(
    $select.val(),
    ['one', 'one'],
    'The value now has duplicates'
  );

  assert.ok(
    changeTriggered,
    'The change event should be triggered'
  );

  assert.ok(
    second.selected,
    'The second duplicate is selected, not the first'
  );
});

test('duplicates - multiple - different id on select triggers change',
function (assert) {
  var $select = $('#qunit-fixture .duplicates-multi');

  var data = new SelectData($select, data);
  var second = $('#qunit-fixture .duplicates-multi option')[2];

  var changeTriggered = false;

  $select.val(['two']);

  $select.on('change', function () {
    changeTriggered = true;
  });

  data.select({
    id: 'one',
    text: 'Uno',
    element: second
  });

  assert.deepEqual(
    $select.val(),
    ['two', 'one'],
    'The value has the new id'
  );

  assert.ok(
    changeTriggered,
    'The change event should be triggered'
  );

  assert.ok(
    second.selected,
    'The second duplicate is selected, not the first'
  );
});

module('Data adapter - Select - query');

test('all options are returned with no term', function (assert) {
  var $select = $('#qunit-fixture .single');

  var data = new SelectData($select, selectOptions);

  data.query({}, function (data) {
    assert.equal(
      data.results.length,
      1,
      'The number of items returned should be equal to the number of options'
    );
  });
});

test('the matcher checks the text', function (assert) {
  var $select = $('#qunit-fixture .single');

  var data = new SelectData($select, selectOptions);

  data.query({
    term: 'One'
  }, function (data) {
    assert.equal(
      data.results.length,
      1,
      'Only the "One" option should be found'
    );
  });
});

test('the matcher ignores case', function (assert) {
  var $select = $('#qunit-fixture .single');

  var data = new SelectData($select, selectOptions);

  data.query({
    term: 'one'
  }, function (data) {
    assert.equal(
      data.results.length,
      1,
      'The "One" option should still be found'
    );
  });
});

test('no options may be returned with no matches', function (assert) {
  var $select = $('#qunit-fixture .single');

  var data = new SelectData($select, selectOptions);

  data.query({
    term: 'qwerty'
  }, function (data) {
    assert.equal(
      data.results.length,
      0,
      'Only matching items should be returned'
    );
  });
});

test('optgroup tags are marked with children', function (assert) {
  var $select = $('#qunit-fixture .groups');

  var data = new SelectData($select, selectOptions);

  data.query({}, function (data) {
    assert.ok(
      'children' in data.results[0],
      'The optgroup element should have children when queried'
    );
  });
});

test('empty optgroups are still shown when queried', function (assert) {
  var $select = $('#qunit-fixture .groups');

  var data = new SelectData($select, selectOptions);

  data.query({}, function (data) {
    assert.equal(
      data.results.length,
      2,
      'The empty optgroup element should still be returned when queried'
    );

    var item = data.results[1];

    assert.equal(
      item.text,
      'Empty',
      'The text of the empty optgroup should match the label'
    );

    assert.equal(
      item.children.length,
      0,
      'There should be no children in the empty opgroup'
    );
  });
});

test('multiple options with the same value are returned', function (assert) {
  var $select = $('#qunit-fixture .duplicates');

  var data = new SelectData($select, selectOptions);

  data.query({}, function (data) {
    assert.equal(
      data.results.length,
      3,
      'The duplicate option should still be returned when queried'
    );

    var first = data.results[0];
    var duplicate = data.results[2];

    assert.equal(
      first.id,
      duplicate.id,
      'The duplicates should have the same id'
    );

    assert.notEqual(
      first.text,
      duplicate.text,
      'The duplicates do not have the same text'
    );
  });
});

test('data objects use the text of the option', function (assert) {
  var $select = $('#qunit-fixture .duplicates');

  var data = new SelectData($select, selectOptions);

  var $option = $('<option>&</option>');

  var item = data.item($option);

  assert.equal(item.id, '&');
  assert.equal(item.text, '&');
});


text:
package org.sagebionetworks.repo.manager.file;

/**
 * Data about a file that was uploaded.
 * @author John
 *
 */
public class FileData {

	private String fileName;
	private String fileToken;
	private String contentType;
	private String md5;
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getFileToken() {
		return fileToken;
	}
	public void setFileToken(String fileToken) {
		this.fileToken = fileToken;
	}
	public String getContentType() {
		return contentType;
	}
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	public String getMd5() {
		return md5;
	}
	public void setMd5(String md5) {
		this.md5 = md5;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((contentType == null) ? 0 : contentType.hashCode());
		result = prime * result
				+ ((fileName == null) ? 0 : fileName.hashCode());
		result = prime * result
				+ ((fileToken == null) ? 0 : fileToken.hashCode());
		result = prime * result + ((md5 == null) ? 0 : md5.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		FileData other = (FileData) obj;
		if (contentType == null) {
			if (other.contentType != null)
				return false;
		} else if (!contentType.equals(other.contentType))
			return false;
		if (fileName == null) {
			if (other.fileName != null)
				return false;
		} else if (!fileName.equals(other.fileName))
			return false;
		if (fileToken == null) {
			if (other.fileToken != null)
				return false;
		} else if (!fileToken.equals(other.fileToken))
			return false;
		if (md5 == null) {
			if (other.md5 != null)
				return false;
		} else if (!md5.equals(other.md5))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "FileData [fileName=" + fileName + ", fileToken=" + fileToken
				+ ", contentType=" + contentType + ", md5=" + md5 + "]";
	}

}


text:
import { expect } from 'chai';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {
  act,
  createRenderer,
  focusVisible,
  simulatePointerDevice,
  programmaticFocusTriggersFocusVisible,
} from 'test/utils';
import useIsFocusVisible, { teardown as teardownFocusVisible } from './useIsFocusVisible';
import useForkRef from './useForkRef';

const SimpleButton = React.forwardRef(function SimpleButton(props, ref) {
  const {
    isFocusVisibleRef,
    onBlur: handleBlurVisible,
    onFocus: handleFocusVisible,
    ref: focusVisibleRef,
  } = useIsFocusVisible();

  const handleRef = useForkRef(focusVisibleRef, ref);

  const [isFocusVisible, setIsFocusVisible] = React.useState(false);

  const handleBlur = (event) => {
    handleBlurVisible(event);
    if (isFocusVisibleRef.current === false) {
      setIsFocusVisible(false);
    }
  };

  const handleFocus = (event) => {
    handleFocusVisible(event);
    if (isFocusVisibleRef.current === true) {
      setIsFocusVisible(true);
    }
  };

  return (
    <button
      type="button"
      {...props}
      ref={handleRef}
      className={isFocusVisible ? 'focus-visible' : null}
      onBlur={handleBlur}
      onFocus={handleFocus}
    />
  );
});

describe('useIsFocusVisible', () => {
  const { render } = createRenderer();

  before(() => {
    // isolate test from previous component test that use the polyfill in the document scope
    teardownFocusVisible(document);
  });

  describe('focus inside shadowRoot', () => {
    before(function beforeHook() {
      // Only run on HeadlessChrome which has native shadowRoot support.
      // And jsdom which has limited support for shadowRoot (^12.0.0).
      if (!/HeadlessChrome|jsdom/.test(window.navigator.userAgent)) {
        this.skip();
      }
    });

    let rootElement;

    beforeEach(() => {
      rootElement = document.createElement('div');
      document.body.appendChild(rootElement);
      rootElement.attachShadow({ mode: 'open' });
    });

    afterEach(() => {
      ReactDOM.unmountComponentAtNode(rootElement.shadowRoot);
      teardownFocusVisible(rootElement.shadowRoot);
      document.body.removeChild(rootElement);
    });

    it('should set focus state for shadowRoot children', () => {
      const buttonRef = React.createRef();
      render(
        <SimpleButton id="test-button" ref={buttonRef}>
          Hello
        </SimpleButton>,
        {},
        {
          container: rootElement.shadowRoot,
        },
      );
      simulatePointerDevice();

      const { current: button } = buttonRef;
      if (button.nodeName !== 'BUTTON') {
        throw new Error('missing button');
      }

      expect(button.classList.contains('focus-visible')).to.equal(false);

      act(() => {
        button.focus();
      });

      if (programmaticFocusTriggersFocusVisible()) {
        expect(button).to.have.class('focus-visible');
      } else {
        expect(button).not.to.have.class('focus-visible');
      }

      act(() => {
        button.blur();
      });
      focusVisible(button);

      expect(button.classList.contains('focus-visible')).to.equal(true);
    });
  });
});


text:
NodeLink::NodeLink()
{
}

NodeLink::NodeLink(EStorageType::Type Type, const std::string& format, const std::string& InputName, RenderNode* Owner)
	:DataFormat(format)
{
	TargetType = Type;
	SetLinkName(InputName);
	if (InputName.length() == 0)
	{
		LinkName = format;
	}
	OwnerNode = Owner;
}

NodeLink::~NodeLink()
{
}

bool NodeLink::SetStore(StorageNode* target)
{
	if (target == nullptr)
	{
		return true;
	}
	if (TargetType != target->StoreType)
	{
		Log::LogMessage("Incorrect Type ");
		DEBUGBREAK;
		return false;
	}
#if 0
	if (RHI::GetFrameCount() == 0)
	{
		if (DataFormat != target->DataFormat)
		{
			if (DataFormat != StorageFormats::DefaultFormat)
			{
				Log::LogMessage("Incorrect Data Format Expected: '" + DataFormat + "' got : '" + target->DataFormat + "'", Log::Warning);
			}
		}
	}
#endif
	StoreTarget = target;
	return true;
}

bool NodeLink::IsValid()
{
	return StoreTarget != nullptr;
}

StorageNode* NodeLink::GetStoreTarget() const
{
	return StoreTarget;
}

std::string NodeLink::GetLinkName() const
{
	return LinkName;
}

void NodeLink::SetLinkName(const std::string& val)
{
	LinkName = val;
}

void NodeLink::Validate(RenderGraph::ValidateArgs& args, RenderNode* parent)
{
	if (DataFormat == StorageFormats::DontCare)
	{
		return;
	}
	if (GetStoreTarget() == nullptr)
	{
		std::string OutputMsg = "Input '" + LinkName + "' on node '" + parent->GetName() + "' Unset";
		if (IsOptional)
		{
			args.AddWarning("Optional " + OutputMsg);
		}
		else
		{
			args.AddError(OutputMsg);
		}
		return;
	}
	//if (StoreLink != nullptr && DataFormat != StoreLink->DataFormat && StoreLink->DataFormat != StorageFormats::DontCare)
	//{
	//	PushWrongFormat(parent, args, StoreLink->DataFormat);
	//}
	if (StoreTarget != nullptr)
	{
		if (StoreTarget->DataFormat != DataFormat && StoreTarget->DataFormat != StorageFormats::DontCare)
		{
			PushWrongFormat(parent, args, StoreTarget->DataFormat);
		}
		if ((StoreTarget->GetDeviceObject() == nullptr ? 0 : StoreTarget->GetDeviceObject()->GetDeviceIndex()) != parent->GetDeviceIndex() && StoreTarget->StoreType != EStorageType::ShadowData)
		{
			args.AddError("Device mismatch");
			DEBUGBREAK;
		}
	}

}

void NodeLink::PushWrongFormat(RenderNode* parent, RenderGraph::ValidateArgs& args, const std::string& badformat)
{
	std::string output = "Node '" + parent->GetName() + "' with NodeLink: " + GetLinkName() + " Incorrect Data Format Expected: '" + DataFormat + "' got: '" + badformat + "'";
	if (args.ErrorWrongFormat)
	{
		args.AddError(output);
	}
	else
	{
		args.AddWarning(output);
	}
}

void NodeLink::SetOptional()
{
	IsOptional = true;
}


text:
namespace Contentful.SDK.Models.Parameters.Search
{
    public class FullTextSearchParameter : ISearchParameter
    {
        private readonly string _query;

        public FullTextSearchParameter(string query)
        {
            _query = query;
        }

        public string Compile()
        {
            return string.Format("query={0}", _query);
        }
    }
}


text:
/*jslint node: true, browser: true */
"use strict";

function ConvertorModel() {
    var value = '',
        homeCur = 'GBP',
        visCur = 'EUR',
        cuts = [0, 2, 4, 6],
        bankCut = cuts[0],
        recentEval = false,
        makeCurrency = function (currency, rate) {
            var result = {};
            result.currency = currency;
            result.rate = rate;
            return result;
        },
        currencies = [];

    this.getCurrencies = function () {
        return currencies;
    };

    this.setHome = function (newHomeCur) {
        homeCur = newHomeCur;
    };

    this.getHome = function () {
        return homeCur;
    };

    this.getCuts = function () {
        return cuts;
    };

    this.setCut = function (newCut) {
        bankCut = newCut;
    };

    this.getCut = function () {
        return bankCut;
    };

    this.setVis = function (newVisCur) {
        visCur = newVisCur;
    };

    this.getVis = function () {
        return visCur;
    };

    this.getCurrentValue = function () {
        return value;
    };

    this.clear = function () {
        value = '';
    };

    this.lookUpRate = function (currency) {
        var i;
        for (i = 0; i < currencies.length; i += 1) {
            if (currencies[i].currency === currency) {
                return currencies[i].rate;
            }
        }
        return -1;
    };

    this.fetchData = function (callback) {
        var rq = new XMLHttpRequest(),
            currency,
            rate,
            newCurrencies = [],
            stored = localStorage.rates ? JSON.parse(localStorage.rates) : false;
        // We have a wee check to see if we have anything stored, and then check if it is
        // less than 24 hours old. Otherwise do the get request.
        if (stored && ((Date.now() - stored[0]) < (1000 * 60 * 60 * 24))) {
            currencies = stored[1];
            callback();
        } else {
            rq.open('GET', 'https://devweb2014.cis.strath.ac.uk/~aes02112/ecbxml.php', true);
            rq.onreadystatechange = function () {
                var result,
                    i;
                if (rq.readyState === 4) {
                    if (rq.status === 200) {
                        result = rq.responseXML;
                        newCurrencies = result.querySelectorAll('Cube[currency]');
                        currencies.length = 0;
                        currencies.push(makeCurrency('EUR', 1));
                        for (i = 0; i < newCurrencies.length; i += 1) {
                            currency = newCurrencies[i].getAttribute('currency');
                            rate = newCurrencies[i].getAttribute('rate');
                            currencies.push(makeCurrency(currency, rate));
                        }
                        callback();
                        localStorage.rates = JSON.stringify([ Date.now(), currencies]);
                    } else {
                        // If we want to update currencies, but the get request fails, continue to use
                        // the old values.
                        currencies = stored[i] === null ? [] : stored[i];
                    }
                }
            };
            rq.send();
        }
    };

    this.evaluate = function () {
        var currentRate = this.lookUpRate(homeCur),
            newRate = this.lookUpRate(visCur);
        recentEval = true;
        return Math.floor((value / currentRate) * newRate * (1 - bankCut / 100));
    };

    this.addDigit = function (digit) {
        if (recentEval) {
            this.clear();
            recentEval = false;
        }
        if (value === '' && digit === '0') {
            return;
        }
        value += String() + digit;
    };

}


text:
#
#######################DISA INFORMATION##################################
# Group ID (Vulid): RHEL-06-000007
# Group Title: SRG-OS-999999
#

# Rule ID: RHEL-06-000007_rule
# Severity: low
# Rule Version (STIG-ID): RHEL-06-000007
# Rule Title: The system must use a separate file system for user home
# directories.
#
# Vulnerability Discussion: Ensuring that "/home" is mounted on its own
# partition enables the setting of more restrictive mount options, and also
# helps ensure that users cannot trivially fill partitions used for log or
# audit data storage.
#
# Responsibility:
# IAControls:
#
# Check Content:
#
# Run the following command to determine if "/home" is on its own
# partition or logical volume:

# $ mount | grep "on /home "

# If "/home" has its own partition or volume group, a line will be
# returned.
# If no line is returned, this is a finding.
#
# Fix Text:
#
# If user home directories will be stored locally, create a separate
# partition for "/home" at installation time (or migrate it later using
# LVM). If "/home" will be mounted from another system such as an NFS
# server, then creating a separate partition is not necessary at
# installation time, and the mountpoint can instead be configured later.
#######################DISA INFORMATION##################################
#
# Global Variables
PDI=RHEL-06-000007
SEVERITY=low
#
#BEGIN_CHECK
. /usr/libexec/aqueduct/functions
MountCheck /home "$PDI: Mount point /home" $SEVERITY $CHECK

#END_CHECK
#BEGIN_REMEDY
#END_REMEDY


text:
using System;
using System.Collections.Generic;

namespace ParallelTestRunner.Impl
{
    public class TestRunnerArgsFactoryImpl : ITestRunnerArgsFactory
    {
        public ITestRunnerArgs ParseArgs(string[] args)
        {
            TestRunnerArgsImpl data = new TestRunnerArgsImpl();
            data.AssemblyList = new List<string>();
            for (int i = 0; i < args.Length; i++)
            {
                string item = args[i].Replace("\"", string.Empty);
                if (item.StartsWith("provider:", StringComparison.InvariantCultureIgnoreCase))
                {
                    data.Provider = item.Remove(0, 9);
                }
                else if (item.StartsWith("threadcount:", StringComparison.InvariantCultureIgnoreCase))
                {
                    int number;
                    int.TryParse(item.Remove(0, 12), out number);
                    data.ThreadCount = number;
                }
                else if (item.StartsWith("root:", StringComparison.InvariantCultureIgnoreCase))
                {
                    data.Root = item.Remove(0, 5);
                    if (data.Root.EndsWith("\\") || data.Root.EndsWith("/"))
                    {
                        data.Root = data.Root.Substring(0, data.Root.Length - 1);
                    }
                }
                else if (item.StartsWith("out:", StringComparison.InvariantCultureIgnoreCase))
                {
                    data.Output = item.Remove(0, 4);
                }
                else if (item.StartsWith("plevel:", StringComparison.InvariantCultureIgnoreCase))
                {
                    PLevel result;
                    if (Enum.TryParse<PLevel>(item.Remove(0, 7), true, out result))
                    {
                        data.PLevel = result;
                    }
                }
                else
                {
                    string[] pathList = item.Split(' ');
                    for (int j = 0; j < pathList.Length; j++)
                    {
                        data.AssemblyList.Add(pathList[j]);
                    }
                }
            }

            return data;
        }
    }
}


text:
/**
 * Created by Xenio on 5/28/17.
 */
export default function ({dispatch}) {
   return next => action => {
       // if the action don't have a payload or
       // the payload don't have a .then property
       // we don't care about it, send it on
       if(!action.payload || !action.payload.then) {
          return next(action);
       }
       // Make sure the promise is resolves
       action.payload
           .then(response => {
               const newResponse =  { ...action, payload: response }
               dispatch(newResponse);
           })
   }
}


text:
var yeoman = require('yeoman-environment');
var SocketAdapter = require('socket-adapter');
var fs = require('fs');
var path = require('path');

function YoWeb(socket, rootDir) {
    this.socket = socket;
    console.log("Creating new yeoman environment for socket", socket.uuid);
    this.env = yeoman.createEnv([], {
        cwd: rootDir
    }, new SocketAdapter(socket));
    this.env.on('error', function(err) {
        console.error("Yeoman Environment Error ");
        console.error(err.message);
    });
}

YoWeb.prototype.getGeneratorNames = function() {
    var generatorNames = this.env.getGeneratorNames();
    var serviceNames = {};
    var generators = {};
    try{
        generators = require('../config/generator-names.json');
    }catch(err){
        console.log('No generator-names config file found');
    }
    generatorNames.forEach(function(name){
       serviceNames[name] = generators[name] || name;
    });
    return serviceNames
};

YoWeb.prototype.generateService = function(service, projectName, callback){
    var namespace = service + ':app';
    console.log('Creating new generator - ' + namespace + ' with project name ' + projectName);
    var gen = this.env.create(namespace, {
        'options': {
            'webPrompt': true,
            "skip-install": true
        },
        'arguments': [projectName]
    });

    gen.destinationRoot(path.join(this.env.cwd, 'dist', this.socket.uuid));
    console.log('Running generator');
    gen.run(callback);
};

YoWeb.prototype.registerGeneratorsIn = function(genPath, done) {
    var self = this;
    this.env.findGeneratorsIn([genPath]).forEach(function(dirPath) {
        try {
            var pkg = JSON.parse(fs.readFileSync(path.join(dirPath, 'package.json')));
        } catch (e) {
            console.log("Unable to register generator at ", dirPath);
            console.log("No package.json file found.");
            return;
        }
        pkg.files.forEach(function(file) {
            var pkg = JSON.parse(fs.readFileSync(path.join(dirPath, 'package.json')));
            var name = pkg.name.split('-').pop();
            var genPath = path.join(dirPath, file, 'index.js');
            if(fs.existsSync(genPath)){
                var splitPath = file.split('/');
                self.env.register(path.join(dirPath, file, 'index.js'), name.concat(':', splitPath[splitPath.length - 1]));
            }
        });
        done();
    });
};

module.exports = YoWeb;


text:
<title><?php echo $title ?></title>

<?php include "menu.php" ?>

<?php echo $title ?>


text:
<?php

namespace coreb2c\user\models;

use coreb2c\user\Finder;
use coreb2c\user\helpers\Password;
use coreb2c\user\traits\ModuleTrait;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use Yii;
use yii\base\Model;

/**
 * LoginForm get user's login and password, validates them and logs the user in. If user has been blocked, it adds
 * an error to login form.
 *
 * @author Abdullah Tulek <abdullah.tulek@coreb2c.com>
 */
class LoginForm extends Model
{
    use ModuleTrait;

    /** @var string User's email or username */
    public $login;

    /** @var string User's plain password */
    public $password;

    /** @var string Whether to remember the user */
    public $rememberMe = false;

    /** @var \coreb2c\user\models\User */
    protected $user;

    /** @var Finder */
    protected $finder;

    /**
     * @param Finder $finder
     * @param array  $config
     */
    public function __construct(Finder $finder, $config = [])
    {
        $this->finder = $finder;
        parent::__construct($config);
    }

    /**
     * Gets all users to generate the dropdown list when in debug mode.
     *
     * @return string
     */
    public static function loginList()
    {
        return ArrayHelper::map(User::find()->where(['blocked_at' => null])->all(), 'username', function ($user) {
            return sprintf('%s (%s)', Html::encode($user->username), Html::encode($user->email));
        });
    }

    /** @inheritdoc */
    public function attributeLabels()
    {
        return [
            'login'      => Yii::t('user', 'Login'),
            'password'   => Yii::t('user', 'Password'),
            'rememberMe' => Yii::t('user', 'Remember me next time'),
        ];
    }

    /** @inheritdoc */
    public function rules()
    {
        $rules = [
            'requiredFields' => [['login'], 'required'],
            'loginTrim' => ['login', 'trim'],
            'confirmationValidate' => [
                'login',
                function ($attribute) {
                    if ($this->user !== null) {
                        $confirmationRequired = $this->module->enableConfirmation
                            && !$this->module->enableUnconfirmedLogin;
                        if ($confirmationRequired && !$this->user->getIsConfirmed()) {
                            $this->addError($attribute, Yii::t('user', 'You need to confirm your email address'));
                        }
                        if ($this->user->getIsBlocked()) {
                            $this->addError($attribute, Yii::t('user', 'Your account has been blocked'));
                        }
                    }
                }
            ],
            'rememberMe' => ['rememberMe', 'boolean'],
        ];

        if (!$this->module->debug) {
            $rules = array_merge($rules, [
                'requiredFields' => [['login', 'password'], 'required'],
                'passwordValidate' => [
                    'password',
                    function ($attribute) {
                        if ($this->user === null || !Password::validate($this->password, $this->user->password_hash)) {
                            $this->addError($attribute, Yii::t('user', 'Invalid login or password'));
                        }
                    }
                ]
            ]);
        }

        return $rules;
    }

    /**
     * Validates if the hash of the given password is identical to the saved hash in the database.
     * It will always succeed if the module is in DEBUG mode.
     *
     * @return void
     */
    public function validatePassword($attribute, $params)
    {
      if ($this->user === null || !Password::validate($this->password, $this->user->password_hash))
        $this->addError($attribute, Yii::t('user', 'Invalid login or password'));
    }

    /**
     * Validates form and logs the user in.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            $this->user->updateAttributes(['last_login_at' => time()]);
            return Yii::$app->getUser()->login($this->user, $this->rememberMe ? $this->module->rememberFor : 0);
        }

        return false;
    }

    /** @inheritdoc */
    public function formName()
    {
        return 'login-form';
    }

    /** @inheritdoc */
    public function beforeValidate()
    {
        if (parent::beforeValidate()) {
            $this->user = $this->finder->findUserByUsernameOrEmail(trim($this->login));

            return true;
        } else {
            return false;
        }
    }
}


text:
package com.google.startupos.common.grpc_auth;

import com.google.common.flogger.FluentLogger;
import com.google.startupos.common.flags.Flag;
import com.google.startupos.common.flags.FlagDesc;
import com.google.startupos.common.flags.Flags;
import io.grpc.ManagedChannel;
import io.grpc.netty.GrpcSslContexts;
import io.netty.handler.ssl.SslContext;
import io.grpc.netty.NettyChannelBuilder;

import java.io.File;
import java.util.logging.Level;

public class Client {
  private static final FluentLogger logger = FluentLogger.forEnclosingClass();
  private static final Integer GRPC_PORT = 9999;

  @FlagDesc(
      name = "certificate_file",
      description = "SSL certificate in PEM format",
      required = true)
  public static final Flag<String> certificateFile = Flag.create("");

  @FlagDesc(name = "token", description = "Firebase ID token to authenticate", required = true)
  public static final Flag<String> token = Flag.create("");

  @FlagDesc(name = "n", description = "Argument for gRPC call", required = true)
  public static final Flag<Integer> n = Flag.create(-1);

  public static void main(String[] args) throws Exception {
    Flags.parseCurrentPackage(args);

    SslContext sslContext =
        GrpcSslContexts.forClient().trustManager(new File(certificateFile.get())).build();
    ManagedChannel channel =
        NettyChannelBuilder.forAddress("localhost", GRPC_PORT).sslContext(sslContext).build();

    GrpcAuthTestGrpc.GrpcAuthTestBlockingStub stub =
        GrpcAuthTestGrpc.newBlockingStub(channel)
            .withInterceptors(new ClientAuthInterceptor(token.get()));

    logger.at(Level.INFO).log("Calling server to increment %d", n.get());
    Protos.Response resp =
        stub.getNextNumber(Protos.Request.newBuilder().setNumber(n.get()).build());
    logger.at(Level.INFO).log("Got %d in response", resp.getNumber());
  }
}


text:
gitlab = node['gitlab']

include_recipe "gitlab::gitlab_shell"
include_recipe "gitlab::database_#{gitlab['database_adapter']}"
include_recipe "gitlab::gitlab"
include_recipe "gitlab::nginx"


text:
layout: job
title: "Junior Product Designer "
subtitle: ONGOING
imagejob: /images/backendteam.png
image-alt-job: Bright Inventions team
hours: full-time
salary: 6000 - 9000 PLN + VAT (B2B) or 5000 - 7500 PLN gross (UoP)
salary_min: 5000
salary_max: 8999
working time: full time
show_new_title_more_about_us: false
button: "join our design team "
published: false
show_recruiter_info: false
hidden: true
technology:
  - Adobe XD
  - Figma
  - Sketch
  - Adobe Illustrator
  - Adobe Photoshop
order: 1
recruting_image2_title: interview
recruting_image3_title: product design task
description: We are seeking a Junior Product Designer who will support our
  product design team. You will learn how to create wireframes, mock-ups and
  prototypes. Apply!
---
## who we are

At Bright Inventions you'll be an important part of a group of talented, ambitious and positive developers, designers, managers and marketers who love to solve real problems and build software that really matters in today's world.

We support and share responsibility with the members of our team. We also actively take responsibility for our own self-development. Positive attitude, flexibility and teamwork are elemental parts of our success. Clients trust us to build things that work and we take that seriously.

## about the job

We are seeking a talented and creative **Junior Product Designer** who would like to support our team in ensuring a first-class user experience across products we do. The role will include working collaboratively with our Product Designer, project managers as well as developers. You will learn how to create wireframes, mock-ups, prototypes and building various components.

This is an exciting and challenging role that offers the opportunity to take part in preparing high-quality designs for the brand and our clients.

## in this role you will

* work on international projects for clients from different industries (FinTech, Retail, Health, Ecommerce, Logistics)
* collaborate with product managers and engineers to successfully deliver designs that meet measurable criteria
* create effective and UI/UX-driven mobile and web interfaces
* measure the success and failures of your design choices
* work on internal marketing projects where you can fully use your creative skills

## preferred qualifications and skills

* at least 6 months of experience in a similar role
* basic knowledge of UI/UX principles
* excellent attention to details
* data-driven approach to problem solving
* eagerness to broaden your knowledge in different industries
* good command of at least one of design tools (e.g. Adobe XD, Sketch, Figma or other)
* very good communication skills both in English and Polish

## we would also appreciate if you are

* familiar with current trends in designs
* up-to-date with Dribble and Behance best design practicwa

## **what you will find at Bright Inventions**  **🧡**
* experienced product designer's support
* **continuous feedback culture** and regular salary review
* **mentoring programme** and regular 1:1 meetings
* flexible working hours and remote work possibility
* 20-26 paid days off + Polish bank holidays
* MultiSport card and private medical package (PZU Zdrowie)
* an opportunity to build strong community via workshops and dev's meetings
* budget for **training and professional books**
* extra time once a month for **self-development**
* board games evenings and weekly lunch initiative
* team retreats once a quarter
* regular sport classes **(running, biking, swimming, yoga)** with a professional coach
* good equipment: MacBook and additional accessories
* good localisation and office in Gdańsk Wrzeszcz with a parking space nearby

**Still some doubts why you may love working with us? [Check our 7 reasons to work at Bright Inventions.](https://brightinventions.pl/blog/reasons-to-join-bright/)**


text:
<?php

class Dicts extends Common
{
    protected $_name = 'dicts';
    protected $_rowClass = 'Dict';

    public function getByGroupId($id) {
        return $this->fetchAll("group_id = $id", "id ASC");
    }

    public function getListByGroupId($id) {
        return $this->getAdapter()->fetchPairs(
            "SELECT id, name FROM {$this->_name} WHERE group_id = $id ORDER BY name ASC"
        );
    }

    public function exists($name, $groupId) {
        return (bool)$this->fetchRow("name = {$this->getAdapter()->quote($name)} AND group_id = $groupId");
    }

    public function add($data) {
        $config = Zend_Registry::get('config');
        if (substr($data['filename'], -4) == '.zip') {
            $zip = new ZipArchive();
            $zip->open("{$config->paths->storage->tmp}/{$data['filename']}");
            $dicts = [];
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $dicts[] = $zip->getNameIndex($i);
            }
            $tmpDir = md5(time() . rand(0, 9999999));
            mkdir("{$config->paths->storage->tmp}/$tmpDir");
            $zip->extractTo("{$config->paths->storage->tmp}/$tmpDir");
            foreach ($dicts as $dict) {
                $data['name'] = $dict;
                $this->_addDict("$tmpDir/$dict", $data);
            }
            Utils::deleteDir("{$config->paths->storage->tmp}/$tmpDir");
        } else {#TODO здесь сделать вывод ошибок, по-любому они могут возникнуть
            $this->_addDict($data['filename'], $data);
        }
        unlink("{$config->paths->storage->tmp}/{$data['filename']}");
    }

    private function _add10InFileEndIfNeed($path) {
        $fh = fopen($path, 'a+');
        fseek($fh, -1, SEEK_END);
        if (fread($fh, 1) != "\n") {
            fseek($fh, 0, SEEK_END);
            fwrite($fh, "\n");
        }
        fclose($fh);
    }

    private function _addDict($tmpPath, $data) {
        $config = Zend_Registry::get('config');
        $hash = md5(time() . rand(0, 1000000));

        $this->_add10InFileEndIfNeed("{$config->paths->storage->tmp}/{$tmpPath}");

        copy("{$config->paths->storage->tmp}/{$tmpPath}", "{$config->paths->storage->dicts}/{$hash}.dict");

        $linesCount = 0;
        $tmpFh = fopen("{$config->paths->storage->dicts}/{$hash}.dict", "r");
        while (!feof($tmpFh)) {
            $tmpData = fread($tmpFh, 1024);
            $linesCount += substr_count($tmpData, "\n");
        }
        fclose($tmpFh);

        $dict = $this->createRow(
            [
                'name' => $data['name'],
                'hash' => $hash,
                'group_id' => $data['group_id'],
                'comment' => $data['comment'],
                'size' => filesize("{$config->paths->storage->dicts}/{$hash}.dict"),
                'count' => $linesCount
            ]
        );
        $dict->save();

        unlink("{$config->paths->storage->tmp}/{$tmpPath}");
    }
}


text:
source /etc/profile.modules

module load gcc
module load matlab
cd ~/deepLearn && srun ./deepFunction 4 'RBM' 'DBN' '128  1500  1500    10' '0  1  1  1' '4_lin_bin' 'PARAL_base' "'iteration.n_epochs', 'learning.lrate', 'learning.cd_k', 'learning.persistent_cd', 'parallel_tempering.use'" '200 1e-3 1 0 1' "'iteration.n_epochs', 'learning.persistent_cd'" '200 0'


text:
import {List, Map, fromJS} from 'immutable';
import {expect} from 'chai';

import reducer from '../src/reducer';

describe('reducer', () => {

  it('handles SET_STATE', () => {
    const initialState = Map();
    const action = {
      type: 'SET_STATE',
      state: Map({
        vote: Map({
          pair: List.of('Trainspotting', '28 Days Later'),
          tally: Map({Trainspotting: 1})
        })
      })
    };
    const nextState = reducer(initialState, action);

    expect(nextState).to.equal(fromJS({
      vote: {
        pair: ['Trainspotting', '28 Days Later'],
        tally: {Trainspotting: 1}
      }
    }));
  });

  it('handles SET_STATE with plain JS payload', () => {
    const initialState = Map();
    const action = {
      type: 'SET_STATE',
      state: {
        vote: {
          pair: ['Trainspotting', '28 Days Later'],
          tally: {Trainspotting: 1}
        }
      }
    };
    const nextState = reducer(initialState, action);

    expect(nextState).to.equal(fromJS({
      vote: {
        pair: ['Trainspotting', '28 Days Later'],
        tally: {Trainspotting: 1}
      }
    }));
  });

  it('handles SET_STATE without initial state', () => {
    const action = {
      type: 'SET_STATE',
      state: {
        vote: {
          pair: ['Trainspotting', '28 Days Later'],
          tally: {Trainspotting: 1}
        }
      }
    };
    const nextState = reducer(undefined, action);

    expect(nextState).to.equal(fromJS({
      vote: {
        pair: ['Trainspotting', '28 Days Later'],
        tally: {Trainspotting: 1}
      }
    }));
  });

  it ('handles VOTE by setting hasVoted', () => {
    const state = fromJS({
      vote: {
        pair: ['Trainspotting', '28 Days Later'],
        tally: {Trainspotting: 1}
      }
    });
    const action = {type: 'VOTE', entry: 'Trainspotting'};
    const nextState = reducer(state, action);

    expect(nextState).to.equal(fromJS({
      vote: {
        pair: ['Trainspotting', '28 Days Later'],
        tally: {Trainspotting: 1}
      },
      hasVoted: 'Trainspotting'
    }));
  });

  it ('does not set hasVoted for VOTE on invalid entry', () => {
    const state = fromJS({
      vote: {
        pair: ['Trainspotting', '28 Days Later'],
        tally: {Trainspotting: 1}
      }
    });
    const action = {type: 'VOTE', entry: 'Sunshine'};
    const nextState = reducer(state, action);

    expect(nextState).to.equal(fromJS({
      vote: {
        pair: ['Trainspotting', '28 Days Later'],
        tally: {Trainspotting: 1}
      }
    }));
  });

  it ('removes hasVoted on SET_STATE if pair changes', () => {
    const initialState = fromJS({
      vote: {
        pair: ['Trainspotting', '28 Days Later'],
        tally: {Trainspotting: 1}
      },
      hasVoted: 'Trainspotting'
    });
    const action = {
      type: 'SET_STATE',
      state: {
        vote: {
          pair: ['Sunshine', 'Slumdog Millionaire']
        }
      }
    };
    const nextState = reducer(initialState, action);

    expect(nextState).to.equal(fromJS({
      vote: {
        pair: ['Sunshine', 'Slumdog Millionaire']
      }
    }));
  });
});


text:
typedef struct {
  UInt32 magicNumber;      // Should be 0x00051607
  UInt32 versionNumber;    // Should be 0x00020000
  char filler[16];         // Zero-filled bytes.
  UInt16 numberOfEntries;  // Number of entries.
} __attribute__((packed)) DoubleHeader;

typedef struct {
  UInt32 entryID;  // Defines what entry is (0 is invalid)
  UInt32 offset;   // Offset from beginning of file to entry data.
  UInt32 length;   // Length of entry data in bytes.
} __attribute__((packed)) DoubleEntryHeader;

@implementation GMAppleDoubleEntry

+ (GMAppleDoubleEntry *)entryWithID:(GMAppleDoubleEntryID)entryID
                               data:(NSData *)data {
  return [[[GMAppleDoubleEntry alloc]
           initWithEntryID:entryID data:data] autorelease];
}

- (id)initWithEntryID:(GMAppleDoubleEntryID)entryID
                 data:(NSData *)data {
  if ((self = [super init])) {
    if (entryID == DoubleEntryInvalid || data == nil) {
      [self release];
      return nil;
    }
    entryID_ = entryID;
    data_ = [data retain];
  }
  return self;
}

- (void)dealloc {
  [data_ release];
  [super dealloc];
}

- (GMAppleDoubleEntryID)entryID {
  return entryID_;
}
- (NSData *)data {
  return data_;
}

@end

@implementation GMAppleDouble

+ (GMAppleDouble *)appleDouble {
  return [[[GMAppleDouble alloc] init] autorelease];
}

+ (GMAppleDouble *)appleDoubleWithData:(NSData *)data {
  GMAppleDouble* appleDouble = [[[GMAppleDouble alloc] init] autorelease];
  if ([appleDouble addEntriesFromAppleDoubleData:data]) {
    return appleDouble;
  }
  return nil;
}

- (id)init {
  if ((self = [super init])) {
    entries_ = [[NSMutableArray alloc] init];
  }
  return self;
}

- (void)dealloc {
  [entries_ release];
  [super dealloc];
}

- (void)addEntry:(GMAppleDoubleEntry *)entry {
  [entries_ addObject:entry];
}

- (void)addEntryWithID:(GMAppleDoubleEntryID)entryID data:(NSData *)data {
  GMAppleDoubleEntry* entry = [GMAppleDoubleEntry entryWithID:entryID data:data];
  [self addEntry:entry];
}

- (BOOL)addEntriesFromAppleDoubleData:(NSData *)data {
  const int len = [data length];
  DoubleHeader header;
  if (len < sizeof(header)) {
    return NO;  // To small to even fit our header.
  }
  [data getBytes:&header length:sizeof(header)];
  if (OSSwapBigToHostInt32(header.magicNumber) != GM_APPLE_DOUBLE_HEADER_MAGIC ||
      OSSwapBigToHostInt32(header.versionNumber) != GM_APPLE_DOUBLE_HEADER_VERSION) {
    return NO;  // Invalid header.
  }
  int count = OSSwapBigToHostInt16(header.numberOfEntries);
  int offset = sizeof(DoubleHeader);
  if (len < (offset + (count * sizeof(DoubleEntryHeader)))) {
    return NO;  // Not enough data to hold all the DoubleEntryHeader.
  }
  for (int i = 0; i < count; ++i, offset += sizeof(DoubleEntryHeader)) {
    // Extract header
    DoubleEntryHeader entryHeader;
    NSRange range = NSMakeRange(offset, sizeof(entryHeader));
    [data getBytes:&entryHeader range:range];

    // Extract data
    range = NSMakeRange(OSSwapBigToHostInt32(entryHeader.offset),
                        OSSwapBigToHostInt32(entryHeader.length));
    if (len < (range.location + range.length)) {
      return NO;  // Given data too small to contain this entry.
    }
    NSData* entryData = [data subdataWithRange:range];
    [self addEntryWithID:OSSwapBigToHostInt32(entryHeader.entryID) data:entryData];
  }

  return YES;
}

- (NSArray *)entries {
  return entries_;
}

- (NSData *)data {
  NSMutableData* entryListData = [NSMutableData data];
  NSMutableData* entryData = [NSMutableData data];
  int dataStartOffset =
    sizeof(DoubleHeader) + [entries_ count] * sizeof(DoubleEntryHeader);
  for (int i = 0; i < [entries_ count]; ++i) {
    GMAppleDoubleEntry* entry = [entries_ objectAtIndex:i];

    DoubleEntryHeader entryHeader;
    memset(&entryHeader, 0, sizeof(entryHeader));
    entryHeader.entryID = OSSwapHostToBigInt32((UInt32)[entry entryID]);
    entryHeader.offset =
      OSSwapHostToBigInt32((UInt32)(dataStartOffset + [entryData length]));
    entryHeader.length = OSSwapHostToBigInt32((UInt32)[[entry data] length]);
    [entryListData appendBytes:&entryHeader length:sizeof(entryHeader)];
    [entryData appendData:[entry data]];
  }

  NSMutableData* data = [NSMutableData data];

  DoubleHeader header;
  memset(&header, 0, sizeof(header));
  header.magicNumber = OSSwapHostToBigConstInt32(GM_APPLE_DOUBLE_HEADER_MAGIC);
  header.versionNumber = OSSwapHostToBigConstInt32(GM_APPLE_DOUBLE_HEADER_VERSION);
  header.numberOfEntries = OSSwapHostToBigInt16((UInt16)[entries_ count]);
  [data appendBytes:&header length:sizeof(header)];
  [data appendData:entryListData];
  [data appendData:entryData];
  return data;
}

@end


text:
package com.microsoft.azure.management.eventhubs.v2017_04_01;

import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.eventhubs.v2017_04_01.implementation.EventHubsManager;
import com.microsoft.azure.management.eventhubs.v2017_04_01.implementation.AccessKeysInner;

/**
 * Type representing AccessKeys.
 */
public interface AccessKeys extends HasInner<AccessKeysInner>, HasManager<EventHubsManager> {
    /**
     * @return the aliasPrimaryConnectionString value.
     */
    String aliasPrimaryConnectionString();

    /**
     * @return the aliasSecondaryConnectionString value.
     */
    String aliasSecondaryConnectionString();

    /**
     * @return the keyName value.
     */
    String keyName();

    /**
     * @return the primaryConnectionString value.
     */
    String primaryConnectionString();

    /**
     * @return the primaryKey value.
     */
    String primaryKey();

    /**
     * @return the secondaryConnectionString value.
     */
    String secondaryConnectionString();

    /**
     * @return the secondaryKey value.
     */
    String secondaryKey();

}