text:
/*
 * TargetParamTable MIB
 *
 * This file was generated by mib2c and is intended for use as a mib module
 * for the ucd-snmp snmpd agent. Edited by Michael Baer
 *
 * last changed 2/2/99.
 */

#include <net-snmp/net-snmp-config.h>
#if HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#include <stdlib.h>
#include <ctype.h>
#if HAVE_WINSOCK_H
#include <winsock.h>
#endif

#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>

#include "snmpTargetParamsEntry.h"

#define snmpTargetParamsOIDLen 11       /*This is base+column,
                                         * i.e. everything but index */

oid             snmpTargetParamsOID[snmpTargetParamsOIDLen] =
    { 1, 3, 6, 1, 6, 3, 12, 1, 3, 1, 0 };

static struct targetParamTable_struct *aPTable = 0;

/*
 * Utility routines
 */

/*
 * TargetParamTable_create creates and returns a pointer
 * to a targetParamTable_struct with default values set
 */
struct targetParamTable_struct
               *
snmpTargetParamTable_create(void)
{
    struct targetParamTable_struct *newEntry;

    newEntry = (struct targetParamTable_struct *)
        malloc(sizeof(struct targetParamTable_struct));

    newEntry->paramName = 0;
    newEntry->mpModel = -1;

    newEntry->secModel = -1;
    newEntry->secName = 0;
    newEntry->secLevel = -1;

    newEntry->storageType = SNMP_STORAGE_NONVOLATILE;
    newEntry->rowStatus = SNMP_ROW_NONEXISTENT;
    newEntry->next = 0;
    return newEntry;
}

/*
 * TargetParamTable_dispose frees the space allocated to a
 * targetParamTable_struct
 */
void
snmpTargetParamTable_dispose(struct targetParamTable_struct *reaped)
{
    free(reaped->paramName);
    free(reaped->secName);

    free(reaped);
}                               /* snmpTargetParamTable_dispose  */

/*
 * snmpTargetParamTable_addToList adds a targetParamTable_struct
 * to a list passed in. The list is assumed to be in a sorted order,
 * low to high and this procedure inserts a new struct in the proper
 * location. Sorting uses OID values based on paramName. A new equal value
 * overwrites a current one.
 */
void
snmpTargetParamTable_addToList(struct targetParamTable_struct *newEntry,
                               struct targetParamTable_struct **listPtr)
{
    static struct targetParamTable_struct *curr_struct, *prev_struct;
    int             i;
    size_t          newOIDLen = 0, currOIDLen = 0;
    oid             newOID[128], currOID[128];

    /*
     * if the list is empty, add the new entry to the top
     */
    if ((prev_struct = curr_struct = *listPtr) == 0) {
        *listPtr = newEntry;
        return;
    } else {
        /*
         * get the 'OID' value of the new entry
         */
        newOIDLen = strlen(newEntry->paramName);
        for (i = 0; i < (int) newOIDLen; i++) {
            newOID[i] = newEntry->paramName[i];
        }

        /*
         * search through the list for an equal or greater OID value
         */
        while (curr_struct != 0) {
            currOIDLen = strlen(curr_struct->paramName);
            for (i = 0; i < (int) currOIDLen; i++) {
                currOID[i] = curr_struct->paramName[i];
            }

            i = snmp_oid_compare(newOID, newOIDLen, currOID, currOIDLen);
            if (i == 0) {       /* Exact match, overwrite with new struct */
                newEntry->next = curr_struct->next;
                /*
                 * if curr_struct is the top of the list
                 */
                if (*listPtr == curr_struct)
                    *listPtr = newEntry;
                else
                    prev_struct->next = newEntry;
                snmpTargetParamTable_dispose(curr_struct);
                return;
            } else if (i < 0) { /* Found a greater OID, insert struct in front of it. */
                newEntry->next = curr_struct;
                /*
                 * if curr_struct is the top of the list
                 */
                if (*listPtr == curr_struct)
                    *listPtr = newEntry;
                else
                    prev_struct->next = newEntry;
                return;
            }
            prev_struct = curr_struct;
            curr_struct = curr_struct->next;
        }
    }
    /*
     * if we're here, no larger OID was ever found, insert on end of list
     */
    prev_struct->next = newEntry;
}                               /* snmpTargeParamTable_addToList  */

void
snmpTargetParamTable_add(struct targetParamTable_struct *newEntry)
{
    snmpTargetParamTable_addToList(newEntry, &aPTable);
}

/*
 * snmpTargetParamTable_remFromList removes a targetParamTable_struct
 * from the list passed in
 */
void
snmpTargetParamTable_remFromList(struct targetParamTable_struct *oldEntry,
                                 struct targetParamTable_struct **listPtr)
{
    struct targetParamTable_struct *tptr;

    if ((tptr = *listPtr) == 0)
        return;
    else if (tptr == oldEntry) {
        *listPtr = (*listPtr)->next;
        snmpTargetParamTable_dispose(tptr);
        return;
    } else {
        while (tptr->next != 0) {
            if (tptr->next == oldEntry) {
                tptr->next = tptr->next->next;
                snmpTargetParamTable_dispose(oldEntry);
                return;
            }
            tptr = tptr->next;
        }
    }
}                               /* snmpTargetParamTable_remFromList  */

/*
 * lookup OID in the link list of Table Entries
 */
struct targetParamTable_struct *
search_snmpTargetParamsTable(oid * baseName,
                             size_t baseNameLen,
                             oid * name, size_t * length, int exact)
{
    static struct targetParamTable_struct *temp_struct;
    int             i;
    size_t          myOIDLen = 0;
    oid             newNum[128];

    /*
     * lookup entry in p / * Get Current MIB ID
     */
    memcpy(newNum, baseName, baseNameLen * sizeof(oid));

    for (temp_struct = aPTable; temp_struct != 0;
         temp_struct = temp_struct->next) {
        for (i = 0; i < (int) strlen(temp_struct->paramName); i++) {
            newNum[baseNameLen + i] = temp_struct->paramName[i];
        }
        myOIDLen = baseNameLen + strlen(temp_struct->paramName);
        i = snmp_oid_compare(name, *length, newNum, myOIDLen);
        /*
         * Assumes that the linked list sorted by OID, low to high
         */
        if ((i == 0 && exact != 0) || (i < 0 && exact == 0)) {
            if (exact == 0) {
                memcpy(name, newNum, myOIDLen * sizeof(oid));
                *length = myOIDLen;
            }
            return temp_struct;
        }
    }
    return (0);
}                               /* search_snmpTargetParamsTable */

/*
 * snmpTargetParams_rowStatusCheck is boolean funciton that  checks
 * the status of a row's values in order to determine whether
 * the row should be notReady or notInService
 */
int
snmpTargetParams_rowStatusCheck(struct targetParamTable_struct *entry)
{
    if ((entry->mpModel < 0) || (entry->secModel < 0) ||
        (entry->secLevel < 0) || (entry->secName == 0))
        return 0;
    else
        return 1;
}                               /* snmtpTargetParamTable_rowStatusCheck */

/*
 * initialization routines
 */

/*
 * this variable defines function callbacks and type return information
 * for the snmpTargetAddrEntry mib
 */

struct variable2 snmpTargetParamsEntry_variables[] = {
    {SNMPTARGETPARAMSMPMODEL, ASN_INTEGER, RWRITE,
     var_snmpTargetParamsEntry, 1, {SNMPTARGETPARAMSMPMODELCOLUMN}},
    {SNMPTARGETPARAMSSECURITYMODEL, ASN_INTEGER, RWRITE,
     var_snmpTargetParamsEntry, 1, {SNMPTARGETPARAMSSECURITYMODELCOLUMN}},
    {SNMPTARGETPARAMSSECURITYNAME, ASN_OCTET_STR, RWRITE,
     var_snmpTargetParamsEntry, 1, {SNMPTARGETPARAMSSECURITYNAMECOLUMN}},
    {SNMPTARGETPARAMSSECURITYLEVEL, ASN_INTEGER, RWRITE,
     var_snmpTargetParamsEntry, 1, {SNMPTARGETPARAMSSECURITYLEVELCOLUMN}},
    {SNMPTARGETPARAMSSTORAGETYPE, ASN_INTEGER, RWRITE,
     var_snmpTargetParamsEntry, 1, {SNMPTARGETPARAMSSTORAGETYPECOLUMN}},
    {SNMPTARGETPARAMSROWSTATUS, ASN_INTEGER, RWRITE,
     var_snmpTargetParamsEntry, 1, {SNMPTARGETPARAMSROWSTATUSCOLUMN}}
};

/*
 * now load this mib into the agents mib table
 */
oid             snmpTargetParamsEntry_variables_oid[] =
    { 1, 3, 6, 1, 6, 3, 12, 1, 3, 1 };

void
init_snmpTargetParamsEntry(void)
{
    aPTable = 0;

    REGISTER_MIB("target/snmpTargetParamsEntry",
                 snmpTargetParamsEntry_variables, variable2,
                 snmpTargetParamsEntry_variables_oid);

    snmpd_register_config_handler("targetParams",
                                  snmpd_parse_config_targetParams, 0,
                                  NULL);

    /*
     * we need to be called back later
     */
    snmp_register_callback(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_STORE_DATA,
                           store_snmpTargetParamsEntry, NULL);
}                               /*  init_snmpTargetParmsEntry  */

int
snmpTargetParams_addParamName(struct targetParamTable_struct *entry,
                              char *cptr)
{
    size_t          len;
    if (cptr == 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargetParamsEntry: no param name in config string\n"));
        return (0);
    } else {
        len = strlen(cptr);
        /*
         * spec check for string 1-32
         */
        if (len < 1 || len > 32) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "ERROR snmpTargetParamsEntry: param name out of range in config string\n"));
            return (0);
        }
        entry->paramName = (char *) malloc(len + 1);
        strncpy(entry->paramName, cptr, len);
        entry->paramName[len] = '\0';
    }
    return (1);
}

int
snmpTargetParams_addMPModel(struct targetParamTable_struct *entry,
                            char *cptr)
{
    if (cptr == 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargetParamsEntry: no mp model in config string\n"));
        return (0);
    } else if (!(isdigit(*cptr))) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargeParamsEntry: mp model is not digit in config string\n"));
        return (0);
    }
    /*
     * spec check MP Model >= 0
     */
    else if ((entry->mpModel = (int) strtol(cptr, (char **) NULL, 0)) < 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargeParamsEntry: mp model out of range in config string\n"));
        return (0);
    }
    return (1);
}                               /* snmpTargetParams_addMPModel  */

