text:
/**********************************************************************
*                                                                     *
* INTEL CORPORATION                                                   *
*                                                                     *
* This software is supplied under the terms of the license included   *
* above.  All use of this driver must be in accordance with the terms *
* of that license.                                                    *
*                                                                     *
* Module Name:  ans_os.h                                              *
*                                                                     *
* Abstract: iANS routines specific to linux                           *
*                                                                     *
* Environment:  This file is intended to be specific to the Linux     *
*               operating system.                                     *
*                                                                     *
**********************************************************************/

#include "ans_driver.h"
#include "ans_os.h"
#include <asm/unaligned.h>

void (*ans_notify)(device_t *dev, int ind_type) = NULL;

BD_ANS_STATUS bd_ans_os_SetCallback(BOARD_PRIVATE_STRUCT *bps,
    IANS_BD_PARAM_HEADER *header)
{
    IANS_BD_ANS_SET_CB *acb = (IANS_BD_ANS_SET_CB *) header;
    ans_notify = acb->notify;
    return BD_ANS_SUCCESS;
}

/* bd_ans_os_Ioctl()
**
**  This function will pull the IANS structures out of the ifr and pass
**  them to the generic ANS module for processing.
**
**  Arguments:  struct device *dev - pointer to the adapters device structure
**              struct ifreq *ifr - the request structure passed down from
**                                  upper layers.
**              int cmd - the number of the IOC to process.  This function
**                        will only process the IANS_BASE_SIOC command.
**
**  Returns:    int - 0 if successful, non-zero otherwise.
*/
int
bd_ans_os_Ioctl(device_t *dev, struct ifreq *ifr, int cmd)
{
    /* get the private data structure from the dev struct */
    BOARD_PRIVATE_STRUCT *bps = dev->priv;
    IANS_BD_PARAM_HEADER *header =  (IANS_BD_PARAM_HEADER *)ifr->ifr_data;
    iANSsupport_t *iANSdata;
    BD_ANS_STATUS status;

    /* get a pointer to the ANS data struct from the ifr */
    iANSdata = ANS_PRIVATE_DATA_FIELD(bps);

    //DEBUGLOG("bd_ans_os_Ioctl: enter\n");

    /* switch on the command */
    switch(cmd) {
    case IANS_BASE_SIOC:
        status = bd_ans_ProcessRequest(bps, iANSdata, header);
        if (status == BD_ANS_SUCCESS)
            return 0;
        /* some problem occured, return error value */
        return -EAGAIN;
    default:
        return -EOPNOTSUPP;
    }
    return 0;
}

/* bd_ans_os_Transmit()
**
**  This function will get the required structures from the skb and
**  pass them to the generic bd_ans_Transmit routine for processing.
**
**  Arguments:  BOARD_PRIVATE_STRUCT *bps - pointer to the boards
**                                          private data structure
**              HW_TX_DESCRIPTOR *txd - pointer to the hardware
**                                      specific tx descriptor
**              struct sk_buff *skb - pointer to the skb which
**                                    describes this packet.
**
**  Returns:    int - 0 if successful, non-zero otherwise.
*/
int
bd_ans_os_Transmit( BOARD_PRIVATE_STRUCT *bps,
    HW_TX_DESCRIPTOR *txd,
    struct sk_buff **skb )
{
    UINT16 vlan_id;     /* don't know if I really need this */
    IANS_ATTR_HEADER *attr_head = iANSGetTransmitAttributeHeader(*skb);
    iANSsupport_t *iANSdata = ANS_PRIVATE_DATA_FIELD(bps);

    /* nothing special to do unless we are in attributed mode */

    /* call the bd_ans_Transmit routine to setup our frame for transmit */
    if (iANSdata->attributed_mode) {

        /* Check to identify misrouted frames */
        /* An explicit check would not have been backward compatible */
        if ((char *)(attr_head->pFirstTLV) != ( (char *)attr_head + sizeof(IANS_ATTR_HEADER) )) {
            //printk("%s warning frame does not contain TLV data",(*skb)->dev->name);
            return 1; // This is not an iANS attributed packet!
        }

        if (bd_ans_Transmit(bps,
            iANSdata,
            attr_head->pFirstTLV,
            txd,
            skb,
            &vlan_id) == BD_ANS_FAILURE)
            return 1;

    }
    return 0;
}

/* bd_ans_os_Receive()
**
**  This function will determine if the adapter is configured
**  for attributed mode, and call the generic ans routine
**  to add any needed tlvs if we are configured to do so.
**  It will also check the routing_mode flag to determine
**  if we need to check to see if we should route frames
**  to ANS.
**
**  Arguments:  BOARD_PRIVATE_STRUCT *bps - pointer to private data struct
**              HW_RX_DESCRIPTOR *rxd - pointer to hw specific frame descriptr
**              struct sk_buff *skb - the OS descriptor for this frame
**
**  Returns:    int - 0 if successful, non-zero otherwise
*/
int
bd_ans_os_Receive(BOARD_PRIVATE_STRUCT *bps,
    HW_RX_DESCRIPTOR *rxd,
    struct sk_buff *skb )
{
    UINT32 length;
    iANSsupport_t *iANSdata = ANS_PRIVATE_DATA_FIELD(bps);
    IANS_ATTR_HEADER *attr_head = iANSGetReceiveAttributeHeader(skb);
    struct sk_buff *dummy_tlv_ptr;
    device_t *dev = DRIVER_DEV_FIELD(bps);

    DEBUGLOG("bd_ans_os_Receive: enter\n");

    /* if we are in attributed mode, we need to fill out tlv structures */
    if (iANSdata->attributed_mode) {
        DEBUGLOG("bd_ans_os_Receive: in attributed mode\n");
        /* setup the TLV pointer first */
        put_unaligned((Per_Frame_Attribute_Header *)
                      (((UCHAR *)attr_head) + sizeof(IANS_ATTR_HEADER)),
                      &(attr_head->pFirstTLV));

        if (bd_ans_Receive(bps,
            iANSdata,
            rxd,
            skb->data,
            skb,
            &dummy_tlv_ptr, /* this isn't used by Linux */
            &length) == BD_ANS_FAILURE) {
            DEBUGLOG("bd_ans_os_Receive: Failed bd_ans_Receive\n");
            return 1;
        }
    } else {
        put_unaligned(NULL, &(attr_head->pFirstTLV));
    }

    /* need to check to see if we are routing rx packets to ANS. If this
     * has been setup, then we need to replace the existing protocol
     * with the ANS protocol and store the original at the head of
     * the skb
     */
    if (iANSdata->routing_mode == IANS_ROUTING_ON) {
        DEBUGLOG("bd_ans_os_Receive: In routing mode\n");
        /* set the protocol here. the eth_type_trans routine
         * changes the data pointer and so we want to do that after
         * we have done any stripping of the packet
         */
        put_unaligned(eth_type_trans(skb, dev),
                      &(attr_head->OriginalProtocol));
        skb->protocol = IANS_FRAME_TYPE;
    } else {
        skb->protocol = eth_type_trans(skb, dev);
    }
    return 0;
}

/* bd_ans_os_Watchdog()
**
**  This function will check on the status fields of the ANS
**  support structure and see if the status has changed since
**  the last time that it was checked.  If it has changed,
**  then we need to alert the ANS protocol somehow.(TBD)
**
**  Arguments:  struct device *dev - pointer to the device structure
**              BOARD_PRIVATE_STRUCT *bps - the driver's private data struct
**
**  Returns: void
*/
void
bd_ans_os_Watchdog(device_t *dev, BOARD_PRIVATE_STRUCT *bps)
{
    IANS_BD_PARAM_STATUS current_status;
    iANSsupport_t *piANSdata = ANS_PRIVATE_DATA_FIELD(bps);

    /* check ans communication protocol.  If we are not up, there is
     * nothing to do.
     */
    if ((piANSdata->iANS_status == IANS_COMMUNICATION_DOWN)
        || (piANSdata->reporting_mode == IANS_STATUS_REPORTING_OFF))
        return;

    /* update the driver's status */
    bd_ans_drv_UpdateStatus(bps);

    /* fill out the current status */
    bd_ans_FillStatus(bps, ANS_PRIVATE_DATA_FIELD(bps), &current_status);

    /* compare the status to the last status update.  If they are different,
     * we need to send an indication.
     */
    /* Compare current status against previous one: if equal, just return */
    if (BD_ANS_BCMP((UCHAR *)&piANSdata->prev_status, (UCHAR *)&current_status,
                    sizeof(IANS_BD_PARAM_STATUS)) == BD_ANS_TRUE) {

        return;
    }

    /* if we are here, we need to send a status change notification */
    /// TBD - need to get indication definition from ans_base_comm.h

    /* as far as I can tell, since it hasn't been defined yet,
     * the thing to do here is to call netdev_state_change(dev).
     * this is a synchronous call to a registered chain of who knows
     * how many protocols, so it seems like this wouldn't be a very good idea...
     */
    BD_ANS_BCOPY((UCHAR *)&piANSdata->prev_status, (UCHAR *)&current_status,
                 sizeof(IANS_BD_PARAM_STATUS));

    DEBUGLOG("bd_ans_os_Watchdog: sending notification\n");
    if (ans_notify)
        ans_notify(dev, IANS_IND_EXT_STATUS_CHANGE);
    DEBUGLOG("bd_ans_os_watchdog: done send\n");

    return;
}

#ifdef IANS_BASE_VLAN_TAGGING
/* bd_ans_os_InsertQtagSW()
**
**  This function will insert the IEEE vlan id into the data portion of the
**  packet.
**
**  Arguments:  BOARD_PRIVATE_STRUCT *bps - pointer to the boards private data
**                                          structure
**              struct sk_buff **skb - pointer to a pointer to the sk_buff
**                                     which describes this packet
**              UINT16 *vlanid - pointer to the vlan id to insert
**
**  Returns:    BD_ANS_STATUS - BD_ANS_FAILURE if a new skb needed to be
**                              allocated but could not, BD_ANS_SUCCESS
**                              otherwise
*/
BD_ANS_STATUS
bd_ans_os_InsertQtagSW(BOARD_PRIVATE_STRUCT *bps, struct sk_buff **skb, UINT16 *vlan_id)
{
    UINT32 count;
    UCHAR *from;
    UCHAR *to;
    peth_vlan_header_t peth_vlan_header;
    struct sk_buff *new_skb;

    DEBUGLOG("bd_ans_os_InsertQtagSW: enter\n");
    /* we can be guarenteed that there is headroom here because we are
     * blowing away the old TLV list since we don't need it anymore.
     */
    if (skb_headroom(*skb) < sizeof(x8021Q_tag_t) ) {
        DEBUGLOG("bd_ans_os_InsertQtagSW: inserting vlan into headroom\n");
        /* reallocate the skb */
        new_skb = skb_realloc_headroom((*skb), sizeof(x8021Q_tag_t));
        if (new_skb == NULL)
            return BD_ANS_FAILURE;

        /* return the old one */
        dev_kfree_skb(*skb);
        *skb = new_skb;
    }

    /* move the da/sa out of the way */
    from = (*skb)->data;
    to = ((UCHAR *)(*skb)->data) - sizeof(x8021Q_tag_t);
    for (count = 0; count < (ETHERNET_ADDRESS_LENGTH*2); count++)
        *to++ = *from++;

    /* adjust the data pointer to new spot */
    skb_push(*skb,sizeof(x8021Q_tag_t));

    /* insert the vlan id in the proper place */
    peth_vlan_header = (peth_vlan_header_t)(*skb)->data;
    peth_vlan_header->Qtag.EtherType = htons(QTAG_TYPE);
    peth_vlan_header->Qtag.VLAN_ID = htons(*vlan_id);
    return BD_ANS_SUCCESS;
}

