text:
#ifndef _H_ncxtypes
#define _H_ncxtypes

/*  FILE: ncxtypes.h
*********************************************************************
*								    *
*			 P U R P O S E				    *
*								    *
*********************************************************************

  Contains NCX typedefs

*********************************************************************
*								    *
*		   C H A N G E	 H I S T O R Y			    *
*								    *
*********************************************************************

date	     init     comment
----------------------------------------------------------------------
14-nov-05    abb      Begun; split from ncx.h
04-feb-06    abb      Move base/nc.h constants into this file
10-nov-07    abb      Split out from ncxconst.h
*/

#include <xmlstring.h>
#include <xmlregexp.h>

#ifndef _H_dlq
#include "dlq.h"
#endif

#ifndef _H_xmlns
#include "xmlns.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

/********************************************************************
*                                                                   *
*                            T Y P E S                              *
*                                                                   *
*********************************************************************/

/* NCX Access Control 'max-access' enumeration values
 * Note that access control is applied to the session
 * and the max-access applies to the user max-access,
 * not the agent max-access.  Only the agent may create
 * or write an object which is classified as 'read-only'.
 *
 * Access is grouped into the following catagories.
 *
 *      none
 *      read-only
 *      read-write
 *      read-create
 *
 *   Merge and Replace are handled as follows:
 *
 *   Requested operation              Effective Access
 *   -------------------------------------------------
 *   merge empty with no-cur-node      --> no-op
 *   merge empty with cur-node         --> no-op
 *   merge non-empty with no-cur-node  --> create
 *   merge non-empty with cur-node     --> write
 *
 *   replace empty into no-cur-node      --> no-op
 *   replace empty into cur-node         --> delete
 *   replace non-empty into no-cur-node  --> create
 *   replace non-empty into cur-node     --> write

 *   Create and Delete are grouped together for access control
 *   purposes, and called 'read-create'
 *
 *   Obviously, the max-access of the ancestor nodes affect any
 *   given nested node, but the enumerations are not purely hierarchical.
 *
 *   Access      Nested Behavior
 *   -------------------------------
 *   [none]      Check the ancestor chain until an explicit value
 *               is found (or the parmset root is reached, where the
 *               default is read-create)
 *
 *   read-only   User may only read this node and all child nodes.
 *               All nested access is also read-only, overriding any
 *               explicit setting of any child nodes
 *
 *   read-write  User may read and write this node and all child nodes,
 *               depending on the max-access of the child node.
 *               Any type of nested access may appear in any child
 *               nodes.  A read-write container may have child nodes
 *               which are read-create objects.  This implies the agent
 *               must create the object in order for the user to write it.
 *
 *   read-create User may have unrestricted access to this node and all
 *               child nodes, depending on the max-access of the child
 *               nodes. Any type of nested access may appear in any
 *               child nodes.
 */
typedef enum ncx_access_t_ {
    NCX_ACCESS_NONE,    /* enum not explicitly set */
    NCX_ACCESS_RO,      /* read-only */
    NCX_ACCESS_RW,      /* read-write (create/delete not allowed) */
    NCX_ACCESS_RC       /* read-create (all access) */
} ncx_access_t;

/* default max-access is all */
#define NCX_DEF_ACCESS NCX_ACCESS_RC

/* NCX Persistence Control
 *
 * Enum mapping of 'data-class' field in the 'parm' and 'type' clauses
 *
 * This data type controls NV-storage and whether a node is returned
 * in the 'get-config' operation and stored in the startup config.
 *
 */
typedef enum ncx_data_class_t_ {
    NCX_DC_NONE,
    NCX_DC_CONFIG,        /* persistent config */
    NCX_DC_STATE          /* state or statistics */
} ncx_data_class_t;

/* enumeration of the built-in NCX types
 * These types cannot be overridden and cannot be imported
 */
typedef enum ncx_btype_t_ {
    NCX_BT_NONE,
    NCX_BT_ANY,
    NCX_BT_BITS,
    NCX_BT_ENUM,
    NCX_BT_EMPTY,
    NCX_BT_BOOLEAN,
    NCX_BT_INT8,
    NCX_BT_INT16,
    NCX_BT_INT32,
    NCX_BT_INT64,
    NCX_BT_UINT8,
    NCX_BT_UINT16,
    NCX_BT_UINT32,
    NCX_BT_UINT64,
    NCX_BT_DECIMAL64,
    NCX_BT_FLOAT64,   /* hidden: just for XPath */
    NCX_BT_STRING,
    NCX_BT_BINARY,
    NCX_BT_INSTANCE_ID,
    NCX_BT_UNION,
    NCX_BT_LEAFREF,
    NCX_BT_IDREF,
    NCX_BT_SLIST,                 /* ncx:xsdlist extension */

    NCX_BT_CONTAINER,
    NCX_BT_CHOICE,
    NCX_BT_CASE,                   /* not a real type */
    NCX_BT_LIST,
    NCX_BT_EXTERN,                 /* not a real type */
    NCX_BT_INTERN                  /* not a real type */

} ncx_btype_t;

#define NCX_FIRST_DATATYPE NCX_BT_ANY
#define NCX_LAST_DATATYPE  NCX_BT_LIST
#define NCX_NUM_BASETYPES  (NCX_LAST_DATATYPE-NCX_FIRST_DATATYPE+1)

/* Enumeration of the basic value type classifications */
typedef enum ncx_tclass_t_ {
    NCX_CL_NONE,
    NCX_CL_BASE,                         /* a built-in base type */
    NCX_CL_SIMPLE,               /* a restriction of a base type */
    NCX_CL_COMPLEX,                            /* a complex type */
    NCX_CL_NAMED,               /* a restriction of a named type */
    NCX_CL_REF             /* internal reference to another type */
} ncx_tclass_t;

/* Enumeration of the different types of index components
 * YANG ONLY SUPPORTS NCX_IT_LOCAL
 */
typedef enum ncx_indextyp_t_ {
    NCX_IT_NONE,
    NCX_IT_INLINE,          /* index simple type declared inline */
    NCX_IT_NAMED,            /* index named type declared inline */
    NCX_IT_LOCAL,               /* local member within the table */
    NCX_IT_SLOCAL,       /* scoped local member within the table */
    NCX_IT_REMOTE,                       /* unscoped remote name */
    NCX_IT_SREMOTE                         /* scoped remote name */
} ncx_indextyp_t;

/* NCX Internal Node Types
 *
 * nodes in the value trees can be different types
 * These enums are used to generate instance IDs and
 * classify data passed to the agt_record_*error functions
 */
typedef enum ncx_node_t_ {
    NCX_NT_NONE,
    NCX_NT_TYP,                                /* typ_template_t */
    NCX_NT_GRP,                                /* grp_template_t */
    NCX_NT_VAL,                                   /* val_value_t */
    NCX_NT_OBJ,                                /* obj_template_t */
    NCX_NT_ERRINFO,                 /* ncx_errinfo_t, error only */
    NCX_NT_STRING,                      /* xmlChar *, error only */
    NCX_NT_CFG,                  /* cfg_template_t *, error only */
    NCX_NT_INDEX,                     /* obj_key_t *, error only */
    NCX_NT_QNAME,                 /* xmlns_qname_t *, error only */
    NCX_NT_UINT32_PTR,                 /* session ID, error only */
    NCX_NT_IMPORT_CB,                            /* ncx_import_t */
    NCX_NT_INCLUDE_CB,                          /* ncx_include_t */
    NCX_NT_REVISION_CB,                         /* ncx_revhist_t */
    NCX_NT_EXTENSION_CB,                       /* ext_template_t */
    NCX_NT_FEATURE_CB,                          /* ncx_feature_t */
    NCX_NT_IDENTITY_CB,                        /* ncx_identity_t */
    NCX_NT_TYPDEF_CB                                /* typ_def_t */
} ncx_node_t;

/* The instance qualifier types are borrowed from ABNF and RelaxNG */
typedef enum ncx_iqual_t_ {
    NCX_IQUAL_NONE,                         /* value not set */
    NCX_IQUAL_ONE,                          /* no iqual == 1 */
    NCX_IQUAL_OPT,                          /* '?' == 0 or 1 */
    NCX_IQUAL_1MORE,                     /* '+' == 1 or more */
    NCX_IQUAL_ZMORE                      /* '*' == 0 or more */
}  ncx_iqual_t;

/* The merge type for the NETCONF merge operation */
typedef enum ncx_merge_t_ {
    NCX_MERGE_NONE,                         /* value not set */
    NCX_MERGE_FIRST,
    NCX_MERGE_LAST,
    NCX_MERGE_SORT
}  ncx_merge_t;

/* typdef search qualifier list */
typedef enum ncx_squal_t_ {
    NCX_SQUAL_NONE,
    NCX_SQUAL_RANGE,
    NCX_SQUAL_VAL,
    NCX_SQUAL_META,
    NCX_SQUAL_APPINFO
}  ncx_squal_t;

/* Enumeration of string restriction types */
typedef enum ncx_strrest_t_ {
    NCX_SR_NONE,
    NCX_SR_PATTERN,
    NCX_SR_ENUM,
    NCX_SR_BIT
}  ncx_strrest_t;

/* Enumeration of number format types */
typedef enum ncx_numfmt_t_ {
    NCX_NF_NONE,
    NCX_NF_OCTAL,
    NCX_NF_DEC,
    NCX_NF_HEX,
    NCX_NF_REAL
}  ncx_numfmt_t;

/* Enumeration of NETCONF protocol layers */
typedef enum ncx_layer_t_ {
    NCX_LAYER_NONE,
    NCX_LAYER_TRANSPORT,
    NCX_LAYER_RPC,
    NCX_LAYER_OPERATION,
    NCX_LAYER_CONTENT
}  ncx_layer_t;

/* enum to identify the agent native target */
typedef enum ncx_agttarg_t_ {
    NCX_AGT_TARG_NONE,
    NCX_AGT_TARG_CANDIDATE,
    NCX_AGT_TARG_RUNNING,
    NCX_AGT_TARG_LOCAL,   /* TBD */
    NCX_AGT_TARG_REMOTE,   /* TBD */
    NCX_AGT_TARG_CAND_RUNNING  /* TBD */
} ncx_agttarg_t;

/* enum to identify the agent native startup mode */
typedef enum ncx_agtstart_t_ {
    NCX_AGT_START_NONE,
    NCX_AGT_START_MIRROR,
    NCX_AGT_START_DISTINCT
} ncx_agtstart_t;

/* enumeration of the different program shutdown modes */
typedef enum ncx_shutdowntyp_t_ {
    NCX_SHUT_NONE,
    NCX_SHUT_RESET,
    NCX_SHUT_RELOAD,
    NCX_SHUT_RESTART,
    NCX_SHUT_EXIT
} ncx_shutdowntyp_t;