int
snmpTargetParams_addSecModel(struct targetParamTable_struct *entry,
                             char *cptr)
{
    if (cptr == 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargetParamsEntry: no sec model in config string\n"));
        return (0);
    } else if (!(isdigit(*cptr))) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargeParamsEntry: security model is not digit in config string\n"));
        return (0);
    }
    /*
     * spec check Sec. Model > 0
     */
    else if ((entry->secModel =
              (int) strtol(cptr, (char **) NULL, 0)) <= 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargetParamsEntry: security model out of range in config string\n"));
        return (0);
    }
    return (1);
}                               /*  snmpTargetParams_addSecModel  */

int
snmpTargetParams_addSecName(struct targetParamTable_struct *entry,
                            char *cptr)
{
    size_t          len;
    if (cptr == 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargetParamsEntry: no security name in config string\n"));
        return (0);
    } else {
        len = strlen(cptr);
        entry->secName = (char *) malloc(len + 1);
        strncpy(entry->secName, cptr, len);
        entry->secName[len] = '\0';
    }
    return (1);
}                               /* snmpTargetParams_addSecName  */

int
snmpTargetParams_addSecLevel(struct targetParamTable_struct *entry,
                             char *cptr)
{
    if (cptr == 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargetParamsEntry: no security level in config string\n"));
        return (0);
    } else if (!(isdigit(*cptr))) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargeParamsEntry: security level is not digit in config string\n"));
        return (0);
    }
    /*
     * no spec range check, but noAuthNoPriv is 1 so...
     */
    else if ((entry->secLevel =
              (int) strtol(cptr, (char **) NULL, 0)) <= 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargeParamsEntry: security level is not greater than 0 in config string\n"));
        return (0);
    }
    return (1);
}                               /*  snmpTargetParams_addSecLevel  */

int
snmpTargetParams_addStorageType(struct targetParamTable_struct *entry,
                                char *cptr)
{
    if (cptr == 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargetParamsEntry: no storage type in config string\n"));
        return (0);
    } else if (!(isdigit(*cptr))) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargeParamsEntry: storage type is not digit in config string\n"));
        return (0);
    }
    /*
     * check that storage type is a possible value
     */
    else if (((entry->storageType = (int) strtol(cptr, (char **) NULL, 0))
              != SNMP_STORAGE_OTHER) &&
             (entry->storageType != SNMP_STORAGE_VOLATILE) &&
             (entry->storageType != SNMP_STORAGE_NONVOLATILE) &&
             (entry->storageType != SNMP_STORAGE_PERMANENT) &&
             (entry->storageType != SNMP_STORAGE_READONLY)) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargeParamsEntry: storage type is not a valid value of"));
        DEBUGMSG(("snmpTargetParamsEntry",
                  " other(%d), volatile(%d), nonvolatile(%d), permanent(%d), or ",
                  SNMP_STORAGE_OTHER, SNMP_STORAGE_VOLATILE,
                  SNMP_STORAGE_NONVOLATILE, SNMP_STORAGE_PERMANENT));
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "readonly(%d) in config string.\n",
                    SNMP_STORAGE_READONLY));

        return (0);
    }
    return (1);
}                               /* snmpTargetParams_addStorageType  */

int
snmpTargetParams_addRowStatus(struct targetParamTable_struct *entry,
                              char *cptr)
{
    if (cptr == 0) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargetParamsEntry: no row status in config string\n"));
        return (0);
    } else if (!(isdigit(*cptr))) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargeParamsEntry: row status is not digit in config string\n"));
        return (0);
    }
    /*
     * check that row status is a valid value
     */
    else if (((entry->rowStatus = (int) strtol(cptr, (char **) NULL, 0))
              != SNMP_ROW_ACTIVE) &&
             (entry->rowStatus != SNMP_ROW_NOTINSERVICE) &&
             (entry->rowStatus != SNMP_ROW_NOTREADY)) {
        DEBUGMSGTL(("snmpTargetParamsEntry",
                    "ERROR snmpTargetParamsEntry: Row Status is not a valid value of "));
        DEBUGMSG(("snmpTargetParamsEntry",
                  "active(%d), notinservice(%d), or notready(%d) in config string.\n",
                  SNMP_ROW_ACTIVE, SNMP_ROW_NOTINSERVICE,
                  SNMP_ROW_NOTREADY));

        return (0);
    }
    return (1);
}                               /* snmpTargetParams_addRowStatus  */

/*
 * timestamp the current entry's modification time
 */
void
update_timestamp(struct targetParamTable_struct *temp_struct)
{
    temp_struct->updateTime = time(NULL);
}

void
snmpd_parse_config_targetParams(const char *token, char *char_ptr)
{
    char           *cptr = char_ptr, buff[1024];
    struct targetParamTable_struct *newEntry;

    newEntry = snmpTargetParamTable_create();

    cptr = copy_nword(cptr, buff, sizeof(buff));
    if (snmpTargetParams_addParamName(newEntry, buff) == 0) {
        snmpTargetParamTable_dispose(newEntry);
        return;
    }
    cptr = copy_nword(cptr, buff, sizeof(buff));
    if (snmpTargetParams_addMPModel(newEntry, buff) == 0) {
        snmpTargetParamTable_dispose(newEntry);
        return;
    }
    cptr = copy_nword(cptr, buff, sizeof(buff));
    if (snmpTargetParams_addSecModel(newEntry, buff) == 0) {
        snmpTargetParamTable_dispose(newEntry);
        return;
    }
    cptr = copy_nword(cptr, buff, sizeof(buff));
    if (snmpTargetParams_addSecName(newEntry, buff) == 0) {
        snmpTargetParamTable_dispose(newEntry);
        return;
    }
    cptr = copy_nword(cptr, buff, sizeof(buff));
    if (snmpTargetParams_addSecLevel(newEntry, buff) == 0) {
        snmpTargetParamTable_dispose(newEntry);
        return;
    }
    cptr = copy_nword(cptr, buff, sizeof(buff));
    if (snmpTargetParams_addStorageType(newEntry, buff) == 0) {
        snmpTargetParamTable_dispose(newEntry);
        return;
    }
    cptr = copy_nword(cptr, buff, sizeof(buff));
    if (snmpTargetParams_addRowStatus(newEntry, buff) == 0) {
        snmpTargetParamTable_dispose(newEntry);
        return;
    }
    snprintf(buff, sizeof(buff),
            "snmp_parse_config_targetParams, read: %s %d %d %s %d %d %d\n",
            newEntry->paramName, newEntry->mpModel, newEntry->secModel,
            newEntry->secName, newEntry->secLevel, newEntry->storageType,
            newEntry->rowStatus);
    buff[ sizeof(buff)-1 ] = 0;
    DEBUGMSGTL(("snmpTargetParamsEntry", buff));

    update_timestamp(newEntry);
    snmpTargetParamTable_addToList(newEntry, &aPTable);
}                               /* snmpd_parse_config_target */

/*
 * shutdown routines
 */

/*
 * store_snmpTargetParamsEntry handles the presistent storage proccess
 * for this MIB table. It writes out all the non-volatile rows
 * to permanent storage on a shutdown
 */
int
store_snmpTargetParamsEntry(int majorID, int minorID, void *serverarg,
                            void *clientarg)
{
    struct targetParamTable_struct *curr_struct;
    char            line[1024];

    strcpy(line, "");
    if ((curr_struct = aPTable) != 0) {
        while (curr_struct != 0) {
            if ((curr_struct->storageType == SNMP_STORAGE_NONVOLATILE ||
                 curr_struct->storageType == SNMP_STORAGE_PERMANENT)
                &&
                (curr_struct->rowStatus == SNMP_ROW_ACTIVE ||
                 curr_struct->rowStatus == SNMP_ROW_NOTINSERVICE)) {
                snprintf(&line[strlen(line)], sizeof(line)-strlen(line)-1,
                        "targetParams %s %i %i %s %i %i %i\n",
                        curr_struct->paramName, curr_struct->mpModel,
                        curr_struct->secModel, curr_struct->secName,
                        curr_struct->secLevel, curr_struct->storageType,
                        curr_struct->rowStatus);
                line[ sizeof(line)-1 ] = 0;

                /*
                 * store to file
                 */
                snmpd_store_config(line);
            }
            curr_struct = curr_struct->next;
        }
    }
    return SNMPERR_SUCCESS;
}                               /*  store_snmpTargetParmsEntry  */

/*
 * MIB table access routines
 */

u_char         *
var_snmpTargetParamsEntry(struct variable * vp,
                          oid * name,
                          size_t * length,
                          int exact,
                          size_t * var_len, WriteMethod ** write_method)
{
    /*
     * variables we may use later
     */
    static long     long_ret;
    static unsigned char string[1500];
    struct targetParamTable_struct *temp_struct;

    switch (vp->magic) {
    case SNMPTARGETPARAMSMPMODEL:
        *write_method = write_snmpTargetParamsMPModel;
        break;
    case SNMPTARGETPARAMSSECURITYMODEL:
        *write_method = write_snmpTargetParamsSecModel;
        break;
    case SNMPTARGETPARAMSSECURITYNAME:
        *write_method = write_snmpTargetParamsSecName;
        break;
    case SNMPTARGETPARAMSSECURITYLEVEL:
        *write_method = write_snmpTargetParamsSecLevel;
        break;
    case SNMPTARGETPARAMSSTORAGETYPE:
        *write_method = write_snmpTargetParamsStorageType;
        break;
    case SNMPTARGETPARAMSROWSTATUS:
        *write_method = write_snmpTargetParamsRowStatus;
        break;
    default:
        *write_method = NULL;
    }

    *var_len = sizeof(long_ret);        /* assume an integer and change later if not */

    /*
     * look for OID in current table
     */
    if ((temp_struct = search_snmpTargetParamsTable(vp->name, vp->namelen,
                                                    name, length,
                                                    exact)) == 0) {
        return (0);
    }

    /*
     * We found what we were looking for, either the next OID or the exact OID
     */
    /*
     * this is where we do the value assignments for the mib results.
     */
    switch (vp->magic) {

    case SNMPTARGETPARAMSMPMODEL:
        /*
         * if unset value, (i.e. new row)
         */
        if (temp_struct->mpModel == -1)
            return (0);
        long_ret = temp_struct->mpModel;
        return (unsigned char *) &long_ret;

    case SNMPTARGETPARAMSSECURITYMODEL:
        /*
         * if unset value, (i.e. new row)
         */
        if (temp_struct->secModel == -1)
            return (0);
        long_ret = temp_struct->secModel;
        return (unsigned char *) &long_ret;

    case SNMPTARGETPARAMSSECURITYNAME:
        /*
         * if unset value, (i.e. new row)
         */
        if (temp_struct->secName == 0)
            return (0);
        /*
         * including null character.
         */
        memcpy(string, temp_struct->secName, strlen(temp_struct->secName));
        string[strlen(temp_struct->secName)] = '\0';
        *var_len = strlen(temp_struct->secName);
        return (unsigned char *) string;

    case SNMPTARGETPARAMSSECURITYLEVEL:
        /*
         * if unset value, (i.e. new row)
         */
        if (temp_struct->secLevel == -1)
            return (0);
        long_ret = temp_struct->secLevel;
        return (unsigned char *) &long_ret;

    case SNMPTARGETPARAMSSTORAGETYPE:
        long_ret = temp_struct->storageType;
        return (unsigned char *) &long_ret;

    case SNMPTARGETPARAMSROWSTATUS:
        long_ret = temp_struct->rowStatus;
        return (unsigned char *) &long_ret;

    default:
        DEBUGMSGTL(("snmpd",
                    "unknown sub-id %d in var_snmpTargetParamsEntry\n",
                    vp->magic));
    }
    return 0;
}                               /* var_snmpTargetParamsEntry */