/* bd_ans_os_StripQtagSW()
**
**  This routine will strip a IEEE tag out of the data area of the
**  skb.  We assume that the data pointer is still pointing to the
**  raw ethernet data (i.e. it better be!)
**
**  Arguments:  struct sk_buff *skb - pointer to the sk_buff which
**                                    describes this packet
**  Returns:    void - you get what you asked for, no checks to see
**                     if it is a valid vlan packet.
*/
void
bd_ans_os_StripQtagSW(struct sk_buff *skb)
{
    unsigned char *to;
    unsigned char *from;
    eth_vlan_header_t *header;

    header = (eth_vlan_header_t *) skb->data;

    /* start from the last byte of the source address and copy to
     * the last byte of the qtag.
     */
    from = &(header->eth_src[5]);
    to = from + sizeof(x8021Q_tag_t);
    while (from >= (unsigned char *)header)
        *to-- = *from--;

    /* reset the data to 4 bytes above what it was. */
    skb_pull(skb, sizeof(x8021Q_tag_t));
}

#endif

/* bd_ans_os_AllocateTLV()
**
**  This function will just set the tlv pointer to the proper place
**  to begin copying TLV information.  Under Linux, this function
**  doesn't do much, it is more complex under other OS.
**
**  struct sk_buff *frame - pointer to the sk_buff which describes
**                          the frame to be passed up.
**  struct sk_buff **tlv  - address of the sk_buff which will contain
**                          the tlv info.
**
**  Returns:  BD_ANS_SUCCESS - always succeeds for now.
*/
BD_ANS_BOOLEAN
bd_ans_os_AllocateTLV(struct sk_buff *frame, struct sk_buff **tlv)
{
    /* since under linux we have our tlv at the head of the
     * frame data, we use the same sk_buff for the tlv as
     * the frame data and do not need to do any new allocation
     */
    *tlv = frame;
    return BD_ANS_SUCCESS;
}

/* bd_ans_os_AttributeFill()
**
**  This function will serve as a translation layer between the generic
**  attribute fill routine and the OS specific data structures.  Tell
**  the generic routines where to fill in the TLV information.
**
**  Arguments:  iANS_Attribute_ID attr_id - the id of the attribute
**              struct sk_buff *skb - the skb which describes the tlv list
**              UINT32 prev_tlv_length - this will tell the routine how
**                                       many bytes to skip to avoid
**                                       writing over previous TLV information
**              void *data             - pointer any associated values that
**                                       belong to this TLV.
**  Returns:    UINT32 - the length of the new TLV
*/
UINT32
bd_ans_os_AttributeFill(iANS_Attribute_ID attr_id,
    struct sk_buff *skb,
    UINT32 prev_tlv_length,
    void *data)
{
    int tlv_length = 0;
    Per_Frame_Attribute_Header *header;

    /* we need to skip any previously filled in attributes so that we
     * don't blow them away.
     */
    header = iANSGetReceiveAttributeHeader(skb)->pFirstTLV;
    header = (Per_Frame_Attribute_Header *)(((UINT8 *)header) + prev_tlv_length);
    tlv_length = bd_ans_AttributeFill(attr_id, header, data);
    /* we don't adjust the len field because the len is in relation to the
     * frame data only.
     */

    return tlv_length;
}

/* bd_ans_os_ReserveSpaceForANS()
**
** ANS requires that we have space in the skb for the following:
**
**  pointer to TLV list
**  old protocol id
**  TLV list with at most 2 TLVs for now
**
**  This function abstracts the call to skb_reserve so that if the
**  amount of space that needs to be reserved changes, this is
**  only needed to be updated in the shared code and not in each
**  individual driver.
**
**  Arguments:  struct sk_buff *skb - the sk_buff which is being
**                                    adjusted.
**
**  Returns:    void.
*/
void
bd_ans_os_ReserveSpaceForANS(struct sk_buff *skb)
{
  /// (??? what is the best way to
  /// handle this variable number of tlv's? Perhaps ANS can set this
  /// number for us in a query or something, or as a define in the
  /// base_comm.h file...)
    skb_reserve(skb, BD_ANS_INFO_SIZE);
}

BD_ANS_STATUS bd_ans_os_ProcessRequest(BOARD_PRIVATE_STRUCT *bps,
                                       iANSsupport_t *iANSdata,
                                       IANS_BD_PARAM_HEADER *header)
{
    switch (header->Opcode) {
    case IANS_OP_ANS_SET_CB:
        DEBUGLOG("bd_ans_ProcessRequest: ans set callbacks\n");
        return (bd_ans_os_SetCallback(bps, header));
    default:
        DEBUGLOG1("bd_ans_os_ProcessRequest: unknown op code = %d\n", header->Opcode);
        return (BD_ANS_FAILURE);
    }
}

BD_ANS_STATUS bd_ans_os_ExtendedGetCapability(BOARD_PRIVATE_STRUCT *bps,
                                              iANSsupport_t *iANSdata,
                                              IANS_BD_PARAM_HEADER *header)
{
    ((IANS_BD_PARAM_EXT_CAP *)header)->BDAllAvailableRouting =
        IANS_ROUTING_NOT_SUPPORTED;
    /* get routing capabilities */
    if (BD_ANS_OS_CAN_ROUTE_RX(bps) == BD_ANS_TRUE) {
        ((IANS_BD_PARAM_EXT_CAP *)header)->BDAllAvailableRouting |=
            IANS_ROUTING_RX_PROTOCOL;
    }
    ((IANS_BD_PARAM_EXT_CAP *)header)->BDFlags = iANSdata->flags.bd_flags;

    return BD_ANS_SUCCESS;
}

BD_ANS_STATUS bd_ans_os_ExtendedSetMode(BOARD_PRIVATE_STRUCT *bps,
                                        iANSsupport_t *iANSdata,
                                        IANS_BD_PARAM_HEADER *header)
{
    IANS_BD_PARAM_EXT_SET_MODE *request = (IANS_BD_PARAM_EXT_SET_MODE *)header;
    if (request->BDIansRoutingMode & IANS_ROUTING_RX_PROTOCOL)
        iANSdata->routing_mode = IANS_ROUTING_ON;
    else
        iANSdata->routing_mode = IANS_ROUTING_OFF;

   return BD_ANS_SUCCESS;
}

BD_ANS_STATUS bd_ans_os_ActivateFastPolling(BOARD_PRIVATE_STRUCT *bps,
                                            iANSsupport_t *iANSdata)
{
    /* initialize the previous status with the current status so
     * that we don't send any bogus status change indications
     */
    bd_ans_drv_UpdateStatus(bps);
    bd_ans_FillStatus(bps, iANSdata, &(iANSdata->prev_status));

    /* tell the driver that we need to start checking the
     * status
     */
    iANSdata->timer_id = bd_ans_drv_StartWatchdog(bps);

    /* a non-zero timer_id indicates that the driver has
     * started the Watchdog.
     */
    if (iANSdata->timer_id == 0)
        return BD_ANS_FAILURE;

    return BD_ANS_SUCCESS;
}

BD_ANS_STATUS bd_ans_os_GetAllCapabilities(BOARD_PRIVATE_STRUCT *bps,
                                            iANSsupport_t *iANSdata)
{
    iANSdata->flags.bd_flags = BD_ANS_HW_FLAGS(bps);
    return BD_ANS_SUCCESS;
}


text:
var database = null;
var table = '';
var databaseType = '';

exports.create = function (type, tableName, scb, ecb) {
    if (type == 'ibeacon') database = require('./ibeaconDB.js');
    if (type == 'distance') database = require('./distanceDB.js');
    if (type == 'sound') database = require('./soundDB.js');

    if (!database.hasDB())
        database.createFile(); // data base file creation
    else if (database.hasDB())
        database.openFile();
    database.createTable(tableName);// data base table creation if not exists
    table = database.getTableName();
    databaseType = database.getDBType();
}

exports.save = function (timestamp, obj, tableName, cb) {
    if (typeof tableName === 'string')
        database.setTableName(tableName)
    if (databaseType == '')
        cb('error');
    if (databaseType == 'ibeacon')
        database.insert(timestamp, obj.uuid, obj.accuracy);
    if (databaseType == 'distance')
        database.insert(timestamp, obj);
    if (databaseType == 'sound')
        database.insert(timestamp, obj);

}

exports.list = function () {
    database.showTableNames();
}
exports.inquire = function (condition, tableName, cb) {
    if (typeof tableName === 'string')
        database.setTableName(tableName)
    if (typeof condition === 'string') {
        if (databaseType == 'ibeacon') {
            database.querying(function (rows) {
                if (rows.length != 0) {
                    rows.forEach(function (row) {
                        //print out results
                        console.log(row.Timestamp + " " + row.UUID + ", " + row.Distance);
                    });
                }
            }, condition);
        }
        if (databaseType == 'distance') {
            database.querying(function (rows) {
                if (rows.length != 0) {
                    rows.forEach(function (row) {
                        //print out results
                        console.log(row.Timestamp + " " + row.cm);
                    });
                }
            }, condition);
        }
        if (databaseType == 'sound') {
            database.querying(function (rows) {
                if (rows.length != 0) {
                    rows.forEach(function (row) {
                        //print out results
                        console.log(row.Timestamp + " " + row.volume);
                    });
                }
            }, condition);
        }
    }
    else {
        if (databaseType == 'ibeacon') {
            database.querying(function (rows) {
                if (rows.length != 0) {
                    rows.forEach(function (row) {
                        //print out results
                        console.log(row.Timestamp + " " + row.UUID + ", " + row.Distance);
                    });
                }
            });
        }
        if (databaseType == 'distance') {
            database.querying(function (rows) {
                if (rows.length != 0) {
                    rows.forEach(function (row) {
                        //print out results
                        console.log(row.Timestamp + " " + row.cm);
                    });
                }
            }, condition);
        }
        if (databaseType == 'sound') {
            database.querying(function (rows) {
                if (rows.length != 0) {
                    rows.forEach(function (row) {
                        //print out results
                        console.log(row.Timestamp + " " + row.volume);
                    });
                }
            }, condition);
        }
    }
}
exports.close = function () {
    database.closeDB();
    console.log('database closed');
}

redpajama_set_name: RedPajamaGithub


text:
package com.netflix.spinnaker.kork.jedis;

import java.util.function.Consumer;
import java.util.function.Function;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.commands.BinaryJedisCommands;
import redis.clients.jedis.commands.JedisCommands;
import redis.clients.jedis.commands.MultiKeyCommands;
import redis.clients.jedis.commands.RedisPipeline;
import redis.clients.jedis.commands.ScriptingCommands;

/**
 * Offers a functional interface over either a vanilla Jedis or Dynomite client.
 *
 * <p>TODO rz - remove withKeyScan once Dyno implements the Jedis interfaces
 */
public interface RedisClientDelegate {

  String name();

  <R> R withCommandsClient(Function<JedisCommands, R> f);

  void withCommandsClient(Consumer<JedisCommands> f);

  <R> R withMultiClient(Function<MultiKeyCommands, R> f);

  void withMultiClient(Consumer<MultiKeyCommands> f);

  <R> R withBinaryClient(Function<BinaryJedisCommands, R> f);

  void withBinaryClient(Consumer<BinaryJedisCommands> f);

  void withPipeline(Consumer<RedisPipeline> f);

  <R> R withPipeline(Function<RedisPipeline, R> f);