/* hardwire the 3 standard configs */
typedef enum ncx_cfg_t_ {
    NCX_CFGID_RUNNING,
    NCX_CFGID_CANDIDATE,
    NCX_CFGID_STARTUP
} ncx_cfg_t;

/* instance string format types */
typedef enum ncx_instfmt_t_ {
    NCX_IFMT_NONE,
    NCX_IFMT_C,
    NCX_IFMT_XPATH1,       /* single-quote Xpath for filter */
    NCX_IFMT_XPATH2,    /* double-quote Xpath for error-path */
    NCX_IFMT_CLI
} ncx_instfmt_t;

/* enumeration for different NETCONF message types */
typedef enum ncx_msgtyp_t_ {
    NCX_MSGTYP_NONE,
    NCX_MSGTYP_HELLO,
    NCX_MSGTYP_RPCREQ,
    NCX_MSGTYP_RPCRPY,
    NCX_MSGTYP_NOTIF
} ncx_msgtyp_t;

/* enumeration for different YANG data-def status values */
typedef enum ncx_status_t_ {
    NCX_STATUS_NONE,
    NCX_STATUS_CURRENT,
    NCX_STATUS_DEPRECATED,
    NCX_STATUS_OBSOLETE
} ncx_status_t;

/* enumeration for CLI handling of bad input data
 * used by yangcli, all others use NCX_BAD_DATA_ERROR
 *
 * NCX_BAD_DATA_IGNORE to silently accept invalid input values
 * NCX_BAD_DATA_WARN to warn and accept invalid input values
 * NCX_BAD_DATA_CHECK to prompt user to keep or re-enter value
 * NCX_BAD_DATA_ERROR to prompt user to re-enter value
 */
typedef enum ncx_bad_data_t_ {
    NCX_BAD_DATA_NONE,
    NCX_BAD_DATA_IGNORE,
    NCX_BAD_DATA_WARN,
    NCX_BAD_DATA_CHECK,
    NCX_BAD_DATA_ERROR
} ncx_bad_data_t;

/* enumeration of val_dump_value display modes */
typedef enum ncx_display_mode_t_ {
    NCX_DISPLAY_MODE_NONE,
    NCX_DISPLAY_MODE_PLAIN,
    NCX_DISPLAY_MODE_PREFIX,
    NCX_DISPLAY_MODE_MODULE,
    NCX_DISPLAY_MODE_XML,
    NCX_DISPLAY_MODE_XML_NONS,
    NCX_DISPLAY_MODE_JSON
} ncx_display_mode_t;

/* XPath expression axis types */
typedef enum ncx_xpath_axis_t_ {
    XP_AX_NONE,
    XP_AX_ANCESTOR,
    XP_AX_ANCESTOR_OR_SELF,
    XP_AX_ATTRIBUTE,
    XP_AX_CHILD,
    XP_AX_DESCENDANT,
    XP_AX_DESCENDANT_OR_SELF,
    XP_AX_FOLLOWING,
    XP_AX_FOLLOWING_SIBLING,
    XP_AX_NAMESPACE,
    XP_AX_PARENT,
    XP_AX_PRECEDING,
    XP_AX_PRECEDING_SIBLING,
    XP_AX_SELF
} ncx_xpath_axis_t;

/* Node name match modes */
typedef enum ncx_name_match_t_ {
    NCX_MATCH_NONE,
    NCX_MATCH_EXACT,
    NCX_MATCH_EXACT_NOCASE,
    NCX_MATCH_ONE,
    NCX_MATCH_ONE_NOCASE,
    NCX_MATCH_FIRST,
    NCX_MATCH_FIRST_NOCASE
} ncx_name_match_t;

typedef struct ncx_dec64_t_ {
    int64  val;        /* adjusted number to fit in 64 bits */
    uint8  digits;      /* number of decimal digits 1 .. 18 */
    uint8  zeroes;      /* number of leading zeroes 0 .. 17 */
} ncx_dec64_t;

/* union of all the basic number types
 * if float not supported, then it is stored as an int64
 */
typedef union ncx_num_t_ {
    int32  i;                            /* NCX_BT_INT */
    int64  l;                           /* NCX_BT_LONG */
    uint32 u;                           /* NCX_BT_UINT */
    uint64 ul;                         /* NCX_BT_ULONG */

#ifdef HAS_FLOAT             /* 'd' used only in XPath */
    double d;                         /* NCX_BT_DOUBLE */
#else
    int64  d;                         /* NCX_BT_DOUBLE */
#endif
    ncx_dec64_t  dec;              /* NCX_BT_DECIMAL64 */
} ncx_num_t;

/* string alias for data types:
 *  NCX_BT_STRING
 *  NCX_BT_OSTRING
 *  NCX_BT_ENAME
 */
typedef xmlChar * ncx_str_t;

typedef const xmlChar * ncx_const_str_t;

/* one NCX_BT_ENUM enumeration value (user may enter 1 of 3 forms) */
typedef struct ncx_enum_t_ {
    const xmlChar *name;     /* bptr to typ_enum_t or dname */
    xmlChar       *dname;    /* malloced enum (value not checked) */
    int32          val;
} ncx_enum_t;

/* one NCX_BT_BITS bit value */
typedef struct ncx_bit_t_ {
    const xmlChar *name;     /* bptr to typ_enum_t.name or this.dname */
    xmlChar       *dname;    /* malloced bit name (value not checked) */
    uint32         pos;      /* position value */
} ncx_bit_t;

/* NCX list member: list of string or number */
typedef struct ncx_lmem_t_ {
    dlq_hdr_t     qhdr;
    union val_ {
	ncx_num_t    num;
	ncx_str_t    str;
	ncx_enum_t   enu;
	ncx_bit_t    bit;
	boolean      boo;
    } val;
    uint32   flags;
} ncx_lmem_t;

/* header for a NCX List */
typedef struct ncx_list_t_ {
    ncx_btype_t  btyp;
    dlq_hdr_t     memQ;                /* Q of ncx_lmem_t */
} ncx_list_t;

/* NCX base64 string node for YANG 'binary' built-in type */
typedef struct ncx_binary_t_ {
    unsigned char   *ustr;            /* binary string */
    uint32           ubufflen;    /* binary buffer len */
    uint32           ustrlen;    /* binary buffer used */
} ncx_binary_t;

/* struct to remember error info
 * tkc->cur_err will be checked before tkc->cur
 * for error information
 */
typedef struct ncx_error_t_ {
    struct ncx_module_t_  *mod;
    uint32                 linenum;
    uint32                 linepos;
} ncx_error_t;

/* YANG extension usage entry */
typedef struct ncx_appinfo_t_ {
    dlq_hdr_t               qhdr;
    xmlChar                *prefix;
    xmlChar                *name;
    xmlChar                *value;
    struct ext_template_t_ *ext;
    dlq_hdr_t              *appinfoQ;
    boolean                 isclone;
    ncx_error_t             tkerr;
} ncx_appinfo_t;

/* YANG revision entry */
typedef struct ncx_revhist_t_ {
    dlq_hdr_t           qhdr;
    xmlChar            *version;
    xmlChar            *descr;
    xmlChar            *ref;
    status_t            res;
    ncx_error_t         tkerr;
} ncx_revhist_t;

/* YANG if-feature entry */
typedef struct ncx_iffeature_t_ {
    dlq_hdr_t              qhdr;
    xmlChar               *prefix;
    xmlChar               *name;
    struct ncx_feature_t_ *feature;
    ncx_error_t            tkerr;
    boolean                seen;          /* for yangdiff */
} ncx_iffeature_t;

typedef enum ncx_feature_code_t_ {
    NCX_FEATURE_CODE_NONE,    /* enum not explicitly set */
    NCX_FEATURE_CODE_STATIC,  /* compile-time if-feature code */
    NCX_FEATURE_CODE_DYNAMIC  /* run-time if-feature code */
} ncx_feature_code_t;

/* NCX session protocol versions supported */
typedef enum ncx_protocol_t_ {
    NCX_PROTO_NONE,
    NCX_PROTO_NETCONF10,      /* RFC 4741 base:1.0  */
    NCX_PROTO_NETCONF11       /* RFC xxxx base:1.1 */
} ncx_protocol_t;

/* YANG feature entry */
typedef struct ncx_feature_t_ {
    dlq_hdr_t           qhdr;
    xmlChar            *name;
    xmlChar            *descr;
    xmlChar            *ref;
    ncx_status_t        status;
    dlq_hdr_t           iffeatureQ;   /* Q of ncx_iffeature_t */
    dlq_hdr_t           appinfoQ;       /* Q of ncx_appinfo_t */
    status_t            res;    /* may be stored with errors */
    boolean             enabled;
    ncx_feature_code_t  code;    /* dynamic or static code-gen */
    ncx_error_t         tkerr;
    boolean             seen;          /* for yangdiff */
} ncx_feature_t;

/* struct for holding r/o pointer to generic internal node
 * for filtering purposes
 */
typedef struct ncx_filptr_t_ {
    dlq_hdr_t             qhdr;
    struct val_value_t_  *node;        /* read-only backptr */
    struct val_value_t_  *virtualnode;  /* virtual val backptr */
    dlq_hdr_t             childQ;  /* Q of ncx_filptr_t */
} ncx_filptr_t;

/* back pointer to a YANG identity
 * used to create an inline tree of valid values
 * for an identity used as a base
 *
 * This inline Q record will be linked in to the
 * childQ of the base identity when the identity
 * containing this struct is using it as a base
 *
 * This thread is only used for client help,
 * to easily list all the QName values that are permitted
 * for a identityref leaf
 */
typedef struct ncx_idlink_t_ {
    dlq_hdr_t  qhdr;
    struct ncx_identity_t_ *identity;
    boolean    inq;
} ncx_idlink_t;

/* YANG identity entry */
typedef struct ncx_identity_t_ {
    dlq_hdr_t             qhdr;
    struct ncx_identity_t_ *base;      /* back-ptr to base id */
    xmlChar              *name;
    xmlChar              *baseprefix;
    xmlChar              *basename;
    xmlChar              *descr;
    xmlChar              *ref;
    ncx_status_t          status;
    dlq_hdr_t             childQ;          /* Q of ncx_idlink_t */
    dlq_hdr_t             appinfoQ;       /* Q of ncx_appinfo_t */
    status_t              res;     /* may be stored with errors */
    boolean               isroot;    /* base==NULL not an error */
    ncx_idlink_t          idlink;
    ncx_error_t           tkerr;
    boolean               seen;                  /* for yangcli */
} ncx_identity_t;

