text:
/*-------------------------------------------------------------------------*
 * File:  AtCmdLib.h
 *-------------------------------------------------------------------------*
 * Description:
 *      The GainSpan AT Command Library (AtCmdLib) provides the functions
 *      that send AT commands to a GainSpan node and looks for a response.
 *      Parse commands are provided to interpret the response data.
 *-------------------------------------------------------------------------*/
#ifndef _GS_ATCMDLIB_H_
#define _GS_ATCMDLIB_H_

#include <stdint.h>
#include <stdbool.h>

/* Parsing related defines */
#define  ATLIBGS_UDP_CLIENT_CID_OFFSET_BYTE        (8)  /* CID parameter offset in UDP connection response */
#define  ATLIBGS_RAW_DATA_STRING_SIZE_MAX          (4)  /* Number of octets representing the data length field in raw data transfer message*/
#define  ATLIBGS_HTTP_RESP_DATA_LEN_STRING_SIZE    (4)  /* Number of octets representing the data length field in HTTP data transfer message*/
#define  ATLIBGS_GSLINK_DATA_LEN_STRING_SIZE       (4)  /* Number of octets representing the data lenght field in GSLink data transfer message */

#define  ATLIBGS_INVALID_CID                    (0xFF) /* invalid CID */

#define ATLIBGS_BSSID_MAX_LENGTH    20
#define ATLIBGS_SSID_MAX_LENGTH     32
#define ATLIBGS_MAC_MAX_LENGTH      18
#define ATLIBGS_PASSWORD_MAX_LENGTH     32      // TODO: Is this correct?
typedef enum {
    ATLIBGS_RET_STATUS_ERROR = 0,
    ATLIBGS_RET_STATUS_OK = 1,
    ATLIBGS_RET_STATUS_VALID_DATA = 2,
    ATLIBGS_RET_STATUS_CONTROL_CODE = 3,
    ATLIBGS_RET_STATUS_MAX
} ATLIBGS_RET_STATUS_E;

typedef enum {
    ATLIBGS_DISABLE = 0, ATLIBGS_ENABLE = 1
} ATLIBGS_STATUS_E;

typedef enum {
    ATLIBGS_CON_TCP_SERVER,
    ATLIBGS_CON_UDP_SERVER,
    ATLIBGS_CON_UDP_CLIENT,
    ATLIBGS_CON_TCP_CLIENT

} ATLIBGS_CON_TYPE;

typedef enum {
    ATLIBGS_RX_STATE_START = 0,
    ATLIBGS_RX_STATE_CMD_RESP,
    ATLIBGS_RX_STATE_ESCAPE_START,
    ATLIBGS_RX_STATE_DATA_HANDLE,
    ATLIBGS_RX_STATE_BULK_DATA_HANDLE,
    ATLIBGS_RX_STATE_HTTP_RESPONSE_DATA_HANDLE,
    ATLIBGS_RX_STATE_RAW_DATA_HANDLE,

    ATLIBGS_RX_STATE_DATA_CID,
    ATLIBGS_RX_STATE_GLINK_DATA_LEN,
    ATLIBGS_RX_STATE_GLINK_DATA_TYPE,
    ATLIBGS_RX_STATE_GSLINK_DATA_HANDLE,

    ATLIBGS_RX_STATE_MAX
} ATLIBGS_RX_STATE_E;

typedef enum {
    ATLIBGS_MSG_ID_NONE = 0,
    ATLIBGS_MSG_ID_OK = 1,
    ATLIBGS_MSG_ID_INVALID_INPUT,
    ATLIBGS_MSG_ID_ERROR,
    ATLIBGS_MSG_ID_ERROR_IP_CONFIG_FAIL,
    ATLIBGS_MSG_ID_ERROR_SOCKET_FAIL,
    ATLIBGS_MSG_ID_DISCONNECT,
    ATLIBGS_MSG_ID_DISASSOCIATION_EVENT,
    ATLIBGS_MSG_ID_APP_RESET,
    ATLIBGS_MSG_ID_OUT_OF_STBY_ALARM,
    ATLIBGS_MSG_ID_OUT_OF_STBY_TIMER,
    ATLIBGS_MSG_ID_UNEXPECTED_WARM_BOOT,
    ATLIBGS_MSG_ID_OUT_OF_DEEP_SLEEP,
    ATLIBGS_MSG_ID_WELCOME_MSG,
    ATLIBGS_MSG_ID_STBY_CMD_ECHO,
    ATLIBGS_MSG_ID_TCP_CON_DONE,
    ATLIBGS_MSG_ID_RESPONSE_TIMEOUT,
    ATLIBGS_MSG_ID_BULK_DATA_RX,
    ATLIBGS_MSG_ID_DATA_RX,
    ATLIBGS_MSG_ID_RAW_DATA_RX,
    ATLIBGS_MSG_ID_ESC_CMD_OK,
    ATLIBGS_MSG_ID_ESC_CMD_FAIL,
    ATLIBGS_MSG_ID_HTTP_RESPONSE_DATA_RX,
    ATLIBGS_MSG_ID_MAX,
    ATLIBGS_MSG_ID_TCP_SERVER_CONNECT,
    ATLIBGS_MSG_ID_GENERAL_MESSAGE
} ATLIBGS_MSG_ID_E;

typedef enum {
    ATLIBGS_ID_INFO_OEM = 0,
    ATLIBGS_ID_INFO_HARDWARE_VERSION = 1,
    ATLIBGS_ID_INFO_SOFTWARE_VERSION = 2
} ATLIBGS_ID_INFO_E;

typedef enum {
    ATLIBGS_PROFILE_ACTIVE = 0,
    ATLIBGS_PROFILE_STORED_0 = 1,
    ATLIBGS_PROFILE_STORED_1 = 2,
} ATLIBGS_PROFILE_E;

typedef enum {
    ATLIBGS_REGDOMAIN_FCC = 0,
    ATLIBGS_REGDOMAIN_ETSI = 1,
    ATLIBGS_REGDOMAIN_TELEC = 2,
    ATLIBGS_REGDOMAIN_UNKNOWN = -1
} ATLIBGS_REGDOMAIN_E;

typedef enum {
    ATLIBGS_AUTHMODE_NONE_WPA = 0,
    ATLIBGS_AUTHMODE_OPEN_WEP = 1,
    ATLIBGS_AUTHMODE_SHARED_WEP = 2,
    ATLIBGS_AUTHMODE_UNKNOWN = -1
} ATLIBGS_AUTHMODE_E;

typedef enum {
    ATLIBGS_WEPKEY1 = 1,
    ATLIBGS_WEPKEY2 = 2,
    ATLIBGS_WEPKEY3 = 3,
    ATLIBGS_WEPKEY4 = 4,
    ATLIBGS_WEPKEY_UNKNOWN = -1
} ATLIBGS_WEPKEY_E;

typedef enum {
    ATLIBGS_OAEAPFAST = 43,
    ATLIBGS_OAEAPTLS = 13,
    ATLIBGS_OAEAPTTLS = 21,
    ATLIBGS_OAEAPPEAP = 25,
    ATLIBGS_IAEAPMSCHAP = 26,
    ATLIBGS_IAEAPGTC = 6,
    ATLIBGS_AU_UNKNOWN = -1
} ATLIBGS_INOUAUTH_E;

typedef enum {
    ATLIBGS_SMAUTO = 0,
    ATLIBGS_SMOPEN = 1,
    ATLIBGS_SMWEP = 2,
    ATLIBGS_SMWPAPSK = 4,
    ATLIBGS_SMWPA2PSK = 8,
    ATLIBGS_SMWPAE = 16,
    ATLIBGS_SMWPA2E = 32,
    ATLIBGS_SM_UNKNOWN = -1
} ATLIBGS_SECURITYMODE_E;

typedef enum {
    ATLIBGS_PROVSECU_OPEN = 1,
    ATLIBGS_PROVSECU_WEP = 2,
    ATLIBGS_PROVSECU_WPA_PER = 3,
    ATLIBGS_PROVSECU_WPA_ENT = 4
} ATLIBGS_PROVSECURITY_E;

typedef enum {
    ATLIBGS_HTTP_HE_AUTH = 2,
    ATLIBGS_HTTP_HE_CONN = 3,
    ATLIBGS_HTTP_HE_CON_ENC = 4,
    ATLIBGS_HTTP_HE_CON_LENGTH = 5,
    ATLIBGS_HTTP_HE_CON_RANGE = 6,
    ATLIBGS_HTTP_HE_CON_TYPE = 7,
    ATLIBGS_HTTP_HE_DATE = 8,
    ATLIBGS_HTTP_HE_EXPIRES = 9,
    ATLIBGS_HTTP_HE_FROM = 10,
    ATLIBGS_HTTP_HE_HOST = 11,
    ATLIBGS_HTTP_HE_IF_MODIF_SIN = 12,
    ATLIBGS_HTTP_HE_LAST_MODIF = 13,
    ATLIBGS_HTTP_HE_LOCATION = 14,
    ATLIBGS_HTTP_HE_PRAGMA = 15,
    ATLIBGS_HTTP_HE_RANGE = 16,
    ATLIBGS_HTTP_HE_REF = 17,
    ATLIBGS_HTTP_HE_SERVER = 18,
    ATLIBGS_HTTP_HE_TRANS_ENC = 19,
    ATLIBGS_HTTP_HE_USER_A = 20,
    ATLIBGS_HTTP_HE_WWW_AUTH = 21,
    ATLIBGS_HTTP_REQ_URL = 23,
    ATLIBGS_HTTP_UNKNOWN = -1
} ATLIBGS_HTTPCLIENT_E;

typedef enum {
    ATLIBGS_RAW_ETH_DIS = 0,
    ATLIBGS_RAW_ETH_NONSNAP = 1,
    ATLIBGS_RAW_ETH_ENABLEALL = 2,
    ATLIBGS_RAW_ETH_UNKNOWN = -1
} ATLIBGS_RAW_ETH_E;

typedef enum {
    ATLIBGS_ASPWMD_ACTIVE_ON = 0,
    ATLIBGS_ASPWMD_MODE_1 = 1,
    ATLIBGS_ASPWMD_MODE_2 = 2,
    ATLIBGS_ASPWMD_MODE_3 = 3,
    ATLIBGS_ASPWMD_UNKNOWN = -1
} ATLIBGS_ASSOCPOWMODE_E;

typedef enum {
    ATLIBGS_SPI_PHASE = 0, ATLIBGS_SPI_PHASE_180 = 1,
} ATLIBGS_SPI_PHASE_E;

typedef enum {
    ATLIBGS_SPI_POLARITY_LOW = 0, ATLIBGS_SPI_POLARITY_HIGH = 1,
} ATLIBGS_SPI_POLARITY_E;

typedef enum {
    ATLIBGS_APP0_BIN = 1,
    ATLIBGS_APP1_BIN = 2,
    ATLIBGS_APP01_BINS = 3,
    ATLIBGS_WLAN_BIN = 4,
    ATLIBGS_ALL_BINS = 7,
    ATLIBGS_FWBIN_UNKNOWN = -1
} ATLIBGS_FIRMWARE_BINARIES_E;

typedef enum {
    ATLIBGS_GPIO10 = 10,
    ATLIBGS_GPIO11 = 11,
    ATLIBGS_GPIO30 = 30,
    ATLIBGS_GPIO31 = 31,
} ATLIBGS_GPIO_PIN_E;

typedef enum {
    ATLIBGS_LOW = 0, ATLIBGS_HIGH = 1,
} ATLIBGS_GPIO_STATE_E;

typedef enum {
    ATLIBGS_FWUPPARAM_SERVERIP = 0,
    ATLIBGS_FWUPPARAM_SERVERPORT = 1,
    ATLIBGS_FWUPPARAM_PROXYPRESENT = 2,
    ATLIBGS_FWUPPARAM_PROXYIP = 3,
    ATLIBGS_FWUPPARAM_PROXYPORT = 4,
    ATLIBGS_FWUPPARAM_SSLENABLE = 5,
    ATLIBGS_FWUPPARAM_CACERT = 6,
    ATLIBGS_FWUPPARAM_WLAN = 7,
    ATLIBGS_FWUPPARAM_APP0 = 8,
    ATLIBGS_FWUPPARAM_APP1 = 9,
    ATLIBGS_FWUPPARAM_UNKNOWN = -1
} ATLIBGS_FWUPGRADEPARAM_E;

typedef enum {
    ATLIBGS_EAPTLS_CAC = 0,
    ATLIBGS_EAPTLS_CLIC = 1,
    ATLIBGS_EAPTLS_PRK = 2,
    ATLIBGS_EAPTLS_BIN = 0,
    ATLIBGS_EAPTLS_HEX = 1,
    ATLIBGS_EAPTLS_FLASH = 0,
    ATLIBGS_EAPTLS_RAM = 1,
    ATLIBGS_EAPTLS_UNKNOWN = -1
} ATLIBGS_EAPTLS_E;