/*
 * Assign a value to the mpModel variable.
 */
int
write_snmpTargetParamsMPModel(int action,
                              u_char * var_val,
                              u_char var_val_type,
                              size_t var_val_len,
                              u_char * statP, oid * name, size_t name_len)
{
    long            long_ret = *((long *) var_val);
    static long     old_mp;
    struct targetParamTable_struct *params = NULL;

    if (action == RESERVE1) {
        if (var_val_type != ASN_INTEGER) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsMPModel: not ASN_INTEGER\n"));
            return SNMP_ERR_WRONGTYPE;
        }
        if (var_val_len != sizeof(long)) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsMPModel: bad length\n"));
            return SNMP_ERR_WRONGLENGTH;
        }
        if (long_ret < 0) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsMPModel: MP Model out of range\n"));
            return SNMP_ERR_INCONSISTENTVALUE;
        }
    } else if (action == RESERVE2) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSMPMODELCOLUMN;
        params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                              snmpTargetParamsOIDLen,
                                              name, &name_len, 1);
        if (params == NULL) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsMPModel: BAD OID\n"));
            return SNMP_ERR_INCONSISTENTNAME;
        } else {
            /*
             * Row exists, check if it is changeable.
             */
            if (params->storageType == SNMP_STORAGE_READONLY) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "write to snmpTargetParamMPModel: row is read only\n"));
                return SNMP_ERR_NOTWRITABLE;
            }
            /*
             * Check if row is active.
             */
            if (params->rowStatus == SNMP_ROW_ACTIVE) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "write to snmpTargetParamsMPModel: this change not allowed in active row.\n"));
                return SNMP_ERR_INCONSISTENTVALUE;
            }

            old_mp = params->mpModel;
            params->mpModel = long_ret;

            if (params->rowStatus == SNMP_ROW_NOTREADY &&
                snmpTargetParams_rowStatusCheck(params)) {
                params->rowStatus = SNMP_ROW_NOTINSERVICE;
            }
        }
    } else if (action == COMMIT) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSMPMODELCOLUMN;
        if ((params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                                   snmpTargetParamsOIDLen,
                                                   name, &name_len,
                                                   1)) != NULL) {
            update_timestamp(params);
        }
    } else if (action == FREE || action == UNDO) {
        /*
         * Try to undo the SET here (abnormal usage of FREE clause)
         */
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSMPMODELCOLUMN;
        if ((params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                                   snmpTargetParamsOIDLen,
                                                   name, &name_len,
                                                   1)) != NULL) {
            if (params->storageType != SNMP_STORAGE_READONLY
                && params->rowStatus != SNMP_ROW_ACTIVE) {
                params->mpModel = old_mp;
                if (params->rowStatus == SNMP_ROW_NOTINSERVICE &&
                    !snmpTargetParams_rowStatusCheck(params)) {
                    params->rowStatus = SNMP_ROW_NOTREADY;
                }
            }
        }
    }

    return SNMP_ERR_NOERROR;
}                               /* write_snmpTargetParamsMPModel */

/*
 * Assign a value to the secModel variable.
 */
int
write_snmpTargetParamsSecModel(int action,
                               u_char * var_val,
                               u_char var_val_type,
                               size_t var_val_len,
                               u_char * statP, oid * name, size_t name_len)
{
    long            long_ret = *((long *) var_val);
    static long     old_sec;
    struct targetParamTable_struct *params = NULL;

    if (action == RESERVE1) {
        if (var_val_type != ASN_INTEGER) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecModel: not ASN_INTEGER\n"));
            return SNMP_ERR_WRONGTYPE;
        }
        if (var_val_len != sizeof(long)) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecModel: bad length\n"));
            return SNMP_ERR_WRONGLENGTH;
        }
        if (long_ret <= 0) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecModel: secModel out of range\n"));
            return SNMP_ERR_WRONGVALUE;
        }
        if (find_sec_mod(long_ret) == NULL && long_ret >= 3) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecModel: secModel %d unsupported\n",
                        long_ret));
            return SNMP_ERR_INCONSISTENTVALUE;
        }

    } else if (action == RESERVE2) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSECURITYMODELCOLUMN;
        params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                              snmpTargetParamsOIDLen,
                                              name, &name_len, 1);
        if (params == NULL) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecModel: BAD OID\n"));
            return SNMP_ERR_INCONSISTENTNAME;
        } else {
            /*
             * Row exists, check if it is changeable.
             */
            if (params->storageType == SNMP_STORAGE_READONLY) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "write to snmpTargetParamSecModel: row is read only\n"));
                return SNMP_ERR_NOTWRITABLE;
            }
            /*
             * Check if row is active.
             */
            if (params->rowStatus == SNMP_ROW_ACTIVE) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "write to snmpTargetParamsSecModel: this change not allowed in active row.\n"));
                return SNMP_ERR_INCONSISTENTVALUE;
            }

            old_sec = params->secModel;
            params->secModel = long_ret;

            if (params->rowStatus == SNMP_ROW_NOTREADY &&
                snmpTargetParams_rowStatusCheck(params)) {
                params->rowStatus = SNMP_ROW_NOTINSERVICE;
            }
        }
    } else if (action == COMMIT) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSECURITYMODELCOLUMN;
        if ((params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                                   snmpTargetParamsOIDLen,
                                                   name, &name_len,
                                                   1)) != NULL) {
            update_timestamp(params);
        }
    } else if (action == FREE || action == UNDO) {
        /*
         * Try to undo the SET here (abnormal usage of FREE clause)
         */
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSECURITYMODELCOLUMN;
        if ((params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                                   snmpTargetParamsOIDLen,
                                                   name, &name_len,
                                                   1)) != NULL) {
            if (params->storageType != SNMP_STORAGE_READONLY
                && params->rowStatus != SNMP_ROW_ACTIVE) {
                params->secModel = old_sec;
                if (params->rowStatus == SNMP_ROW_NOTINSERVICE &&
                    !snmpTargetParams_rowStatusCheck(params)) {
                    params->rowStatus = SNMP_ROW_NOTREADY;
                }
            }
        }
    }

    return SNMP_ERR_NOERROR;
}                               /* write_snmpTargetParamsSecModel */

/*
 * Assign a value to the SecLevel variable.
 */
int
write_snmpTargetParamsSecLevel(int action,
                               u_char * var_val,
                               u_char var_val_type,
                               size_t var_val_len,
                               u_char * statP, oid * name, size_t name_len)
{
    long            long_ret = *((long *) var_val);
    static long     old_level;
    struct targetParamTable_struct *params = NULL;

    if (action == RESERVE1) {
        if (var_val_type != ASN_INTEGER) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecLevel: not ASN_INTEGER\n"));
            return SNMP_ERR_WRONGTYPE;
        }
        if (var_val_len != sizeof(long)) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecLevel: bad length\n"));
            return SNMP_ERR_WRONGLENGTH;
        }
        if (long_ret <= 0 || long_ret > 3) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecLevel: security level is not noAuthNoPriv(1), authNopriv(2) or authPriv(3)\n"));
            return SNMP_ERR_WRONGVALUE;
        }
    } else if (action == RESERVE2) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSECURITYLEVELCOLUMN;
        params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                              snmpTargetParamsOIDLen,
                                              name, &name_len, 1);
        if (params == NULL) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecLevel: BAD OID\n"));
            return SNMP_ERR_INCONSISTENTNAME;
        } else {
            /*
             * Row exists, check if it is changeable.
             */
            if (params->storageType == SNMP_STORAGE_READONLY) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "write to snmpTargetParamSecLevel: row is read only\n"));
                return SNMP_ERR_NOTWRITABLE;
            }
            /*
             * Check if row is active.
             */
            if (params->rowStatus == SNMP_ROW_ACTIVE) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "write to snmpTargetParamsSecLevel: this change not allowed in active row.\n"));
                return SNMP_ERR_INCONSISTENTVALUE;
            }

            old_level = params->secLevel;
            params->secLevel = long_ret;

            if (params->rowStatus == SNMP_ROW_NOTREADY &&
                snmpTargetParams_rowStatusCheck(params)) {
                params->rowStatus = SNMP_ROW_NOTINSERVICE;
            }
        }
    } else if (action == COMMIT) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSECURITYLEVELCOLUMN;
        if ((params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                                   snmpTargetParamsOIDLen,
                                                   name, &name_len,
                                                   1)) != NULL) {
            update_timestamp(params);
        }
    } else if (action == FREE || action == UNDO) {
        /*
         * Try to undo the SET here (abnormal usage of FREE clause)
         */
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSECURITYLEVELCOLUMN;
        if ((params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                                   snmpTargetParamsOIDLen,
                                                   name, &name_len,
                                                   1)) != NULL) {
            if (params->storageType != SNMP_STORAGE_READONLY
                && params->rowStatus != SNMP_ROW_ACTIVE) {
                params->secLevel = old_level;
                if (params->rowStatus == SNMP_ROW_NOTINSERVICE &&
                    !snmpTargetParams_rowStatusCheck(params)) {
                    params->rowStatus = SNMP_ROW_NOTREADY;
                }
            }
        }
    }

    return SNMP_ERR_NOERROR;
}                               /* write_snmpTargetParamsSecLevel */