  void syncPipeline(RedisPipeline p);

  boolean supportsMultiKeyPipelines();

  void withMultiKeyPipeline(Consumer<Pipeline> f);

  <R> R withMultiKeyPipeline(Function<Pipeline, R> f);

  boolean supportsTransactions();

  void withTransaction(Consumer<Transaction> f);

  <R> R withTransaction(Function<Transaction, R> f);

  boolean supportsScripting();

  void withScriptingClient(Consumer<ScriptingCommands> f);

  <R> R withScriptingClient(Function<ScriptingCommands, R> f);

  void withKeyScan(String pattern, int count, Consumer<RedisScanResult> f);
}


text:
<?php
// In the top frame, we use cookies for session.
if (!defined('COOKIE_SESSION')) define('COOKIE_SESSION', true);
require_once("../../config.php");
require_once("../../admin/admin_util.php");
require_once("key-util.php");

use \Tsugi\Util\U;
use \Tsugi\UI\CrudForm;

\Tsugi\Core\LTIX::getConnection();

header('Content-Type: text/html; charset=utf-8');
session_start();
require_once("../gate.php");
if ( $REDIRECTED === true || ! isset($_SESSION["admin"]) ) return;

if ( ! isAdmin() ) {
    die('Must be admin');
}

$inedit = U::get($_REQUEST,'edit');

$tablename = "{$CFG->dbprefix}lti_key";
$current = $CFG->getCurrentFileUrl(__FILE__);
$from_location = "keys";
$allow_delete = true;
$allow_edit = true;
$where_clause = '';
$query_fields = array();
$fields = array('key_id', 'key_title', 'key_key', 'secret', 'deploy_key', 'issuer_id',
     'lms_issuer', 'lms_client', 'lms_oidc_auth', 'lms_keyset_url', 'lms_token_url', 'lms_token_audience',
     'xapi_url', 'xapi_user', 'xapi_password',
     'caliper_url', 'caliper_key',
     'created_at', 'updated_at', 'user_id',
);

$realfields = array('key_id', 'key_title', 'key_key', 'key_sha256', 'secret', 'deploy_key', 'deploy_sha256',
     'issuer_id',
     'lms_issuer', 'lms_issuer_sha256', 'lms_client', 'lms_oidc_auth', 'lms_keyset_url', 'lms_token_url', 'lms_token_audience',
     'xapi_url', 'xapi_user', 'xapi_password',
     'caliper_url', 'caliper_key',
     'created_at', 'updated_at', 'user_id',
);

$titles = array(
    'key_key' => 'LTI 1.1: OAuth Consumer Key',
    'secret' => 'LTI 1.1: OAuth Consumer Secret',
    'deploy_key' => 'LTI 1.3: Deployment ID (from the Platform)',
    'issuer_id' => 'LTI 1.3: Issuer',
);

if ( isset($_POST['issuer_id']) && strlen($_POST['issuer_id']) == 0 ) $_POST['issuer_id'] = null;
if ( isset($_POST['key_key']) && strlen($_POST['key_key']) == 0 ) $_POST['key_key'] = null;
if ( isset($_POST['user_id']) && strlen($_POST['user_id']) == 0 ) $_POST['user_id'] = null;

// Check the complex interaction of constraints
$key_id = U::get($_POST,'key_id');
$key_key = U::get($_POST,'key_key');
$deploy_key = U::get($_POST,'deploy_key');
$issuer_id = U::get($_POST,'issuer_id');

// Check the complex validation
if ( count($_POST) > 0 && U::get($_POST,'doUpdate') && strlen($key_id) > 0 ) {
    $row = $PDOX->rowDie( "SELECT * FROM {$CFG->dbprefix}lti_key
            WHERE key_id = :key_id",
        array(':key_id' => $key_id)
    );

    $redir = U::add_url_parm('key-detail', 'key_id', $key_id);
    $redir = U::add_url_parm($redir, 'edit', 'yes');
    if ( ! $row ) {
        $_SESSION['error'] = "Could not load the old row";
        header("Location: ".$redir);
        return;
    }

    $old_key_key = $row['key_key'];
    $old_deploy_key = $row['deploy_key'];
    $old_issuer_id = $row['issuer_id'];
    $lms_issuer = $row['lms_issuer'];

    $retval = validate_key_details($key_key, $deploy_key, $issuer_id, $lms_issuer, $old_key_key, $old_deploy_key, $old_issuer_id);

    if ( ! $retval ) {
        header("Location: ".$redir);
        return;
    }
}

// Handle the post data
$row =  CrudForm::handleUpdate($tablename, $realfields, $where_clause,
    $query_fields, $allow_edit, $allow_delete, $titles);

if ( $row === CrudForm::CRUD_FAIL || $row === CrudForm::CRUD_SUCCESS ) {
    header('Location: '.$from_location);
    return;
}

if ( ! $inedit && U::get($row, 'issuer_id') > 0 ) {
    $issuer_row = $PDOX->rowDie("SELECT issuer_key, issuer_client FROM {$CFG->dbprefix}lti_issuer WHERE issuer_id = :issuer_id",
        array(':issuer_id' => U::get($row, 'issuer_id'))
    );
    if ( $issuer_row ) {
        $row['issuer_id'] = $issuer_row['issuer_key'].' ('.$issuer_row['issuer_client'].')';
    }
}

$key_type = '';
if ( is_string($row['key_key']) && strlen($row['key_key']) > 1 && is_string($row['secret']) && strlen($row['secret']) > 0 ) {
    $key_type .= 'LTI 1.1';
}
if ( is_string($row['lms_issuer']) && strlen($row['lms_issuer']) > 0 && is_string($row['deploy_key']) && strlen($row['deploy_key']) > 0) {
    if ( strlen($key_type) > 0 ) $key_type .= ' / ';
    $key_type .= 'LTI 1.3';
} else if ( isset($row['issuer_key']) && is_string($row['issuer_key']) && strlen($row['issuer_key']) > 0 && is_string($row['deploy_key']) && strlen($row['deploy_key']) > 0) {
    if ( strlen($key_type) > 0 ) $key_type .= ' / ';
    $key_type .= 'LTI 1.3';
}
if ( $key_type == '' ) $key_type = 'Draft';

$OUTPUT->header();
$OUTPUT->bodyStart();
$OUTPUT->topNav();
$OUTPUT->flashMessages();

?>

Tennant Details
  Refresh
  Exit

Key status: <?= $key_type ?>

Key Data

About Keys

Brightspace

Sakai

Moodle

Blackboard

Canvas

Manual Configuration