/* representation of one module or submodule during and after parsing */
typedef struct ncx_module_t_ {
    dlq_hdr_t         qhdr;
    xmlChar          *name;
    xmlChar          *version;
    xmlChar          *organization;
    xmlChar          *contact_info;
    xmlChar          *descr;
    xmlChar          *ref;
    xmlChar          *ns;       /* malloc:main, copy:submod */
    xmlChar          *prefix;   /* may be empty in a submod */
    xmlChar          *xmlprefix;   /* will be diff. if duplicate */
    xmlChar          *source;              /* full filespec */
    xmlChar          *belongs;             /* set if submod */

    const xmlChar    *sourcefn;      /* ptr to fn in source */
    const xmlChar    *belongsver;    /* back ptr to mod ver */

    xmlns_id_t        nsid;            /* assigned by xmlns */
    uint32            langver;
    boolean           ismod;     /* module/submodule keyword */
    boolean           stmtmode;       /* T: save yang_stmt_t */
    boolean           added;         /* T: don't free on err */
    boolean           defaultrev;  /* T: use for default ver */
    status_t          status;         /* module parse result */
    uint32            errors;            /* yangdump results */
    uint32            warnings;          /* yangdump results */

    dlq_hdr_t         revhistQ;        /* Q of ncx_revhist_t */
    dlq_hdr_t         importQ;          /* Q of ncx_import_t */
    dlq_hdr_t         includeQ;        /* Q of ncx_include_t */
    dlq_hdr_t         typeQ;          /* Q of typ_template_t */
    dlq_hdr_t         groupingQ;      /* Q of grp_template_t */
    dlq_hdr_t         datadefQ;       /* Q of obj_template_t */
    dlq_hdr_t         extensionQ;     /* Q of ext_template_t */
    dlq_hdr_t         deviationQ;    /* Q of obj_deviation_t */
    dlq_hdr_t         featureQ;        /* Q of ncx_feature_t */
    dlq_hdr_t         identityQ;      /* Q of ncx_identity_t */
    dlq_hdr_t         appinfoQ;        /* Q of ncx_appinfo_t */
    dlq_hdr_t         typnameQ;        /* Q of ncx_typname_t */
    dlq_hdr_t         saveimpQ;    /* Q of yang_import_ptr_t */
                                  /* saved from pcb->allimpQ */
    dlq_hdr_t         stmtQ;             /* Q of yang_stmt_t */
                             /* saved for top, yang, docmode */

    struct ncx_module_t_ *parent;  /* if this is a submodule */

    /* Q of yang_node_t to track all submodules */
    dlq_hdr_t         allincQ;     /* used if parent == NULL */

    dlq_hdr_t         incchainQ;   /* used if parent == NULL */

    ncx_list_t        devmodlist;     /* for deviations list */

} ncx_module_t;

/* enumeration for different NCX module conversion output types */
typedef enum ncx_cvttyp_t_ {
    NCX_CVTTYP_NONE,
    NCX_CVTTYP_XSD,
    NCX_CVTTYP_SQL,
    NCX_CVTTYP_SQLDB,
    NCX_CVTTYP_HTML,
    NCX_CVTTYP_YANG,
    NCX_CVTTYP_COPY,
    NCX_CVTTYP_H,
    NCX_CVTTYP_C,
    NCX_CVTTYP_CPP_TEST,
    NCX_CVTTYP_YIN,
    NCX_CVTTYP_TG2,
    NCX_CVTTYP_YH,
    NCX_CVTTYP_YC,
    NCX_CVTTYP_UH,
    NCX_CVTTYP_UC
} ncx_cvttyp_t;

/* enum for with-defaults enum values */
typedef enum ncx_withdefaults_t_ {
    NCX_WITHDEF_NONE,
    NCX_WITHDEF_REPORT_ALL,
    NCX_WITHDEF_REPORT_ALL_TAGGED,
    NCX_WITHDEF_TRIM,
    NCX_WITHDEF_EXPLICIT
} ncx_withdefaults_t;

/* One 'import' clause in YANG */
typedef struct ncx_import_t_ {
    dlq_hdr_t           qhdr;
    xmlChar            *module;
    xmlChar            *prefix;
    xmlChar            *revision;
    ncx_module_t       *mod;                   /* back-ptr */
    boolean             used;
    boolean             usexsd;        /* FALSE if duplicate */
    boolean       force_yuma_nc; /* HACK: TRUE if yuma-nc replacing ietf-nc */
    dlq_hdr_t           appinfoQ;
    ncx_error_t         tkerr;
    status_t            res;   /* set to NO_ERR if the import was parsed OK */
} ncx_import_t;

/* One 'include' clause, YANG only */
typedef struct ncx_include_t_ {
    dlq_hdr_t             qhdr;
    xmlChar              *submodule;
    xmlChar              *revision;
    struct ncx_module_t_ *submod;                 /* back-ptr */
    boolean               usexsd;       /* FALSE if duplicate */
    dlq_hdr_t             appinfoQ;
    ncx_error_t           tkerr;
} ncx_include_t;

/* enum for REQUIRED vs. OPTIONAL token */
typedef enum ncx_opt_t_ {
    NCX_REQ,                              /* clause is required */
    NCX_OPT                               /* clause is optional */
} ncx_opt_t;

/* enum for WHITESPACE ALLOWED vs. WHITESPACE NOT ALLOWED string */
typedef enum ncx_strtyp_t_ {
    NCX_WSP,                 /* whitespace allowed: quoted string */
    NCX_NO_WSP         /* whitespace not allowed: unquoted string */
} ncx_strtyp_t;

/* YANG must statement struct */
typedef struct ncx_errinfo_t_ {
    dlq_hdr_t         qhdr;
    xmlChar          *descr;
    xmlChar          *ref;
    xmlChar          *error_app_tag;
    xmlChar          *error_message;
    boolean           seen;                     /* for yangdiff */
} ncx_errinfo_t;

/* keep track of the typenames used for local typedefs
 * only used by ncxdump to generate XSDs
 */
typedef struct ncx_typname_t_ {
    dlq_hdr_t                        qhdr;
    struct typ_template_t_          *typ;
    const xmlChar                   *typname;
    xmlChar                         *typname_malloc;
} ncx_typname_t;

/* user function callback template when a module is
 * loaded into the system
 *
 * ncx_load_cbfn_t
 *
 *  Run an instrumentation-defined function
 *  for a 'module-loaded' event
 *
 * INPUTS:
 *   mod == module that was added to the registry
 *
 */
typedef void (*ncx_load_cbfn_t) (ncx_module_t *mod);

/* user function callback template to traverse all module
 * features for a specified module
 *
 * ncx_feature_cbfn_t
 *
 *  Run an instrumentation-defined function
 *  for each feature found in the module (enabled or not)
 *
 * INPUTS:
 *    mod == module originally passed to the main
 *           function, which contains the 'feature'
 *    feature == feature being processed in the traversal
 *    cookie == cookie originally passed to the main function
 *
 * RETURNS:
 *    TRUE if processing should continue
 *    FALSE if feature traversal should terminate
 */
typedef boolean (*ncx_feature_cbfn_t) (const ncx_module_t *mod,
				       ncx_feature_t *feature,
				       void *cookie);

/* enum for get-schema format type enum values
 * matches the schema-format identities in RFC 6022
 */
typedef enum ncx_modformat_t_ {
    NCX_MODFORMAT_NONE,
    NCX_MODFORMAT_XSD,
    NCX_MODFORMAT_YANG,
    NCX_MODFORMAT_YIN,
    NCX_MODFORMAT_RNG,
    NCX_MODFORMAT_RNC
} ncx_modformat_t;

/* used with obj_deviation_t to defer object lookups */
typedef struct ncx_save_deviations_t_ {
    dlq_hdr_t    qhdr;
    dlq_hdr_t    importQ;        /* Q of ncx_import_t */
    dlq_hdr_t    deviationQ;  /* Q of obj_deviation_t */
    xmlChar     *devmodule;
    xmlChar     *devrevision;
    xmlChar     *devnamespace;
    xmlChar     *devprefix;
} ncx_save_deviations_t;

/* type of confirmEvent in the sysConfirmedCommit notification */
typedef enum ncx_confirm_event_t_ {
    NCX_CC_EVENT_NONE,
    NCX_CC_EVENT_START,
    NCX_CC_EVENT_CANCEL,
    NCX_CC_EVENT_TIMEOUT,
    NCX_CC_EVENT_EXTEND,
    NCX_CC_EVENT_COMPLETE
} ncx_confirm_event_t;

#ifdef __cplusplus
}  /* end extern 'C' */
#endif

#endif	    /* _H_ncxtypes */


text:
title: 'Retrospective on the EnerGuide API: a lot of "firsts" and lessons learned'
description: >-
  As our partnership with NRCan on the EnerGuide API winds down, the CDS product
  team held a retrospective to reflect on our experience, accomplishments and
  lessons learned.
author: 'Jennifer Fletcher, Partnerships'
date: '2018-04-25 09:00:00 -0400'
image: https://de2an9clyit2x.cloudfront.net/blog_energuide_retro_f4780d2e1d.jpg
image-alt: >-
  Seven members of the team are seated around a table. They are looking at two
  people standing at the front of the room grouping post-it notes on on the
  whiteboard.
translationKey: retrospective-on-energuide-api
thumb: https://de2an9clyit2x.cloudfront.net/small_blog_energuide_retro_f4780d2e1d.jpg
---

As our partnership with NRCan on the EnerGuide API winds down, the CDS product team held a retrospective to reflect on our experience, accomplishments and lessons learned.

## What is a retrospective?

A retrospective or "retro" is a technique often used in agile development at the completion of a sprint. Sprints are used to accomplish something in a defined period of time (at CDS we do two week sprints). Each sprint contains:

* a goal of what is to be built
* a design
* a flexible plan that guides the build
* the work of building, and
* the result of the build (at a minimum, some increment of usable functionality)

At CDS, we hold a retro at the end of each sprint to review what worked, what didn't work, and what we could have done differently. Each team does this a little differently, but in this case, team members were given a few minutes to independently answer the following:

* What went well during this sprint?
* What didn't go well during this sprint?
* General comments and/or questions

Responses are written on post-it notes or shared virtually by remote team members. When finished, each member takes a minute to explain their responses to the group.

As members share their responses to these three questions, themes start to emerge. The retro facilitator groups responses by theme for later voting by team members.

Once everyone has contributed, each member is allowed to vote on up to three themes for team discussion.The themes with the greatest number of votes are discussed in greater detail, which generates lessons learned for the product team.