typedef enum {
    ATLIBGS_SOCKET_OPTION_TYPE_SOCK = 65535,
    ATLIBGS_SOCKET_OPTION_TYPE_IP = 0,
    ATLIBGS_SOCKET_OPTION_TYPE_TCP = 6,
    ATLIBGS_SOCKET_OPTION_TYPE_UNKNOWN = -1
} ATLIBGS_SOCKET_OPTION_TYPE_E;

typedef enum {
    ATLIBGS_SOCKET_OPTION_PARAM_TCP_MAXRT = 0x10,
    ATLIBGS_SOCKET_OPTION_PARAM_TCP_KEEPALIVE = 0x4001,
    ATLIBGS_SOCKET_OPTION_PARAM_SO_KEEPALIVE = 0x8,
    ATLIBGS_SOCKET_OPTION_PARAM_TCP_KEEPALIVE_COUNT = 0x4005,
    ATLIBGS_SOCKET_OPTION_PARAM_UNKNOWN = -1
} ATLIBGS_SOCKET_OPTION_PARAM_E;

typedef enum {
    ATLIBGS_HTTPSEND_GET = 1,
    ATLIBGS_HTTPSEND_POST = 3,
    ATLIBGS_HTTPSEND_UNKNOWN = -1
} ATLIBGS_HTTPSEND_E;

typedef enum {
    ATLIBGS_TRAUTO = 0,
    ATLIBGS_TR1MBPS = 2,
    ATLIBGS_TR2MBPS = 4,
    ATLIBGS_TR5p5MBPS = 11,
    ATLIBGS_TR11MBPS = 22,
    ATLIBGS_TR_UNKNOWN = -1
} ATLIBGS_TRANSRATE_E;

typedef enum {
    ATLIBGS_UNSOLICITEDTX_RT1 = 130,
    ATLIBGS_UNSOLICITEDTX_RT2 = 132,
    ATLIBGS_UNSOLICITEDTX_RT55 = 139,
    ATLIBGS_UNSOLICITEDTX_RT11 = 150,
    ATLIBGS_UNSOLICITEDTX_UNKNOWN = -1
} ATLIBGS_UNSOLICITEDTX_E;

typedef enum {
    ATLIBGS_RFWAVETXSTART_RATE1 = 0,
    ATLIBGS_RFWAVETXSTART_RATE2 = 1,
    ATLIBGS_RFWAVETXSTART_RATE55 = 2,
    ATLIBGS_RFWAVETXSTART_RATE11 = 3,
    ATLIBGS_RFWAVETXSTART_UNKNOWN = -1
} ATLIBGS_RFWAVETXSTART_E;

typedef enum {
    ATLIBGS_RFFRAMETXSTART_RATE1 = 2,
    ATLIBGS_RFFRAMETXSTART_RATE2 = 4,
    ATLIBGS_RFFRAMETXSTART_RATE55 = 11,
    ATLIBGS_RFFRAMETXSTART_RATE11 = 22,
    ATLIBGS_RFFRAMETXSTART_UNKNOWN = -1
} ATLIBGS_RFFRAMETXSTART_E;

typedef enum {
    ATLIBGS_STATIONMODE_INFRASTRUCTURE = 0,
    ATLIBGS_STATIONMODE_AD_HOC = 1,
    ATLIBGS_STATIONMODE_LIMITED_AP = 2,
    ATLIBGS_STATIONMODE_UNKNOWN = -1
} ATLIBGS_STATIONMODE_E;

typedef uint8_t ATLIBGS_IPv4[4];

typedef union {
    ATLIBGS_IPv4 ipv4;
//  ATLIBGS_IPv6 ipv6; // placeholder
} ATLIBGS_IP;

typedef struct {
    char bssid[ATLIBGS_BSSID_MAX_LENGTH + 1];
    char ssid[ATLIBGS_SSID_MAX_LENGTH + 1];
    uint8_t channel;
    ATLIBGS_STATIONMODE_E station;
    int8_t signal;
    ATLIBGS_SECURITYMODE_E security;
} ATLIBGS_NetworkScanEntry;

typedef struct {
    char mac[ATLIBGS_MAC_MAX_LENGTH + 1];
    uint8_t connected;
    ATLIBGS_STATIONMODE_E mode;
    char bssid[ATLIBGS_BSSID_MAX_LENGTH + 1];
    char ssid[ATLIBGS_SSID_MAX_LENGTH + 1];
    uint8_t channel;
    ATLIBGS_SECURITYMODE_E security;
    char signal;
    ATLIBGS_IP addr;
    ATLIBGS_IP subnet;
    ATLIBGS_IP gateway;
    ATLIBGS_IP dns1;
    ATLIBGS_IP dns2;
    uint32_t rxCount;
    uint32_t txCount;
} ATLIBGS_NetworkStatus;

typedef struct {
    char ssid[ATLIBGS_SSID_MAX_LENGTH + 1];
    uint8_t channel;
    uint8_t conn_type;
    char password[ATLIBGS_PASSWORD_MAX_LENGTH + 1];
    ATLIBGS_STATIONMODE_E station;
    ATLIBGS_PROVSECURITY_E security;
    uint8_t dhcp_enable;
    uint8_t auto_dns_enable;
    ATLIBGS_IPv4 ip;
    ATLIBGS_IPv4 subnet;
    ATLIBGS_IPv4 gateway;
    ATLIBGS_IPv4 dns1;
    ATLIBGS_IPv4 dns2;
    uint8_t tcpIPClientHostIP;
} ATLIBGS_WEB_PROV_SETTINGS;

#define  ATLIBGS_CR_CHAR          0x0D     /* octet value in hex representing Carriage return    */
#define  ATLIBGS_LF_CHAR          0x0A     /* octet value in hex representing Line feed             */
#define  ATLIBGS_ESC_CHAR         0x1B     /* octet value in hex representing application level ESCAPE sequence */

/* Special characters used for data mode handling */
#define  ATLIBGS_DATA_MODE_NORMAL_START_CHAR_S      'S'
#define  ATLIBGS_DATA_MODE_NORMAL_END_CHAR_E        'E'
#define  ATLIBGS_DATA_MODE_BULK_START_CHAR_Z        'Z'
#define  ATLIBGS_DATA_MODE_BULK_START_CHAR_H        'H'
#define  ATLIBGS_DATA_MODE_RAW_INDICATION_CHAR_COL  ':'
#define  ATLIBGS_DATA_MODE_RAW_INDICATION_CHAR_R    'R'
#define  ATLIBGS_DATA_MODE_ESC_OK_CHAR_O            'O'
#define  ATLIBGS_DATA_MODE_ESC_FAIL_CHAR_F          'F'
#define  ATLIBGS_DATA_MODE_UDP_START_CHAR_u         'u'

#define ATLIBGS_DATA_MODE_GSLINK_START_CHAR_K       'K'
#define ATLIBGS_DATA_MODE_GSLINK_START_CHAR_G       'G'

#define  GSLINK_GET_XML      1
#define  GSLINK_GET_RAW      2
#define  GSLINK_POST_XML     3
#define  GSLINK_SET_RAW      4
#define  GSLINK_GET_RESP     6
#define  GSLINK_POST_RESP    7

#define  ESC_G_VALUE_INIT    0
#define  ESC_G_VALUE_ENABLE  1
#define  ESC_G_VALUE_END     2

/************* Following control octets are  used by SPI driver layer *****************************/
#define  ATLIBGS_SPI_ESC_CHAR               (0xFB)    /* Start transmission indication */
#define  ATLIBGS_SPI_IDLE_CHAR              (0xF5)    /* synchronous IDLE */
#define  ATLIBGS_SPI_XOFF_CHAR              (0xFA)    /* Stop transmission indication */
#define  ATLIBGS_SPI_XON_CHAR               (0xFD)    /* Start transmission indication */
#define  ATLIBGS_SPI_INVALID_CHAR_ALL_ONE   (0xFF)    /* Invalid character possibly recieved during reboot */
#define  ATLIBGS_SPI_INVALID_CHAR_ALL_ZERO  (0x00)    /* Invalid character possibly recieved during reboot */
#define  ATLIBGS_SPI_READY_CHECK            (0xF3)    /* SPI link ready check */
#define  ATLIBGS_SPI_READY_ACK              (0xF3)    /* SPI link ready response */
#define  ATLIBGS_SPI_CTRL_BYTE_MASK         (0x80)    /* Control byte mask */

/************* End of  SPI driver layer  specific defines*****************************/
#define ATLIBGS_RX_MAX_LINES                20

/* this should be tied to a timer, faster processor larger the number */
//#define  ATLIBGS_RESPONSE_TIMEOUT_COUNT    (0xFFFFFFFF) /* Time out value for reponse message */
#define  ATLIBGS_RESPONSE_TIMEOUT_COUNT    (0x2FFFFFF) // OK for SPI
/*************<Function prototye forward delarations >***************/

ATLIBGS_MSG_ID_E AtLibGs_Check(void);
ATLIBGS_MSG_ID_E AtLibGs_SetEcho(uint8_t mode);
ATLIBGS_MSG_ID_E AtLibGs_SetMAC(char *pAddr);
ATLIBGS_MSG_ID_E AtLibGs_SetMAC2(char *pAddr);
ATLIBGS_MSG_ID_E AtLibGs_GetMAC(char *mac);
ATLIBGS_MSG_ID_E AtLibGs_GetMAC2(char *mac);
ATLIBGS_MSG_ID_E AtLibGs_CalcNStorePSK(char *pSsid, char *pPsk);
//ATLIBGS_MSG_ID_E AtLibGs_WlanConnStat( ATLIBGS_N);
ATLIBGS_MSG_ID_E AtLibGs_GetNetworkStatus(ATLIBGS_NetworkStatus *pStatus);
ATLIBGS_MSG_ID_E AtLibGs_DHCPSet(uint8_t mode);
ATLIBGS_MSG_ID_E AtLibGs_Assoc(char *pSsid, char *pBssid, uint8_t channel);
ATLIBGS_MSG_ID_E AtLibGs_TCPClientStart(
        char *pRemoteTcpSrvIp,
        int16_t pRemoteTcpSrvPort,
        uint8_t *cid);
ATLIBGS_MSG_ID_E AtLibGs_UDPClientStart(
        char *pRemoteUdpSrvIp,
        char *pRemoteUdpSrvPort,
        char *pUdpLocalPort);

ATLIBGS_MSG_ID_E AtLibGs_CloseAll(void);

ATLIBGS_MSG_ID_E AtLibGs_BatteryCheckStart(uint16_t interval);
ATLIBGS_MSG_ID_E AtLibGs_GotoSTNDBy(
        char *nsec,
        uint32_t dealy,
        uint8_t alarm1_Pol,
        uint8_t alarm2_Pol);
ATLIBGS_MSG_ID_E AtLibGs_PSK(char *pPsk);
ATLIBGS_MSG_ID_E AtLibGs_EnableDeepSleep(void);
ATLIBGS_MSG_ID_E AtLibGs_StoreNwConn(void);
ATLIBGS_MSG_ID_E AtLibGs_ReStoreNwConn(void);
ATLIBGS_MSG_ID_E AtLibGs_IPSet(char *pIpAddr, char *pSubnet, char *pGateway);

ATLIBGS_MSG_ID_E AtLibGs_SaveProfile(uint8_t profile);
ATLIBGS_MSG_ID_E AtLibGs_LoadProfile(uint8_t profile);
ATLIBGS_MSG_ID_E AtLibGs_ResetFactoryDefaults(void);
ATLIBGS_MSG_ID_E AtLibGs_GetRssi(void);
ATLIBGS_MSG_ID_E AtLibGs_DisAssoc(void);
ATLIBGS_MSG_ID_E AtLibGs_FWUpgrade(
        char *pSrvip,
        uint16_t srvport,
        uint16_t srcPort,
        char *pSrcIP);
ATLIBGS_MSG_ID_E AtLibGs_BatteryCheckStop(void);
ATLIBGS_MSG_ID_E AtLibGs_MultiCast(uint8_t mode);
ATLIBGS_MSG_ID_E AtLibGs_Version(void);
ATLIBGS_MSG_ID_E AtLibGs_Mode(ATLIBGS_STATIONMODE_E mode);
ATLIBGS_MSG_ID_E AtLibGs_UDPServer_Start(uint16_t pUdpSrvPort, uint8_t *cid);
ATLIBGS_MSG_ID_E AtLibGs_TCPServer_Start(uint16_t pTcpSrvPort, uint8_t *cid);
ATLIBGS_MSG_ID_E AtLibGs_DNSLookup(char* pUrl);
ATLIBGS_MSG_ID_E AtLibGs_Close(uint8_t cid);
ATLIBGS_MSG_ID_E AtLibGs_SetWRetryCount(uint16_t count);
ATLIBGS_MSG_ID_E AtLibGs_GetErrCount(uint32_t *errorCount);
ATLIBGS_MSG_ID_E AtLibGs_EnableRadio(uint8_t mode);
ATLIBGS_MSG_ID_E AtLibGs_EnablePwSave(uint8_t mode);
ATLIBGS_MSG_ID_E AtLibGs_SetTime(char* pDate, char *pTime);
ATLIBGS_MSG_ID_E AtLibGs_EnableExternalPA(uint8_t mode);
ATLIBGS_MSG_ID_E AtLibGs_SyncLossInterval(uint16_t interval);
ATLIBGS_MSG_ID_E AtLibGs_PSPollInterval(uint16_t interval);
ATLIBGS_MSG_ID_E AtLibGs_SetTxPower(uint8_t power);
ATLIBGS_MSG_ID_E AtLibGs_SetDNSServerIP(char *pDNS1, char *pDNS2);
ATLIBGS_MSG_ID_E AtLibGs_EnableAutoConnect(uint8_t mode);
void AtLibGs_SwitchFromAutoToCmd(void);
ATLIBGS_MSG_ID_E AtLibGs_StoreWAutoConn(char * pSsid, uint8_t channel);
ATLIBGS_MSG_ID_E AtLibGs_StoreNAutoConn(char* pIpAddr, int16_t pRmtPort);
ATLIBGS_MSG_ID_E AtLibGs_StoreATS(uint8_t param, uint8_t value);
ATLIBGS_MSG_ID_E AtLibGs_BData(uint8_t mode);
typedef struct {
    char ssid[ATLIBGS_SSID_MAX_LENGTH + 1];
    char password[ATLIBGS_PASSWORD_MAX_LENGTH + 1];
    uint16_t channel;
} AtLibGs_WPSResult;