/*
 * Assign a value to the storageType variable.
 */
int
write_snmpTargetParamsStorageType(int action,
                                  u_char * var_val,
                                  u_char var_val_type,
                                  size_t var_val_len,
                                  u_char * statP,
                                  oid * name, size_t name_len)
{
    long            long_ret = *((long *) var_val);
    static long     old_st;
    struct targetParamTable_struct *params = NULL;

    if (action == RESERVE1) {
        if (var_val_type != ASN_INTEGER) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsStorageType: not ASN_INTEGER\n"));
            return SNMP_ERR_WRONGTYPE;
        }
        if (var_val_len != sizeof(long)) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsStorageType: bad length\n"));
            return SNMP_ERR_WRONGLENGTH;
        }
        if (long_ret != SNMP_STORAGE_OTHER &&
            long_ret != SNMP_STORAGE_VOLATILE &&
            long_ret != SNMP_STORAGE_NONVOLATILE) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsStorageType: attempted storage type not a valid"));
            DEBUGMSG(("snmpTargetParamsEntry",
                      " value of other(%d), volatile(%d), or nonvolatile(%d)\n",
                      SNMP_STORAGE_OTHER, SNMP_STORAGE_VOLATILE,
                      SNMP_STORAGE_NONVOLATILE));
            return SNMP_ERR_WRONGVALUE;
        }
    } else if (action == RESERVE2) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSTORAGETYPECOLUMN;
        params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                              snmpTargetParamsOIDLen,
                                              name, &name_len, 1);
        if (params == NULL) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsStorageType: BAD OID\n"));
            return SNMP_ERR_INCONSISTENTNAME;
        } else {
            /*
             * Row exists, check if it is changeable.
             */
            if (params->storageType == SNMP_STORAGE_READONLY ||
                params->storageType == SNMP_STORAGE_PERMANENT) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "write to snmpTargetParamsStorageType: row has unchangeable storage status: %d\n",
                            params->storageType));
                return SNMP_ERR_INCONSISTENTVALUE;
            }

            old_st = params->storageType;
            params->storageType = long_ret;
        }
    } else if (action == FREE || action == UNDO) {
        /*
         * Try to undo the SET here (abnormal usage of FREE clause)
         */
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSTORAGETYPECOLUMN;
        if ((params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                                   snmpTargetParamsOIDLen,
                                                   name, &name_len,
                                                   1)) != NULL) {
            if (params->storageType != SNMP_STORAGE_READONLY
                && params->storageType != SNMP_STORAGE_PERMANENT) {
                params->storageType = old_st;
            }
        }
    }

    return SNMP_ERR_NOERROR;
}                               /* write_snmpTargetParamsStorageType */

/*
 * Assign a value to the secName variable.
 */
int
write_snmpTargetParamsSecName(int action,
                              u_char * var_val,
                              u_char var_val_type,
                              size_t var_val_len,
                              u_char * statP, oid * name, size_t name_len)
{
    static char    *old_name;
    struct targetParamTable_struct *params = NULL;

    if (action == RESERVE1) {
        if (var_val_type != ASN_OCTET_STR) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecName: not ASN_OCTET_STR\n"));
            return SNMP_ERR_WRONGTYPE;
        }
        if (var_val_len > 255 || var_val_len < 0) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecName: bad length\n"));
            return SNMP_ERR_WRONGLENGTH;
        }
    } else if (action == RESERVE2) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSECURITYNAMECOLUMN;
        params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                              snmpTargetParamsOIDLen,
                                              name, &name_len, 1);
        if (params == NULL) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsSecName: BAD OID\n"));
            return SNMP_ERR_INCONSISTENTNAME;
        } else {
            /*
             * Row exists, check if it is changeable.
             */
            if (params->storageType == SNMP_STORAGE_READONLY) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "write to snmpTargetParamSecName: row is read only\n"));
                return SNMP_ERR_NOTWRITABLE;
            }
            /*
             * Check if row is active.
             */
            if (params->rowStatus == SNMP_ROW_ACTIVE) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "write to snmpTargetParamsSecName: this change not allowed in active row.\n"));
                return SNMP_ERR_INCONSISTENTVALUE;
            }

            old_name = params->secName;
            params->secName = (char *) malloc(var_val_len + 1);
            if (params->secName == NULL) {
                return SNMP_ERR_RESOURCEUNAVAILABLE;
            }
            memcpy(params->secName, var_val, var_val_len);
            params->secName[var_val_len] = '\0';

            if (params->rowStatus == SNMP_ROW_NOTREADY &&
                snmpTargetParams_rowStatusCheck(params)) {
                params->rowStatus = SNMP_ROW_NOTINSERVICE;
            }
        }
    } else if (action == COMMIT) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSECURITYNAMECOLUMN;
        if ((params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                                   snmpTargetParamsOIDLen,
                                                   name, &name_len,
                                                   1)) != NULL) {
            update_timestamp(params);
            SNMP_FREE(old_name);
            old_name = NULL;
        }
    } else if (action == FREE || action == UNDO) {
        /*
         * Try to undo the SET here (abnormal usage of FREE clause)
         */
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSSECURITYNAMECOLUMN;
        if ((params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                                   snmpTargetParamsOIDLen,
                                                   name, &name_len,
                                                   1)) != NULL) {
            if (params->storageType != SNMP_STORAGE_READONLY
                && params->rowStatus != SNMP_ROW_ACTIVE) {
                SNMP_FREE(params->secName);
                params->secName = old_name;
                if (params->rowStatus == SNMP_ROW_NOTINSERVICE &&
                    !snmpTargetParams_rowStatusCheck(params)) {
                    params->rowStatus = SNMP_ROW_NOTREADY;
                }
            }
        }
    }

    return SNMP_ERR_NOERROR;
}                               /* write_snmpTargetParamsSecName */

/*
 * snmpTargeParams_createNewRow is called from write_snmpTargetParamsRowStatus
 * when a new row is required. It creates a new row with
 * the index of the passed in 'name' (i.e. full index OID) and
 * adds it to the linked list. 'name' should be the full OID of the new index.
 * It passes back 0 if unsuccessfull.
 */
int
snmpTargetParams_createNewRow(oid * name, size_t name_len)
{
    int             pNameLen, i;
    struct targetParamTable_struct *temp_struct;

    /*
     * setup a new snmpTargetParamTable structure and add it to the list
     */
    pNameLen = name_len - snmpTargetParamsOIDLen;
    if (pNameLen > 0) {
        temp_struct = snmpTargetParamTable_create();
        temp_struct->paramName = (char *) malloc(pNameLen + 1);

        for (i = 0; i < pNameLen; i++) {
            temp_struct->paramName[i] =
                (char) name[i + snmpTargetParamsOIDLen];
        }

        temp_struct->paramName[pNameLen] = '\0';
        temp_struct->rowStatus = SNMP_ROW_NOTREADY;

        update_timestamp(temp_struct);
        snmpTargetParamTable_addToList(temp_struct, &aPTable);

        return 1;
    }

    return 0;
}                               /* snmpTargetParams_createNewRow */

/*
 * Assign a value to the Row Status variable
 */
int
write_snmpTargetParamsRowStatus(int action,
                                u_char * var_val,
                                u_char var_val_type,
                                size_t var_val_len,
                                u_char * statP,
                                oid * name, size_t name_len)
{
    static long     value;
    struct targetParamTable_struct *params = NULL;

    if (action == RESERVE1) {
        if (var_val_type != ASN_INTEGER) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsRowStatus not ASN_INTEGER\n"));
            return SNMP_ERR_WRONGTYPE;
        }
        if (var_val_len != sizeof(long)) {
            DEBUGMSGTL(("snmpTargetParamsEntry",
                        "write to snmpTargetParamsRowStatus: bad length\n"));
            return SNMP_ERR_WRONGLENGTH;
        }
        value = *((long *) var_val);
        if (value == SNMP_ROW_NOTREADY || value < 1 || value > 6) {
            return SNMP_ERR_WRONGVALUE;
        }

        /*
         * Check index value is reasonable.
         */

        if (name_len < snmpTargetParamsOIDLen + 1 ||
            name_len > snmpTargetParamsOIDLen + 32) {
            DEBUGMSGTL(("snmpTargetParamsEntry", "bad index length %d\n",
                        name_len - snmpTargetParamsOIDLen));
            return SNMP_ERR_NOCREATION;
        }

        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSROWSTATUSCOLUMN;
        params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                              snmpTargetParamsOIDLen,
                                              name, &name_len, 1);
        if (params != NULL) {
            if (value == SNMP_ROW_CREATEANDGO
                || value == SNMP_ROW_CREATEANDWAIT) {
                value = SNMP_ROW_NOTREADY;
                return SNMP_ERR_INCONSISTENTVALUE;
            }
            if (params->storageType == SNMP_STORAGE_READONLY) {
                DEBUGMSGTL(("snmpTargetParamsEntry",
                            "row is read only\n"));
                return SNMP_ERR_NOTWRITABLE;
            }
            if (params->storageType == SNMP_STORAGE_PERMANENT) {
                if (value == SNMP_ROW_DESTROY) {
                    DEBUGMSGTL(("snmpTargetParamsEntry",
                                "unable to destroy permanent row\n"));
                    return SNMP_ERR_INCONSISTENTVALUE;
                }
            }
        } else {
            if (value == SNMP_ROW_ACTIVE || value == SNMP_ROW_NOTINSERVICE) {
                return SNMP_ERR_INCONSISTENTVALUE;
            }
            if (value == SNMP_ROW_CREATEANDGO
                || value == SNMP_ROW_CREATEANDWAIT) {
                if (snmpTargetParams_createNewRow(name, name_len) == 0) {
                    DEBUGMSGTL(("snmpTargetParamsEntry",
                                "couldn't malloc() new row\n"));
                    return SNMP_ERR_RESOURCEUNAVAILABLE;
                }
            }
        }
    } else if (action == ACTION) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSROWSTATUSCOLUMN;
        params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                              snmpTargetParamsOIDLen,
                                              name, &name_len, 1);
        if (params != NULL) {
            if (value == SNMP_ROW_CREATEANDGO) {
                /*
                 * Check whether all the required objects have been set.
                 */
                if (snmpTargetParams_rowStatusCheck(params)) {
                    params->rowStatus = SNMP_ROW_ACTIVE;
                } else {
                    params->rowStatus = SNMP_ROW_NOTREADY;
                }
            } else if (value == SNMP_ROW_CREATEANDWAIT) {
                /*
                 * Check whether all the required objects have been set.
                 */
                if (snmpTargetParams_rowStatusCheck(params)) {
                    params->rowStatus = SNMP_ROW_NOTINSERVICE;
                } else {
                    params->rowStatus = SNMP_ROW_NOTREADY;
                }
            } else if (value == SNMP_ROW_ACTIVE) {
                if (params->rowStatus == SNMP_ROW_NOTINSERVICE) {
                    params->rowStatus = SNMP_ROW_ACTIVE;
                } else if (params->rowStatus == SNMP_ROW_NOTREADY) {
                    return SNMP_ERR_INCONSISTENTVALUE;
                }
            } else if (value == SNMP_ROW_NOTINSERVICE) {
                if (params->rowStatus == SNMP_ROW_ACTIVE) {
                    params->rowStatus = SNMP_ROW_NOTINSERVICE;
                } else if (params->rowStatus == SNMP_ROW_NOTREADY) {
                    return SNMP_ERR_INCONSISTENTVALUE;
                }
            }
        }
    } else if (action == COMMIT) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSROWSTATUSCOLUMN;
        params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                              snmpTargetParamsOIDLen,
                                              name, &name_len, 1);
        if (params != NULL) {
            if (value == SNMP_ROW_DESTROY) {
                snmpTargetParamTable_remFromList(params, &aPTable);
            }
            if (value == SNMP_ROW_ACTIVE || value == SNMP_ROW_NOTINSERVICE) {
                update_timestamp(params);
            }
        }
    } else if (action == UNDO || action == FREE) {
        snmpTargetParamsOID[snmpTargetParamsOIDLen - 1] =
            SNMPTARGETPARAMSROWSTATUSCOLUMN;
        params = search_snmpTargetParamsTable(snmpTargetParamsOID,
                                              snmpTargetParamsOIDLen,
                                              name, &name_len, 1);
        if (value == SNMP_ROW_CREATEANDGO
            || value == SNMP_ROW_CREATEANDWAIT) {
            if (params != NULL) {
                snmpTargetParamTable_remFromList(params, &aPTable);
            }
        }
    }
    return SNMP_ERR_NOERROR;
}