<?php
$extra_buttons=false;
$row['lti13_tool_keyset_url'] = $CFG->wwwroot . '/lti/keyset';
$from_location = null;
$retval = CrudForm::updateForm($row, $fields, $current, $from_location, $allow_edit, $allow_delete,$extra_buttons,$titles);
if ( is_string($retval) ) die($retval);
echo("
\n");
$dynamicConfigUrl = U::addSession($CFG->wwwroot . "/admin/key/auto.php?tsugi_key=" . $row['key_id'], true);
$contentItemUrl = $CFG->wwwroot . "/lti/store/";
$canvasContentItemUrl = $CFG->wwwroot . "/lti/store/canvas-config.xml";
$storeUrl = $CFG->wwwroot . "/store/";
?>

Tenant Key Options

A single entry in this table defines a "distinct tenant" in Tsugi.
Data in Tsugi data is isolated to a tenant.  You can route both
LTI 1.1 and LTI 1.3 launches to one tenant by setting fields on
this entry properly.   If a tenant key is in "Draft" status - launches
will not work.

For LTI 1.1, set the oauth_consumer_key and secret.

For LTI 1.3, you can either
(a) create a global issuer and select it here, and then set the deployment_id
or you can
(b) leave the global issuer unset and set all of the LMS values in this screen.  If you mix
a global issuer and per-key LTI 1.3 settings, you will most likely end up with a tenant that
won't be able to receive launches.

If this is a pre-existing LTI 1.1 tenant, the LMS must provide the oauth_consumer_key
and secret connected to its LTI 1.3 launches, and then Tsugi can link the accounts
and courses regardless of the type of launch.  For this to work, the LMS must support
LTI Advantage legacy LTI 1.1 support.

Sometimes you need to give the LMS the Tsugi URLs to make a new security arrangement
before they can give you the Platform values to put into either a global issuer
on this form.  We solve this "who goes first" problem in Tsugi by allowing you to create
a "draft" or incomplete key and then come back later to add the LMS / Platform provided data.

IMS LTI Advantage Dynamic Registration

Sakai, Moodle, and Brightspace support the
IMS Dynamic Registration
process.  This process takes
a draft Tsugi key, and sends its data to the LMS and the LMSresponds with all of its values
and Tsugi automatically update the Tenant key with the LMS values.  It is basically a one-click
LTI Advantage install.

LTI Advantage Dynamic Registration URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $dynamicConfigUrl ?>');return false;">Copy</button>

<?= htmlentities($dynamicConfigUrl) ?>

The
IMS Dynamic Registration
process is supported by Brightspace, Moodle, and Sakai.  You create a Tenant key in
Tsugi with a title, and issuer, then take the Dynamic Registration URL
from this page and paste it into the LMS configuration process.

To use the Dynamic Registration URL in your Learning Management System,
keep this window open in a separate tab while using the LMS in another tab
as the Dynamic Registration process requires that you stay logged in to this system
in order to ensure you have permission to perform this confguration exchange.

Dynamic Registration sets up the security relationship between a tool and LMS.  Values like
the Issuer, ClientID, Keyset URL, etc. will be set up.  If the issuer data returned by the LMS
matches an existing issuer in this system, that issuer will be used for this key, otherwise
the new issuer data will be added to this key.

A secondary and optional part of Dynamic Registration is to communicate the Deployment ID for this tenant / key.
Sometimes this is included in the dynamic registration exchange (Sakai, Moodle, and Brightspace for example).
For other LMS's you may need to run the dynamic registration process, and then manually enter the Deployment Id
later.  LTI Advantage keys without a Deployment ID will not work in Tsugi.  Since Sakai and Moodle usually run in a "single-tenant"
model, they usually use a deployment_id of 1.

Important:
Once the LMS has finished its registration in the other tab, come back to this tab or window, press "Refresh"
and check to verify that the key has been set up properly.  Sometimes you get logged out and will need to log back
in to check the results of the dynamic registration process.

LTI 1.3

Brightspace supports
IMS Dynamic Registration.

In Brightspace, go to the settings (gear icon) drop down, and select
External Learning Tools -> LTI Advantage -> New Deployment.  Before
we can create the deployment, we need to register a tool which can be launched
from the help/question mark link by the "Tool" drop
down that brings up a pop up - then click on Register and it will pop up a new window.  Then
press Register Tool.

Select Dynamic, check the Configure Deployment checkbox and enter the Dynamic Configuration
URL and press Register.  Bright space will open another new tab which will come back to Tsugi.  Once Tsugi
and Brightspace exchange all their data, and update their respective configurations,
press Continue Tool Registration in the LMS.

Then in Brightspace make sure you have a Tool, Deployment, and then set up one or more Links to tell BrightSpace
where to show Tsugi in the Brightspace UI.  The Deep Linking Quicklink works pretty well for Tsugi but
others might be useful as well.   The URL to provide to use for Deep Linking Quicklink is the Tsugi store URL:

Tsugi App Store URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $contentItemUrl ?>');return false;">Copy</button>

<?= htmlentities($contentItemUrl) ?>

LTI Advantage Dynamic Registration URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $dynamicConfigUrl ?>');return false;">Copy</button>

<?= htmlentities($dynamicConfigUrl) ?>

LTI 1.1

You can install Tsugi as a
Content-Item
(i.e. a tool picker) by using the consumer_key and consumer_secret and the following
URL.

Tsugi App Store URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $contentItemUrl ?>');return false;">Copy</button>

<?= htmlentities($contentItemUrl) ?>

You can also install direct LTI 1.1 launches to individual tools on this system.  You can
see any installed tools in the
<a href="<?= htmlentities($storeUrl) ?>" target="_blank">Tsugi App Store on this system.
Each tool listing provides its direct launch endpoints.

LTI 1.3

Sakai supports
IMS Dynamic Registration.

In Sakai go into Administration Workspace -> External Tools -> LTI Advantage Auto Provision

Give the tool a title, and press Auto Provision.  Sakai will create a draft integration and give you the
option to Use LTI Advantage Auto Configuration - press that button and enter the Dynamic Configuration
URL.

LTI Advantage Dynamic Registration URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $dynamicConfigUrl ?>');return false;">Copy</button>

<?= htmlentities($dynamicConfigUrl) ?>

Sakai supports the optional part of Dynamic Registration and so it provides the Deployment ID for this tenant / key
in the Dynamic Registration process so once the process is done - the Tenant should be fully configured and ready to launch.
Sakai systems are not usually multi-tenant so they usually use a deployment_id of 1.

LTI 1.1

You can install Tsugi as a
Content-Item
(i.e. a tool picker) by using the consumer_key and consumer_secret and the following
URL.

Tsugi App Store URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $contentItemUrl ?>');return false;">Copy</button>

<?= htmlentities($contentItemUrl) ?>

You can also install direct LTI 1.1 launches to individual tools on this system.  You can
see any installed tools in the
<a href="<?= htmlentities($storeUrl) ?>" target="_blank">Tsugi App Store on this system.
Each tool listing provides its direct launch endpoints.

LTI 1.3

Moodle supports
IMS Dynamic Registration.

In Moodle go into Site Administration -> Plugins -> Manage Tools -> Add LTI Advantage

Moodle will prompt you for the Dynamic Registration URL.

LTI Advantage Dynamic Registration URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $dynamicConfigUrl ?>');return false;">Copy</button>

<?= htmlentities($dynamicConfigUrl) ?>

Moodle supports the optional part of Dynamic Registration and so it provides the Deployment ID for this tenant / key
in the Dynamic Registration process so once the process is done - the Tenant should be fully configured and ready to launch.
Moodle systems are not usually multi-tenant so they usually use a deployment_id of 1.

LTI 1.1

You can install Tsugi as a
Content-Item
(i.e. a tool picker) by using the consumer_key and consumer_secret and the following
URL.

Tsugi App Store URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $contentItemUrl ?>');return false;">Copy</button>

<?= htmlentities($contentItemUrl) ?>

You can also install direct LTI 1.1 launches to individual tools on this system.  You can
see any installed tools in the
<a href="<?= htmlentities($storeUrl) ?>" target="_blank">Tsugi App Store on this system.
Each tool listing provides its direct launch endpoints.

LTI 1.3

<?php
$key_id = $row['key_id'];
$oidc_login = $CFG->wwwroot . '/lti/oidc_login/' . $key_id;
$oidc_redirect = $CFG->wwwroot . '/lti/oidc_launch';
$lti13_keyset = $CFG->wwwroot . '/lti/keyset';
$deep_link = $CFG->wwwroot . '/lti/store/';

?>

These URLs need to be provided to your LMS registration associated with this key.
You can create a draft key, then provide these values to the LMS.
Then the LMS can us the values to
complete its configuration process and provide you the needed
values (which may include a new issuer) so that you can finish configuring this key.

LTI 1.3 OpenID Connect Endpoint: <a href="#" onclick="copyToClipboardNoScroll(this, '<?= $oidc_login ?>');return false;">Copy
<?= $oidc_login ?>

LTI 1.3 Tool Redirect Endpoint: <a href="#" onclick="copyToClipboardNoScroll(this, '<?= $oidc_redirect ?>');return false;">Copy
<?= $oidc_redirect ?>

LTI 1.3 Tool Keyset URL: <a href="#" onclick="copyToClipboardNoScroll(this, '<?= $lti13_keyset ?>');return false;">Copy
<?= $lti13_keyset ?>

LTI Content Item / Deep Link Endpoint: <a href="#" onclick="copyToClipboardNoScroll(this, '<?= $deep_link ?>');return false;">Copy
<?= $deep_link ?>

LTI 1.1

You can install Tsugi as a
Content-Item
(i.e. a tool picker) by using the consumer_key and consumer_secret and the following
URL.

Canvas LTI 1.1 Configuration URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $canvasContentItemUrl ?>');return false;">Copy</button>

<?= htmlentities($canvasContentItemUrl) ?>

LTI 1.3

To use LTI 1.3 in Canvas,
you should first create an Issuer in Tsugi and then use that Issuer to create
the Tenant Key.  A Canvas Issuer is a set of URLs and a Client ID
(like 38288000000000436).  Once the issuer is created, you need
to create a deployment in Canvas to get a Deployment ID
(like a16eaea622168ab8327cddef847ccabeea459a79).

Create a Tsugi tenant key by selecting the Canvas issuer and adding
the Deployment Id.  At that point the tenant key should start working.

In Canvas you create a Deployment ID by using the + App
in your course settings or by having an administrator do the + App
for you.

LTI 1.1

You can install Tsugi as a
Content-Item
(i.e. a tool picker) by using the consumer_key and consumer_secret and the following
URL.

Canvas LTI 1.1 Configuration URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $canvasContentItemUrl ?>');return false;">Copy</button>

<?= htmlentities($canvasContentItemUrl) ?>

<?php
require_once("blackboard-detail.php");
?>

LTI 1.1

You can install Tsugi as a
Content-Item
(i.e. a tool picker) by using the consumer_key and consumer_secret and the following
URL.

Tsugi App Store URL:
<button href="#" onclick="copyToClipboardNoScroll(this, '<?= $contentItemUrl ?>');return false;">Copy</button>

<?= htmlentities($contentItemUrl) ?>

You can also install direct LTI 1.1 launches to individual tools on this system.  You can
see any installed tools in the
<a href="<?= htmlentities($storeUrl) ?>" target="_blank">Tsugi App Store on this system.
Each tool listing provides its direct launch endpoints.

<?php
$OUTPUT->footerStart();

$sql = "SELECT issuer_id, issuer_key, issuer_client
    FROM {$CFG->dbprefix}lti_issuer";
$issuer_rows = $PDOX->allRowsDie($sql);

if ( $inedit && count($issuer_rows) > 0 ) {
    $select_text = "<select id=\"issuer_id_select\"><option value=\"\">No Global Issuer Selected</option>";
    foreach($issuer_rows as $issuer_row) {
        $selected = $row['issuer_id'] == $issuer_row['issuer_id'] ? ' selected ' : '';
        $select_text .= '<option value="'.$issuer_row['issuer_id'].'"'.$selected.'>'.htmlentities($issuer_row['issuer_key']. ' ('.$issuer_row['issuer_client'].')')."</option>";
    }
    $select_text .= "</select>";
    // echo(htmlentities($select_text));

?>

<?php
}

$OUTPUT->footerEnd();


text:
package ws.zettabyte.zettalib.baseclasses;

import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.fluids.IFluidHandler;
import cofh.api.energy.IEnergyHandler;

public abstract class TileEntityBase extends TileEntity
{

    protected TileEntity[] adjTileEnts = new TileEntity[6];
    //To make the coder's life easier and save performance via caching casts. Gotta go fast.
    protected TileEntityBase[] adjTEBs = new TileEntityBase[6];
    protected IEnergyHandler[] adjEnergyHandlers = new IEnergyHandler[6];
    protected IFluidHandler[] adjFluidHandlers = new IFluidHandler[6];

    public TileEntityBase()
    {
    }

    protected boolean initialized = false;

    protected void updateAdjacency (TileEntity toUpdate, int side)
    {
        adjTileEnts[side] = toUpdate;
        if (toUpdate instanceof TileEntityBase)
        {
            adjTEBs[side] = (TileEntityBase) toUpdate;
        }
        if (toUpdate instanceof IEnergyHandler)
        {
            adjEnergyHandlers[side] = (IEnergyHandler) toUpdate;
        }
        if (toUpdate instanceof IFluidHandler)
        {
            adjFluidHandlers[side] = (IFluidHandler) toUpdate;
        }
    }

    @Override
    public void updateEntity ()
    {
        super.updateEntity();
        tryInit();
    }

    protected void tryInit ()
    {
        super.updateEntity();
        if (!initialized)
        {
            init();
            initialized = true;
        }
    }

    protected void init ()
    {
        //Update adjacency info.
        ForgeDirection dir;
        for (int i = 0; i < 6; i++)
        {
            dir = ForgeDirection.VALID_DIRECTIONS[i];
            TileEntity tileEntity = worldObj.getBlockTileEntity(xCoord + dir.offsetX, yCoord + dir.offsetY, zCoord + dir.offsetZ);
            if (tileEntity != null)
            {
                this.updateAdjacency(tileEntity, i);
            }
        }
    }
    //Called when the block is about to be destroyed.
    public void onKill () {};
}


text:
namespace biosim {
  namespace che {
    namespace io {
      // reads sse pool files (only helix and sheet lines)
      class file_sse_pool {
      public:
        // read ps and ss from a given file
        static assembly read(std::string const &__filename);
        // read ps and ss from a given file and extends the ps to the given reference length
        static assembly read(std::string const &__filename, assembly const &__reference);
      }; // class file_sse_pool
    } // namespace io
  } // namespace che
} // namespace biosim

#endif // che_io_file_sse_pool_h


text:
An AccountCredential object encapsulates the information needed to authenticate a user.

Use the `createAccountCredential` method to create an account credential
that uses the OAuth open authentication standard.

## Reference

### + createAccountCredential({...})

Initializes an account credential using OAuth or OAuth2.

#### OAuth parameters

- *oauth_token*: The client application's token.
- *token_secret*: The client application's secret token.

Returns a newly initialized account credential.

    var accountCredential = Social.createAccountCredential({
      oauth_token: 'lorenipsum',
      token_secret: 'ipsumlorem'
    });

#### OAuth2 parameters

- *oauth2_token*: The client oauth2 token
- *refresh_token*: The refresh token to renew the account.
- *expiricy_date*: A Date representing the token expiration date.

Accounts can optionally use the OAuth open authentication standard to
authenticate your client application so you can perform operations on behalf of
the user. Instead of the user giving their username and password to login, the
user authenticates directly with the server and your client application
receives a token that grants it access to specific resources for a defined
duration. The authentication mechanism uses a key and secret scheme similar to
the public and private keys used by ssh. A token is a random string of letters
and numbers that is unique and paired with a secret to protect the token from
being abused. You initialize account credentials using this token and secret
token.

### - AccountCredential.oauthToken

The token used for the credential. [STRING]

### - AccountCredential.oauthRefreshToken

The refresh token used for the credential. [STRING]

### - AccountCredential.expiryDate

The expiration date of the credential. [DATE]


text:
PopupBoxManager = new function() {
    this.Collection = new Array();
    this.TimerCollection = new Array();

    this.RegistryPopupBox = function(popupBox) {
        this.Collection[popupBox.ID] = popupBox;
    };

    this.GetPopupBoxByID = function(id) {
        return this.Collection[id];
    };

    this.AjaxCallback = function(result) { };
};

var PopupBoxContainerElementID = 'container';

PopupBox = function(id, width, height, backgroundCSSClass, borderCSSClass, serverMethodFullName, params) {
    this.Height = height;
    this.Width = width;

    this.BorderCSSClass = borderCSSClass;
    this.BackgroundCSSClass = backgroundCSSClass;

    this.ID = id;
    this.ContentID = '_' + id;
    this.IsVisible = false;

    this.TimerHandler = null;
    this.CurrentElementID = '';
    this.PreviousElementID = '';

    this.VisibleWidth = -1;
    this.VisibleHeight = -1;

    this.ServerMethodFullName = serverMethodFullName;
    if (typeof (params) === "object") {
        if (params.hasOwnProperty("apiMethodName")) {
            this.ApiMethodName = params.apiMethodName;
        }
        if (params.hasOwnProperty("tmplName")) {
            this.TmplName = params.tmplName;
        }
        if (params.hasOwnProperty("tmplParams")) {
            this.tmplParams = params.tmplParams;
        }
        if (params.hasOwnProperty("customFactory")) {
            this.CustomFactory = params.customFactory;
        }
    }

    this.BeginBox = '
';
    this.EndBox = '
';
    this.Content = '

';

    this.Init = function() {
        jq('#' + PopupBoxContainerElementID).append(this.BeginBox + this.Content + this.EndBox);
    };

    PopupBoxManager.RegistryPopupBox(this);
    if (jq('#' + PopupBoxContainerElementID).length > 0) {
        this.Init();
    } else {
        var popupBoxID = this.ID;
        jq(document).ready(function() {
            PopupBoxManager.GetPopupBoxByID(popupBoxID).Init();
        });
    };

    this.SetContent = function(content) {
        jq('#' + this.ContentID).html(content);
        jq('#' + this.ID).css({
            'width': this.Width + 'px'
        });

    };

    this.CheckVisible = function () {
        var self = this;

        if (self.IsVisible == false) {//popup should be hidden
            clearInterval(self.checkVisibleHandler);
            self.checkVisibleHandler = null;

            if (jq('#' + self.ID).is(':visible')) {
                jq("#" + self.ID).fadeOut("slow");
            }
        } else {
            self.checkVisibleHandler = setTimeout(function () {
                self.CheckVisible();
            }, 313);
        }
    };

    this.RegistryElement = function(idElement, methodParams) {
        var popupBoxID = this.ID;
        jq('#' + idElement)
            .on("mouseover", function () {
                PopupBoxManager.GetPopupBoxByID(popupBoxID).ExecAndShow(idElement, methodParams);
            })
            .on("mouseout", function () {
                PopupBoxManager.GetPopupBoxByID(popupBoxID).StopTimer();
            })
            .on("click", function () {
                PopupBoxManager.GetPopupBoxByID(popupBoxID).StopTimer();
            });

        jq(document).on("keypress", function (evt) {
            if (!(evt.hasOwnProperty("ctrlKey") && evt.ctrlKey === true && (evt.which === 99 || evt.which === 97))) {//ctrl + c and ctrl + a
                PopupBoxManager.GetPopupBoxByID(popupBoxID).StopTimer();
            }
        });
    };

    this.RegistryElementOnLive = function(idElement, methodParams) {
        var popupBoxID = this.ID;
        jq(document)
            .on('mouseover', '#' + idElement, function () {
                PopupBoxManager.GetPopupBoxByID(popupBoxID).ExecAndShow(idElement, methodParams);
            })
            .on('mouseout', '#' + idElement, function () {
                PopupBoxManager.GetPopupBoxByID(popupBoxID).StopTimer();
            })
            .on('click', '#' + idElement, function () {
                PopupBoxManager.GetPopupBoxByID(popupBoxID).StopTimer();
            });

        jq(document).on("keypress", function (evt) {
            if (!(evt.hasOwnProperty("ctrlKey") && evt.ctrlKey === true && (evt.which === 99 || evt.which === 97))) {//ctrl + c and ctrl + a
                PopupBoxManager.GetPopupBoxByID(popupBoxID).StopTimer();
            }
        });
    };

    this.ExecAndShow = function(idElement, methodParams) {
        this.CurrentElementID = idElement;
        if (this.CurrentElementID == this.PreviousElementID && 1 == 2) {
            setTimeout("PopupBoxManager.GetPopupBoxByID('" + this.ID + "').Show('" + idElement + "')", 850);
            return;
        } else {
            if (this.TimerHandler)
                clearInterval(this.TimerHandler);

            this.PreviousElementID = this.CurrentElementID;

            if (typeof (this.ApiMethodName) != "undefined" && this.ApiMethodName != "") {
                this.TimerHandler = setTimeout("PopupBoxManager.GetPopupBoxByID('" + this.ID + "').ExecApiCode('" + idElement + "','" + methodParams + "')", 850);
            } else {
                this.TimerHandler = setTimeout("PopupBoxManager.GetPopupBoxByID('" + this.ID + "').ExecAjaxCode('" + idElement + "','" + methodParams + "')", 850);
            }
        }
    };

    this.ExecApiCode = function(idElement, methodParams) {
        var popupBoxID = this.ID;
        eval(this.ApiMethodName + "({popupBoxID: \"" + this.ID + "\"}," + methodParams + "," +
        "{" +
        "success:" + this.ApiCallback + "," +
        "error:" + function () {
                PopupBoxManager.GetPopupBoxByID(popupBoxID).StopTimer();
            } + "," +
        "before:" + function() {
                PopupBoxManager.GetPopupBoxByID(popupBoxID).SetContent('');
                PopupBoxManager.GetPopupBoxByID(popupBoxID).Show(idElement);
            }
        +"})");
    };

    this.ExecAjaxCode = function(idElement, methodParams) {
        var popupBoxID = this.ID;
        AjaxPro.onLoading = function(b) {
            if (b) {
                PopupBoxManager.GetPopupBoxByID(popupBoxID).SetContent('');
                PopupBoxManager.GetPopupBoxByID(popupBoxID).Show(idElement);
            }
        };
        eval(this.ServerMethodFullName + "(" + methodParams + ",\"" + this.ID + "\",this.AjaxCallback);");
    };

    this.AjaxCallback = function(result) {
        AjaxPro.onLoading = function(b) { };
        var ppb = PopupBoxManager.GetPopupBoxByID(result.value.rs1);
        ppb.SetContent(result.value.rs2);
        ppb.SetPopupPosition(ppb.CurrentElementID);
    };

    this.ApiCallback = function(params, data) {
        var ppb = PopupBoxManager.GetPopupBoxByID(params.popupBoxID);
        if (typeof (ppb.CustomFactory) === "function") {
            ppb.CustomFactory.apply(this, [data]);
        }
        data.isPrivateForMe = data.isPrivate && !ASC.CRM.Data.IsCRMAdmin;
        if (data.isPrivate && data.accessList) {
            for (var i = 0; i < data.accessList.length; i++) {
                if (data.accessList[i].id == Teamlab.profile.id) {
                    data.isPrivateForMe = false;
                }
            }
        }

        if (ppb.tmplParams) {
            data = jq.extend(data, ppb.tmplParams);
        }

        var $newContent = jq.tmpl(ppb.TmplName, data);
        ppb.SetContent($newContent);
        ppb.SetPopupPosition(ppb.CurrentElementID);
    };

    this.SetPopupPosition = function (idElement) {
        if (jq('#' + idElement).length == 0) return;
        var ppbHeight = jq('#' + this.ID).height(),

            w = jq(window),
            TopPadding = w.scrollTop(),
            LeftPadding = w.scrollLeft(),
            ScrWidth = w.width(),
            ScrHeight = w.height(),

            idBox = this.ID,
            pos = jq('#' + idElement).offset(),
            elHeight = jq('#' + idElement).height(),

            left = "",
            top = "";

        if ((pos.left + this.Width) > (LeftPadding + ScrWidth)) {
            left = pos.left - this.Width + 'px';
        } else {
            left = pos.left + 'px';
        }

        if ((pos.top + ppbHeight + elHeight) > (TopPadding + ScrHeight)) {
            top = pos.top - 5 - ppbHeight + 'px';
        } else {
            top = pos.top + 3 + elHeight + 'px'
        }
        jq('#' + idBox).css({
            'left': left,
            'top': top
        });
    };

    this.Show = function(idElement) {
        this.SetPopupPosition(idElement);

        var idBox = this.ID,
            $box = jq('#' + idBox);
        this.VisibleWidth = -1;
        this.VisibleHeight = -1;

        if ($box.is(':visible') == false) {
            this.IsVisible = true;
            $box.fadeIn("slow");

            $box.on("mouseout", function () {
                PopupBoxManager.GetPopupBoxByID(idBox).SetVisible(false);
            });

            $box.on("mouseover", function () {
                PopupBoxManager.GetPopupBoxByID(idBox).SetVisible(true);
            });
        }

        this.CheckVisible();
    };

    this.SetVisible = function(state) {
        if (jq('#' + this.ID).is(':visible')) {
            this.IsVisible = state;
        }
    };

    this.StopTimer = function() {
        try {
            this.IsVisible = false;
            clearInterval(this.TimerHandler);
            this.TimerHandler = null;
        }
        catch (e) { };
    };
};


text:
module APNs4r

  require 'socket'
  require 'openssl'

  class ApnsConnection

    protected
    def connect host, port, overrides = {}
      ctx = OpenSSL::SSL::SSLContext.new()
      ctx.cert = OpenSSL::X509::Certificate.new(File::read(overrides[:apns4r_cert_file] || OPTIONS[:apns4r_cert_file]))
      ctx.key  = OpenSSL::PKey::RSA.new(File::read(overrides[:apns4r_cert_key] || OPTIONS[:apns4r_cert_key]))

      begin
        s = TCPSocket.new(host, port)
        ssl = OpenSSL::SSL::SSLSocket.new(s, ctx)
        ssl.connect # start SSL session
        ssl.sync_close = true # close underlying socket on SSLSocket#close
        ssl
      rescue Errno::ETIMEDOUT
        nil
      end
    end

  end

end


text:
/**
 * This package contains all the classes used to parse and manage new thresholds
 * format according to the Nagios specification RFC
 * (http://nagiosplugins.org/rfc/new_threshold_syntax).
 *
 * As per the RFC:
 *
 *

 * Threshold arguments are specified like:
 *
 * --threshold={threshold definition}
 *
 * The threshold definition is a subgetopt format of the form:
 *
 * metric={metric},ok={range},warn={range},crit={range},unit={unit},
 * prefix={SI prefix}
 *
 * Where:
 *

 *
ok, warn, crit are called "levels"
 *
any of ok, warn, crit, unit or prefix are optional
 *
if ok, warning and critical are not specified, then no alert is
 * raised, but the performance data will be returned
 *
the unit can be specified with plugins that do not know about the
 * type of value returned (SNMP, Windows performance counters, etc.)
 *
the prefix is used to multiply the input range and possibly for
 * display data. The prefixes allowed are defined by NIST:
 *

 *
http://physics.nist.gov/cuu/Units/prefixes.html
 *
http://physics.nist.gov/cuu/Units/binary.html
 *

 *
ok, warning or critical can be repeated to define an additional range.
 * This allows non-continuous ranges to be defined
 *
warning can be abbreviated to warn or w
 *
critical can be abbreviated to crit or c
 *

 *

 */
package it.jnrpe.utils.thresholds;


text:
<?php

namespace OAuth\OAuth2\Service;

use Buzz\Browser;
use OAuth\Common\Consumer\CredentialsInterface;
use OAuth\Common\Exception\Exception;
use OAuth\Common\Http\Exception\TokenResponseException;
use OAuth\Common\Http\Url;
use OAuth\Common\Service\AbstractService as BaseAbstractService;
use OAuth\Common\Storage\TokenStorageInterface;
use OAuth\Common\Token\AbstractToken;
use OAuth\Common\Token\Exception\ExpiredTokenException;
use OAuth\Common\Token\TokenInterface;
use OAuth\OAuth2\Service\Exception\InvalidAuthorizationStateException;
use OAuth\OAuth2\Service\Exception\InvalidScopeException;
use OAuth\OAuth2\Service\Exception\MissingRefreshTokenException;

abstract class AbstractService extends BaseAbstractService implements ServiceInterface
{

    /** @const OAUTH_VERSION */
    const OAUTH_VERSION = 2;
    /** @var array */
    protected $scopes;
    /** @var bool */
    protected $stateParameterInAuthUrl;
    /** @var string */
    protected $apiVersion;
    /** @var int */
    protected $authorizationMethod = self::AUTHORIZATION_METHOD_HEADER_OAUTH;
    /** @var array */
    protected $extraApiHeaders = [];
    /** @var array */
    protected $extraOAuthHeaders = [];

    /**
     * @param CredentialsInterface $credentials
     * @param \Buzz\Browser| $httpTransporter
     * @param TokenStorageInterface $storage
     * @param array $scopes
     * @param Url|string|null $baseApiUri
     * @param bool $stateParameterInAuthUrl
     * @param string $apiVersion
     *
     * @throws InvalidScopeException
     */
    public function __construct(
        CredentialsInterface $credentials,
        Browser $httpTransporter,
        TokenStorageInterface $storage,
        array $scopes = [],
        $baseApiUri = null,
        $apiVersion = "",
        $stateParameterInAuthUrl = false
    ) {
        parent::__construct($credentials, $httpTransporter, $storage, $baseApiUri);
        $this->stateParameterInAuthUrl = $stateParameterInAuthUrl;

        foreach ($scopes as $scope) {
            if (!$this->isValidScope($scope)) {
                throw new InvalidScopeException('Scope ' . $scope . ' is not valid for service ' . get_class($this));
            }
        }

        $this->scopes = $scopes;

        if ($apiVersion) {
            $this->apiVersion = $apiVersion;
        }

        if ($this->baseApiUri) {
            $this->injectApiVersionToUri($this->baseApiUri);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthorizationEndpoint()
    {
        return $this->injectApiVersionToUri(parent::getAuthorizationEndpoint());
    }

    /**
     * {@inheritdoc}
     */
    public function getAccessTokenEndpoint()
    {
        return $this->injectApiVersionToUri(parent::getAccessTokenEndpoint());
    }

    /**
     * Parses the access token response and returns a TokenInterface.
     *
     * @abstract
     *
     * @param string $responseBody
     *
     * @return TokenInterface
     * @throws TokenResponseException
     */
    abstract protected function parseAccessTokenResponse($responseBody);

    /**
     * {@inheritdoc}
     */
    public function getAuthorizationUri(array $additionalParameters = [])
    {
        $parameters = array_merge(
            [
                'type'          => 'web_server',
                'client_id'     => $this->credentials->getConsumerId(),
                'redirect_uri'  => $this->credentials->getCallbackUrl(),
                'response_type' => 'code',
            ],
            $additionalParameters
        );

        $parameters[ 'scope' ] = implode(' ', $this->scopes);

        if ($this->needsStateParameterInAuthUrl()) {
            if (!isset($parameters[ 'state' ])) {
                $parameters[ 'state' ] = $this->generateAuthorizationState();
            }
            $this->storeAuthorizationState($parameters[ 'state' ]);
        }

        // Build the url
        $url = clone $this->getAuthorizationEndpoint();
        $url->getQuery()->modify($parameters);

        return $url;
    }

    /**
     * {@inheritdoc}
     * @throws ExpiredTokenException
     * @throws Exception
     */
    public function request($path, array $body = [], $method = 'GET', array $extraHeaders = [])
    {
        $uri = $this->determineRequestUriFromPath($path);
        /** @var AbstractToken $token */
        $token = $this->storage->retrieveAccessToken($this->service());

        if ($token->isExpired()) {
            throw new ExpiredTokenException(
                sprintf(
                    'Token expired on %s at %s',
                    date('m/d/Y', $token->getEndOfLife()),
                    date('h:i:s A', $token->getEndOfLife())
                )
            );
        }

        // add the token where it may be needed
        if (static::AUTHORIZATION_METHOD_HEADER_OAUTH === $this->getAuthorizationMethod()) {
            $extraHeaders = array_merge(['Authorization' => 'OAuth ' . $token->getAccessToken()], $extraHeaders);
        } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING === $this->getAuthorizationMethod()) {
            $uri->getQuery()->modify(['access_token' => $token->getAccessToken()]);
        } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V2 === $this->getAuthorizationMethod()) {
            $uri->getQuery()->modify(['oauth2_access_token' => $token->getAccessToken()]);
        } elseif (static::AUTHORIZATION_METHOD_QUERY_STRING_V3 === $this->getAuthorizationMethod()) {
            $uri->getQuery()->modify(['apikey' => $token->getAccessToken()]);
        } elseif (static::AUTHORIZATION_METHOD_HEADER_BEARER === $this->getAuthorizationMethod()) {
            $extraHeaders = array_merge(['Authorization' => 'Bearer ' . $token->getAccessToken()], $extraHeaders);
        }

        $extraHeaders = array_merge($this->getExtraApiHeaders(), $extraHeaders);

        return $this->httpRequest($uri, $body, $extraHeaders, $method);
    }

    /**
     * Accessor to the storage adapter to be able to retrieve tokens
     *
     * @return TokenStorageInterface
     */
    public function getStorage()
    {
        return $this->storage;
    }

    /**
     * {@inheritdoc}
     */
    public function requestAccessToken($code, $state = null)
    {
        if (null !== $state) {
            $this->validateAuthorizationState($state);
        }

        $bodyParams = [
            'code'          => $code,
            'client_id'     => $this->credentials->getConsumerId(),
            'client_secret' => $this->credentials->getConsumerSecret(),
            'redirect_uri'  => $this->credentials->getCallbackUrl(),
            'grant_type'    => 'authorization_code',
        ];

        $responseBody = $this->httpRequest(
            $this->getAccessTokenEndpoint(),
            $bodyParams,
            $this->getExtraOAuthHeaders()
        );

        $token = $this->parseAccessTokenResponse($responseBody);
        $this->storage->storeAccessToken($this->service(), $token);

        return $token;
    }

    /**
     * Refreshes an OAuth2 access token.
     *
     * @param TokenInterface $token
     *
     * @return TokenInterface $token
     * @throws MissingRefreshTokenException
     */
    public function refreshAccessToken(TokenInterface $token)
    {
        $refreshToken = $token->getRefreshToken();

        if (empty($refreshToken)) {
            throw new MissingRefreshTokenException();
        }

        $parameters = [
            'grant_type'    => 'refresh_token',
            'type'          => 'web_server',
            'client_id'     => $this->credentials->getConsumerId(),
            'client_secret' => $this->credentials->getConsumerSecret(),
            'refresh_token' => $refreshToken,
        ];

        $responseBody = $this->httpRequest(
            $this->getAccessTokenEndpoint(),
            $parameters,
            $this->getExtraOAuthHeaders()
        );
        $token = $this->parseAccessTokenResponse($responseBody);
        $this->storage->storeAccessToken($this->service(), $token);

        return $token;
    }

    /**
     * Return whether or not the passed scope value is valid.
     *
     * @param string $scope
     *
     * @return bool
     */
    public function isValidScope($scope)
    {
        $reflectionClass = new \ReflectionClass(get_class($this));

        return in_array($scope, $reflectionClass->getConstants(), true);
    }

    /**
     * Check if the given service need to generate a unique state token to build the authorization url
     *
     * @return bool
     */
    public function needsStateParameterInAuthUrl()
    {
        return $this->stateParameterInAuthUrl;
    }

    /**
     * Validates the authorization state against a given one
     *
     * @param string $state
     *
     * @throws InvalidAuthorizationStateException
     */
    protected function validateAuthorizationState($state)
    {
        if ($this->retrieveAuthorizationState() !== $state) {
            throw new InvalidAuthorizationStateException();
        }
    }

    /**
     * Generates a random string to be used as state
     *
     * @return string
     */
    protected function generateAuthorizationState()
    {
        return md5(rand());
    }

    /**
     * Retrieves the authorization state for the current service
     *
     * @return string
     */
    protected function retrieveAuthorizationState()
    {
        return $this->storage->retrieveAuthorizationState($this->service());
    }

    /**
     * Stores a given authorization state into the storage
     *
     * @param string $state
     */
    protected function storeAuthorizationState($state)
    {
        $this->storage->storeAuthorizationState($this->service(), $state);
    }

    /**
     * Return any additional headers always needed for this service implementation's OAuth calls.
     *
     * @return array
     */
    protected function getExtraOAuthHeaders()
    {
        return $this->extraOAuthHeaders;
    }

    /**
     * Return any additional headers always needed for this service implementation's API calls.
     *
     * @return array
     */
    protected function getExtraApiHeaders()
    {
        return $this->extraApiHeaders;
    }

    /**
     * Returns a class constant from ServiceInterface defining the authorization method used for the API
     * Header is the sane default.
     *
     * @return int
     */
    protected function getAuthorizationMethod()
    {
        return $this->authorizationMethod;
    }

    /**
     * Returns api version string if is set else retrun empty string
     *
     * @return string
     */
    protected function getApiVersionString()
    {
        return !(empty($this->apiVersion)) ? "/" . $this->apiVersion : "";
    }

    /**
     * Replaces "/{apiVersion}" to configured proper api version, or remove version from URI if it's have not configured
     *
     * @param Url $uri
     *
     * @return Url
     */
    protected function injectApiVersionToUri(Url $uri)
    {
        $uri->setPath(str_replace('/{apiVersion}', $this->getApiVersionString(), '/' . urldecode($uri->getPath())));

        return $uri;
    }

    /**
     * {@inheritdoc}
     */
    public function isRequestArgumentsPassed(array $request)
    {
        return !empty($request[ 'code' ]);
    }

    /**
     * {@inheritdoc}
     */
    public function retrieveAccessTokenByReqArgs(array $request)
    {
        if (!$this->isRequestArgumentsPassed($request)) {
            throw new Exception('Code has not passed to request arguments!');
        }

        $code = $request[ 'code' ];
        $state = !empty($request[ 'state' ]) ? $request[ 'state' ] : null;

        $this->requestAccessToken($code, $state);

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function isGlobalRequestArgumentsPassed()
    {
        return $this->isRequestArgumentsPassed($this->getGlobalRequestArguments());
    }

    /**
     * {@inheritdoc}
     */
    public function retrieveAccessTokenByGlobReqArgs()
    {
        return $this->retrieveAccessTokenByReqArgs($this->getGlobalRequestArguments());
    }

    /**
     * {@inheritdoc}
     */
    public function getAccessToken()
    {
        return $this->storage->retrieveAccessToken($this->service());
    }
}


text:
package org.springframework.security.config.http;

import java.util.List;

import jakarta.servlet.Filter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @author Luke Taylor
 * @author Josh Cummings
 */
@ExtendWith(SpringTestContextExtension.class)
public class FormLoginConfigTests {

	private static final String CONFIG_LOCATION_PREFIX = "classpath:org/springframework/security/config/http/FormLoginConfigTests";

	public final SpringTestContext spring = new SpringTestContext(this);

	@Autowired
	MockMvc mvc;

	@Test
	public void getProtectedPageWhenFormLoginConfiguredThenRedirectsToDefaultLoginPage() throws Exception {
		this.spring.configLocations(this.xml("WithAntRequestMatcher")).autowire();
		// @formatter:off
		this.mvc.perform(get("/"))
				.andExpect(redirectedUrl("http://localhost/login"));
		// @formatter:on
	}

	@Test
	public void authenticateWhenDefaultTargetUrlConfiguredThenRedirectsAccordingly() throws Exception {
		this.spring.configLocations(this.xml("WithDefaultTargetUrl")).autowire();
		// @formatter:off
		MockHttpServletRequestBuilder loginRequest = post("/login")
				.param("username", "user")
				.param("password", "password")
				.with(csrf());
		this.mvc.perform(loginRequest)
				.andExpect(redirectedUrl("/default"));
		// @formatter:on
	}

	@Test
	public void authenticateWhenConfiguredWithSpelThenRedirectsAccordingly() throws Exception {
		this.spring.configLocations(this.xml("UsingSpel")).autowire();
		// @formatter:off
		MockHttpServletRequestBuilder loginRequest = post("/login")
				.param("username", "user")
				.param("password", "password")
				.with(csrf());
		this.mvc.perform(loginRequest)
				.andExpect(redirectedUrl(WebConfigUtilsTests.URL + "/default"));
		MockHttpServletRequestBuilder invalidPassword = post("/login")
				.param("username", "user")
				.param("password", "wrong")
				.with(csrf());
		this.mvc.perform(invalidPassword)
				.andExpect(redirectedUrl(WebConfigUtilsTests.URL + "/failure"));
		this.mvc.perform(get("/"))
				.andExpect(redirectedUrl("http://localhost" + WebConfigUtilsTests.URL + "/login"));
		// @formatter:on
	}

	@Test
	public void autowireWhenLoginPageIsMisconfiguredThenDetects() {
		assertThatExceptionOfType(BeanCreationException.class)
				.isThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashLoginPage")).autowire());
	}

	@Test
	public void autowireWhenDefaultTargetUrlIsMisconfiguredThenDetects() {
		assertThatExceptionOfType(BeanCreationException.class)
				.isThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashDefaultTargetUrl")).autowire());
	}

	@Test
	public void authenticateWhenCustomHandlerBeansConfiguredThenInvokesAccordingly() throws Exception {
		this.spring.configLocations(this.xml("WithSuccessAndFailureHandlers")).autowire();
		// @formatter:off
		MockHttpServletRequestBuilder loginRequest = post("/login")
				.param("username", "user")
				.param("password", "password")
				.with(csrf());
		this.mvc.perform(loginRequest)
				.andExpect(status().isIAmATeapot());
		MockHttpServletRequestBuilder invalidPassword = post("/login")
				.param("username", "user")
				.param("password", "wrong")
				.with(csrf());
		this.mvc.perform(invalidPassword)
				.andExpect(status().isIAmATeapot());
		// @formatter:on
	}

	@Test
	public void authenticateWhenCustomUsernameAndPasswordParametersThenSucceeds() throws Exception {
		this.spring.configLocations(this.xml("WithUsernameAndPasswordParameters")).autowire();
		this.mvc.perform(post("/login").param("xname", "user").param("xpass", "password").with(csrf()))
				.andExpect(redirectedUrl("/"));
	}

	/**
	 * SEC-2919 - DefaultLoginGeneratingFilter incorrectly used if login-url="/login"
	 */
	@Test
	public void autowireWhenCustomLoginPageIsSlashLoginThenNoDefaultLoginPageGeneratingFilterIsWired()
			throws Exception {
		this.spring.configLocations(this.xml("ForSec2919")).autowire();
		this.mvc.perform(get("/login")).andExpect(content().string("teapot"));
		assertThat(getFilter(this.spring.getContext(), DefaultLoginPageGeneratingFilter.class)).isNull();
	}

	@Test
	public void authenticateWhenCsrfIsEnabledThenRequiresToken() throws Exception {
		this.spring.configLocations(this.xml("WithCsrfEnabled")).autowire();
		// @formatter:off
		MockHttpServletRequestBuilder loginRequest = post("/login")
				.param("username", "user")
				.param("password", "password");
		this.mvc.perform(loginRequest)
				.andExpect(status().isForbidden());
		// @formatter:on
	}

	@Test
	public void authenticateWhenCsrfIsDisabledThenDoesNotRequireToken() throws Exception {
		this.spring.configLocations(this.xml("WithCsrfDisabled")).autowire();
		// @formatter:off
		MockHttpServletRequestBuilder loginRequest = post("/login")
				.param("username", "user")
				.param("password", "password");
		this.mvc.perform(loginRequest)
				.andExpect(status().isFound());
		// @formatter:on
	}

	/**
	 * SEC-3147: authentication-failure-url should be contained "error" parameter if
	 * login-page="/login"
	 */
	@Test
	public void authenticateWhenLoginPageIsSlashLoginAndAuthenticationFailsThenRedirectContainsErrorParameter()
			throws Exception {
		this.spring.configLocations(this.xml("ForSec3147")).autowire();
		// @formatter:off
		MockHttpServletRequestBuilder loginRequest = post("/login")
				.param("username", "user")
				.param("password", "wrong")
				.with(csrf());
		this.mvc.perform(loginRequest)
				.andExpect(redirectedUrl("/login?error"));
		// @formatter:on
	}

	private Filter getFilter(ApplicationContext context, Class<? extends Filter> filterClass) {
		FilterChainProxy filterChain = context.getBean(BeanIds.FILTER_CHAIN_PROXY, FilterChainProxy.class);
		List<Filter> filters = filterChain.getFilters("/any");
		for (Filter filter : filters) {
			if (filter.getClass() == filterClass) {
				return filter;
			}
		}
		return null;
	}

	private String xml(String configName) {
		return CONFIG_LOCATION_PREFIX + "-" + configName + ".xml";
	}

	@RestController
	public static class LoginController {

		@GetMapping("/login")
		public String ok() {
			return "teapot";
		}

	}

	public static class TeapotAuthenticationHandler
			implements AuthenticationSuccessHandler, AuthenticationFailureHandler {

		@Override
		public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
				AuthenticationException exception) {
			response.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
		}

		@Override
		public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
				Authentication authentication) {
			response.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
		}

	}

}