Here's what we took away from our final retro for the EnerGuide API product.

## Lessons learned

* **Team communication must extend beyond daily stand-up meetings**. Daily team stand-ups are a great way to keep everyone on the same page, raise issues and bring new team members up to speed quickly. But, to ensure everyone works together as a team and not teams within a team (i.e. research, design, development, etc.), members need to ensure communication with one another throughout the day.

* **Incorporate weekly partner stand-ups starting at the discovery phase**. Our partnership with NRCan included weekly partner standups, which helped ensure our partner was on the same page as us in terms of what we'd accomplished, what we needed to accomplish and any blockers we needed to remove. Starting this practice at the discovery (rather than at the build phase) would have been a great learning experience for our partner and could have helped in better understanding user needs.

* **Conduct user research with real users**. It became apparent early on in our user research that some of the users we spoke with were one or more people removed from the users we needed to speak with. Probing to find out who the ultimate end user was led us to the specific information we needed.

* **No design decision is too small for usability testing**. To demonstrate the capability of the API to non-technical users, we built a Proof of Concept (PoC) web page. Usability testing was conducted to determine whether a predictive query tool would work for users. While this was a very small task to ask users to do, the insights garnered proved invaluable in determining the design direction to take.

* **A dedicated product manager with a single vision for the product is critical to challenging assumptions and ensuring product team alignment**. As this was one of our early partnerships, we had to get to work in the absence of a dedicated product manager. While a few team members did a pretty good job sharing this role, a dedicated product manager would have saved us some time and hiccups along the way.

* **Co-locate whenever possible**. Co-locating at NRCan helped us tailor our capacity building to meet the needs of the NRCan developers we were working with and, in turn, having NRCan developers co-locate at CDS gave them insight into how we work.

As we concluded the final NRCan EnerGuide API product sprint, one of the themes that emerged was "firsts" for NRCan's Office of Energy Efficiency. From [automated testing](https://digital.canada.ca/2018/03/26/automated-testing-blog/) and using [GraphQL](https://graphql.org/learn/) to build the API itself, we broke new ground. Most importantly, we were able to help NRCan realize the value of putting users at the forefront of product design, and get their feet wet with adopting modern development practices.

redpajama_set_name: RedPajamaGithub


text:
package co.runrightfast.vertx.core.hazelcast.impl;

import co.runrightfast.core.hazelcast.impl.TypesafeHazelcastConfig;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigUtil;
import lombok.extern.java.Log;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author alfio
 */
@Log
public class TypesafeHazelcastConfigTest {

    private static com.typesafe.config.Config config;

    @BeforeClass
    public static void setUpClass() {
        ConfigFactory.invalidateCaches();
        config = ConfigFactory.load(String.format("%s.conf", TypesafeHazelcastConfigTest.class.getSimpleName()));
    }

    @After
    public void afterTest() {
        Hazelcast.shutdownAll();
    }

    /**
     * Test of getHazelcastConfig method, of class TypesafeHazelcastConfig.
     */
    @Test
    public void testGetHazelcastConfig() {
        System.out.println("getConfig");
        final TypesafeHazelcastConfig typesafeHazelcastConfig = new TypesafeHazelcastConfig("testGetConfig", config.getConfig(ConfigUtil.joinPath("Hazelcast", "application-1")));
        final Config hazelcastConfig = typesafeHazelcastConfig.getHazelcastConfig();
        assertThat(hazelcastConfig, is(notNullValue()));
        assertThat(hazelcastConfig.getInstanceName(), is("testGetConfig"));
    }

    /**
     * Test of getHazelcastConfig method, of class TypesafeHazelcastConfig.
     */
    @Test(expected = NullPointerException.class)
    public void testGetHazelcastConfig_null_arg() {
        new TypesafeHazelcastConfig("testGetConfig", null);
    }

}


text:
function pos = linePosition3d(point, line)
%LINEPOSITION3D Return the position of a 3D point projected on a 3D line.
%
%   T = linePosition3d(POINT, LINE)
%   Computes position of point POINT on the line LINE, relative to origin
%   point and direction vector of the line.
%   LINE has the form [x0 y0 z0 dx dy dy],
%   POINT has the form [x y z], and is assumed to belong to line.
%   The result T is the value such that POINT = LINE(1:3) + T * LINE(4:6).
%   If POINT does not belong to LINE, the position of its orthogonal
%   projection is computed instead.
%
%   T = linePosition3d(POINT, LINES)
%   If LINES is an array of NL lines, return NL positions, corresponding to
%   each line.
%
%   T = linePosition3d(POINTS, LINE)
%   If POINTS is an array of NP points, return NP positions, corresponding
%   to each point.
%
%   See also:
%   lines3d, createLine3d, distancePointLine3d, projPointOnLine3d
%
%   ---------
%   author : David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 17/02/2005.
%

%   HISTORY
%   05/01/2007 update doc
%   28/10/2010 change to bsxfun calculation for arbitrary input sizes
%       (Thanks to Sven Holcombe)

% vector from line origin to point
dp = bsxfun(@minus, point, line(:,1:3));

% direction vector of the line
vl = line(:, 4:6);

% precompute and check validity of denominator
denom = sum(vl.^2, 2);
invalidLine = denom < eps;
denom(invalidLine) = 1;

% compute position using dot product normalized with norm of line vector.
pos = bsxfun(@rdivide, sum(bsxfun(@times, dp, vl), 2), denom);

% position on a degenerated line is set to 0
pos(invalidLine) = 0;


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Hist. pl. Pyrénées 132. 1813

#### Original name
null

### Remarks
null


text:
namespace NextBirthday.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Birthday
    {
        public int BirthdayId { get; set; }
        public System.DateTime Birthdate { get; set; }
        public string Name { get; set; }
    }
}


text:
import util from '../util';

export default class NavigatorTransitionAnimator {

  /**
   * @param {Object} options
   * @param {String} options.timing
   * @param {Number} options.duration
   * @param {Number} options.delay
   */
  constructor(options) {
    options = util.extend({
      timing: 'linear',
      duration: '0.4',
      delay: '0'
    }, options || {});

    this.timing = options.timing;
    this.duration = options.duration;
    this.delay = options.delay;
  }

  push(enterPage, leavePage, callback) {
    callback();
  }

  pop(enterPage, leavePage, callback) {
    callback();
  }
}


text:
package services.actor

import akka.actor.{Actor, ActorLogging}
import common.ConfHelper.ConfigHelper
import common.FileHelper.FileHelper
import common.FqueueHelper.FqueueHelper
import play.api.libs.json._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}

/** Created by horatio on 10/27/15.
  */
class SceneActor extends Actor with ActorLogging {

  import services.actor.LogActor.{Err, Info, Warn}
  import services.actor.RecommendActor.QueryOryx
  import services.actor.SceneActor._
  import services.business.Scenes

  val actorPath = context.self.path.toString.split("/")
  val name = actorPath.last
  val logActor = context.actorSelection("../LogActor")
  val recommend = context.actorSelection("../RecommendActor")
  val noMatches = Map[String, Map[String, String]]()

  def receive = {
    case PullFq =>
      val fqClient = FqueueHelper.client()
      Future(fqClient.pull(queue)) onComplete {
        case Success(records) =>
          if (records.isEmpty) {
            logActor ! Warn(s"$name: PullFq: no records to pull")
            Thread.sleep(interval)
            self ! PullFq
          }
          else self ! Judge(records.get, rules)

        case Failure(ex) =>
          logActor ! Err(s"$name: PullFq: $ex")
          Thread.sleep(interval)
          self ! PullFq
      }

    case LoadMap =>

      /**
       * rules: Map[SceneId, Trigger] = Map[SceneId, Map[Variable, Value]]
       * sceneIds: Map[SceneId, Priority]
       */
      sceneIds = ConfigHelper.getMap(sceneIdsFile, separator)
      rules = loadRules(rulesFile, sceneIds.values)
      logActor ! Info(s"$rules\n")

    case Judge(records, rules) =>

      /**
       * Scenes.juage return a composite Map: Map[Uid, Map[SceneId, SendTime]]
       */
      Future(Scenes.judge(records, rules, sceneIds)) onComplete {
        case Success(matches) =>
          if (matches != noMatches) {
            logActor ! Info(s"$name: Judge: $matches")
            recommend ! QueryOryx(matches, priorities)
          }
        case Failure(ex) =>
          logActor ! Err(s"$name: Judge: $ex")
          Thread.sleep(interval)
      }
      Thread.sleep(interval)
      self ! PullFq
  }
}

object SceneActor {
  object PullFq
  object LoadMap
  case class Judge(records: String, rules: Map[String, Map[String, JsValue]])
  object Pause

  def loadRules(rulesFile: String, sceneIds: Iterable[String]): Map[String, Map[String, JsValue]] = {
    import scala.collection.mutable.{Map => muMap}
    val rulesBuffer = Json.parse(FileHelper.readFile(rulesFile)).as[Map[String, JsValue]]
    val rules = muMap[String, Map[String, JsValue]]()

    sceneIds.par map { sceneId =>
      val rule = muMap[String, JsValue]()
      rulesBuffer.keys map { tid =>
        tid.substring(0, 2) match {
          case `sceneId` =>
            val code = tid.substring(3)
            val triggers = rulesBuffer.get(tid).get
            rule += code -> triggers
          case _ =>
        }
      }
      rules += sceneId -> rule.toMap
    }
    rules.toMap
  }

  val dynConfig = ConfigHelper.getConf()
  val queue = dynConfig.getString("Actor.Scene.Fqueue")
  val interval = dynConfig.getString("Actor.Scene.PullInterval").toInt
  val priorityFile = dynConfig.getString("Actor.Recommend.Priority")
  val rulesFile = dynConfig.getString("Actor.Scene.Rules")
  val sceneIdsFile = dynConfig.getString("Actor.Scene.Identities")
  val separator = dynConfig.getString("Actor.Scene.Separator")

  var priorities = ConfigHelper.getMap(priorityFile, separator)
  var sceneIds = ConfigHelper.getMap(sceneIdsFile, separator)
  var rules = loadRules(rulesFile, sceneIds.values)
}


text:
#ifndef  color_generic_constant__make
#define  color_generic_constant__make

// ::color::make::constant::_internal::make( c )

 namespace color
  {
   namespace constant
    {

     //namespace /*_internal*/
     // {

       template< typename constant_name, typename category_name >
        struct make
         {
          typedef category_name   category_type;
          typedef constant_name   constant_type;

          typedef typename ::color::trait::container<category_type>::output_type       container_output_type;

          static void process( container_output_type & m )
           {
            // do nothing;
           }
         };

     // }
    }
  }

#endif


text:
<?php