struct targetParamTable_struct *
get_paramEntry(char *name)
{
    static struct targetParamTable_struct *ptr;
    for (ptr = aPTable; ptr; ptr = ptr->next) {
        if (strcmp(ptr->paramName, name) == 0) {
            return ptr;
        }
    }
    return NULL;
}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require "ostruct"
require File.expand_path('../fixtures/classes', __FILE__)

describe "OpenStruct#==" do
  before :each do
    @os = OpenStruct.new(name: "John")
  end

  it "returns false when the passed argument is no OpenStruct" do
    (@os == Object.new).should be_false
    (@os == "Test").should be_false
    (@os == 10).should be_false
    (@os == :sym).should be_false
  end

  it "returns true when self and other are equal method/value wise" do
    (@os == @os).should be_true
    (@os == OpenStruct.new(name: "John")).should be_true
    (@os == OpenStructSpecs::OpenStructSub.new(name: "John")).should be_true

    (@os == OpenStruct.new(name: "Jonny")).should be_false
    (@os == OpenStructSpecs::OpenStructSub.new(name: "Jonny")).should be_false

    (@os == OpenStruct.new(name: "John", age: 20)).should be_false
    (@os == OpenStructSpecs::OpenStructSub.new(name: "John", age: 20)).should be_false
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.svcet.cashportal.web.beans;

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

import com.svcet.cashportal.domain.product.ft.FundTransfer;

public class FundTransferInquiryResponse {

	List<FundTransfer> fundTransferList = new ArrayList<FundTransfer>();

	public List<FundTransfer> getFundTransferList() {
		return fundTransferList;
	}

	public void setFundTransferList(List<FundTransfer> fundTransferList) {
		this.fundTransferList = fundTransferList;
	};

}


text:
package modi.indicators;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;

public class I_RandomLayout implements Indicator {

	private Point start;
	private Point end;

	public I_RandomLayout() {
		start = new Point(0,0);
		end = new Point(0,0);
	}

	@Override
	public void draw(Graphics2D g2) {
		g2.setStroke(new BasicStroke(2));
		g2.setColor(Color.red);

		g2.drawLine(start.x, start.y, end.x, start.y);
		g2.drawLine(start.x, end.y, end.x, end.y);
		g2.drawLine(start.x, start.y, start.x, end.y);
		g2.drawLine(end.x, start.y, end.x, end.y);
	}

	public void setStart(Point start) {
		this.start = start;
	}

	public void setEnd(Point end) {
		this.end = end;
	}
}


text:
import React, { HTMLAttributes, ReactElement } from 'react';
import classnames from 'classnames';
import styles from './Grid.module.scss';

const Grid = (
	props: {
		columns?: number;
		children: ReactElement | ReactElement[] | HTMLCollection;
	} & HTMLAttributes<HTMLDivElement>,
) => {
	const { children, columns = 3, className, ...rest } = props;
	return (
		<div
			className={classnames(styles.grid, className)}
			{...rest}
			style={{
				gridTemplateColumns: `repeat(
            auto-fit,
            minmax(${Math.floor(100 / columns) - 10}rem, 1fr)
        )`,
			}}
		>
			{children}
		</div>
	);
};

export default Grid;


text:
mkdir release && pushd release
cmake -DCMAKE_BUILD_TYPE=Release ..
make VERBOSE=1
install -d $PREFIX/bin
install bindash $PREFIX/bin
popd


text:
<?php

namespace Zimbra\Enum\Tests;

use \PHPUnit_Framework_TestCase;
use Zimbra\Enum\ConvActionOp;

/**
 * Testcase class for ConvActionOp.
 */
class ConvActionOpTest extends PHPUnit_Framework_TestCase
{
    public function testConvActionOp()
    {
        $values = [
            'DELETE'   => 'delete',
            'READ'     => 'read',
            'FLAG'     => 'flag',
            'PRIORITY' => 'priority',
            'TAG'      => 'tag',
            'MOVE'     => 'move',
            'SPAM'     => 'spam',
            'TRASH'    => 'trash',
        ];
        foreach ($values as $enum => $value)
        {
            $this->assertSame(ConvActionOp::$enum()->value(), $value);
        }
    }
}


text:
var mongoose = require('mongoose');

var incidentSchema = new mongoose.Schema({
	_id         : {type: mongoose.Schema.Types.ObjectId, unique: true},
	Date       : Date,
	Loc: {
		type: {type: String},
		coordinates: {type: [Number]}    //[long,lat]
	},
	ReportType       : String,
	Address    : String
});

incidentSchema.index({ Loc: '2dsphere' });

module.exports = mongoose.model('Incident', incidentSchema);


text:
"""
SQLAlchemy adapter module.

@see: U{SQLAlchemy homepage<http://www.sqlalchemy.org>}

@since: 0.4
"""

from sqlalchemy.orm import collections

import pyamf
from pyamf.adapters import util

pyamf.add_type(collections.InstrumentedList, util.to_list)
pyamf.add_type(collections.InstrumentedDict, util.to_dict)
pyamf.add_type(collections.InstrumentedSet, util.to_set)

if hasattr(collections, 'CollectionAdapter'):
    pyamf.add_type(collections.CollectionAdapter, util.to_list)


text:
import os.path
import subprocess
import shutil

from gii.core import *
from gii.qt.dialogs   import requestString, alertMessage
from util.SQScript import SQScriptCompiler
from mock import _MOCK

##----------------------------------------------------------------##
def _getModulePath( path ):
	import os.path
	return os.path.dirname( __file__ ) + '/' + path

EMPTY_SQ_SCRIPT = '''//sqscript
!start

'''

##----------------------------------------------------------------##
class SQScriptAssetCreator(AssetCreator):
	def getAssetType( self ):
		return 'sq_script'

	def getLabel( self ):
		return 'SQScript'

	def createAsset( self, name, contextNode, assetType ):
		ext = '.sq'
		filename = name + ext
		if contextNode.isType('folder'):
			nodepath = contextNode.getChildPath( filename )
		else:
			nodepath = contextNode.getSiblingPath( filename )

		fullpath = AssetLibrary.get().getAbsPath( nodepath )
		if os.path.exists(fullpath):
			raise Exception('File already exist:%s'%fullpath)
		fp = open(fullpath,'w')
		fp.write( EMPTY_SQ_SCRIPT )
		fp.close()
		return nodepath

##----------------------------------------------------------------##
class SQScriptAssetManager(AssetManager):
	def getMetaType(self):
		return 'script'

	def getName(self):
		return 'asset_manager.sq_script'

	def acceptAssetFile( self, filePath ):
		if os.path.isdir(filePath): return False
		if not filePath.endswith( '.sq' ): return False
		return True

	def importAsset( self, node, reload = False ):
		node.assetType = 'sq_script'
		node.setObjectFile( 'data', node.getCacheFile( 'data' ) )
		compiler = SQScriptCompiler()
		try:
			root = compiler.parseFile( node.getAbsFilePath() )
		except Exception, e:
			logging.error( e )
			return False

		jsonHelper.trySaveJSON( root.toJSON(), node.getAbsObjectFile( 'data' ) )
		return True

	def editAsset(self, node):
		editor = app.getModule( 'sq_script_editor' )
		if not editor:
			return alertMessage( 'Editor not load', 'Asset Editor not found!' )
		else:
			editor.openAsset( node )

SQScriptAssetManager().register()
SQScriptAssetCreator().register()
AssetLibrary.get().setAssetIcon( 'sq_script',  'story' )

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


text:
// configlist.h
// LMNO LALR(1) parser generator
//
// Copyright ©2010 Brigham Toskin
// (Based on LEMON v1 parser generator, public domain)
//////////////////////////////////////////////////////

void Configlist_init(/* void */);
struct config *Configlist_add(/* struct rule *, int */);
struct config *Configlist_addbasis(/* struct rule *, int */);
void Configlist_closure(/* void */);
void Configlist_sort(/* void */);
void Configlist_sortbasis(/* void */);
struct config *Configlist_return(/* void */);
struct config *Configlist_basis(/* void */);
void Configlist_eat(/* struct config * */);
void Configlist_reset(/* void */);


text:
package org.tensorics.core.tensor;