ATLIBGS_MSG_ID_E AtLibGs_StartWPSPUSH(AtLibGs_WPSResult *result);
ATLIBGS_MSG_ID_E AtLibGs_StartWPSPIN(char* pin, AtLibGs_WPSResult *result);
ATLIBGS_MSG_ID_E AtLibGs_GetInfo(
        ATLIBGS_ID_INFO_E info,
        char* infotext,
        int16_t maxchars);
ATLIBGS_MSG_ID_E AtLibGs_GetScanTimes(uint16_t *min, uint16_t *max);
ATLIBGS_MSG_ID_E AtLibGs_SetScanTimes(uint16_t min, uint16_t max);
ATLIBGS_MSG_ID_E AtLibGs_SetDefaultProfile(uint8_t profile);
ATLIBGS_MSG_ID_E AtLibGs_GetProfile(
        ATLIBGS_PROFILE_E profile,
        char *text,
        uint16_t maxChars);
ATLIBGS_MSG_ID_E AtLibGs_GetRegulatoryDomain(ATLIBGS_REGDOMAIN_E *regDomain);
ATLIBGS_MSG_ID_E AtLibGs_SetRegulatoryDomain(ATLIBGS_REGDOMAIN_E regDomain);
ATLIBGS_MSG_ID_E AtLibGs_NetworkScan(
        const char *SSID,
        uint8_t channel,
        uint16_t scantime,
        ATLIBGS_NetworkScanEntry *entries,
        uint8_t maxEntries,
        uint8_t *numEntries);

typedef struct {
    // IP address string of unit on other side
    char ip[17];

    // Local port id
    uint16_t port;

    // Connection id of the current
    uint8_t cid;

    // Pointer to buffer to receive message
    uint8_t *message;

    // Returned length of current message
    uint16_t numBytes;
} ATLIBGS_UDPMessage;

typedef struct {
    // Connection id of the current
    uint8_t cid;

    // Pointer to buffer to receive message
    const uint8_t *message;

    // Returned length of current message
    uint16_t numBytes;
} ATLIBGS_TCPMessage;

typedef struct {
    // Which server created this connection?
    uint8_t server_cid;

    // Newly created cid for communication
    uint8_t cid;

    // IP number of incoming connection
    char ip[16];

    // Connection port (local allocated port number)
    uint16_t port;
} ATLIBGS_TCPConnection;

ATLIBGS_MSG_ID_E AtLibGs_WaitForTCPMessage(uint32_t timeout);
void AtLibGs_ParseTCPData(
        const uint8_t *received,
        uint16_t length,
        ATLIBGS_TCPMessage *rxm);
ATLIBGS_MSG_ID_E AtLibGs_WaitForTCPConnection(
        ATLIBGS_TCPConnection *connection,
        uint32_t timeout);

typedef struct {
    // Connection id of the current
    uint8_t cid;

    // Pointer to buffer to receive message
    const uint8_t *message;

    // Returned length of current message
    uint16_t numBytes;
} ATLIBGS_HTTPMessage;

ATLIBGS_MSG_ID_E AtLibGs_WaitForHTTPMessage(uint32_t timeout);
void AtLibGs_ParseHTTPData(
        const uint8_t *received,
        uint8_t length,
        ATLIBGS_HTTPMessage *rxm);

ATLIBGS_MSG_ID_E AtLibGs_WaitForUDPMessage(uint32_t timeout);
void AtLibGs_ParseUDPData(
        const uint8_t *received,
        uint8_t length,
        ATLIBGS_UDPMessage *msg);

// TODO: Put all functions in same order/grouping as in command reference list
ATLIBGS_MSG_ID_E AtLibGs_DisAssoc2(void);
ATLIBGS_MSG_ID_E AtLibGs_GetTransmitRate(void);
ATLIBGS_MSG_ID_E AtLibGs_GetClientInfo(void);
ATLIBGS_MSG_ID_E AtLibGs_SetAuthentictionMode(ATLIBGS_AUTHMODE_E authmode);
ATLIBGS_MSG_ID_E AtLibGs_SetWEPKey(ATLIBGS_WEPKEY_E keynum, char key[]);
ATLIBGS_MSG_ID_E AtLibGs_SetWPAKey(char key[]);
ATLIBGS_MSG_ID_E
AtLibGs_SetListenBeaconInterval(bool enable, uint16_t interval);
ATLIBGS_MSG_ID_E AtLibGs_SetTransmitRate(ATLIBGS_TRANSRATE_E transrate);
ATLIBGS_MSG_ID_E AtLibGs_EnableDHCPServer(void);
ATLIBGS_MSG_ID_E AtLibGs_DisableDHCPServer(void);
ATLIBGS_MSG_ID_E AtLibGs_EnableDNSServer(char server[]);
ATLIBGS_MSG_ID_E AtLibGs_DisableDNSServer(void);
ATLIBGS_MSG_ID_E AtLibGs_SetEAPConfiguration(
        ATLIBGS_INOUAUTH_E oa,
        ATLIBGS_INOUAUTH_E ia,
        char user[],
        char pass[]);
ATLIBGS_MSG_ID_E AtLibGs_AddSSLCertificate(
        char name[],
        bool hex,
        uint16_t size,
        bool ram);
ATLIBGS_MSG_ID_E AtLibGs_DeleteSSLCertificate(char name[]);
ATLIBGS_MSG_ID_E AtLibGs_SetSecurity(ATLIBGS_SECURITYMODE_E security);
ATLIBGS_MSG_ID_E AtLibGs_SSLOpen(uint8_t cid, char name[]);
ATLIBGS_MSG_ID_E AtLibGs_SSLClose(uint8_t cid);
ATLIBGS_MSG_ID_E AtLibGs_HTTPConf(ATLIBGS_HTTPCLIENT_E param, char value[]);
ATLIBGS_MSG_ID_E AtLibGs_HTTPConfDel(ATLIBGS_HTTPCLIENT_E param);
ATLIBGS_MSG_ID_E AtLibGs_HTTPClose(uint8_t cid);
ATLIBGS_MSG_ID_E AtLibGs_RawETHFrameConf(ATLIBGS_RAW_ETH_E enable);
ATLIBGS_MSG_ID_E AtLibGs_BulkDataTrans(bool enable);
ATLIBGS_MSG_ID_E AtLibGs_SetBatteryCheckFreq(uint16_t freq);
ATLIBGS_MSG_ID_E AtLibGs_GetBatteryCheckFreq(uint16_t *freq);
ATLIBGS_MSG_ID_E AtLibGs_GetBatteryValue(void);
ATLIBGS_MSG_ID_E AtLibGs_EnterDeepSleep(uint32_t milliseconds);
ATLIBGS_MSG_ID_E AtLibGs_AssocPowerSaveMode(ATLIBGS_ASSOCPOWMODE_E mode);
ATLIBGS_MSG_ID_E AtLibGs_SetTransmitPower(uint8_t power);
ATLIBGS_MSG_ID_E AtLibGs_StartAutoConnect(void);
ATLIBGS_MSG_ID_E AtLibGs_ConfigAPAutoConnect(void);
ATLIBGS_MSG_ID_E AtLibGs_ReturnAutoConnect(void);
ATLIBGS_MSG_ID_E AtLibGs_WebProv(char username[], char password[]);
ATLIBGS_MSG_ID_E AtLibGs_WebLogoAdd(uint16_t size);
ATLIBGS_MSG_ID_E AtLibGs_RFAsyncFrameRX(uint16_t channel);
ATLIBGS_MSG_ID_E AtLibGs_RFStop(void);
ATLIBGS_MSG_ID_E AtLibGs_SetPassPhrase(char *pPhrase);
ATLIBGS_MSG_ID_E AtLibGs_SPIConf(
        ATLIBGS_SPI_POLARITY_E polarity,
        ATLIBGS_SPI_PHASE_E phase);
ATLIBGS_MSG_ID_E AtLibGs_Reset(void);
ATLIBGS_MSG_ID_E AtLibGs_MemoryTrace(void);
ATLIBGS_MSG_ID_E AtLibGs_StartFirmwareUpdate(ATLIBGS_FIRMWARE_BINARIES_E bins);
ATLIBGS_MSG_ID_E AtLibGs_GetTime(void);
ATLIBGS_MSG_ID_E AtLibGs_SetGPIO(
        ATLIBGS_GPIO_PIN_E GPIO,
        ATLIBGS_GPIO_STATE_E state);
ATLIBGS_MSG_ID_E AtLibGs_EnableEnhancedAsync(bool on);
ATLIBGS_MSG_ID_E AtLibGs_EnableVerbose(bool on);
ATLIBGS_MSG_ID_E AtLibGs_GetNetworkConfiguration(void);
ATLIBGS_MSG_ID_E AtLibGs_FWUpgradeConfig(
        ATLIBGS_FWUPGRADEPARAM_E param,
        char value[]);
ATLIBGS_MSG_ID_E AtLibGs_GetCIDInfo(void);
ATLIBGS_MSG_ID_E AtLibGs_BatterySetWarnLevel(
        uint16_t level,
        uint16_t freq,
        uint16_t standby);
ATLIBGS_MSG_ID_E AtLibGs_SetEAPCertificate(
        ATLIBGS_EAPTLS_E cert,
        ATLIBGS_EAPTLS_E binhex,
        uint16_t size,
        ATLIBGS_EAPTLS_E flashram);
ATLIBGS_MSG_ID_E AtLibGs_Ping(
        char ip[],
        uint16_t trails,
        uint16_t timeout,
        uint16_t len,
        uint8_t tos,
        uint8_t ttl,
        char payload[]);
ATLIBGS_MSG_ID_E AtLibGs_TraceRoute(
        char ip[],
        uint16_t interval,
        uint8_t maxhops,
        uint8_t minhops,
        uint8_t tos);
ATLIBGS_MSG_ID_E AtLibGs_SNTPsync(
        bool enable,
        char ip[],
        uint8_t timeout,
        bool periodic,
        uint32_t frequency);
ATLIBGS_MSG_ID_E AtLibGs_SetSocketOptions(
        uint8_t cid,
        ATLIBGS_SOCKET_OPTION_TYPE_E type,
        ATLIBGS_SOCKET_OPTION_PARAM_E param,
        uint32_t value);
ATLIBGS_MSG_ID_E AtLibGs_HTTPOpen(
        char host[],
        uint16_t port,
        bool sslenabled,
        char certname[],
        char proxy[],
        uint16_t timeout,
        uint8_t *cid);
ATLIBGS_MSG_ID_E AtLibGs_HTTPSend(
        uint8_t cid,
        ATLIBGS_HTTPSEND_E type,
        uint16_t timeout,
        char page[],
        uint16_t size,
        const void *txBuf);
ATLIBGS_MSG_ID_E AtLibGs_UnsolicitedTXRate(
        uint16_t frame,
        uint16_t seq,
        uint8_t chan,
        ATLIBGS_UNSOLICITEDTX_E rate,
        uint32_t wmm,
        char mac[],
        char bssid[],
        uint16_t len);
ATLIBGS_MSG_ID_E AtLibGs_RFAsyncFrameTX(
        uint8_t channel,
        uint8_t power,
        ATLIBGS_RFFRAMETXSTART_E rate,
        uint16_t times,
        uint16_t interval,
        uint8_t frameControl,
        uint16_t durationId,
        uint16_t sequenceControl,
        uint16_t frameLen,
        bool shortPreamble,
        bool scramblerOff,
        char dstMac[],
        char srcMac[]);
ATLIBGS_MSG_ID_E AtLibGs_RFWaveTXStart(
        bool isModulated,
        uint16_t channel,
        ATLIBGS_RFWAVETXSTART_E rate,
        bool longPreamble,
        bool scramblerOn,
        bool continousWaveRX,
        uint8_t power,
        char ssid[]);