declare(strict_types=1);

namespace Tests\Legacy\AlgoWeb\PODataLaravel\Unit\Models;

use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\Association;
use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\EntityGubbins;
use AlgoWeb\PODataLaravel\Models\ObjectMap\Map;
use Mockery as m;
use Tests\Legacy\AlgoWeb\PODataLaravel\TestCase;

class ObjectMapTest extends TestCase
{
    public function testAddBadAssociation()
    {
        $foo   = new Map();
        $assoc = m::mock(Association::class);

        $expected = 'Association type not yet handled';
        $actual   = null;

        try {
            $foo->addAssociation($assoc);
        } catch (\InvalidArgumentException $e) {
            $actual = $e->getMessage();
        }
        $this->assertEquals($expected, $actual);
    }

    public function testSetEmptyEntities()
    {
        $foo = new Map();

        $foo->setEntities([]);
        $this->assertEquals(0, count($foo->getEntities()));
    }

    public function testSetEntitiesGood()
    {
        $foo     = new Map();
        $gubbins = new EntityGubbins();
        $gubbins->setClassName('SpaceJam');

        $foo->setEntities([$gubbins]);
        $result = $foo->getEntities();
        $this->assertTrue(is_array($result));
        $this->assertTrue(isset($result['SpaceJam']));
        $this->assertTrue($result['SpaceJam'] instanceof EntityGubbins);
        $this->assertEquals('SpaceJam', $result['SpaceJam']->getClassName());
    }

    public function testSetEntitiesBad()
    {
        $foo = new Map();

        $expected = 'Entities array must contain only EntityGubbins objects';
        $actual   = null;

        try {
            $foo->setEntities([null, 'abc']);
        } catch (\InvalidArgumentException $e) {
            $actual = $e->getMessage();
        }
        $this->assertEquals($expected, $actual);
    }

    public function testAssociationsOnEmpty()
    {
        $foo = new Map();

        $result = $foo->getAssociations();
        $this->assertTrue(is_array($result));
        $this->assertEquals(0, count($result));
    }
}


text:
from oslo_serialization import jsonutils
from oslo_utils import uuidutils
from oslo_utils import versionutils
from sqlalchemy import or_
from sqlalchemy.sql import null

import nova.conf
from nova.db import api as db
from nova.db.sqlalchemy import api as sa_api
from nova.db.sqlalchemy import models
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
from nova.objects import pci_device_pool

CONF = nova.conf.CONF