/**
 * The most generic interface of a multidimensional object within tensorics. Values can be retrieved from it and it
 * knows for which positions it contains values.
 *
 * @param <V> the type of the values of the tensoric object
 * @author kfuchsbe
 */
public interface Tensoric<V> {

    /**
     * @param position the position in the N-dimensional space where to find the value.
     * @return the value at the given position
     * @throws IllegalArgumentException         when number of coordinates is not sufficient
     * @throws java.util.NoSuchElementException if the tensor contains no element for the given position
     */
    V get(Position position);

    /**
     * @param coordinates form N-dimensional space where to find the value.
     * @return a value at the given coordinates.
     * @throws IllegalArgumentException         if the number of coordinates in incorrect
     * @throws java.util.NoSuchElementException if the tensor contains no element for the position constructed from the
     *                                          given coordinates.
     */
    default V get(Object... coordinates) {
        return get(Position.of(coordinates));
    }

    /**
     * Returns {@code true} if the tensoric object contains the given position, {@code false} otherwise.
     *
     * @param position the position to be checked
     * @return {@code true} if the position is contained in the tensoric object, {@code false} otherwise.
     */
    boolean contains(Position position);

    /**
     * Convenience method for {@link #contains(Position)}, with the position constructed from the given coordinates.
     *
     * @param coordinates the coordinates which represent the position to be checked
     * @return {@code true} if the position represented by the given coordinates is contained in the tensoric object,
     * {@code false} otherwise.
     */
    default boolean contains(Object... coordinates) {
        return contains(Position.of(coordinates));
    }

}


text:
package com.marklogic.client.example.extension;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import com.marklogic.client.DatabaseClient;
import com.marklogic.client.DatabaseClientFactory;
import com.marklogic.client.DatabaseClientFactory.Authentication;
import com.marklogic.client.FailedRequestException;
import com.marklogic.client.ForbiddenUserException;
import com.marklogic.client.ResourceNotFoundException;
import com.marklogic.client.admin.ExtensionMetadata;
import com.marklogic.client.admin.MethodType;
import com.marklogic.client.admin.ResourceExtensionsManager;
import com.marklogic.client.admin.ResourceExtensionsManager.MethodParameters;
import com.marklogic.client.document.DocumentManager.Metadata;
import com.marklogic.client.document.XMLDocumentManager;
import com.marklogic.client.example.cookbook.Util;
import com.marklogic.client.example.cookbook.Util.ExampleProperties;
import com.marklogic.client.io.DocumentMetadataHandle;
import com.marklogic.client.io.Format;
import com.marklogic.client.io.InputStreamHandle;
import com.marklogic.client.io.StringHandle;

/**
 * BatchManagerExample illustrates executing a batch of document read, write,
 * or delete requests using the BatchManager example of a Resource Extension.
 */
public class BatchManagerExample {
	public static void main(String[] args)
	throws IOException, ResourceNotFoundException, ForbiddenUserException, FailedRequestException {
		run(Util.loadProperties());
	}

	// install and then use the resource extension
	public static void run(ExampleProperties props)
	throws IOException, ResourceNotFoundException, ForbiddenUserException, FailedRequestException {
		System.out.println("example: "+BatchManagerExample.class.getName());

		installResourceExtension(props.host, props.port,
				props.adminUser, props.adminPassword, props.authType);

		useResource(props.host, props.port,
				props.writerUser, props.writerPassword, props.authType);

		tearDownExample(props.host, props.port,
				props.adminUser, props.adminPassword, props.authType);
	}

	// install the resource extension on the server
	public static void installResourceExtension(String host, int port, String user, String password, Authentication authType)
	throws IOException {
		// create the client
		DatabaseClient client = DatabaseClientFactory.newClient(host, port, user, password, authType);

		// create a manager for resource extensions
		ResourceExtensionsManager resourceMgr = client.newServerConfigManager().newResourceExtensionsManager();

		// specify metadata about the resource extension
		ExtensionMetadata metadata = new ExtensionMetadata();
		metadata.setTitle("Document Batch Resource Services");
		metadata.setDescription("This plugin supports batch processing for documents");
		metadata.setProvider("MarkLogic");
		metadata.setVersion("0.1");

		// acquire the resource extension source code
		InputStream sourceStream = Util.openStream(
			"scripts"+File.separator+BatchManager.NAME+".xqy");
		if (sourceStream == null)
			throw new RuntimeException("Could not read example resource extension");

		// create a handle on the extension source code
		InputStreamHandle handle = new InputStreamHandle(sourceStream);

		// write the resource extension to the database
		resourceMgr.writeServices(BatchManager.NAME, handle, metadata,
				new MethodParameters(MethodType.POST));

		System.out.println("Installed the resource extension on the server");

		// release the client
		client.release();
	}

	// use the resource manager
	public static void useResource(String host, int port, String user, String password, Authentication authType)
	throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException {
		// create the client
		DatabaseClient client = DatabaseClientFactory.newClient(host, port, user, password, authType);

		setUpExample(client);

		// create the batch manager
		BatchManager batchMgr = new BatchManager(client);

		// collect the request items
		BatchManager.BatchRequest request = batchMgr.newBatchRequest();
		request.withRead("/batch/read1.xml", "application/xml");
		request.withRead("/batch/read2.xml", Metadata.COLLECTIONS, "application/xml");
		request.withDelete("/batch/delete1.xml");
		request.withWrite("/batch/write1.xml",
				new StringHandle().withFormat(Format.XML).with("<write1/>"));
		DocumentMetadataHandle meta2 = new DocumentMetadataHandle();
		meta2.getCollections().add("/batch/collection2");
		request.withWrite("/batch/write2.xml",
				meta2,
				new StringHandle().withFormat(Format.XML).with("<write2/>"));

		// apply the request
		BatchManager.BatchResponse response = batchMgr.apply(request);

		System.out.println("Applied the batch request with " +
				(response.getSuccess() ? "success" : "failure")+":");

		// iterate over the response items
		while (response.hasNext()) {
			BatchManager.OutputItem item = response.next();
			BatchManager.OperationType itemType = item.getOperationType();
			String itemUri = item.getUri();
			if (item.getSuccess()) {
				System.out.println(itemType.name().toLowerCase()+" on "+itemUri);

				// inspect the response for a document read request
				if (itemType == BatchManager.OperationType.READ) {
					BatchManager.ReadOutput readItem = (BatchManager.ReadOutput) item;

					// show the document metadata read from the database
					if (readItem.hasMetadata()) {
						StringHandle metadataHandle = readItem.getMetadata(new StringHandle());
						System.out.println("with metadata:\n"+metadataHandle.get());
					}
					// show the document content read from the database
					if (readItem.hasContent()) {
						StringHandle contentHandle = readItem.getContent(new StringHandle());
						System.out.println("with content:\n"+contentHandle.get());
					}
				}
			} else {
				System.out.println(itemType.name().toLowerCase()+" failed on "+itemUri);
				if (item.hasException()) {
					StringHandle exceptionHandle = item.getException(new StringHandle());
					System.out.println("with exception:\n"+exceptionHandle.get());
				}
			}
		}

		// release the client
		client.release();
	}

	// create some documents to work with
	public static void setUpExample(DatabaseClient client)
	throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException {
		XMLDocumentManager docMgr = client.newXMLDocumentManager();

		StringHandle handle = new StringHandle();

		docMgr.write("/batch/read1.xml",   handle.with("<read1/>"));
		DocumentMetadataHandle meta2 = new DocumentMetadataHandle();
		meta2.getCollections().add("/batch/collection2");
		docMgr.write("/batch/read2.xml",   meta2, handle.with("<read2/>"));
		docMgr.write("/batch/delete1.xml", handle.with("<delete1/>"));
	}

	// clean up by deleting the example resource extension
	public static void tearDownExample(
			String host, int port, String user, String password, Authentication authType)
	throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException {
		DatabaseClient client = DatabaseClientFactory.newClient(host, port, user, password, authType);

		XMLDocumentManager docMgr = client.newXMLDocumentManager();
		docMgr.delete("/batch/read1.xml");
		docMgr.delete("/batch/read2.xml");
		docMgr.delete("/batch/write1.xml");
		docMgr.delete("/batch/write2.xml");

		ResourceExtensionsManager resourceMgr = client.newServerConfigManager().newResourceExtensionsManager();

		resourceMgr.deleteServices(BatchManager.NAME);

		client.release();
	}
}


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29601_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Gyrodata Directional

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Survey

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Oxy USA, Inc. Lease: Kenneth Stroh Well: 5-1H-143-97, 7" Casing
Location: H & P #35 3, Dunn County, North Dakota Job Number: RM1214GVC726

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">MEASURED DEPTH feet

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Final Station Closure:

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Page 7 of7

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">INCL

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">deg.

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Distance:

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">387.40 {'1

    <p class="styleSans5.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">95.29 deg.

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">AZIMU TH

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">deg.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">DOGLEG SEVERITY

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">VERTICAL DEPTH

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">DIST.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">AZIMU TH

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">deg./ 100 ft.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">CLOSURE

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">feet

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">HORIZONTAL COORDINATES

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">feet

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">deg.

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">feet