text: Born in Japan but raised in the southern Appalachian Mountains, I never left Nashville once I came to study at Vanderbilt University. A keen observer of people, places and systems, coupled with a deep love for design, I've often bought magazines, not only to read the content, but so I can save the cover design. My desire now is to craft an online experience that people yearn to return to.


text:
package eluvio.lmdb.api;

public class LMDBException extends RuntimeException {
  private static final long serialVersionUID = 1L;

  public final int rc;

  protected LMDBException(int rc, String message) {
    super(message);
    this.rc = rc;
  }

  public final static class KeyExists extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected KeyExists(int rc, String message){ super(rc, message); }
  }

  public final static class NotFound extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected NotFound(int rc, String message){ super(rc, message); }
  }

  public final static class PageNotFound extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected PageNotFound(int rc, String message){ super(rc, message); }
  }

  public final static class Corrupted extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected Corrupted(int rc, String message){ super(rc, message); }
  }

  public final static class Panic extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected Panic(int rc, String message){ super(rc, message); }
  }

  public final static class VersionMismatch extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected VersionMismatch(int rc, String message){ super(rc, message); }
  }

  public final static class Invalid extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected Invalid(int rc, String message){ super(rc, message); }
  }

  public final static class MapFull extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected MapFull(int rc, String message){ super(rc, message); }
  }

  public final static class DBSFull extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected DBSFull(int rc, String message){ super(rc, message); }
  }

  public final static class ReadersFull extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected ReadersFull(int rc, String message){ super(rc, message); }
  }

  public final static class TLSFull extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected TLSFull(int rc, String message){ super(rc, message); }
  }

  public final static class TxnFull extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected TxnFull(int rc, String message){ super(rc, message); }
  }

  public final static class CursorFull extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected CursorFull(int rc, String message){ super(rc, message); }
  }

  public final static class PageFull extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected PageFull(int rc, String message){ super(rc, message); }
  }

  public final static class MapResized extends LMDBException {
    private static final long serialVersionUID = 1L;
    MapResized(int rc, String message){ super(rc, message); }
  }

  public final static class Incompatible extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected Incompatible(int rc, String message){ super(rc, message); }
  }

  public final static class BadRSlot extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected BadRSlot(int rc, String message){ super(rc, message); }
  }

  public final static class BadTxn extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected BadTxn(int rc, String message){ super(rc, message); }
  }

  public final static class BadValSize extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected BadValSize(int rc, String message){ super(rc, message); }
  }

  public final static class BadDBI extends LMDBException {
    private static final long serialVersionUID = 1L;
    protected BadDBI(int rc, String message){ super(rc, message); }
  }
}