uint8_t AtLibGs_ParseUDPClientCid(void);
uint8_t AtLibGs_ParseWlanConnStat(void);
uint8_t AtLibGs_ParseNodeIPv4Address(ATLIBGS_IPv4 *ip);
void AtLibGs_ParseIPv4Address(const char *line, ATLIBGS_IPv4 *ip);
void AtLibGs_IPv4AddressToString(ATLIBGS_IPv4 *ip, char *string);
uint8_t AtLibGs_ParseRssiResponse(int16_t *pRssi);
uint8_t AtLibGs_ParseUDPServerStartResponse(uint8_t *pConnId);
uint8_t AtLibGs_ParseTCPServerStartResponse(uint8_t *pConnId);
uint8_t AtLibGs_ParseDNSLookupResponse(char *ipAddr);
uint16_t AtLibGs_ParseIntoLines(char *text, char *pLines[], uint16_t maxLines);
uint8_t AtLibGs_ParseIntoTokens(
        char *line,
        char deliminator,
        char *tokens[],
        uint8_t maxTokens);
ATLIBGS_SECURITYMODE_E AtLibGs_ParseSecurityMode(const char *string);
void AtLibGs_ParseIPAddress(const char *string, ATLIBGS_IP *ip);

ATLIBGS_MSG_ID_E AtLibGs_CommandSend(void);
ATLIBGS_MSG_ID_E AtLibGs_CommandSendString(char *aString);
void AtLibGs_DataSend(const void *pTxData, uint16_t dataLen);
ATLIBGS_MSG_ID_E AtLibGs_SendTCPData(
        uint8_t cid,
        const void *txBuf,
        uint16_t dataLen);
ATLIBGS_MSG_ID_E AtLibGs_SendUDPData(
        uint8_t cid,
        const void *txBuf,
        uint16_t dataLen,
        ATLIBGS_CON_TYPE conType,
        const char *pUdpClientIP,
        uint16_t udpClientPort);

void AtLibGs_BulkDataTransfer(uint8_t cid, const void *pData, uint16_t dataLen);
ATLIBGS_MSG_ID_E AtLibGs_checkEOFMessage(const char *pBuffer);
ATLIBGS_MSG_ID_E AtLibGs_ReceiveDataHandle(uint32_t timeout);
ATLIBGS_MSG_ID_E AtLibGs_ReceiveDataProcess(uint8_t rxData);
ATLIBGS_MSG_ID_E AtLibGs_ResponseHandle(void);
ATLIBGS_MSG_ID_E AtLibGs_ProcessRxChunk(const void *rxBuf, uint16_t bufLen);
void AtLibGs_LinkCheck(void);
void AtLibGs_FlushIncomingMessage(void);
uint8_t AtLibGs_IsNodeResetDetected(void);
void AtLibGs_SetNodeResetFlag(void);
void AtLibGs_ClearNodeResetFlag(void);
uint8_t AtLibGs_IsNodeAssociated(void);
void AtLibGs_SetNodeAssociationFlag(void);
void AtLibGs_ClearNodeAssociationFlag(void);

void AtLibGs_FlushRxBuffer(void);
void AtLibGs_ConvertNumberTo4DigitASCII(uint16_t myNum, char *pStr);
ATLIBGS_MSG_ID_E AtLibGs_GetWebProvSettings(
        ATLIBGS_WEB_PROV_SETTINGS *wp,
        uint32_t timeout);

ATLIBGS_MSG_ID_E AtLibGs_SetXMLParse(uint8_t mode);
ATLIBGS_MSG_ID_E AtLibGs_WebServer(uint8_t mode, char username[], char password[], char SSL[], char idleTimeOut[]);
ATLIBGS_MSG_ID_E AtLibGs_StartMDNS(void);
ATLIBGS_MSG_ID_E AtLibGs_AnnounceMDNS(void);
ATLIBGS_MSG_ID_E AtLibGs_RegisterMDNSHost(char hostname[], char domain[]);
ATLIBGS_MSG_ID_E  AtLibGs_RegisterMDNSService(char *pServerName, char *pServerSubType, char *pServiceType, \
                                             char *pProtocol,  char *pDomain, char *pPort,  char *pKey1 );
ATLIBGS_MSG_ID_E AtLibGs_SetWEP1( int8_t *pWEP);

ATLIBGS_MSG_ID_E
    AtLibGs_AddCert(const char *name,
                    bool isLocRam,
                    const uint8_t *cert,
                    uint16_t certSize);

extern void AtLibGs_Init(void);

// User supplied routines
extern void App_ProcessIncomingData(uint8_t rxData);
void App_DelayMS(uint32_t cnt);
void App_Write(const void *txData, uint16_t dataLength);
bool App_Read(uint8_t *rxData, uint16_t dataLength, uint8_t blockFlag);
ATLIBGS_MSG_ID_E AtLibGs_ConfigAntenna(uint8_t mode);
uint8_t AtLibGs_ParseGetMacResponse(char *pMAC);
#endif /* _GS_ATCMDLIB_H_ */

/*-------------------------------------------------------------------------*
 * End of File:  AtCmdLib.h
 *-------------------------------------------------------------------------*/


text:
rss
===

Keywords: Erlang, RSS, Delicious

A very simple Erlang based RSS feed fetcher. It parses the results into a list of item titles.

Uses httpc, xmerl without any external libraries.

Installation
------------

$ make

   or

$ make tests

Usage RSS
---------

1> rss:init().

2> rss:url("http://del.icio.us/rss/popular/cats").

{ok,[<<"Spectacular DIY Tree Branch Cat Tree "...>>,
     <<"Kittens and Mom Scenarios and How to Trap - Alley Cat Allies">>,
     <<"This Cat Is Better at Jenga Than Any of You">>,
     <<"Fred The Undercover Kitty">>,
     <<"Boots the cat with only two paws is the cutest ninja ever!">>,
     <<"I wish my kitty were big enough to hug - The Oatmeal">>,
     <<"Superhero Cats | InspireFirst">>,<<"We Love Cats!:">>,
     <<"Lioness Kills Baboon, It"...>>],
    []}

Usage Delicious
---------------

1> rss:init().

2> delicious:popular("pies").

[<<"Teeny Lamothe's Pear & Goat Cheese Tart | Serious Eats : Recipes">>,
 <<"www.howdini.com">>,
 <<"Diabetic Strawberry Rhubarb Pie | ThriftyFun">>,
 <<"Key Lime Pie Recipe | Key Lime Pie with Coconut Crust | Two Peas & Their Pod">>,
 <<"Cuidados para unos pies saludables">>,
 <<"www.ireallylovechocolate.com">>,
 <<"Blackberry Pot Pies Recipe : Ree Drummond : Food Network">>]

redpajama_set_name: RedPajamaGithub


text:
package com.fishercoder.hbasemr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

/**
 * Created by stevesun on 5/11/17.
 */
public class DataImporter {
    private static final Logger LOG = LoggerFactory.getLogger(DataImporter.class);

    public static void main(String[] args) throws Exception {
        System.out.println("In here.");
        String [] pages = {"/", "/a.html", "/b.html", "/c.html"};

        Configuration config = HBaseConfiguration.create();
        config.set("hbase.master", "localhost:60000");
        Connection conn = ConnectionFactory.createConnection(config);
        Table htable = conn.getTable(TableName.valueOf("access_logs1"));

        int totalRecords = 100;
        int maxID = totalRecords / 10;
        Random rand = new Random();
        System.out.println("Importing " + totalRecords + " records ....");
        for (int i=0; i < totalRecords; i++)
        {
            int userID = rand.nextInt(maxID) + 1;
            byte [] rowkey = Bytes.add(Bytes.toBytes(userID), Bytes.toBytes(i));
            String randomPage = pages[rand.nextInt(pages.length)];
            Put put = new Put(rowkey);
            put.addColumn(Bytes.toBytes("details"), Bytes.toBytes("page"), Bytes.toBytes(randomPage));
            System.out.println("created one put.");
            htable.put(put);
            System.out.println("put one record into htable.");
        }
        htable.close();
        System.out.println("Done");
    }

}


text:
define("rebound-htmlbars/hooks/subexpr", ["exports"], function (exports) {
  "use strict";

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

  function subexpr(env, scope, helperName, params, hash) {
    var helper = this.lookupHelper(helperName, env);

    if (helper) {
      return this.invokeHelper(null, env, scope, null, params, hash, helper, {}, undefined);
    }

    return this.get(env, scope, helperName);
  }
});


text:
package com.bumptech.glide.integration.volley;

import com.android.volley.Request;
import com.android.volley.Request.Priority;
import com.bumptech.glide.load.data.DataFetcher.DataCallback;
import java.io.InputStream;
import java.util.Map;

/**
 * Used to construct a custom Volley request, such as for authentication header decoration.
 */
public interface VolleyRequestFactory {

  /**
   * Returns a Volley request for the given image url. The given future should be put as a
   * listener or called when the request completes.
   */

  Request<byte[]> create(String url, DataCallback<? super InputStream> callback,
      Priority priority, Map<String, String> headers);

}


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

using GitConnector.Configuration;

using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.WsFederation;

using Owin;
using System.Net;
using System.Threading.Tasks;

namespace GitConnector.Security
{
    public class FederationAuthenticationProvider : AuthenticationProvider
    {
        public override void Configure(IAppBuilder app)
        {
            if (String.IsNullOrEmpty(FederationSettings.MetadataAddress))
            {
                throw new ArgumentException("Missing federation declaration in config", "FederationMetadataAddress");
            }

            if (String.IsNullOrEmpty(FederationSettings.Realm))
            {
                throw new ArgumentException("Missing federation declaration in config", "FederationRealm");

            }

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
            {
                MetadataAddress = FederationSettings.MetadataAddress,
                Wtrealm = FederationSettings.Realm,
                Notifications = new WsFederationAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (context) =>
                    {
                        if (context.OwinContext.Response.StatusCode == (int)HttpStatusCode.Unauthorized && context.Request.Headers.ContainsKey("AuthNoRedirect"))
                        {
                            context.HandleResponse();
                        }

                        return Task.FromResult(0);
                    }
                }
            });
        }

        public override void SignIn(string username, string returnUrl)
        {
            HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = returnUrl }, WsFederationAuthenticationDefaults.AuthenticationType);
        }

        public override void SignOut()
        {
            HttpContext.Current.GetOwinContext().Authentication.SignOut(WsFederationAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
        }
    }
}


text:
.class interface abstract Lcom/google/inject/internal/MoreTypes$CompositeType;
.super Ljava/lang/Object;
.source "MoreTypes.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/google/inject/internal/MoreTypes;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x60a
    name = "CompositeType"
.end annotation