text:
cask "gpg-suite" do
  version "2021.3"
  sha256 "4a3ca87d9d8363542873b5eb695d85186ab1ff00d5adf2c37c3d055dd78d0a4d"

  url "https://releases.gpgtools.org/GPG_Suite-#{version}.dmg"
  name "GPG Suite"
  desc "Tools to protect your emails and files"
  homepage "https://gpgtools.org/"

  livecheck do
    url :homepage
    regex(/href=.*?GPG_Suite[._-]v?(\d+(?:\.\d+)+)\.dmg/i)
  end

  auto_updates true
  conflicts_with cask: [
    "gpg-suite-nightly",
    "gpg-suite-no-mail",
    "gpg-suite-pinentry",
  ], formula: "gpg"
  depends_on macos: ">= :mojave"

  pkg "Install.pkg"

  uninstall_postflight do
    ["gpg", "gpg2", "gpg-agent"].map { |exec_name| "/usr/local/bin/#{exec_name}" }.each do |exec|
      File.rm(exec) if File.exist?(exec) && File.readlink(exec).include?("MacGPG2")
    end
  end

  uninstall script:    {
    executable: "#{staged_path}/Uninstall.app/Contents/Resources/GPG Suite Uninstaller.app/Contents/Resources/uninstall.sh",
    sudo:       true,
  },
            pkgutil:   "org.gpgtools.*",
            quit:      [
              "com.apple.mail",
              "org.gpgtools.gpgkeychain",
              "org.gpgtools.gpgkeychainaccess",
              "org.gpgtools.gpgmail.upgrader",
              "org.gpgtools.gpgservices",
              # TODO: add "killall -kill gpg-agent"
            ],
            launchctl: [
              "org.gpgtools.gpgmail.enable-bundles",
              "org.gpgtools.gpgmail.patch-uuid-user",
              "org.gpgtools.gpgmail.user-uuid-patcher",
              "org.gpgtools.gpgmail.uuid-patcher",
              "org.gpgtools.Libmacgpg.xpc",
              "org.gpgtools.macgpg2.fix",
              "org.gpgtools.macgpg2.gpg-agent",
              "org.gpgtools.macgpg2.shutdown-gpg-agent",
              "org.gpgtools.macgpg2.updater",
              "org.gpgtools.updater",
            ],
            delete:    [
              "/Library/Application Support/GPGTools",
              "/Library/Frameworks/Libmacgpg.framework",
              "/Library/Mail/Bundles.gpgmail*",
              "/Library/Mail/Bundles/GPGMail.mailbundle",
              "/Library/PreferencePanes/GPGPreferences.prefPane",
              "/Library/Services/GPGServices.service",
              "/Network/Library/Mail/Bundles/GPGMail.mailbundle",
              "/private/etc/manpaths.d/MacGPG2",
              "/private/etc/paths.d/MacGPG2",
              "/private/tmp/gpg-agent",
              "/usr/local/MacGPG2",
            ]

  zap trash: [
    "~/Containers/com.apple.mail/Data/Library/Frameworks/Libmacgpg.framework",
    "~/Library/Application Support/GPGTools",
    "~/Library/Caches/org.gpgtools.gpg*",
    "~/Library/Containers/com.apple.mail/Data/Library/Preferences/org.gpgtools.*",
    "~/Library/Frameworks/Libmacgpg.framework",
    "~/Library/LaunchAgents/org.gpgtools.*",
    "~/Library/Mail/Bundles/GPGMail.mailbundle",
    "~/Library/PreferencePanes/GPGPreferences.prefPane",
    "~/Library/Preferences/org.gpgtools.*",
    "~/Library/Services/GPGServices.service",
  ]

  caveats do
    files_in_usr_local
  end
end


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

exports.default = function (mdPath) {
    var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var exclude = void 0,
        watcher = void 0;

    mdPath = (0, _path.resolve)(mdPath);
    exclude = [/node_modules/];

    if (!(0, _fs.existsSync)(mdPath)) {
        _logger2.default.error('markdown file directory not exist');
        return;
    }

    if (opts.exclude) {
        exclude = exclude.concat(opts.exclude);
    }

    watcher = _chokidar2.default.watch(mdPath, { ignored: exclude });
    watcher.on('add', function (path) {
        return correctExt(path) && (0, _utils.add)(path, getPagePath(path));
    });
    watcher.on('change', function (path) {
        return correctExt(path) && (0, _utils.change)(path, getPagePath(path));
    });
    watcher.on('unlink', function (path) {
        return correctExt(path) && (0, _utils.remove)(path, getPagePath(path));
    });
};

var _logger = require('../logger');

var _logger2 = _interopRequireDefault(_logger);

var _chokidar = require('chokidar');

var _chokidar2 = _interopRequireDefault(_chokidar);

var _fs = require('fs');

var _utils = require('./utils');

var _path = require('path');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var STATIC_PATH = '../server/static/';
var PAGE_PATH = (0, _path.resolve)((0, _path.join)(__dirname, STATIC_PATH, 'pages'));

function getPagePath(path) {
    return (0, _path.resolve)((0, _path.join)(PAGE_PATH, (0, _path.basename)(path, '.md') + '.vue'));
}

function correctExt(path) {
    return (0, _path.extname)(path) === '.md';
}


text:
<?php

namespace EmagUserBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;

/**
 * EmagUser class file
 *
 * PHP Version 5.6
 *
 * @category Entity
 * @author   Guillaume ORAIN <guillaume.orain27@laposte.net>
 */

/**
 * EmagUser class
 *
 * @category Entity
 * @author   Guillaume ORAIN <guillaume.orain27@laposte.net>
 *
 * @ORM\Table(name="emag_user")
 * @ORM\Entity(repositoryClass="EmagUserBundle\Repository\EmagUserRepository")
 */
class EmagUser extends BaseUser
{
    /**
     * @var int
     *
     * @ORM\Column(name="id_emag_user", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="CoreBundle\Entity\Compte")
     * @ORM\JoinTable(
     *     name="emag_user_compte",
     *     joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id_emag_user")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="compte_id", referencedColumnName="id_compte", unique=true)}
     * )
     */
    private $comptes;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="CoreBundle\Entity\Categorie")
     * @ORM\JoinTable(
     *     name="emag_user_categorie",
     *     joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id_emag_user")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="categorie_id", referencedColumnName="id_categorie", unique=true)}
     * )
     */
    private $categories;

    /**
     * EmagUser constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->comptes    = new ArrayCollection();
        $this->categories = new ArrayCollection();
    }

    /**
     * Add compte
     *
     * @param \CoreBundle\Entity\Compte $compte
     *
     * @return EmagUser
     */
    public function addCompte(\CoreBundle\Entity\Compte $compte)
    {
        $this->comptes[] = $compte;

        return $this;
    }

    /**
     * Remove compte
     *
     * @param \CoreBundle\Entity\Compte $compte
     */
    public function removeCompte(\CoreBundle\Entity\Compte $compte)
    {
        $this->comptes->removeElement($compte);
    }

    /**
     * Get comptes
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getComptes()
    {
        return $this->comptes;
    }

    /**
     * Add category
     *
     * @param \CoreBundle\Entity\Categorie $category
     *
     * @return EmagUser
     */
    public function addCategory(\CoreBundle\Entity\Categorie $category)
    {
        $this->categories[] = $category;

        return $this;
    }

    /**
     * Remove category
     *
     * @param \CoreBundle\Entity\Categorie $category
     */
    public function removeCategory(\CoreBundle\Entity\Categorie $category)
    {
        $this->categories->removeElement($category);
    }

    /**
     * Get categories
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCategories()
    {
        return $this->categories;
    }
}


text:
---
title: "Custom options rendering/templating on Magento"
published: true
date: 06/13/2014 11:00pm
taxonomy:
    category: blog
    tag: [magento]
---

Overriding custom options rendering in Magento is like being dropped off into somewhere in the desert without a map. Let me guide you into this process !

===

**Our objective** : Customize the rendering of a Magento product custom option.

For example, we're going to customize a classic select field into clickable images.

**prerequisites** : Having a loaded module. Mine is `Nls_Catalog`.

###1. Add a new product custom option type to the backend

Create a new module or open an existing module config file and add the catalog/product/options block:

    <global>
      ...
      <catalog>
        <product>
          <options>
            <custom>
              <groups>
                <engravingstyle translate="label" module="nls_catalog">
                  Engraving<render>nls_catalog/adminhtml_catalog_product_edit_tab_options_type_engravingstyle</render>
                  <types>
                    <engravingstyle translate="label" module="nls_catalog">
                      Engraving style
                    </engravingstyle>
                  </types>
              </groups>
            </custom>
          </options>
        </product>
      </catalog>
      ...
    </global>

To avoid any "magento-looking-the-wrong-block" problems, tag the group the same as the type.

In our case, we want to have the same behaviour in the backend than a select option. To do so, we're just going to extend the Magento Select Type. Create the corresponding type :

    <?php

    class Nls_Catalog_Block_Adminhtml_Catalog_Product_Edit_Tab_Options_Type_Engravingstyle
    extends Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Type_Select
    {

    }

It should be located into `app/code/local/Nls/Catalog/Block/Adminhtml/Catalog/Product/Edit/Tab/Options/Type/Engravingstyle.php`.

The next step is to override Magento Options Tab to include our type. That's an ugly override but it's the only way to add our type to the template.

Create the file : It should be located into `app/code/local/Nls/Catalog/Block/Adminhtml/Catalog/Product/Edit/Tab/Options/Option.php`. Add this class content inside :

    <?php

    class Nls_Catalog_Block_Adminhtml_Catalog_Product_Edit_Tab_Options_Option
    extends Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Option
    {
        /**
         * Class constructor
         */
        public function __construct()
        {
          parent::__construct();
          $this->setTemplate('nls_catalog/product/edit/options/option.phtml');
        }
    }

Create now the template file associated to the previous block by copying  `app/design/adminhtml/default/default/catalog/product/edit/options/option.phtml` into `app/design/adminhtml/default/default/nls_catalog/product/edit/options/option.phtml`. We could have created a new adminhtml theme but in this case we would had to copy the entire adminhtml folder ...

Edit the newly created `option.phtml` and add your type wherever the select type is used in a switch :

    switch(element.getValue()){
        case 'drop_down':
          case 'radio':
          case 'checkbox':
          case 'multiple':
          case 'engravingstyle':
          case 'ringsize':
            selectOptionType.bindAddButton();
              break;
    }

You should normally add it 4 times in this files.

Go into the **Custom options** tab of any product. You should have a new option type in the select drop-down.