text:
package org.apache.asterix.metadata.entitytupletranslators;

import java.io.IOException;

import org.apache.asterix.common.exceptions.AsterixException;
import org.apache.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
import org.apache.asterix.metadata.MetadataException;
import org.apache.asterix.metadata.bootstrap.MetadataPrimaryIndexes;
import org.apache.asterix.metadata.bootstrap.MetadataRecordTypes;
import org.apache.asterix.metadata.entities.Node;
import org.apache.asterix.om.base.AInt64;
import org.apache.asterix.om.base.AMutableInt64;
import org.apache.asterix.om.types.BuiltinType;
import org.apache.hyracks.algebricks.common.exceptions.NotImplementedException;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;

/**
 * Translates a Node metadata entity to an ITupleReference and vice versa.
 */
public class NodeTupleTranslator extends AbstractTupleTranslator<Node> {

    // Field indexes of serialized Node in a tuple.
    // First key field.
    public static final int NODE_NODENAME_TUPLE_FIELD_INDEX = 0;
    // Payload field containing serialized Node.
    public static final int NODE_PAYLOAD_TUPLE_FIELD_INDEX = 1;

    private AMutableInt64 aInt64 = new AMutableInt64(-1);
    @SuppressWarnings("unchecked")
    private ISerializerDeserializer<AInt64> int64Serde = AqlSerializerDeserializerProvider.INSTANCE
            .getSerializerDeserializer(BuiltinType.AINT64);