# virtual methods
.method public abstract isFullySpecified()Z
.end method


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="user">
	<!-- 以下与实体类的中字段一致 -->
	<sql id="selectId">
		userId,
		userName,
		(select r.name from role r where id in (SELECT ur.role_id FROM user_role ur
		WHERE ur.user_id=userId)) roleName,
		userPassword,
		userNickname,
		userRealname,
		userAge,
		userSex,
		userAddress,
		userPhone,
		userMail,
		userQQ,
		regTime,
		(select ul.loginTime from userloginlist ul where ul.userId=userId order By ul.loginTime desc limit 1,1) lastLogintime,
		level,
		province,
		city,
		bankName,
		branchBank,
		subbranchBank,
		openBankName,
		bankAccountName,
		bankAccount,
		accountType,
		pay,
		mark,
		status,
		parentNumber
	</sql>
	<!--resultType="User" 每返回一条结果封装到User里 -->
	<select id="query" resultType="User" parameterType="java.util.HashMap">
		select
		<include refid="selectId" />
		from user
		<where>
			<if test="t.userName != null and t.userName != ''">
				userName like '%${t.userName}%'
				</if>
			<if test="t.userNickname != null and t.userNickname != ''">
				and userNickname like '%${t.userNickname}%'
				</if>
		</where>
	</select>
	<!-- 总记录数 -->
	<select id="count" parameterType="User" resultType="int">
		select count(0) from user
		<where>
			<if test="userName != null and userName != ''">
				userName like '%${userName}%'
				</if>
			<if test="userNickname != null and userNickname != ''">
				and userNickname like '%${userNickname}%'
				</if>
		</where>
	</select>
	<!-- 增加用户 -->
	<insert id="add" parameterType="User">
		insert into user( userName,
		userPassword,
		userNickname, userRealname,
		userAge, userSex, userAddress,
		userPhone,
		userMail, userQQ, level,
		province,
		city,
		bankName,
		branchBank,
		subbranchBank,
		openBankName,
		bankAccountName,
		bankAccount,
		accountType,
		pay,
		mark,
		status,
		parentNumber )
		values (#{userName},
		#{userPassword},
		#{userNickname}, #{userRealname},
		#{userAge},
		#{userSex},
		#{userAddress}, #{userPhone}, #{userMail},
		#{userQQ},
		#{level},
		#{province},
		#{city},
		#{bankName}, #{branchBank},
		#{subbranchBank},
		#{openBankName},
		#{bankAccountName}, #{bankAccount}, #{accountType},
		#{pay},
		#{mark},#{status},
		#{parentNumber})
	</insert>

	<delete id="deleteById" parameterType="String">
		delete from user where
		userId=#{userId}
	</delete>
	<select id="getById" parameterType="String" resultType="User">
		select
		<include refid="selectId" />
		from user where userId=#{userId}
	</select>
	<update id="update" parameterType="User">
		update user
		<set>
			<if test="userName != null and userName != ''">
				userName=#{userName},
			</if>
			<if test="userPassword != null and userPassword != ''">
				userPassword=#{userPassword},
			</if>
			<if test="userNickname != null and userNickname != ''">
				userNickname=#{userNickname},
			</if>
			<if test="userRealname != null and userRealname != ''">
				userRealname=#{userRealname},
			</if>
			<if test="userAge != null and userAge != ''">
				userAge=#{userAge},
			</if>
			<if test="userSex != null and userSex != ''">
				userSex=#{userSex},
			</if>
			<if test="userAddress != null and userAddress != ''">
				userAddress=#{userAddress},
			</if>
			<if test="userPhone != null and userPhone != ''">
				userPhone=#{userPhone},
			</if>
			<if test="userMail != null and userMail != ''">
				userMail=#{userMail},
			</if>
			<if test="userQQ != null and userQQ != ''">
				userQQ=#{userQQ},
			</if>
			<if test="level != null and level != ''">
				level=#{level},
			</if>
			province=#{province},
		city=#{city},
		bankName=#{bankName},
		branchBank=#{branchBank},
		subbranchBank=#{subbranchBank},
		openBankName=#{openBankName},
		bankAccountName=#{bankAccountName},
		bankAccount=#{bankAccount},
		accountType=#{accountType},
		pay=#{pay},
		mark=#{mark},
		status=#{status},
		parentNumber =#{parentNumber}
		</set>
		where userId=#{userId}
	</update>

	<!-- 验证用户登陆 -->
	<select id="countUser" parameterType="User" resultType="int">
	    select count(*) from user where
	    userName=#{userName} and userPassword=#{userPassword}
	</select>

	<!-- 根据用户名查出userId -->
	<select id="queryUserName" parameterType="String" resultType="User">
	  select
	  <include refid="selectId"/>
	  from user where userName=#{userName}
	</select>
</mapper>


text:
layout: documentation
title: How to Use PHP 5.3 Namespaces
---

# How to Use PHP 5.3 Namespaces #

The generated model classes can use a namespace. It eases the management of large database models, and makes the Propel model classes integrate with PHP 5.3 applications in a clean way.

## Namespace Declaration And Inheritance ##

To define a namespace for a model class, you just need to specify it in a `namespace` attribute of the `<table>` element for a single table, or in the `<database>` element to set the same namespace to all the tables.

Here is an example schema using namespaces:

{% highlight xml %}
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<database name="bookstore" defaultIdMethod="native" namespace="Bookstore">

    <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
    <column name="title" type="VARCHAR" required="true" primaryString="true" />
    <column name="isbn" required="true" type="VARCHAR" size="24" phpName="ISBN" />
    <column name="price" required="false" type="FLOAT" />
    <column name="publisher_id" required="false" type="INTEGER" description="Foreign Key Publisher" />
    <column name="author_id" required="false" type="INTEGER" description="Foreign Key Author" />
    <foreign-key foreignTable="publisher" onDelete="setnull">
      <reference local="publisher_id" foreign="id" />
    </foreign-key>
    <foreign-key foreignTable="author" onDelete="setnull" onUpdate="cascade">
      <reference local="author_id" foreign="id" />
    </foreign-key>

    <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER"/>
    <column name="first_name" required="true" type="VARCHAR" size="128" />
    <column name="last_name" required="true" type="VARCHAR" size="128" />
    <column name="email" type="VARCHAR" size="128" />

    <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
    <column name="name" required="true" type="VARCHAR" size="128" default="Penguin" />

    <column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER"/>
    <column name="login" required="true" type="VARCHAR" size="128" />
    <column name="email" type="VARCHAR" size="128" />

</database>
{% endhighlight %}

The `<database>` element defines a `namespace` attribute. The `book` and `author` tables inherit their namespace from the database, therefore the generated classes for these tables will be `\Bookstore\Book` and `\Bookstore\Author`.

The `publisher` table defines a `namespace` attribute on its own, which _extends_ the database namespace. That means that the generated class will be `\Bookstore\Book\Publisher`.

As for the `user` table, it defines an absolute namespace (starting with a backslash), which _overrides_ the database namespace. The generated class for the `user` table will be `Admin\User`.

>**Tip**
You can use subnamespaces (i.e. namespaces containing backslashes) in the `namespace` attribute.

## Using Namespaced Models ##

Namespaced models benefit from the Propel runtime autoloading just like the other model classes. You just need to alias them, or to use their fully qualified name.

{% highlight php %}
<?php
// use an alias
use Bookstore\Book;
$book = new Book();

// or use fully qualified name
$book = new \Bookstore\Book();
{% endhighlight %}

Relation names forged by Propel don't take the namespace into account. That means that related getter and setters make no mention of it:

{% highlight php %}
<?php
$author = new \Bookstore\Author();
$book = new \Bookstore\Book();
$book->setAuthor($author);
$book->save();
{% endhighlight %}

The namespace is used for the ActiveRecord class, but also for the Query and Peer classes. Just remember that when you use relation names ina query, the namespace should not appear:

{% highlight php %}
<?php
$author = \Bookstore\AuthorQuery::create()
  ->useBookQuery()
    ->filterByPrice(array('max' => 10))
  ->endUse()
  ->findOne();
{% endhighlight %}

Related tables can have different namespaces, it doesn't interfere with the functionality provided by the object model:

{% highlight php %}
<?php
$book = \Bookstore\BookQuery::create()
  ->findOne();
echo get_class($book->getPublisher());
// \Bookstore\Book\Publisher
{% endhighlight %}

>**Tip**
Using namespaces make generated model code incompatible with versions of PHP less than 5.3. Beware that you will not be able to use your model classes in an older PHP application.

## Using Namespaces As A Directory Structure ##

In a schema, you can define a `package` attribute on a `<database>` or a `<table>` tag to generate model classes in a subdirectory (see [Multi-Component](multi-component-data-model.html)). If you use namespaces to autoload your classes based on a SplClassAutoloader (see [http://groups.google.com/group/php-standards](http://groups.google.com/group/php-standards)), then you may find yourself repeating the `namespace` data in the `package` attribute:

{% highlight xml %}
<database name="bookstore" defaultIdMethod="native"
  namespace="Foo\Bar" package="Foo.Bar">
{% endhighlight %}

To avoid such repetitions, just set the `propel.namespace.autoPackage` setting to `true` in your `build.properties`:

{% highlight ini %}
propel.namespace.autoPackage = true
{% endhighlight %}

Now Propel will automatically create a `package` attribute, and therefore distribute model classes in subdirectories, based on the `namespace` attribute, and you can  omit the manual `package` attribute in the schema:

{% highlight xml %}
<database name="bookstore" defaultIdMethod="native" namespace="Foo\Bar">
{% endhighlight %}


text:
<bill session="110" type="h" number="7030" updated="2009-01-09T07:17:51-05:00">
	<status><introduced date="1222142400" datetime="2008-09-23"/></status>

	<introduced date="1222142400" datetime="2008-09-23"/>
	<titles>
		<title type="official" as="introduced">To make available for oil and gas leasing, under the 2007-2012 oil and gas leasing program, areas of the Outer Continental Shelf for which expenditures for such leasing are prohibited on September 19, 2008.</title>
	</titles>
	<sponsor id="400400"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1222142400" datetime="2008-09-23"><text>Referred to the House Committee on Natural Resources.</text></action>
		<action date="1222660800" datetime="2008-09-29"><text>Referred to the Subcommittee on Energy and Mineral Resources.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	9/23/2008--Introduced.<br/>Allows any area of the Outer Continental Shelf (OCS) for which expenditure of federal funds for oil and gas leasing is prohibited on September 19, 2008, to be leased under the 2007-2012 oil and gas leasing program under the Outer Continental Shelf Lands Act, effective upon the termination of such prohibition.
	</summary>
</bill>


text:
// I2Cdev library collection - Main I2C device class
// Abstracts bit and byte I2C R/W functions into a convenient class
// 11/1/2011 by Jeff Rowberg <jeff@rowberg.net>
//
// Changelog:
//     2012-10-11 - add SPI bit and byte R/W functions
//     2011-11-01 - fix write*Bits mask calculation (thanks sasquatch @ Arduino forums)
//     2011-10-03 - added automatic Arduino version detection for ease of use
//     2011-10-02 - added Gene Knight's NBWire TwoWire class implementation with small modifications
//     2011-08-31 - added support for Arduino 1.0 Wire library (methods are different from 0.x)
//     2011-08-03 - added optional timeout parameter to read* methods to easily change from default
//     2011-08-02 - added support for 16-bit registers
//                - fixed incorrect Doxygen comments on some methods
//                - added timeout value for read operations (thanks mem @ Arduino forums)
//     2011-07-30 - changed read/write function structures to return success or byte counts
//                - made all methods static for multi-device memory savings
//     2011-07-28 - initial release

#include "I2Cdev.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
    // NBWire implementation based heavily on code by Gene Knight <Gene@Telobot.com>
    // Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
    // Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html
    TwoWire Wire;
#endif

/** Default constructor.
 */
I2Cdev::I2Cdev() {
}

/** Read a single bit from an 8-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param bitNum Bit position to read (0-7)
 * @param data Container for single bit value
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readBit(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t *data, uint16_t timeout) {
    uint8_t b;
    uint8_t count = readByte(useSPI, devAddr, regAddr, &b, timeout);
    *data = b & (1 << bitNum);
    return count;
}

/** Read a single bit from a 16-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param bitNum Bit position to read (0-15)
 * @param data Container for single bit value
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readBitW(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t *data, uint16_t timeout) {
    uint16_t b;
    uint8_t count = readWord(useSPI, devAddr, regAddr, &b, timeout);
    *data = b & (1 << bitNum);
    return count;
}

/** Read multiple bits from an 8-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param bitStart First bit position to read (0-7)
 * @param length Number of bits to read (not more than 8)
 * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readBits(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data, uint16_t timeout) {
    // 01101001 read byte
    // 76543210 bit numbers
    //    xxx   args: bitStart=4, length=3
    //    010   masked
    //   -> 010 shifted
    uint8_t count, b, r = 0;
    if ((count = readByte(useSPI, devAddr, regAddr, &b, timeout)) != 0) {
        for (uint8_t i = bitStart; i > bitStart - length; i--) {
            r |= (b & (1 << i));
        }
        r >>= (bitStart - length + 1);
        *data = r;
    }
    return count;
}

/** Read multiple bits from a 16-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param bitStart First bit position to read (0-15)
 * @param length Number of bits to read (not more than 16)
 * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05)
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (1 = success, 0 = failure, -1 = timeout)
 */
int8_t I2Cdev::readBitsW(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t *data, uint16_t timeout) {
    // 1101011001101001 read byte
    // fedcba9876543210 bit numbers
    //    xxx           args: bitStart=12, length=3
    //    010           masked
    //           -> 010 shifted
    uint8_t count;
    uint16_t w, r = 0;
    if ((count = readWord(useSPI, devAddr, regAddr, &w, timeout)) != 0) {
        for (uint8_t i = bitStart; i > bitStart - length; i--) {
            r |= (w & (1 << i));
        }
        r >>= (bitStart - length + 1);
        *data = r;
    }
    return count;
}

/** Read single byte from an 8-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param data Container for byte value read from device
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readByte(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t *data, uint16_t timeout) {
    return readBytes(useSPI, devAddr, regAddr, 1, data, timeout);
}

/** Read single word from a 16-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address
 * @param regAddr Register regAddr to read from
 * @param data Container for word value read from device
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Status of read operation (true = success)
 */
int8_t I2Cdev::readWord(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint16_t *data, uint16_t timeout) {
    return readWords(useSPI, devAddr, regAddr, 1, data, timeout);
}

/** Read multiple bytes from an 8-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address
 * @param regAddr First register regAddr to read from
 * @param length Number of bytes to read
 * @param data Buffer to store read data in
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Number of bytes read (0 indicates failure)
 */
int8_t I2Cdev::readBytes(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t *data, uint16_t timeout) {
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print(useSPI ? "SPI (0x" : "I2C 0x");
        Serial.print(devAddr, HEX);
        Serial.print(") reading ");
        Serial.print(length, DEC);
        Serial.print(" bytes from 0x");
        Serial.print(regAddr, HEX);
        Serial.print("...");
    #endif
    int8_t count = 0;
	// I2C
	if (!useSPI) {
		Wire.beginTransmission(devAddr);
		#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
			Wire.send(regAddr);
		#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
			Wire.write(regAddr);
		#endif
		Wire.endTransmission();
		Wire.beginTransmission(devAddr);
		Wire.requestFrom(devAddr, length);

		uint32_t t1 = millis();
		for (; Wire.available() && (timeout == 0 || millis() - t1 < timeout); count++) {
			#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
				data[count] = Wire.receive();
			#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
				data[count] = Wire.read();
			#endif
			#ifdef I2CDEV_SERIAL_DEBUG
				Serial.print(data[count], HEX);
				if (count + 1 < length) Serial.print(" ");
			#endif
		}
		if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout
		//Wire.endTransmission();

	} else {
	    digitalWrite(devAddr, LOW);
		byte Addr = regAddr | 0x80;
		SPI.transfer(Addr);
		for (uint8_t cnt=0; cnt < length; cnt++) {
			data[cnt] = SPI.transfer(0);
			count++;
		}
		digitalWrite(devAddr, HIGH);
	}
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print(". Done (");
        Serial.print(count, DEC);
        Serial.println(" read).");
    #endif
    return count;
}

/** Read multiple words from a 16-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address or Slave Select pin if SPI
 * @param regAddr First register regAddr to read from
 * @param length Number of words to read
 * @param data Buffer to store read data in
 * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout)
 * @return Number of words read (0 indicates failure)
 */
int8_t I2Cdev::readWords(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t *data, uint16_t timeout) {
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print(useSPI ? "SPI (0x" : "I2C (0x");
        Serial.print(devAddr, HEX);
        Serial.print(") reading ");
        Serial.print(length, DEC);
        Serial.print(" words from 0x");
        Serial.print(regAddr, HEX);
        Serial.print("...");
    #endif

    int8_t count = 0;

    Wire.beginTransmission(devAddr);
    #if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
        Wire.send(regAddr);
    #elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
        Wire.write(regAddr);
    #endif

	if (!useSPI) {
		Wire.endTransmission();

		Wire.beginTransmission(devAddr);
		Wire.requestFrom(devAddr, (uint8_t)(length * 2)); // length=words, this wants bytes

		uint32_t t1 = millis();
		bool msb = true; // starts with MSB, then LSB
		for (; Wire.available() && count < length && (timeout == 0 || millis() - t1 < timeout);) {
			if (msb) {
				// first byte is bits 15-8 (MSb=15)
				#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
					data[count] = Wire.receive() << 8;
				#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
					data[count] = Wire.read() << 8;
				#endif
			} else {
				// second byte is bits 7-0 (LSb=0)
				#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
					data[count] |= Wire.receive();
				#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
					data[count] |= Wire.read();
				#endif
				#ifdef I2CDEV_SERIAL_DEBUG
					Serial.print(data[count], HEX);
					if (count + 1 < length) Serial.print(" ");
				#endif
				count++;
			}
			msb = !msb;
		}
		if (timeout > 0 && millis() - t1 >= timeout && count < length) count = -1; // timeout

		//Wire.endTransmission();
	} else {
		uint8_t _byteCnt = (uint8_t)(length * 2);
		byte Addr = regAddr | 0x80;
		digitalWrite(devAddr, LOW);
		SPI.transfer(Addr);
		bool msb = true;
		for (uint8_t cnt=0; cnt < _byteCnt; cnt++) {
			if (msb) {
				data[cnt] = SPI.transfer(0) << 8;
			}
			else
			{
				data[cnt] |= SPI.transfer(0);
				#ifdef I2CDEV_SERIAL_DEBUG
					Serial.print(data[count], HEX);
					if (count + 1 < length) Serial.print(" ");
				#endif
				count++;
			}
			msb = !msb;
		}
		digitalWrite(devAddr, HIGH);
	}

    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print(". Done (");
        Serial.print(count, DEC);
        Serial.println(" read).");
    #endif

    return count;
}

/** write a single bit in an 8-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address or Slave Select pin if SPI
 * @param regAddr Register regAddr to write to
 * @param bitNum Bit position to write (0-7)
 * @param value New bit value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBit(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data) {
    uint8_t b;
    readByte(useSPI, devAddr, regAddr, &b);
    b = (data != 0) ? (b | (1 << bitNum)) : (b & ~(1 << bitNum));
    return writeByte(useSPI, devAddr, regAddr, b);
}

/** write a single bit in a 16-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address or Slave Select pin if SPI
 * @param regAddr Register regAddr to write to
 * @param bitNum Bit position to write (0-15)
 * @param value New bit value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBitW(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t bitNum, uint16_t data) {
    uint16_t w;
    readWord(useSPI, devAddr, regAddr, &w);
    w = (data != 0) ? (w | (1 << bitNum)) : (w & ~(1 << bitNum));
    return writeWord(useSPI,devAddr, regAddr, w);
}

/** Write multiple bits in an 8-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address or Slave Select pin if SPI
 * @param regAddr Register regAddr to write to
 * @param bitStart First bit position to write (0-7)
 * @param length Number of bits to write (not more than 8)
 * @param data Right-aligned value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBits(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) {
    //      010 value to write
    // 76543210 bit numbers
    //    xxx   args: bitStart=4, length=3
    // 01000000 shift left (8 - length)    ]
    // 00001000 shift right (7 - bitStart) ] --- two shifts ensure all non-important bits are 0
    // 11100011 mask byte
    // 10101111 original value (sample)
    // 10100011 original & mask
    // 10101011 masked | value
    uint8_t b;
    if (readByte(useSPI, devAddr, regAddr, &b) != 0) {
        //uint8_t mask = (0xFF << (8 - length)) | (0xFF >> (bitStart + length - 1));
        uint8_t mask = (0xFF << (bitStart + 1)) | 0xFF >> ((8 - bitStart) + length - 1);
        data <<= (8 - length);
        data >>= (7 - bitStart);
        b &= mask;
        b |= data;
        return writeByte(useSPI, devAddr, regAddr, b);
    } else {
        return false;
    }
}

/** Write multiple bits in a 16-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address or Slave Select pin if SPI
 * @param regAddr Register regAddr to write to
 * @param bitStart First bit position to write (0-15)
 * @param length Number of bits to write (not more than 16)
 * @param data Right-aligned value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBitsW(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint16_t data) {
    //              010 value to write
    // fedcba9876543210 bit numbers
    //    xxx           args: bitStart=12, length=3
    // 01000000         shift left (16 - length)    ]
    // 00001000         shift right (15 - bitStart) ] --- two shifts ensure all non-important bits are 0
    // 11100011         mask byte
    // 10101111         original value (sample)
    // 10100011         original & mask
    // 10101011         masked | value
    uint16_t w;
    if (readWord(useSPI, devAddr, regAddr, &w) != 0) {
        //uint16_t mask = (0xFFFF << (16 - length)) | (0xFFFF >> (bitStart + length - 1));
        uint16_t mask = (0xFFFF << (bitStart + 1)) | 0xFFFF >> ((16 - bitStart) + length - 1);
        data <<= (16 - length);
        data >>= (15 - bitStart);
        w &= mask;
        w |= data;
        return writeWord(useSPI, devAddr, regAddr, w);
    } else {
        return false;
    }
}

/** Write single byte to an 8-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address or Slave Select pin if SPI
 * @param regAddr Register address to write to
 * @param data New byte value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeByte(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t data) {
    return writeBytes(useSPI, devAddr, regAddr, 1, &data);
}

/** Write single word to a 16-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address or Slave Select pin if SPI
 * @param regAddr Register address to write to
 * @param data New word value to write
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeWord(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint16_t data) {
    return writeWords(useSPI, devAddr, regAddr, 1, &data);
}

/** Write multiple bytes to an 8-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address or Slave Select pin if SPI
 * @param regAddr First register address to write to
 * @param length Number of bytes to write
 * @param data Buffer to copy new data from
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeBytes(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint8_t* data) {
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print(useSPI ? "SPI Slave (0x" : "I2C (0x" );
        Serial.print(devAddr, HEX);
        Serial.print(") writing ");
        Serial.print(length, DEC);
        Serial.print(" bytes to 0x");
        Serial.print(regAddr, HEX);
        Serial.print("...");
    #endif

	if (!useSPI) {
    Wire.beginTransmission(devAddr);
		#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
			Wire.send((uint8_t) regAddr); // send address
		#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
			Wire.write((uint8_t) regAddr); // send address
		#endif
		for (uint8_t i = 0; i < length; i++) {
			#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
				Wire.send((uint8_t) data[i]);
			#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
				Wire.write((uint8_t) data[i]);
			#endif
			#ifdef I2CDEV_SERIAL_DEBUG
				Serial.print(data[i], HEX);
				if (i + 1 < length) Serial.print(" ");
			#endif
		}
		// docs say this returns a byte, but it causes a compiler error
		//uint8_t status = Wire.endTransmission();
		Wire.endTransmission();
	} else {
		digitalWrite(devAddr, LOW);
		SPI.transfer(regAddr);
		for (uint8_t cnt=0; cnt < length; cnt++) {
			SPI.transfer(data[cnt]);
			#ifdef I2CDEV_SERIAL_DEBUG
				Serial.print(data[cnt], HEX);
				if (cnt + 1 < length) Serial.print(" ");
			#endif
		}
		digitalWrite(devAddr, HIGH);
	}

    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.println(". Done.");
    #endif
    return true; //status == 0;
}

/** Write multiple words to a 16-bit device register.
 * @param useSPI  true : use SPI
 * @param devAddr I2C slave device address or Slave Select pin if SPI
 * @param regAddr First register address to write to
 * @param length Number of words to write
 * @param data Buffer to copy new data from
 * @return Status of operation (true = success)
 */
bool I2Cdev::writeWords(bool useSPI, uint8_t devAddr, uint8_t regAddr, uint8_t length, uint16_t* data) {
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.print(useSPI ? "SPI Slave (0x" : "I2C (0x" );
        Serial.print(devAddr, HEX);
        Serial.print(") writing ");
        Serial.print(length, DEC);
        Serial.print(" words to 0x");
        Serial.print(regAddr, HEX);
        Serial.print("...");
    #endif

	if (!useSPI) {
		Wire.beginTransmission(devAddr);
		#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
			Wire.send(regAddr); // send address
		#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
			Wire.write(regAddr); // send address
		#endif
		for (uint8_t i = 0; i < length * 2; i++) {
			#if ((I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO < 100) || I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE)
				Wire.send((uint8_t)(data[i++] >> 8)); // send MSB
				Wire.send((uint8_t)data[i]);          // send LSB
			#elif (I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE && ARDUINO >= 100)
				Wire.write((uint8_t)(data[i++] >> 8)); // send MSB
				Wire.write((uint8_t)data[i]);          // send LSB
			#endif
			#ifdef I2CDEV_SERIAL_DEBUG
				Serial.print(data[i], HEX);
				if (i + 1 < length) Serial.print(" ");
			#endif
		}
		// docs say this returns a byte, but it causes a compiler error
		//uint8_t status = Wire.endTransmission();
		Wire.endTransmission();
	} else {
		digitalWrite(devAddr, LOW);
		SPI.transfer(regAddr);
		for ( uint8_t w = 0; w<length*2; w++) {
			SPI.transfer((uint8_t)data[w++]>>8);
			SPI.transfer((uint8_t)data[w]);
			#ifdef I2CDEV_SERIAL_DEBUG
				Serial.print(data[w], HEX);
				if (w + 1 < length) Serial.print(" ");
			#endif
		}
		digitalWrite(devAddr, HIGH);
	}
    #ifdef I2CDEV_SERIAL_DEBUG
        Serial.println(". Done.");
    #endif
    return true; //status == 0;
}

/** Default timeout value for read operations.
 * Set this to 0 to disable timeout detection.
 */
uint16_t I2Cdev::readTimeout = I2CDEV_DEFAULT_READ_TIMEOUT;

#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_NBWIRE
    // NBWire implementation based heavily on code by Gene Knight <Gene@Telobot.com>
    // Originally posted on the Arduino forum at http://arduino.cc/forum/index.php/topic,70705.0.html
    // Originally offered to the i2cdevlib project at http://arduino.cc/forum/index.php/topic,68210.30.html

    /*
    call this version 1.0

    Offhand, the only funky part that I can think of is in nbrequestFrom, where the buffer
    length and index are set *before* the data is actually read. The problem is that these
    are variables local to the TwoWire object, and by the time we actually have read the
    data, and know what the length actually is, we have no simple access to the object's
    variables. The actual bytes read *is* given to the callback function, though.

    The ISR code for a slave receiver is commented out. I don't have that setup, and can't
    verify it at this time. Save it for 2.0!

    The handling of the read and write processes here is much like in the demo sketch code:
    the process is broken down into sequential functions, where each registers the next as a
    callback, essentially.

    For example, for the Read process, twi_read00 just returns if TWI is not yet in a
    ready state. When there's another interrupt, and the interface *is* ready, then it
    sets up the read, starts it, and registers twi_read01 as the function to call after
    the *next* interrupt. twi_read01, then, just returns if the interface is still in a
    "reading" state. When the reading is done, it copies the information to the buffer,
    cleans up, and calls the user-requested callback function with the actual number of
    bytes read.

    The writing is similar.

    Questions, comments and problems can go to Gene@Telobot.com.

    Thumbs Up!
    Gene Knight

    */

    uint8_t TwoWire::rxBuffer[NBWIRE_BUFFER_LENGTH];
    uint8_t TwoWire::rxBufferIndex = 0;
    uint8_t TwoWire::rxBufferLength = 0;

    uint8_t TwoWire::txAddress = 0;
    uint8_t TwoWire::txBuffer[NBWIRE_BUFFER_LENGTH];
    uint8_t TwoWire::txBufferIndex = 0;
    uint8_t TwoWire::txBufferLength = 0;

    //uint8_t TwoWire::transmitting = 0;
    void (*TwoWire::user_onRequest)(void);
    void (*TwoWire::user_onReceive)(int);

    static volatile uint8_t twi_transmitting;
    static volatile uint8_t twi_state;
    static uint8_t twi_slarw;
    static volatile uint8_t twi_error;
    static uint8_t twi_masterBuffer[TWI_BUFFER_LENGTH];
    static volatile uint8_t twi_masterBufferIndex;
    static uint8_t twi_masterBufferLength;
    static uint8_t twi_rxBuffer[TWI_BUFFER_LENGTH];
    static volatile uint8_t twi_rxBufferIndex;
    //static volatile uint8_t twi_Interrupt_Continue_Command;
    static volatile uint8_t twi_Return_Value;
    static volatile uint8_t twi_Done;
    void (*twi_cbendTransmissionDone)(int);
    void (*twi_cbreadFromDone)(int);

    void twi_init() {
        // initialize state
        twi_state = TWI_READY;

        // activate internal pull-ups for twi
        // as per note from atmega8 manual pg167
        sbi(PORTC, 4);
        sbi(PORTC, 5);

        // initialize twi prescaler and bit rate
        cbi(TWSR, TWPS0); // TWI Status Register - Prescaler bits
        cbi(TWSR, TWPS1);

        /* twi bit rate formula from atmega128 manual pg 204
        SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR))
        note: TWBR should be 10 or higher for master mode
        It is 72 for a 16mhz Wiring board with 100kHz TWI */

        TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2; // bitrate register
        // enable twi module, acks, and twi interrupt

        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);

        /* TWEN - TWI Enable Bit
        TWIE - TWI Interrupt Enable
        TWEA - TWI Enable Acknowledge Bit
        TWINT - TWI Interrupt Flag
        TWSTA - TWI Start Condition
        */
    }

    typedef struct {
        uint8_t address;
        uint8_t* data;
        uint8_t length;
        uint8_t wait;
        uint8_t i;
    } twi_Write_Vars;

    twi_Write_Vars *ptwv = 0;
    static void (*fNextInterruptFunction)(void) = 0;

    void twi_Finish(byte bRetVal) {
        if (ptwv) {
            free(ptwv);
            ptwv = 0;
        }
        twi_Done = 0xFF;
        twi_Return_Value = bRetVal;
        fNextInterruptFunction = 0;
    }

    uint8_t twii_WaitForDone(uint16_t timeout) {
        uint32_t endMillis = millis() + timeout;
        while (!twi_Done && (timeout == 0 || millis() < endMillis)) continue;
        return twi_Return_Value;
    }

    void twii_SetState(uint8_t ucState) {
        twi_state = ucState;
    }

    void twii_SetError(uint8_t ucError) {
        twi_error = ucError ;
    }

    void twii_InitBuffer(uint8_t ucPos, uint8_t ucLength) {
        twi_masterBufferIndex = 0;
        twi_masterBufferLength = ucLength;
    }

    void twii_CopyToBuf(uint8_t* pData, uint8_t ucLength) {
        uint8_t i;
        for (i = 0; i < ucLength; ++i) {
            twi_masterBuffer[i] = pData[i];
        }
    }

    void twii_CopyFromBuf(uint8_t *pData, uint8_t ucLength) {
        uint8_t i;
        for (i = 0; i < ucLength; ++i) {
            pData[i] = twi_masterBuffer[i];
        }
    }

    void twii_SetSlaRW(uint8_t ucSlaRW) {
        twi_slarw = ucSlaRW;
    }

    void twii_SetStart() {
        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTA);
    }

    void twi_write01() {
        if (TWI_MTX == twi_state) return; // blocking test
        twi_transmitting = 0 ;
        if (twi_error == 0xFF)
            twi_Finish (0);    // success
        else if (twi_error == TW_MT_SLA_NACK)
            twi_Finish (2);    // error: address send, nack received
        else if (twi_error == TW_MT_DATA_NACK)
            twi_Finish (3);    // error: data send, nack received
        else
            twi_Finish (4);    // other twi error
        if (twi_cbendTransmissionDone) return twi_cbendTransmissionDone(twi_Return_Value);
        return;
    }

    void twi_write00() {
        if (TWI_READY != twi_state) return; // blocking test
        if (TWI_BUFFER_LENGTH < ptwv -> length) {
            twi_Finish(1); // end write with error 1
            return;
        }
        twi_Done = 0x00; // show as working
        twii_SetState(TWI_MTX); // to transmitting
        twii_SetError(0xFF); // to No Error
        twii_InitBuffer(0, ptwv -> length); // pointer and length
        twii_CopyToBuf(ptwv -> data, ptwv -> length); // get the data
        twii_SetSlaRW((ptwv -> address << 1) | TW_WRITE); // write command
        twii_SetStart(); // start the cycle
        fNextInterruptFunction = twi_write01; // next routine
        return twi_write01();
    }

    void twi_writeTo(uint8_t address, uint8_t* data, uint8_t length, uint8_t wait) {
        uint8_t i;
        ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
        ptwv -> address = address;
        ptwv -> data = data;
        ptwv -> length = length;
        ptwv -> wait = wait;
        fNextInterruptFunction = twi_write00;
        return twi_write00();
    }

    void twi_read01() {
        if (TWI_MRX == twi_state) return; // blocking test
        if (twi_masterBufferIndex < ptwv -> length) ptwv -> length = twi_masterBufferIndex;
        twii_CopyFromBuf(ptwv -> data, ptwv -> length);
        twi_Finish(ptwv -> length);
        if (twi_cbreadFromDone) return twi_cbreadFromDone(twi_Return_Value);
        return;
    }

    void twi_read00() {
        if (TWI_READY != twi_state) return; // blocking test
        if (TWI_BUFFER_LENGTH < ptwv -> length) twi_Finish(0); // error return
        twi_Done = 0x00; // show as working
        twii_SetState(TWI_MRX); // reading
        twii_SetError(0xFF); // reset error
        twii_InitBuffer(0, ptwv -> length - 1); // init to one less than length
        twii_SetSlaRW((ptwv -> address << 1) | TW_READ); // read command
        twii_SetStart(); // start cycle
        fNextInterruptFunction = twi_read01;
        return twi_read01();
    }

    void twi_readFrom(uint8_t address, uint8_t* data, uint8_t length) {
        uint8_t i;

        ptwv = (twi_Write_Vars *)malloc(sizeof(twi_Write_Vars));
        ptwv -> address = address;
        ptwv -> data = data;
        ptwv -> length = length;
        fNextInterruptFunction = twi_read00;
        return twi_read00();
    }

    void twi_reply(uint8_t ack) {
        // transmit master read ready signal, with or without ack
        if (ack){
            TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT) | _BV(TWEA);
        } else {
            TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWINT);
        }
    }

    void twi_stop(void) {
        // send stop condition
        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT) | _BV(TWSTO);

        // wait for stop condition to be exectued on bus
        // TWINT is not set after a stop condition!
        while (TWCR & _BV(TWSTO)) {
            continue;
        }

        // update twi state
        twi_state = TWI_READY;
    }

    void twi_releaseBus(void) {
        // release bus
        TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA) | _BV(TWINT);

        // update twi state
        twi_state = TWI_READY;
    }

    SIGNAL(TWI_vect) {
        switch (TW_STATUS) {
            // All Master
            case TW_START:     // sent start condition
            case TW_REP_START: // sent repeated start condition
                // copy device address and r/w bit to output register and ack
                TWDR = twi_slarw;
                twi_reply(1);
                break;

            // Master Transmitter
            case TW_MT_SLA_ACK:  // slave receiver acked address
            case TW_MT_DATA_ACK: // slave receiver acked data
                // if there is data to send, send it, otherwise stop
                if (twi_masterBufferIndex < twi_masterBufferLength) {
                    // copy data to output register and ack
                    TWDR = twi_masterBuffer[twi_masterBufferIndex++];
                    twi_reply(1);
                } else {
                    twi_stop();
                }
                break;

            case TW_MT_SLA_NACK:  // address sent, nack received
                twi_error = TW_MT_SLA_NACK;
                twi_stop();
                break;

            case TW_MT_DATA_NACK: // data sent, nack received
                twi_error = TW_MT_DATA_NACK;
                twi_stop();
                break;

            case TW_MT_ARB_LOST: // lost bus arbitration
                twi_error = TW_MT_ARB_LOST;
                twi_releaseBus();
                break;

            // Master Receiver
            case TW_MR_DATA_ACK: // data received, ack sent
                // put byte into buffer
                twi_masterBuffer[twi_masterBufferIndex++] = TWDR;

            case TW_MR_SLA_ACK:  // address sent, ack received
                // ack if more bytes are expected, otherwise nack
                if (twi_masterBufferIndex < twi_masterBufferLength) {
                    twi_reply(1);
                } else {
                    twi_reply(0);
                }
                break;

            case TW_MR_DATA_NACK: // data received, nack sent
                // put final byte into buffer
                twi_masterBuffer[twi_masterBufferIndex++] = TWDR;

            case TW_MR_SLA_NACK: // address sent, nack received
                twi_stop();
                break;

        // TW_MR_ARB_LOST handled by TW_MT_ARB_LOST case

        // Slave Receiver (NOT IMPLEMENTED YET)
        /*
            case TW_SR_SLA_ACK:   // addressed, returned ack
            case TW_SR_GCALL_ACK: // addressed generally, returned ack
            case TW_SR_ARB_LOST_SLA_ACK:   // lost arbitration, returned ack
            case TW_SR_ARB_LOST_GCALL_ACK: // lost arbitration, returned ack
                // enter slave receiver mode
                twi_state = TWI_SRX;

                // indicate that rx buffer can be overwritten and ack
                twi_rxBufferIndex = 0;
                twi_reply(1);
                break;

            case TW_SR_DATA_ACK:       // data received, returned ack
            case TW_SR_GCALL_DATA_ACK: // data received generally, returned ack
                // if there is still room in the rx buffer
                if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) {
                    // put byte in buffer and ack
                    twi_rxBuffer[twi_rxBufferIndex++] = TWDR;
                    twi_reply(1);
                } else {
                    // otherwise nack
                    twi_reply(0);
                }
                break;

            case TW_SR_STOP: // stop or repeated start condition received
                // put a null char after data if there's room
                if (twi_rxBufferIndex < TWI_BUFFER_LENGTH) {
                    twi_rxBuffer[twi_rxBufferIndex] = 0;
                }

                // sends ack and stops interface for clock stretching
                twi_stop();

                // callback to user defined callback
                twi_onSlaveReceive(twi_rxBuffer, twi_rxBufferIndex);

                // since we submit rx buffer to "wire" library, we can reset it
                twi_rxBufferIndex = 0;

                // ack future responses and leave slave receiver state
                twi_releaseBus();
                break;

            case TW_SR_DATA_NACK:       // data received, returned nack
            case TW_SR_GCALL_DATA_NACK: // data received generally, returned nack
                // nack back at master
                twi_reply(0);
                break;

            // Slave Transmitter
            case TW_ST_SLA_ACK:          // addressed, returned ack
            case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
                // enter slave transmitter mode
                twi_state = TWI_STX;

                // ready the tx buffer index for iteration
                twi_txBufferIndex = 0;

                // set tx buffer length to be zero, to verify if user changes it
                twi_txBufferLength = 0;

                // request for txBuffer to be filled and length to be set
                // note: user must call twi_transmit(bytes, length) to do this
                twi_onSlaveTransmit();

                // if they didn't change buffer & length, initialize it
                if (0 == twi_txBufferLength) {
                    twi_txBufferLength = 1;
                    twi_txBuffer[0] = 0x00;
                }

                // transmit first byte from buffer, fall through

            case TW_ST_DATA_ACK: // byte sent, ack returned
                // copy data to output register
                TWDR = twi_txBuffer[twi_txBufferIndex++];

                // if there is more to send, ack, otherwise nack
                if (twi_txBufferIndex < twi_txBufferLength) {
                    twi_reply(1);
                } else {
                    twi_reply(0);
                }
                break;

            case TW_ST_DATA_NACK: // received nack, we are done
            case TW_ST_LAST_DATA: // received ack, but we are done already!
                // ack future responses
                twi_reply(1);
                // leave slave receiver state
                twi_state = TWI_READY;
                break;
            */

            // all
            case TW_NO_INFO:   // no state information
                break;

            case TW_BUS_ERROR: // bus error, illegal stop/start
                twi_error = TW_BUS_ERROR;
                twi_stop();
                break;
        }

        if (fNextInterruptFunction) return fNextInterruptFunction();
    }

    TwoWire::TwoWire() { }

    void TwoWire::begin(void) {
        rxBufferIndex = 0;
        rxBufferLength = 0;

        txBufferIndex = 0;
        txBufferLength = 0;

        twi_init();
    }

    void TwoWire::beginTransmission(uint8_t address) {
        //beginTransmission((uint8_t)address);

        // indicate that we are transmitting
        twi_transmitting = 1;

        // set address of targeted slave
        txAddress = address;

        // reset tx buffer iterator vars
        txBufferIndex = 0;
        txBufferLength = 0;
    }

    uint8_t TwoWire::endTransmission(uint16_t timeout) {
        // transmit buffer (blocking)
        //int8_t ret =
        twi_cbendTransmissionDone = NULL;
        twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
        int8_t ret = twii_WaitForDone(timeout);

        // reset tx buffer iterator vars
        txBufferIndex = 0;
        txBufferLength = 0;

        // indicate that we are done transmitting
        // twi_transmitting = 0;
        return ret;
    }

    void TwoWire::nbendTransmission(void (*function)(int)) {
        twi_cbendTransmissionDone = function;
        twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
        return;
    }

    void TwoWire::send(uint8_t data) {
        if (twi_transmitting) {
            // in master transmitter mode
            // don't bother if buffer is full
            if (txBufferLength >= NBWIRE_BUFFER_LENGTH) {
                return;
            }

            // put byte in tx buffer
            txBuffer[txBufferIndex] = data;
            ++txBufferIndex;

            // update amount in buffer
            txBufferLength = txBufferIndex;
        } else {
            // in slave send mode
            // reply to master
            //twi_transmit(&data, 1);
        }
    }

    uint8_t TwoWire::receive(void) {
        // default to returning null char
        // for people using with char strings
        uint8_t value = 0;

        // get each successive byte on each call
        if (rxBufferIndex < rxBufferLength) {
            value = rxBuffer[rxBufferIndex];
            ++rxBufferIndex;
        }

        return value;
    }

    uint8_t TwoWire::requestFrom(uint8_t address, int quantity, uint16_t timeout) {
        // clamp to buffer length
        if (quantity > NBWIRE_BUFFER_LENGTH) {
            quantity = NBWIRE_BUFFER_LENGTH;
        }

        // perform blocking read into buffer
        twi_cbreadFromDone = NULL;
        twi_readFrom(address, rxBuffer, quantity);
        uint8_t read = twii_WaitForDone(timeout);

        // set rx buffer iterator vars
        rxBufferIndex = 0;
        rxBufferLength = read;

        return read;
    }

    void TwoWire::nbrequestFrom(uint8_t address, int quantity, void (*function)(int)) {
        // clamp to buffer length
        if (quantity > NBWIRE_BUFFER_LENGTH) {
            quantity = NBWIRE_BUFFER_LENGTH;
        }

        // perform blocking read into buffer
        twi_cbreadFromDone = function;
        twi_readFrom(address, rxBuffer, quantity);
        //uint8_t read = twii_WaitForDone();

        // set rx buffer iterator vars
        //rxBufferIndex = 0;
        //rxBufferLength = read;

        rxBufferIndex = 0;
        rxBufferLength = quantity; // this is a hack

        return; //read;
    }

    uint8_t TwoWire::available(void) {
        return rxBufferLength - rxBufferIndex;
    }