![magento_custom_type](http://static.nls.io/blog/magento_custom_type.png)

Create that test option now !

###2. Create a front-end renderer

The first step is to override the way Magento find the correct block to output your option. That's a bit ugly too but skiing this step forces us to create a complete new type without overriding any existent. Such  pain for a very little gain.

Copy `app/code/core/Mage/Catalog/Block/Product/View/Options.php` into the file `app/code/local/Nls/Catalog/Block/Product/View/Options.php` and modify the class name. Add and if condition on your type :

    <?php
    class Nls_Catalog_Block_Product_View_Options extends Mage_Catalog_Block_Product_View_Options
    {
      /**
       * Get option html block
       *
       * @param Mage_Catalog_Model_Product_Option $option
       */
      public function getOptionHtml(Mage_Catalog_Model_Product_Option $option)
      {
        if($option->getType() == 'engravingstyle') {
          $renderer = $this->getOptionRender('engravingstyle');
        }
        else {
          $renderer = $this->getOptionRender(
            $this->getGroupOfOption($option->getType())
          );
        }

        if (is_null($renderer['renderer'])) {
          $renderer['renderer'] = $this->getLayout()->createBlock($renderer['block'])
            ->setTemplate($renderer['template']);
        }
        return $renderer['renderer']
          ->setProduct($this->getProduct())
          ->setOption($option)
          ->toHtml();
      }
    }

In order to have Magento using this class, we must rewrite the original in your config.xml :

    <config>
      <global>
          ...
        <models>
          <catalog>
            <rewrite>
              <product_option>Nls_Catalog_Model_Product_Option</product_option>
            </rewrite>
          </catalog>
        </models>
          ...
      </global>
    </config>

Make sure you have overrided the `catalog.xml` layout file into your module.
Open it and find the `product.info.options` block.

Add the new OptionRender action into the layout file :

    <action method="addOptionRenderer">
      <type>engravingstyle</type>
        <block>nls_catalog/product_view_options_type_engravingstyle</block>
        <template>catalog/product/view/options/type/engravingstyle.phtml</template>
    </action>

Create the matching block. In my case : `app/code/local/Nls/Catalog/Block/Product/View/Options/Type/Engravingstyle.php`.

    <?php
    class Nls_Catalog_Block_Product_View_Options_Type_Engravingstyle extends  Mage_Catalog_Block_Product_View_Options_Abstract
    {
        protected $_template = 'catalog/product/view/options/type/engravingstyle.phtml';

        public function __contruct(){
          parent::__construct();
        }
    }

Create the template file linked to this block : `app/design/frontend/<package>/<theme>/catalog/product/view/options/type/engravingstyle.phtml`

Add the following content :

    <?php $_option = $this->getOption(); ?>

<label<?php if ($_option->getIsRequire()) echo ' class="required"' ?>><?php if ($_option->getIsRequire()) echo '*' ?><?php echo  $this->htmlEscape($_option->getTitle()) ?>
        <?php echo $this->getFormatedPrice() ?>

    <dd<?php if ($_option->decoratedIsLast){?> class="last"<?php }?>>

          <?php foreach ($_option->getValues() as $o => $value) : ?>
            <li class="<?php echo strtolower(str_replace(' ', '_', $value->getTitle())); ?>">
            <?php echo $this->__($value->getTitle()); ?>

          <?php endforeach; ?>

**You should now have a nice `ul>li` on your product page for this option !**


text:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE TABLE [dbo].[ReleasedZip4](
[Zip4ID] [int] IDENTITY(1,1) NOT NULL,
[Zip] [int] NOT NULL,
[Zip4] [int] NOT NULL,
[BeginDate] [datetime] NULL,
[SunsetDate] [datetime] NULL,
CONSTRAINT [pk_releasedZip4_pid] PRIMARY KEY CLUSTERED
(
[Zip4ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


text:
import { combineReducers } from 'redux';
import comics from './comic';
import searchState from './search';
import uiState from './ui';
import config from './config';
import { routerReducer } from 'react-router-redux';

const rootReducer = combineReducers({
	comics,
	searchState,
	uiState,
	config,
	routing: routerReducer
});

export default rootReducer;


text:
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package google.registry.model;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import google.registry.model.EppResource.BuilderWithTransferData;
import google.registry.model.EppResource.ResourceWithTransferData;
import google.registry.model.contact.Contact;
import google.registry.model.domain.Domain;
import google.registry.model.eppcommon.StatusValue;
import google.registry.model.eppcommon.Trid;
import google.registry.model.poll.PendingActionNotificationResponse;
import google.registry.model.poll.PendingActionNotificationResponse.ContactPendingActionNotificationResponse;
import google.registry.model.poll.PendingActionNotificationResponse.DomainPendingActionNotificationResponse;
import google.registry.model.poll.PollMessage;
import google.registry.model.reporting.HistoryEntry;
import google.registry.model.transfer.DomainTransferData;
import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferResponse;
import google.registry.model.transfer.TransferResponse.ContactTransferResponse;
import google.registry.model.transfer.TransferResponse.DomainTransferResponse;
import google.registry.model.transfer.TransferStatus;
import org.joda.time.DateTime;

/** Static utility functions for resource transfers. */
public final class ResourceTransferUtils {

  private ResourceTransferUtils() {}

  /** Statuses for which an exDate should be added to transfer responses. */
  private static final ImmutableSet<TransferStatus> ADD_EXDATE_STATUSES = Sets.immutableEnumSet(
      TransferStatus.PENDING, TransferStatus.CLIENT_APPROVED, TransferStatus.SERVER_APPROVED);

  /**
   * Create a transfer response using the id and type of this resource and the specified {@link
   * TransferData}.
   */
  public static TransferResponse createTransferResponse(
      EppResource eppResource, TransferData transferData) {
    assertIsContactOrDomain(eppResource);
    TransferResponse.Builder<? extends TransferResponse, ?> builder;
    if (eppResource instanceof Contact) {
      builder = new ContactTransferResponse.Builder().setContactId(eppResource.getForeignKey());
    } else {
      DomainTransferData domainTransferData = (DomainTransferData) transferData;
      builder =
          new DomainTransferResponse.Builder()
              .setDomainName(eppResource.getForeignKey())
              .setExtendedRegistrationExpirationTime(
                  ADD_EXDATE_STATUSES.contains(domainTransferData.getTransferStatus())
                      ? domainTransferData.getTransferredRegistrationExpirationTime()
                      : null);
    }
    builder
        .setGainingRegistrarId(transferData.getGainingRegistrarId())
        .setLosingRegistrarId(transferData.getLosingRegistrarId())
        .setPendingTransferExpirationTime(transferData.getPendingTransferExpirationTime())
        .setTransferRequestTime(transferData.getTransferRequestTime())
        .setTransferStatus(transferData.getTransferStatus());
    return builder.build();
  }

  /**
   * Create a pending action notification response indicating the resolution of a transfer.
   *
   *
The returned object will use the id and type of this resource, the trid of the resource's
   * last transfer request, and the specified status and date.
   */
  public static PendingActionNotificationResponse createPendingTransferNotificationResponse(
      EppResource eppResource,
      Trid transferRequestTrid,
      boolean actionResult,
      DateTime processedDate) {
    assertIsContactOrDomain(eppResource);
    return eppResource instanceof Contact
        ? ContactPendingActionNotificationResponse.create(
            eppResource.getForeignKey(), actionResult, transferRequestTrid, processedDate)
        : DomainPendingActionNotificationResponse.create(
            eppResource.getForeignKey(), actionResult, transferRequestTrid, processedDate);
  }

  private static void assertIsContactOrDomain(EppResource eppResource) {
    checkState(eppResource instanceof Contact || eppResource instanceof Domain);
  }

  /** If there is a transfer out, delete the server-approve entities and enqueue a poll message. */
  public static <R extends EppResource & ResourceWithTransferData>
      void handlePendingTransferOnDelete(
          R resource, R newResource, DateTime now, HistoryEntry historyEntry) {
    if (resource.getStatusValues().contains(StatusValue.PENDING_TRANSFER)) {
      TransferData oldTransferData = resource.getTransferData();
      tm().delete(oldTransferData.getServerApproveEntities());
      tm().put(
              new PollMessage.OneTime.Builder()
                  .setRegistrarId(oldTransferData.getGainingRegistrarId())
                  .setEventTime(now)
                  .setMsg(TransferStatus.SERVER_CANCELLED.getMessage())
                  .setResponseData(
                      ImmutableList.of(
                          createTransferResponse(newResource, newResource.getTransferData()),
                          createPendingTransferNotificationResponse(
                              resource, oldTransferData.getTransferRequestTrid(), false, now)))
                  .setHistoryEntry(historyEntry)
                  .build());
    }
  }

  /**
   * Turn a resource into a builder with its pending transfer resolved.
   *
   *
This removes the {@link StatusValue#PENDING_TRANSFER} status, sets the {@link
   * TransferStatus}, clears all the server-approve fields on the {@link TransferData}, and sets the
   * expiration time of the last pending transfer to now.
   */
  private static <
          R extends EppResource & ResourceWithTransferData,
          B extends EppResource.Builder<R, B> & BuilderWithTransferData<TransferData, B>>
      B resolvePendingTransfer(R resource, TransferStatus transferStatus, DateTime now) {
    checkArgument(
        resource.getStatusValues().contains(StatusValue.PENDING_TRANSFER),
        "Resource is not in pending transfer status.");
    checkArgument(!resource.getTransferData().isEmpty(), "No old transfer data to resolve.");
    @SuppressWarnings("unchecked")
    B builder = (B) resource.asBuilder();

    return builder
        .removeStatusValue(StatusValue.PENDING_TRANSFER)
        .setTransferData(
            (TransferData)
                resource
                    .getTransferData()
                    .copyConstantFieldsToBuilder()
                    .setTransferStatus(transferStatus)
                    .setPendingTransferExpirationTime(checkNotNull(now))
                    .build());
  }

  /**
   * Resolve a pending transfer by awarding it to the gaining client.
   *
   *
This removes the {@link StatusValue#PENDING_TRANSFER} status, sets the {@link
   * TransferStatus}, clears all the server-approve fields on the {@link TransferData}, sets the new
   * client id, and sets the last transfer time and the expiration time of the last pending transfer
   * to now.
   */
  public static <
          R extends EppResource & ResourceWithTransferData,
          B extends EppResource.Builder<R, B> & BuilderWithTransferData<TransferData, B>>
      R approvePendingTransfer(R resource, TransferStatus transferStatus, DateTime now) {
    checkArgument(transferStatus.isApproved(), "Not an approval transfer status");
    B builder = resolvePendingTransfer(resource, transferStatus, now);
    return builder
        .setLastTransferTime(now)
        .setPersistedCurrentSponsorRegistrarId(resource.getTransferData().getGainingRegistrarId())
        .build();
  }

  /**
   * Resolve a pending transfer by denying it.
   *
   *
This removes the {@link StatusValue#PENDING_TRANSFER} status, sets the {@link
   * TransferStatus}, clears all the server-approve fields on the {@link TransferData}, sets the
   * expiration time of the last pending transfer to now, sets the last EPP update time to now, and
   * sets the last EPP update client id to the given client id.
   */
  public static <R extends EppResource & ResourceWithTransferData> R denyPendingTransfer(
      R resource, TransferStatus transferStatus, DateTime now, String lastEppUpdateRegistrarId) {
    checkArgument(transferStatus.isDenied(), "Not a denial transfer status");
    return resolvePendingTransfer(resource, transferStatus, now)
        .setLastEppUpdateTime(now)
        .setLastEppUpdateRegistrarId(lastEppUpdateRegistrarId)
        .build();
  }
}