@base.NovaObjectRegistry.register
class ComputeNode(base.NovaPersistentObject, base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: Added get_by_service_id()
    # Version 1.2: String attributes updated to support unicode
    # Version 1.3: Added stats field
    # Version 1.4: Added host ip field
    # Version 1.5: Added numa_topology field
    # Version 1.6: Added supported_hv_specs
    # Version 1.7: Added host field
    # Version 1.8: Added get_by_host_and_nodename()
    # Version 1.9: Added pci_device_pools
    # Version 1.10: Added get_first_node_by_host_for_old_compat()
    # Version 1.11: PciDevicePoolList version 1.1
    # Version 1.12: HVSpec version 1.1
    # Version 1.13: Changed service_id field to be nullable
    # Version 1.14: Added cpu_allocation_ratio and ram_allocation_ratio
    # Version 1.15: Added uuid
    # Version 1.16: Added disk_allocation_ratio
    # Version 1.17: Added mapped
    # Version 1.18: Added get_by_uuid().
    # Version 1.19: Added get_by_nodename().
    VERSION = '1.19'

    fields = {
        'id': fields.IntegerField(read_only=True),
        'uuid': fields.UUIDField(read_only=True),
        'service_id': fields.IntegerField(nullable=True),
        'host': fields.StringField(nullable=True),
        'vcpus': fields.IntegerField(),
        'memory_mb': fields.IntegerField(),
        'local_gb': fields.IntegerField(),
        'vcpus_used': fields.IntegerField(),
        'memory_mb_used': fields.IntegerField(),
        'local_gb_used': fields.IntegerField(),
        'hypervisor_type': fields.StringField(),
        'hypervisor_version': fields.IntegerField(),
        'hypervisor_hostname': fields.StringField(nullable=True),
        'free_ram_mb': fields.IntegerField(nullable=True),
        'free_disk_gb': fields.IntegerField(nullable=True),
        'current_workload': fields.IntegerField(nullable=True),
        'running_vms': fields.IntegerField(nullable=True),
        # TODO(melwitt): cpu_info is non-nullable in the schema but we must
        # wait until version 2.0 of ComputeNode to change it to non-nullable
        'cpu_info': fields.StringField(nullable=True),
        'disk_available_least': fields.IntegerField(nullable=True),
        'metrics': fields.StringField(nullable=True),
        'stats': fields.DictOfNullableStringsField(nullable=True),
        'host_ip': fields.IPAddressField(nullable=True),
        # TODO(rlrossit): because of history, numa_topology is held here as a
        # StringField, not a NUMATopology object. In version 2 of ComputeNode
        # this will be converted over to a fields.ObjectField('NUMATopology')
        'numa_topology': fields.StringField(nullable=True),
        # NOTE(pmurray): the supported_hv_specs field maps to the
        # supported_instances field in the database
        'supported_hv_specs': fields.ListOfObjectsField('HVSpec'),
        # NOTE(pmurray): the pci_device_pools field maps to the
        # pci_stats field in the database
        'pci_device_pools': fields.ObjectField('PciDevicePoolList',
                                               nullable=True),
        'cpu_allocation_ratio': fields.FloatField(),
        'ram_allocation_ratio': fields.FloatField(),
        'disk_allocation_ratio': fields.FloatField(),
        'mapped': fields.IntegerField(),
        }

    def obj_make_compatible(self, primitive, target_version):
        super(ComputeNode, self).obj_make_compatible(primitive, target_version)
        target_version = versionutils.convert_version_to_tuple(target_version)
        if target_version < (1, 17):
            if 'mapped' in primitive:
                del primitive['mapped']
        if target_version < (1, 16):
            if 'disk_allocation_ratio' in primitive:
                del primitive['disk_allocation_ratio']
        if target_version < (1, 15):
            if 'uuid' in primitive:
                del primitive['uuid']
        if target_version < (1, 14):
            if 'ram_allocation_ratio' in primitive:
                del primitive['ram_allocation_ratio']
            if 'cpu_allocation_ratio' in primitive:
                del primitive['cpu_allocation_ratio']
        if target_version < (1, 13) and primitive.get('service_id') is None:
            # service_id is non-nullable in versions before 1.13
            try:
                service = objects.Service.get_by_compute_host(
                    self._context, primitive['host'])
                primitive['service_id'] = service.id
            except (exception.ComputeHostNotFound, KeyError):
                # NOTE(hanlind): In case anything goes wrong like service not
                # found or host not being set, catch and set a fake value just
                # to allow for older versions that demand a value to work.
                # Setting to -1 will, if value is later used result in a
                # ServiceNotFound, so should be safe.
                primitive['service_id'] = -1
        if target_version < (1, 9) and 'pci_device_pools' in primitive:
            del primitive['pci_device_pools']
        if target_version < (1, 7) and 'host' in primitive:
            del primitive['host']
        if target_version < (1, 6) and 'supported_hv_specs' in primitive:
            del primitive['supported_hv_specs']
        if target_version < (1, 5) and 'numa_topology' in primitive:
            del primitive['numa_topology']
        if target_version < (1, 4) and 'host_ip' in primitive:
            del primitive['host_ip']
        if target_version < (1, 3) and 'stats' in primitive:
            # pre 1.3 version does not have a stats field
            del primitive['stats']

    @staticmethod
    def _host_from_db_object(compute, db_compute):
        if (('host' not in db_compute or db_compute['host'] is None) and
                'service_id' in db_compute and
                db_compute['service_id'] is not None):
            # FIXME(sbauza) : Unconverted compute record, provide compatibility
            # This has to stay until we can be sure that any/all compute nodes
            # in the database have been converted to use the host field

            # Service field of ComputeNode could be deprecated in a next patch,
            # so let's use directly the Service object
            try:
                service = objects.Service.get_by_id(
                    compute._context, db_compute['service_id'])
            except exception.ServiceNotFound:
                compute.host = None
                return
            try:
                compute.host = service.host
            except (AttributeError, exception.OrphanedObjectError):
                # Host can be nullable in Service
                compute.host = None
        elif 'host' in db_compute and db_compute['host'] is not None:
            # New-style DB having host as a field
            compute.host = db_compute['host']
        else:
            # We assume it should not happen but in case, let's set it to None
            compute.host = None

    @staticmethod
    def _from_db_object(context, compute, db_compute):
        special_cases = set([
            'stats',
            'supported_hv_specs',
            'host',
            'pci_device_pools',
            ])
        fields = set(compute.fields) - special_cases
        online_updates = {}
        for key in fields:
            value = db_compute[key]
            # NOTE(sbauza): Since all compute nodes don't possibly run the
            # latest RT code updating allocation ratios, we need to provide
            # a backwards compatible way of hydrating them.
            # As we want to care about our operators and since we don't want to
            # ask them to change their configuration files before upgrading, we
            # prefer to hardcode the default values for the ratios here until
            # the next release (Newton) where the opt default values will be
            # restored for both cpu (16.0), ram (1.5) and disk (1.0)
            # allocation ratios.
            # TODO(yikun): Remove this online migration code when all ratio
            # values are NOT 0.0 or NULL
            ratio_keys = ['cpu_allocation_ratio', 'ram_allocation_ratio',
                          'disk_allocation_ratio']
            if key in ratio_keys and value in (None, 0.0):
                # ResourceTracker is not updating the value (old node)
                # or the compute node is updated but the default value has
                # not been changed
                r = getattr(CONF, key)
                # NOTE(yikun): If the allocation ratio record is not set, the
                # allocation ratio will be changed to the
                # CONF.x_allocation_ratio value if x_allocation_ratio is
                # set, and fallback to use the CONF.initial_x_allocation_ratio
                # otherwise.
                init_x_ratio = getattr(CONF, 'initial_%s' % key)
                value = r if r else init_x_ratio
                online_updates[key] = value
            elif key == 'mapped':
                value = 0 if value is None else value

            setattr(compute, key, value)

        if online_updates:
            db.compute_node_update(context, compute.id, online_updates)

        stats = db_compute['stats']
        if stats:
            compute.stats = jsonutils.loads(stats)

        sup_insts = db_compute.get('supported_instances')
        if sup_insts:
            hv_specs = jsonutils.loads(sup_insts)
            hv_specs = [objects.HVSpec.from_list(hv_spec)
                        for hv_spec in hv_specs]
            compute.supported_hv_specs = hv_specs

        pci_stats = db_compute.get('pci_stats')
        if pci_stats is not None:
            pci_stats = pci_device_pool.from_pci_stats(pci_stats)
        compute.pci_device_pools = pci_stats
        compute._context = context

        # Make sure that we correctly set the host field depending on either
        # host column is present in the table or not
        compute._host_from_db_object(compute, db_compute)

        compute.obj_reset_changes()

        return compute

    @base.remotable_classmethod
    def get_by_id(cls, context, compute_id):
        db_compute = db.compute_node_get(context, compute_id)
        return cls._from_db_object(context, cls(), db_compute)

    @base.remotable_classmethod
    def get_by_uuid(cls, context, compute_uuid):
        nodes = ComputeNodeList.get_all_by_uuids(context, [compute_uuid])
        # We have a unique index on the uuid column so we can get back 0 or 1.
        if not nodes:
            raise exception.ComputeHostNotFound(host=compute_uuid)
        return nodes[0]

    # NOTE(hanlind): This is deprecated and should be removed on the next
    # major version bump
    @base.remotable_classmethod
    def get_by_service_id(cls, context, service_id):
        db_computes = db.compute_nodes_get_by_service_id(context, service_id)
        # NOTE(sbauza): Old version was returning an item, we need to keep this
        # behaviour for backwards compatibility
        db_compute = db_computes[0]
        return cls._from_db_object(context, cls(), db_compute)

    @base.remotable_classmethod
    def get_by_host_and_nodename(cls, context, host, nodename):
        db_compute = db.compute_node_get_by_host_and_nodename(
            context, host, nodename)
        return cls._from_db_object(context, cls(), db_compute)

    @base.remotable_classmethod
    def get_by_nodename(cls, context, hypervisor_hostname):
        '''Get by node name (i.e. hypervisor hostname).

        Raises ComputeHostNotFound if hypervisor_hostname with the given name
        doesn't exist.
        '''
        db_compute = db.compute_node_get_by_nodename(
            context, hypervisor_hostname)
        return cls._from_db_object(context, cls(), db_compute)

    # TODO(pkholkin): Remove this method in the next major version bump
    @base.remotable_classmethod
    def get_first_node_by_host_for_old_compat(cls, context, host,
                                              use_slave=False):
        computes = ComputeNodeList.get_all_by_host(context, host, use_slave)
        # FIXME(sbauza): Ironic deployments can return multiple
        # nodes per host, we should return all the nodes and modify the callers
        # instead.
        # Arbitrarily returning the first node.
        return computes[0]

    @staticmethod
    def _convert_stats_to_db_format(updates):
        stats = updates.pop('stats', None)
        if stats is not None:
            updates['stats'] = jsonutils.dumps(stats)

    @staticmethod
    def _convert_host_ip_to_db_format(updates):
        host_ip = updates.pop('host_ip', None)
        if host_ip:
            updates['host_ip'] = str(host_ip)

    @staticmethod
    def _convert_supported_instances_to_db_format(updates):
        hv_specs = updates.pop('supported_hv_specs', None)
        if hv_specs is not None:
            hv_specs = [hv_spec.to_list() for hv_spec in hv_specs]
            updates['supported_instances'] = jsonutils.dumps(hv_specs)

    @staticmethod
    def _convert_pci_stats_to_db_format(updates):
        if 'pci_device_pools' in updates:
            pools = updates.pop('pci_device_pools')
            if pools is not None:
                pools = jsonutils.dumps(pools.obj_to_primitive())
            updates['pci_stats'] = pools

    @base.remotable
    def create(self):
        if self.obj_attr_is_set('id'):
            raise exception.ObjectActionError(action='create',
                                              reason='already created')
        updates = self.obj_get_changes()
        if 'uuid' not in updates:
            updates['uuid'] = uuidutils.generate_uuid()
            self.uuid = updates['uuid']

        self._convert_stats_to_db_format(updates)
        self._convert_host_ip_to_db_format(updates)
        self._convert_supported_instances_to_db_format(updates)
        self._convert_pci_stats_to_db_format(updates)

        db_compute = db.compute_node_create(self._context, updates)
        self._from_db_object(self._context, self, db_compute)

    @base.remotable
    def save(self, prune_stats=False):
        # NOTE(belliott) ignore prune_stats param, no longer relevant

        updates = self.obj_get_changes()
        updates.pop('id', None)
        self._convert_stats_to_db_format(updates)
        self._convert_host_ip_to_db_format(updates)
        self._convert_supported_instances_to_db_format(updates)
        self._convert_pci_stats_to_db_format(updates)

        db_compute = db.compute_node_update(self._context, self.id, updates)
        self._from_db_object(self._context, self, db_compute)

    @base.remotable
    def destroy(self):
        db.compute_node_delete(self._context, self.id)

    def update_from_virt_driver(self, resources):
        # NOTE(pmurray): the virt driver provides a dict of values that
        # can be copied into the compute node. The names and representation
        # do not exactly match.
        # TODO(pmurray): the resources dict should be formalized.
        keys = ["vcpus", "memory_mb", "local_gb", "cpu_info",
                "vcpus_used", "memory_mb_used", "local_gb_used",
                "numa_topology", "hypervisor_type",
                "hypervisor_version", "hypervisor_hostname",
                "disk_available_least", "host_ip", "uuid"]
        for key in keys:
            if key in resources:
                # The uuid field is read-only so it should only be set when
                # creating the compute node record for the first time. Ignore
                # it otherwise.
                if key == 'uuid' and 'uuid' in self:
                    continue
                setattr(self, key, resources[key])

        # supported_instances has a different name in compute_node
        if 'supported_instances' in resources:
            si = resources['supported_instances']
            self.supported_hv_specs = [objects.HVSpec.from_list(s) for s in si]

@base.NovaObjectRegistry.register
class ComputeNodeList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    #              ComputeNode <= version 1.2
    # Version 1.1 ComputeNode version 1.3
    # Version 1.2 Add get_by_service()
    # Version 1.3 ComputeNode version 1.4
    # Version 1.4 ComputeNode version 1.5
    # Version 1.5 Add use_slave to get_by_service
    # Version 1.6 ComputeNode version 1.6
    # Version 1.7 ComputeNode version 1.7
    # Version 1.8 ComputeNode version 1.8 + add get_all_by_host()
    # Version 1.9 ComputeNode version 1.9
    # Version 1.10 ComputeNode version 1.10
    # Version 1.11 ComputeNode version 1.11
    # Version 1.12 ComputeNode version 1.12
    # Version 1.13 ComputeNode version 1.13
    # Version 1.14 ComputeNode version 1.14
    # Version 1.15 Added get_by_pagination()
    # Version 1.16: Added get_all_by_uuids()
    # Version 1.17: Added get_all_by_not_mapped()
    VERSION = '1.17'
    fields = {
        'objects': fields.ListOfObjectsField('ComputeNode'),
        }

    @base.remotable_classmethod
    def get_all(cls, context):
        db_computes = db.compute_node_get_all(context)
        return base.obj_make_list(context, cls(context), objects.ComputeNode,
                                  db_computes)

    @base.remotable_classmethod
    def get_all_by_not_mapped(cls, context, mapped_less_than):
        """Return ComputeNode records that are not mapped at a certain level"""
        db_computes = db.compute_node_get_all_mapped_less_than(
            context, mapped_less_than)
        return base.obj_make_list(context, cls(context), objects.ComputeNode,
                                  db_computes)

    @base.remotable_classmethod
    def get_by_pagination(cls, context, limit=None, marker=None):
        db_computes = db.compute_node_get_all_by_pagination(
            context, limit=limit, marker=marker)
        return base.obj_make_list(context, cls(context), objects.ComputeNode,
                                  db_computes)

    @base.remotable_classmethod
    def get_by_hypervisor(cls, context, hypervisor_match):
        db_computes = db.compute_node_search_by_hypervisor(context,
                                                           hypervisor_match)
        return base.obj_make_list(context, cls(context), objects.ComputeNode,
                                  db_computes)

    # NOTE(hanlind): This is deprecated and should be removed on the next
    # major version bump
    @base.remotable_classmethod
    def _get_by_service(cls, context, service_id, use_slave=False):
        try:
            db_computes = db.compute_nodes_get_by_service_id(
                context, service_id)
        except exception.ServiceNotFound:
            # NOTE(sbauza): Previous behaviour was returning an empty list
            # if the service was created with no computes, we need to keep it.
            db_computes = []
        return base.obj_make_list(context, cls(context), objects.ComputeNode,
                                  db_computes)

    @staticmethod
    @db.select_db_reader_mode
    def _db_compute_node_get_all_by_host(context, host, use_slave=False):
        return db.compute_node_get_all_by_host(context, host)

    @base.remotable_classmethod
    def get_all_by_host(cls, context, host, use_slave=False):
        db_computes = cls._db_compute_node_get_all_by_host(context, host,
                                                      use_slave=use_slave)
        return base.obj_make_list(context, cls(context), objects.ComputeNode,
                                  db_computes)

    @staticmethod
    @db.select_db_reader_mode
    def _db_compute_node_get_all_by_uuids(context, compute_uuids):
        db_computes = sa_api.model_query(context, models.ComputeNode).filter(
            models.ComputeNode.uuid.in_(compute_uuids)).all()
        return db_computes

    @base.remotable_classmethod
    def get_all_by_uuids(cls, context, compute_uuids):
        db_computes = cls._db_compute_node_get_all_by_uuids(context,
                                                            compute_uuids)
        return base.obj_make_list(context, cls(context), objects.ComputeNode,
                                  db_computes)

    @staticmethod
    @db.select_db_reader_mode
    def _db_compute_node_get_by_hv_type(context, hv_type):
        db_computes = context.session.query(models.ComputeNode).filter(
            models.ComputeNode.hypervisor_type == hv_type).all()
        return db_computes

    @classmethod
    def get_by_hypervisor_type(cls, context, hv_type):
        db_computes = cls._db_compute_node_get_by_hv_type(context, hv_type)
        return base.obj_make_list(context, cls(context), objects.ComputeNode,
                                  db_computes)

def _get_node_empty_ratio(context, max_count):
    """Query the DB for non-deleted compute_nodes with 0.0/None alloc ratios

    Results are limited by ``max_count``.
    """
    return context.session.query(models.ComputeNode).filter(or_(
        models.ComputeNode.ram_allocation_ratio == '0.0',
        models.ComputeNode.cpu_allocation_ratio == '0.0',
        models.ComputeNode.disk_allocation_ratio == '0.0',
        models.ComputeNode.ram_allocation_ratio == null(),
        models.ComputeNode.cpu_allocation_ratio == null(),
        models.ComputeNode.disk_allocation_ratio == null()
    )).filter(models.ComputeNode.deleted == 0).limit(max_count).all()

@sa_api.pick_context_manager_writer
def migrate_empty_ratio(context, max_count):
    cns = _get_node_empty_ratio(context, max_count)

    # NOTE(yikun): If it's an existing record with 0.0 or None values,
    # we need to migrate this record using 'xxx_allocation_ratio' config
    # if it's set, and fallback to use the 'initial_xxx_allocation_ratio'
    # otherwise.
    for cn in cns:
        for t in ['cpu', 'disk', 'ram']:
            current_ratio = getattr(cn, '%s_allocation_ratio' % t)
            if current_ratio in (0.0, None):
                r = getattr(CONF, "%s_allocation_ratio" % t)
                init_x_ratio = getattr(CONF, "initial_%s_allocation_ratio" % t)
                conf_alloc_ratio = r if r else init_x_ratio
                setattr(cn, '%s_allocation_ratio' % t, conf_alloc_ratio)
        context.session.add(cn)
    found = done = len(cns)
    return found, done


text:
This theme is designed by Xiaoying Riley at 3rd Wave Media (http://themes.3rdwavemedia.com/). Visit her website for more themes [http://themes.3rdwavemedia.com/](http://themes.3rdwavemedia.com/)

I have made this into a Jekyll Theme.
**Demo:** [http://webjeda.com/online-cv/](http://webjeda.com/online-cv/)

The default theme would look like this

![online cv Jekyll theme](https://github.com/sharu725/online-cv/raw/master/assets/images/online-cv-jekyll-theme.png)

The theme is responsive

![online cv responsive Jekyll theme](https://github.com/sharu725/online-cv/raw/master/assets/images/online-cv-responsive-jekyll-theme.png)

There are 6 color schemes available

![online cv Jekyll theme](https://github.com/sharu725/online-cv/raw/master/assets/images/online-cv-jekyll-theme-2.png)

## Installation
* Fork the repository
* Go to settings and set Github Pages source as master.
* Your new site should be ready at https://username.github.io/online-cv/

[Watch my video on instlallation](https://www.youtube.com/embed/T2nx6tj-ZH4)

Thanks to [Nelson Estevão](https://github.com/nelsonmestevao) for all the [contributions](https://github.com/sharu725/online-cv/commits?author=nelsonmestevao).

Check out for more themes: [**Jekyll Themes**](http://jekyll-themes.com)


text:
layout:			script-page
title:			"All tags scripts"
date:			2015-05-13
author:			"Arpit Bhayani"
category:		meta-script
comments:		false
short-desc:		Get all tags present in the site here.
---
<section>
{% for t in site.tags %}
{{t[0]}}
{% endfor %}
</section>


text:
ByteArrayDataInput::ByteArrayDataInput(const unsigned char* buffer) {
   this->buffer = buffer;
   position = 0;
}

ByteArrayDataInput::~ByteArrayDataInput() {
}

bool ByteArrayDataInput::ReadBoolean() {
   return ReadByte() != 0;
}

unsigned char ByteArrayDataInput::ReadByte() {
   return buffer[position++];
}

unsigned short ByteArrayDataInput::ReadShort() {
   unsigned short x = buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   return x;
}

unsigned int ByteArrayDataInput::ReadInt() {
   unsigned int x = buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   return x;
}

unsigned long ByteArrayDataInput::ReadLong() {
   unsigned long x = buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   x <<= 8;
   x |= buffer[position++];
   return x;
}

double ByteArrayDataInput::ReadDouble() {
   union {
      unsigned long l;
      double d;
   } u;
   u.l = ReadLong();
   return u.d;
}

std::string ByteArrayDataInput::ReadString() {
   unsigned short length = ReadShort();
   position += length;
   return std::string((const char*) (buffer + (position - length)), (size_t) length);
}

void ByteArrayDataInput::Read(unsigned char* buffer, unsigned int offset, unsigned int length) {
   memcpy(buffer + offset, this->buffer + position, length);
   position += length;
}


text:
import re
import collections
import requests

from threeML.io.network import internet_connection_is_active

def compute_fermi_relative_mission_times(trigger_time):
    """

    If the user has the requests library, this function looks
    online to the HEASARC xtime utility and computes other mission
    times relative to the input MET

    :param trigger_time: a fermi MET
    :return: mission time in a python dictionary
    """
    mission_dict = collections.OrderedDict()

    if trigger_time == 0:
        return None

    # Complements to Volodymyr Savchenko

    xtime_url = "https://heasarc.gsfc.nasa.gov/cgi-bin/Tools/xTime/xTime.pl"

    pattern = """
.*?(.*?)	.*?.*?	.*?(.*?)	.*?
"""

    args = dict(
        time_in_sf=trigger_time,
        timesys_in="u",
        timesys_out="u",
        apply_clock_offset="yes",
    )

    if internet_connection_is_active():

        content = requests.get(xtime_url, params=args).content

        mission_info = re.findall(pattern, content, re.S)

        mission_dict["UTC"] = mission_info[0][-1]
        mission_dict[mission_info[7][1]] = mission_info[7][2]  # LIGO
        mission_dict[mission_info[8][1]] = mission_info[8][2]  # NUSTAR
        mission_dict[mission_info[12][1]] = mission_info[12][2]  # RXTE
        mission_dict[mission_info[16][1]] = mission_info[16][2]  # SUZAKU
        mission_dict[mission_info[20][1]] = mission_info[20][2]  # SWIFT
        mission_dict[mission_info[24][1]] = mission_info[24][2]  # CHANDRA

        return mission_dict

    else:

        return None


text:
package com.fondesa.lyra.coder.base;

import com.fondesa.lyra.sharedtest.BundleTestCase;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import static junit.framework.Assert.assertEquals;

/**
 * Unit test class for {@link CharCoder}.
 */
@RunWith(RobolectricTestRunner.class)
public class CharCoderTest extends BundleTestCase {
    private CharCoder mCoder = new CharCoder();

    @Test
    public void testSerializeCharPrimitive() {
        char expectedValue = 'x';
        mCoder.serialize(bundle(), randomKey(), expectedValue);
        assertEquals(expectedValue, bundle().getChar(randomKey()));
    }

    @Test
    public void testSerializeCharObject() {
        Character expectedValue = 'x';
        mCoder.serialize(bundle(), randomKey(), expectedValue);
        assertEquals(expectedValue, ((Character) bundle().getChar(randomKey())));
    }

    @Test
    public void testDeserializeCharPrimitive() {
        char expectedValue = 'x';
        bundle().putChar(randomKey(), expectedValue);
        assertEquals((Character) expectedValue, mCoder.deserialize(bundle(), randomKey()));
    }

    @Test
    public void testDeserializeCharObject() {
        Character expectedValue = 'x';
        bundle().putChar(randomKey(), expectedValue);
        assertEquals(expectedValue, mCoder.deserialize(bundle(), randomKey()));
    }
}


text:
package network::dlink::standard::snmp::mode::components::temperature;

use strict;
use warnings;

my $map_status = {
    1 => 'ok', 2 => 'abnormal'
};

my $mapping_equipment = {
    swTemperatureCurrent => { oid => '.1.3.6.1.4.1.171.12.11.1.8.1.2' }
};
my $mapping_industrial = {
    description    => { oid => '.1.3.6.1.4.1.171.14.5.1.1.1.1.3' }, # dEntityExtEnvTempDescr
    current        => { oid => '.1.3.6.1.4.1.171.14.5.1.1.1.1.4' }, # dEntityExtEnvTempCurrent
    threshold_low  => { oid => '.1.3.6.1.4.1.171.14.5.1.1.1.1.5' }, # dEntityExtEnvTempThresholdLow
    threshold_high => { oid => '.1.3.6.1.4.1.171.14.5.1.1.1.1.6' }, # dEntityExtEnvTempThresholdHigh
    status         => { oid => '.1.3.6.1.4.1.171.14.5.1.1.1.1.7', map => $map_status } # dEntityExtEnvTempStatus
};
my $oid_dEntityExtEnvTempEntry = '.1.3.6.1.4.1.171.14.5.1.1.1.1';

my $mapping_common = {
    description    => { oid => '.1.3.6.1.4.1.171.17.5.1.1.1.1.3' }, # esEntityExtEnvTempDescr
    current        => { oid => '.1.3.6.1.4.1.171.17.5.1.1.1.1.4' }, # esEntityExtEnvTempCurrent
    threshold_low  => { oid => '.1.3.6.1.4.1.171.17.5.1.1.1.1.5' }, # esEntityExtEnvTempThresholdLow
    threshold_high => { oid => '.1.3.6.1.4.1.171.17.5.1.1.1.1.6' }, # esEntityExtEnvTempThresholdHigh
    status         => { oid => '.1.3.6.1.4.1.171.17.5.1.1.1.1.7', map => $map_status } # esEntityExtEnvTempStatus
};
my $oid_esEntityExtEnvTempEntry = '.1.3.6.1.4.1.171.17.5.1.1.1.1';

sub load {
    my ($self) = @_;

    push @{$self->{request}},
        { oid => $mapping_equipment->{swTemperatureCurrent}->{oid} },
        { oid => $oid_dEntityExtEnvTempEntry, start => $mapping_industrial->{description}->{oid} },
        { oid => $oid_esEntityExtEnvTempEntry, start => $mapping_common->{description}->{oid} }
    ;
}

sub check_temperature_equipment {
    my ($self, %options) = @_;

    foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{ $mapping_equipment->{swTemperatureCurrent}->{oid} }})) {
        $oid =~ /^$mapping_equipment->{swTemperatureCurrent}->{oid}\.(.*)$/;
        my $instance = $1;
        my $result = $self->{snmp}->map_instance(mapping => $mapping_equipment, results => $self->{results}->{ $mapping_equipment->{swTemperatureCurrent}->{oid} }, instance => $instance);

        next if ($self->check_filter(section => 'temperature', instance => $instance));
        $self->{components}->{temperature}->{total}++;

        $self->{output}->output_add(long_msg =>
            sprintf(
                "temperature '%s' is %dC.",
                $instance,
                $result->{swTemperatureCurrent}
            )
        );

        my ($exit, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'temperature', instance => $instance, value => $result->{swTemperatureCurrent});
        if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
            $self->{output}->output_add(
                severity => $exit,
                short_msg => sprintf(
                    "Temperature '%s' is %s degree centigrade",
                    $instance,
                    $result->{swTemperatureCurrent}
                )
            );
        }
        $self->{output}->perfdata_add(
            unit => 'C',
            nlabel => 'hardware.temperature.celsius',
            instances => $instance,
            value => $result->{swTemperatureCurrent},
            warning => $warn,
            critical => $crit
        );
    }
}

sub check_temperature {
    my ($self, %options) = @_;

    foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{ $options{entry} }})) {
        next if ($oid !~ /^$options{mapping}->{status}->{oid}\.(\d+)\.(\d+)$/);
        my ($unit_id, $temp_id) = ($1, $2);
        my $instance = $1 . '.' . $2;
        my $result = $self->{snmp}->map_instance(mapping => $options{mapping}, results => $self->{results}->{ $options{entry} }, instance => $instance);

        my $description = 'unit' . $unit_id . ':temp' . $temp_id;
        next if ($self->check_filter(section => 'temperature', instance => $instance));
        $self->{components}->{temperature}->{total}++;

        $self->{output}->output_add(
            long_msg => sprintf(
                "temperature '%s' status is '%s' [instance: %s, description: %s, current: %s]",
                $description,
                $result->{status},
                $instance,
                $result->{description},
                $result->{current}
            )
        );
        my $exit = $self->get_severity(section => 'temperature', value => $result->{status});
        if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
            $self->{output}->output_add(
                severity =>  $exit,
                short_msg => sprintf(
                    "temperature '%s' status is %s",
                    $description, $result->{status}
                )
            );
        }

        next if (!defined($result->{current}));

        my ($exit2, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'temperature', instance => $instance, value => $result->{current});
        if ($checked == 0) {
            my $warn_th = '';
            my $crit_th = defined($result->{threshold_high}) && $result->{threshold_high} =~ /\d/ ? $result->{threshold_high} : '';
            $crit_th = $result->{threshold_low} . ':' . $crit_th if (defined($result->{threshold_low}) && $result->{threshold_low} =~ /\d/);

            $self->{perfdata}->threshold_validate(label => 'warning-temperature-instance-' . $instance, value => $warn_th);
            $self->{perfdata}->threshold_validate(label => 'critical-temperature-instance-' . $instance, value => $crit_th);
            $warn = $self->{perfdata}->get_perfdata_for_output(label => 'warning-temperature-instance-' . $instance);
            $crit = $self->{perfdata}->get_perfdata_for_output(label => 'critical-temperature-instance-' . $instance)
        }

        if (!$self->{output}->is_status(value => $exit2, compare => 'ok', litteral => 1)) {
            $self->{output}->output_add(
                severity => $exit2,
                short_msg => sprintf(
                    "temperature '%s' is %s degree centigrate",
                    $description,
                    $result->{current}
                )
            );
        }
        $self->{output}->perfdata_add(
            unit => 'C',
            nlabel => 'hardware.temperature.celsius',
            instances => ['unit' . $unit_id, 'temp' . $temp_id],
            value => $result->{current},
            warning => $warn,
            critical => $crit
        );
    }
}

sub check {
    my ($self) = @_;

    $self->{output}->output_add(long_msg => 'checking temperatures');
    $self->{components}->{temperature} = {name => 'temperatures', total => 0, skip => 0};
    return if ($self->check_filter(section => 'temperature'));

    check_temperature_equipment($self);
    check_temperature($self, entry => $oid_dEntityExtEnvTempEntry, mapping => $mapping_industrial);
    check_temperature($self, entry => $oid_esEntityExtEnvTempEntry, mapping => $mapping_common);
}

1;


text:
using System;
using CommandLineParser.Exceptions;

namespace CommandLineParser.Attributes
{
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public sealed class FlagAttribute : Attribute
    {
        private readonly string shortName;
        private readonly string name;
        public readonly bool required;

        public FlagAttribute(string name = null, string shortName = null, bool required = false)
        {
            this.name = name;
            this.required = required;
            this.shortName = shortName;
            if (!string.IsNullOrWhiteSpace(shortName) && shortName.Length > 1) throw new LengthExceededException(1);
            if (!string.IsNullOrWhiteSpace(name)) this.name = this.name.ToLower();
        }

        public string Name
        {
            get { return name; }
        }

        public string ShortName
        {
            get { return shortName; }
        }

        public bool Required
        {
            get { return required; }
        }
    }
}


text:
package crackingthecode;

public final class Chapter6BrainTeasers {
    /**
     * 6.1 - Add arithmetic operators (plus, minus, times, divide) to make the following expression
     * true: 3 1 3 6 = 8. You can use any parentheses you'd like.
     */
    public double arithmeticOperators() {
        // int division = 0, use double
        return (3.0 + 1.0) / (3.0 / 6.0); // ((3 + 1) / 3) * 6 = 8
    }

    /**
     * 6.2 - There is an 8x8 chess board in which two diagonally opposite corners have been cut off.
     * You are given 31 dominos, and a single domino can cover exactly two squares. Can you use the 31
     * dominos to cover the entire board? Prove your answer (by providing an example, or showing why
     * it's impossible).
     */
    public int chessPieces() {
        // 1 domino     = 2 squares
        // 31 dominoes  = 62 squares
        // 8x8 grid     = 64 squares

        // 31 dominos cannot cover the entire board without the corners being removed
        // If each corner that was cut was exactly 1 or more squares then it can cover.

        // The book solution mentions 30 black and 32 white squares and said it is impossible
        // because of the colors(colors were not mentioned, only the board itself in the question).

        // The question did not say to "equally" cover the colors.

        return 8 * 8;
    }

    /**
     * 6.3 - You have a five quart jug and a three quart jug, and an unlimited supply of water (but no
     * measuring cups). How would you come up with exactly four quarts of water? NOTE: The jugs are
     * oddly shaped, such that filling up exactly 'half' of the jug would be impossible.
     */
    public int exactJugs() {
        // Sine you have a 5 quart jug and a 3 quart jug, you can fill up the 5 quart jug and
        // use the 5 quart jug to full up the 3 quart jug. When the 3 quart jug is full, you know
        // that you have exactly 2 quarts.

        // You can repeat this process one more time to get 4 quarts of water.

        return (5 - 3) * 2;
    }

    /*
     * 6.4 - A bunch of men are on an island. A genie comes down and gathers everyone to- gether and
     * places a magical hat on some people's heads (i.e., at least one person has a hat). The hat is
     * magical: it can be seen by other people, but not by the wearer of the hat himself. To remove
     * the hat, those (and only those who have a hat) must dunk themselves underwater at exactly
     * midnight. If there are n people and c hats, how long does it take the men to remove the hats?
     * The men cannot tell each other (in any way) that they have a hat.
     * FOLLOW UP
     * Prove that your solution is correct.
     */
    // n - people
    // c - hats, atleast one person has a hat

    /*
     * 6.5 - There is a building of 100 floors. If an egg drops from the Nth floor or above it will
     * break. If it's dropped from any floor below, it will not break. You're given 2 eggs. Find N,
     * while minimizing the number of drops for the worst case.
     */
    // 100 floors
    // if N >= break else !break
    // Only given 2 eggs

    // If we start from the bottom floor 1, first egg breaks at floor 2, then we know that N == 2

    /**
     * 6.6 - There are one hundred closed lockers in a hallway. A man begins by opening all one
     * hundred lockers. Next, he closes every second locker. Then he goes to every third locker and
     * closes it if it is open or opens it if it is closed (e.g., he toggles every third locker).
     * After his one hundredth pass in the hallway, in which he toggles only locker number one
     * hundred, how many lockers are open?
     */
    // Time - O(N), Space - O(N)
    public int lockersOpen() {
        // 100 - open
        // 100/2 - 50 - closes every second locker

        // basic demonstration with 10:
        // |_| - open
        // |x| - closed
        // 10 - |_|_|_|_|_|_|_|_|_|_| - toggle 1
        // 5  - |_|x|_|x|_|x|_|x|_|x|  - toggle 2
        // 6  - |_|x|x|x|_|_|_|x|x|x|  - toggle 3
        // 4  - |_|x|x|_|_|_|_|_|x|x|  - toggle 4
        // 4  - |_|x|x|_|x|_|_|_|x|_|  - toggle 5
        // 5  - |_|x|x|_|x|x|_|_|x|_|  - toggle 6
        // 6  - |_|x|x|_|x|x|x|_|x|_|  - toggle 7
        // 7  - |_|x|x|_|x|x|x|x|x|_|  - toggle 8
        // 6  - |_|x|x|_|x|x|x|x|_|_|  - toggle 9
        // 7  - |_|x|x|_|x|x|x|x|_|x|  - toggle 10

        // "After his one hundredth pass in the hallway", he repeated 100 times?

        int numLockers = 100;
        boolean[] lockers = new boolean[numLockers];
        int toggleCount = 1; // you can't divide 0 /0 - (0 % 0), must be greater than 1
        int openLockers = 0;

        // Toggle lockers
        while (toggleCount < numLockers) {
            for (int i = 0; i < numLockers; i++) {
                if (i % toggleCount == 0) {
                    lockers[i] = !lockers[i];
                }
            }

            toggleCount++;
        }

        // Count open lockers
        for (boolean bool : lockers) {
            if (bool) {
                openLockers++;
            }
        }

        return openLockers;
    }
}


text:
local PANEL = {};

function PANEL:Init ( )
	self.InventoryBlocks = {};

	local fakeX, fakeY = 1, 0;
	for y = 1, INVENTORY_HEIGHT do
		for x = 1, INVENTORY_WIDTH do
			fakeY = fakeY + 1;
			if (fakeY > 5) then
				fakeY = 1;
				fakeX = fakeX + 1;
			end

			local newBlock = vgui.Create("perp2_trade_inv_block", self);
			newBlock:SetCoordinates(x, y);
			newBlock.fXPos, newBlock.fYPos = fakeX, fakeY;
			self.InventoryBlocks[newBlock.itemID] = newBlock;
		end
	end

	self.Description = true;
	//self:SetSkin("ugperp")
end

function PANEL:PerformLayout ( )
	local bufferSize = 5;

	local curY = bufferSize;

	local blocksPerRow = (INVENTORY_HEIGHT * INVENTORY_WIDTH) / 5;

	for i, v in pairs(self.InventoryBlocks) do
		local x = v.fXPos;
		local y = v.fYPos;

		v:SetSize(self.SizeOfBlock, self.SizeOfBlock);
		v:SetPos((bufferSize * x) + ((x - 1) * self.SizeOfBlock), (bufferSize * y) + ((y - 1) * self.SizeOfBlock));
		v:GrabItem(true);
	end
end

function PANEL:Paint ( )
	SKIN:PaintFrame(self, true);
end

function PANEL:SetDescription ( ) end

vgui.Register("perp2_trade_inv", PANEL);