#endif


text:
//
//  ROUSerialQueueTimer.h
//  RoUTPTests
//
//  Created by Yan Rabovik on 02.07.13.
//  Copyright (c) 2013 Yan Rabovik. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ROUSerialQueueTimer : NSObject
/**
 @param queue The queue where the target selector will be performed.
 It MUST be a serial queue. The queue is retained.
 @param leeway The amount of time, in seconds, that the system can defer the timer for improved system performance or power consumption
 @note Timer is intentionally not thread-safe and its methods should be called only from
 the queue it is created with.
 */
+(id)scheduledTimerWithQueue:(dispatch_queue_t)queue
                      target:(id)target
                    selector:(SEL)selector
                timeInterval:(NSTimeInterval)timeInterval
                      leeway:(NSTimeInterval)leeway;
-(void)fire;
/**
 @discussion You typically use this method to adjust the firing time of a repeating timer. For example, you could use it in situations where you want to repeat an action multiple times in the future, but at irregular time intervals. Adjusting the firing time of a single timer would likely incur less expense than creating multiple timer objects and then destroying them.
 @param fireDate The new date at which to fire the receiver. If the new date is in the past, this method sets the fire time to the current time.
 */
-(void)setFireDate:(NSDate *)fireDate;
-(void)invalidate;
-(NSDate *)lastFireDate;