    // @SuppressWarnings("unchecked")
    // private ISerializerDeserializer<ARecord> recordSerDes =
    // NonTaggedSerializerDeserializerProvider.INSTANCE
    // .getSerializerDeserializer(recordType);

    public NodeTupleTranslator(boolean getTuple) {
        super(getTuple, MetadataPrimaryIndexes.NODE_DATASET.getFieldCount());
    }

    @Override
    public Node getMetadataEntityFromTuple(ITupleReference frameTuple) throws IOException {
        throw new NotImplementedException();
        // TODO: Implement this.
        // try {
        // byte[] serRecord =
        // frameTuple.getFieldData(MetadataUtils.DUMMY_FIELD_NUMBER);
        // int recordStartOffset = frameTuple.getFieldStart(1);
        // int recordLength = frameTuple.getFieldLength(1);
        // ByteArrayInputStream stream = new ByteArrayInputStream(serRecord,
        // recordStartOffset, recordLength);
        // DataInput in = new DataInputStream(stream);
        // ARecord rec = (ARecord) recordSerDes.deserialize(in);
        // String nodeName = ((AString) rec.getValueByPos(0)).getStringValue();
        // int numOfCores = ((AInt32) rec.getValueByPos(1)).getIntegerValue();
        // int workMemSize = ((AInt32) rec.getValueByPos(2)).getIntegerValue();
        // IACursor cursor = ((AOrderedList) rec.getValueByPos(3)).getCursor();
        // List<String> nodeStores = new ArrayList<String>();
        // while (cursor.next())
        // nodeStores.add(((AString) cursor.get()).getStringValue());
        // return new Node(nodeName, numOfCores, workMemSize, nodeStores);
        // } catch (IOException e) {
        // throw new AlgebricksException(e);
        // }
    }