@end


text: This site may contain copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are using this material in an effort to advance understanding of the CodeIgniter MVC framework. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law.


text:
import { PixelRatio, Dimensions } from 'react-native';

const screenW = Dimensions.get( 'window' ).width;
const screenH = Dimensions.get( 'window' ).height;
const fontScale = PixelRatio.getFontScale();

/**
 *  以iphone6为基准,如果以其他尺寸为基准的话,
 *  请修改下面的 defaultWidth 和 defaultHeight 为对应尺寸即可. 以下为1倍图时
 */
const defaultWidth = 375;
const defaultHeight = 667;

//缩放比例
const _scaleWidth = screenW / defaultWidth;
const _scaleHeight = screenH / defaultHeight;

export function px2dp( size ) {
  return px2dpW( size );
}

/**
 * 屏幕适配,缩放size , 默认根据宽度适配,纵向也可以使用此方法
 * 横向的尺寸直接使用此方法
 * 如:width ,paddingHorizontal ,paddingLeft ,paddingRight ,marginHorizontal ,marginLeft ,marginRight
 * @param size 设计图的尺寸
 * @returns {number}
 */
export function px2dpW( size ) {
  return size * _scaleWidth;
}

/**
 * 屏幕适配 , 纵向的尺寸使用此方法应该会更趋近于设计稿
 * 如:height ,paddingVertical ,paddingTop ,paddingBottom ,marginVertical ,marginTop ,marginBottom
 * @param size 设计图的尺寸
 * @returns {number}
 */
export function px2dpH( size ) {
  return size * _scaleHeight;
}

/**
 * 设置字体的size(单位px)
 * @param size 传入设计稿上的px , allowFontScaling 是否根据设备文字缩放比例调整,默认不会
 * @returns {Number} 返回实际sp
 */
export function px2sp( size, allowFontScaling = false ) {
  const scale = Math.min( _scaleWidth, _scaleHeight );
  const fontSize = allowFontScaling ? 1 : fontScale;
  return ( size * scale ) / fontSize;
}


text:
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">

Search for an item

    <form class="search">

            Category:
            <select id="category">
                <option value="cmr">Camera</option>
                <option value="lpt">Laptop</option>
                <option value="tab">Tablet</option>
                <option value="phn">Phone</option>
            </select>

            Search:
            <input id="search" type="text" name="search" placeholder="Search Keyword"/>

    </form>

        <button class="primary search-submit" onclick="search()">Search</button>

Loading...


text:
#ifndef SYSUTILITY_H
#define SYSUTILITY_H

#include "config.h"
#include "MC2String.h"

/**
  *   Utility functions that are system/OS dependent.
  *
  */
namespace SysUtility
{

/**
 *    Ignores pipe signals that would halt the program
 *    if the connection is closed. Now read returns -1
 *    instead. Has no effect in MSC.
 */
void ignorePipe();

/**
 *    Sets the default signal handler for SIGPIPE.
 *    Has no effect in MSC.
 */
void setPipeDefault();

/**
 * Sets if ignorePipe and setPipeDefault should do anything or not.
 */
void setChangePipeSignal( bool on );

/// ignores pipes until it goes out of scope
struct IgnorePipe {
   IgnorePipe() {
      SysUtility::ignorePipe();
   }
   ~IgnorePipe() {
      SysUtility::setPipeDefault();
   }
};

/**
 *   Returns process total size (code + stack + data etc).
 *   @result size in 1024 byte blocks (0 if not supported)
 */
uint32 getProcessTotalSize();

/**
 *   Returns process data size (data + stack).
 *   @result size in 1024 byte blocks (0 if not supported)
 */
uint32 getProcessDataSize();

/**
 *   Returns process resident size (data/code/etc of the process currently in memory).
 *   @result size in 1024 byte blocks (0 if not supported)
 */
uint32 getProcessResidentSize();

/**
 *   Dump process info. Dump all available process info, used
 *   when we're about to exit due to a fatal error such as failure
 *   to allocate memory, etc. Should *not* allocate anything on the
 *   heap and *not* put anything on the stack!
 *   Print/dumps nothing if not supported.
 */
void dumpProcessInfo();

MC2String getMemoryInfo();

/**
 *    Prints backtrace. At least on linux.
 */
void printBacktrace();

/**
 *    Gets the back trace. At least on linux.
 */
void getBacktrace( vector<MC2String>& bt );

/**
 * Prints information about the heap. Used for
 * diagnosing memory problems such as fragmentation
 * and leaks.
 */
void printHeapStatus( std::ostream& os );

/**
 * Attempts to increase the nice value of the current process
 * to the newPrio nice value.
 * The function does not even attempt to
 * set a negative priority even if requested.
 * @param newPrio The requested new priority.
 */
void setPriority( uint32 newPrio );

};
#endif // SYSUTILITY_H


text:
package com.oppo.base.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * ClassName:ZipUtil
 * Function: 文件解压/压缩操作
 *
 * @author   80036381
 * @version
 * @since    Ver 1.1
 * @Date	 2011-10-17  下午04:56:27
 */
public class ZipUtil {

	/**
	 * 解压指定的文件到指定路径
	 * @param sourcePath zip文件的路径
	 * @param destDir 解压后文件存放的路径
	 * @return
	 */
	public static boolean unzip(String sourcePath, String destDir) throws IOException {
		//判断文件是否存在且是否是普通文件
		File sFile = new File(sourcePath);
		if(!sFile.exists() || !sFile.isFile()) {
			return false;
		}

		//创建文件目录
		if(!FileOperate.createDir(destDir, false)) {
			return false;
		}

		ZipInputStream zis = null;

		try {
			zis = new ZipInputStream(new FileInputStream(sFile));
			BufferedInputStream bis = new BufferedInputStream(zis);

			ZipEntry ze;
			while((ze = zis.getNextEntry()) != null) {
				if(!ze.isDirectory()) {
					//得到新的文件
					File destFile = new File(destDir, ze.getName());
					//保存数据到新文件中
					FileOperate.saveStreamToFile(destFile, bis);
				}

				zis.closeEntry();
			}

			return true;
		} finally {
			FileOperate.close(zis);
		}
	}

	/**
	 * 压缩指定文件到指定的路径
	 * @param sourceFiles 源文件路径
	 * @param relatePath 源文件的相对路径,如relatePath为e:\a,
	 * 		sourceFile为e:\a\b\c.txt,则sourceFile压缩后的路径为b\c.txt
	 * @param destPath 压缩后的文件路径
	 * @return 是否压缩成功
	 * @throws IOException
	 */
	public static boolean zip(String[] sourceFiles, String relatePath, String destPath) throws IOException {
		ZipOutputStream zos = null;

		int relateLen = (null == relatePath) ? 0 : relatePath.length();

		try {
			zos = new ZipOutputStream(new FileOutputStream(destPath));
			BufferedOutputStream bos = new BufferedOutputStream(zos);

			for(int i = 0; i < sourceFiles.length; i++) {
				String path = sourceFiles[i];

				//zip名称修正
				String zipName = path.substring(relateLen);
				if(zipName.startsWith(File.separator)) {
					zipName = zipName.substring(1);
				}

				ZipEntry zipEntry = new ZipEntry(new String(zipName.getBytes(), "ascii"));
				zos.putNextEntry(zipEntry);

				//读取文件内容并写入压缩流中
				FileInputStream fis = null;
				try {
					fis = new FileInputStream(path);

					byte[] data = new byte[4096];
					int readLen;
					while((readLen = fis.read(data)) != -1) {
						bos.write(data, 0, readLen);
					}

					bos.flush();
				} finally {
					FileOperate.close(fis);
				}
			}

			zos.finish();

			return true;
		} finally {
			FileOperate.close(zos);
		}
	}

	public static void main(String[] args) {
		try {
//			long start = System.currentTimeMillis();
//			for(int i = 0; i < 100; i++)
			ZipUtil.zip(new String[] {
					"G:\\drivers_tools\\adb_fastboot tool\\adb.exe",
					"G:\\drivers_tools\\adb_fastboot tool\\fastboot.exe",
					"G:\\drivers_tools\\adb_fastboot tool\\AdbWinUsbApi.dll"
					}, "G:\\drivers_tools", "G:\\drivers_tools\\test.zip");
//			long total = System.currentTimeMillis() - start;
//			System.out.println("耗时:" + total);

			ZipUtil.unzip("G:\\1\\1.zip", "g:\\des1");
			System.out.println("operate complate!");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}