    @Override
    public ITupleReference getTupleFromMetadataEntity(Node instance) throws IOException, MetadataException {
        // write the key in the first field of the tuple
        tupleBuilder.reset();
        aString.setValue(instance.getNodeName());
        stringSerde.serialize(aString, tupleBuilder.getDataOutput());
        tupleBuilder.addFieldEndOffset();

        // write the payload in the second field of the tuple
        recordBuilder.reset(MetadataRecordTypes.NODE_RECORDTYPE);
        // write field 0
        fieldValue.reset();
        aString.setValue(instance.getNodeName());
        stringSerde.serialize(aString, fieldValue.getDataOutput());
        recordBuilder.addField(MetadataRecordTypes.NODE_ARECORD_NODENAME_FIELD_INDEX, fieldValue);

        // write field 1
        fieldValue.reset();
        aInt64.setValue(instance.getNumberOfCores());
        int64Serde.serialize(aInt64, fieldValue.getDataOutput());
        recordBuilder.addField(MetadataRecordTypes.NODE_ARECORD_NUMBEROFCORES_FIELD_INDEX, fieldValue);

        // write field 2
        fieldValue.reset();
        aInt64.setValue(instance.getWorkingMemorySize());
        int64Serde.serialize(aInt64, fieldValue.getDataOutput());
        recordBuilder.addField(MetadataRecordTypes.NODE_ARECORD_WORKINGMEMORYSIZE_FIELD_INDEX, fieldValue);

        // write field 3
        // listBuilder.reset((AOrderedListType)
        // recordType.getFieldTypes()[3]);
        // this.stores = instance.getStores();
        // for (String field : this.stores) {
        // itemValue.reset();
        // aString.setValue(field);
        // stringSerde.serialize(aString, itemValue.getDataOutput());
        // listBuilder.addItem(itemValue);
        // }
        // fieldValue.reset();
        // listBuilder.write(fieldValue.getDataOutput());
        // recordBuilder.addField(3, fieldValue);

        try {
            recordBuilder.write(tupleBuilder.getDataOutput(), true);
        } catch (AsterixException e) {
            throw new MetadataException(e);
        }
        tupleBuilder.addFieldEndOffset();
        tuple.reset(tupleBuilder.getFieldEndOffsets(), tupleBuilder.getByteArray());
        return tuple;
    }
}


text:
package org.gitlab4j.api.webhook;

import java.util.List;

import org.gitlab4j.api.models.Assignee;
import org.gitlab4j.api.models.User;
import org.gitlab4j.api.utils.JacksonJson;

public class IssueEvent extends AbstractEvent {

    public static final String X_GITLAB_EVENT = "Issue Hook";
    public static final String OBJECT_KIND = "issue";

    private User user;
    private EventProject project;
    private EventRepository repository;
    private ObjectAttributes objectAttributes;
    private List<Assignee> assignees;
    private Assignee assignee;
    private List<EventLabel> labels;
    private IssueChanges changes;

    public String getObjectKind() {
        return (OBJECT_KIND);
    }

    public void setObjectKind(String objectKind) {
        if (!OBJECT_KIND.equals(objectKind))
            throw new RuntimeException("Invalid object_kind (" + objectKind + "), must be '" + OBJECT_KIND + "'");
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public EventProject getProject() {
        return project;
    }

    public void setProject(EventProject project) {
        this.project = project;
    }

    public EventRepository getRepository() {
        return repository;
    }

    public void setRepository(EventRepository repository) {
        this.repository = repository;
    }

    public List<Assignee> getAssignees() {
        return assignees;
    }

    public void setAssignees(List<Assignee> assignees) {
        this.assignees = assignees;
    }

    public Assignee getAssignee() {
        return assignee;
    }

    public void setAssignee(Assignee assignee) {
        this.assignee = assignee;
    }

    public List<EventLabel> getLabels() {
        return labels;
    }

    public void setLabels(List<EventLabel> labels) {
        this.labels = labels;
    }

    public IssueChanges getChanges() {
        return changes;
    }

    public void setChanges(IssueChanges changes) {
        this.changes = changes;
    }

    public ObjectAttributes getObjectAttributes() {
        return this.objectAttributes;
    }

    public void setObjectAttributes(ObjectAttributes objectAttributes) {
        this.objectAttributes = objectAttributes;
    }

    public static class ObjectAttributes extends EventIssue {
    }

    @Override
    public String toString() {
        return (JacksonJson.toJsonString(this));
    }
}


text:
package edu.cs4730.actmapdemo;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 *  this setups the  recyclerview, the data is handled via the viewmodel.
 */
public class myListFragment extends Fragment {
    String TAG = "ListFragment";
    RecyclerView mRecyclerView;
    myAdapter mAdapter;
    DataViewModel mViewModel;

    public myListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View myView = inflater.inflate(R.layout.fragment_my_list, container, false);
        //setup the RecyclerView
        mRecyclerView = myView.findViewById(R.id.list);
        mViewModel = new ViewModelProvider(requireActivity()).get(DataViewModel.class);
        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //and default animator
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //setup the adapter, which is myAdapter, see the code.
        mAdapter = new myAdapter(null, R.layout.rowlayout);
        //add the adapter to the recyclerview
        mRecyclerView.setAdapter(mAdapter);

        mViewModel.getData().observe(getViewLifecycleOwner(), new Observer<ArrayList<objData>>() {
            @Override
            public void onChanged(ArrayList<objData> objData) {
                if (mAdapter != null)
                    mAdapter.updateData(objData);
            }
        });

        return myView;
    }
}


text:
using UnityEngine;
using System.Collections;

public class CharacterScript : MonoBehaviour {

	//Need to move enemy stuff into enemyscript or gamescript.
	public GameObject enemy;
	public GameObject enemyOther;
	GameObject enemyClone;

	int enemyCount = 0;
	int maxEnemyCount = 3;
	Vector3 enemyPos;
	public float movespeed = 1f;

	void SpawnEnemy(){
		// Left or right spawn.
		int r = Random.Range(1, 3);
		if(r == 1){	enemyPos = new Vector3(5, -2.4f, 0); }
		else if(r == 2){ enemyPos = new Vector3(-5, -2.4f, 0); }

		r = Random.Range(1, 3);
		if(r == 1){
			enemyClone = Instantiate(enemy, enemyPos, enemy.transform.rotation) as GameObject;
		}
		else if(r == 2){
			enemyClone = Instantiate(enemyOther, enemyPos, enemyOther.transform.rotation) as GameObject;
		}

		// If auto-spawn enemy is on
		if(enemyCount < maxEnemyCount-1){
			//Invoke("SpawnEnemy", 2);
		}
	}

	// Update is called once per frame
	void Update () {
		// Count enemies in scene;
		enemyCount = GameObject.FindGameObjectsWithTag("Enemy").Length;
		// Enemy spawn, position and destroy.
		if(enemyCount < maxEnemyCount){
			if(!IsInvoking("SpawnEnemy")){
				//Invoke("SpawnEnemy", 2);
			}
		}

		// Spawn enemy
		if(Input.GetKeyDown(KeyCode.Space)){
			SpawnEnemy();
		}

		// Movement WASD

		// Press W to Jump.
		if(Input.GetKey("w"))
			rigidbody.MovePosition(new Vector3(rigidbody.position.x
			                                   ,rigidbody.position.y+movespeed/5
			                                   ,rigidbody.position.z));
		// Press A to go Left.
		if(Input.GetKey("a"))
			rigidbody.MovePosition(new Vector3(rigidbody.position.x-movespeed/5
			                                   ,rigidbody.position.y
			                                   ,rigidbody.position.z));
		// Press S to go Down.
		if(Input.GetKey("s"))
			rigidbody.MovePosition(new Vector3(rigidbody.position.x
			                                   ,rigidbody.position.y-movespeed/5
			                                   ,rigidbody.position.z));
		// Press D to go Right.
		if(Input.GetKey("d"))
			rigidbody.MovePosition(new Vector3(rigidbody.position.x+movespeed/5
			                                   ,rigidbody.position.y
			                                   ,rigidbody.position.z));
	}

	void OnCollisionEnter(Collision col){
		if(col.transform.name.Contains("Enemy")){
			//take away health for now until enemy can shoot.
		}
	}
}


text:
package org.aksw.mlbenchmark.resultloader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Simon Bin on 16-4-28.
 */
public class ResultLoaderBase {
	public List<String> getResults() {
		return results;
	}

	List<String> results = new LinkedList<>();
	public void loadResults(File input) throws IOException {
		results.clear();
		BufferedReader reader = new BufferedReader(new FileReader(input));
		String line;
		while ((line = reader.readLine()) != null) {
			if (line.matches("^\\s*$") || line.matches("^\\s*;")) {
				// skip, it is blank or comment
				continue;
			}
			results.add(line);
		}
		reader.close();
	}

	public boolean isEmpty() {
		return results.isEmpty();
	}
}


text:
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { AppData } from '../../providers/app-data';
import { PersonDetailsPage } from '../person-details/person-details';

@Component({
  selector: 'page-concern',
  templateUrl: 'concern.html'
})
export class ConcernPage {
  userid:string;
  users:any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public appData: AppData) {
     this.userid = navParams.get('personid');
  }

  ngAfterViewInit() {
      this.appData.getConcernList(this.userid).then(res => {
          this.users = res;
      }, err => {
          this.users = err;
      })
   }
   goDetail(personID){
     this.navCtrl.push(PersonDetailsPage,{personid:personID});
   }
}


text:
int func_outside_namespace();

// Test class outside namespace...
class class_outside_namespace
{

};

// Test variables outside namespace...
class_outside_namespace cls1;
int variable;

// Test a namespace...
namespace mynamespace
{
	class class_inside_namespace { int i; };

	class_inside_namespace cls2;
	int var;
};


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/bg_title"
    >

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:paddingTop="2dp"
      android:paddingBottom="2dp"
      android:background="@color/bg_layout"
      android:orientation="horizontal"
      android:gravity="center_horizontal"
      >
    <Button
        android:id="@+id/btn_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_read"
        android:layout_marginRight="40dp"
        />

    <Button
        android:id="@+id/btn_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:text="@string/btn_send"
        />

  </LinearLayout>

</RelativeLayout>


text:
package org.apache.flink.api.java.record.io;

import org.apache.flink.types.Record;

/**
 * The abstract base class for all output formats that are file based. Contains the logic to open/close the target
 * file streams.
 */
public abstract class FileOutputFormat extends org.apache.flink.api.common.io.FileOutputFormat<Record> {

	private static final long serialVersionUID = 3832934435044920834L;
}


text:
{% extends "content/base.html" %}

{% block content %}

    {% if event_list %}
        {% for event in event_list %}

{{ event.event_title }}

                    {{ event.event_venue }}
                    {{ event.event_date }}

 {{ event.event_description }}

        {% endfor %}
    {% else %}

No events to display.

    {% endif %}

{% endblock %}