text:
// TI File $Revision: /main/5 $
// Checkin $Date: May 14, 2008   16:30:31 $
//###########################################################################
//
// FILE:   DSP2833x_Mcbsp.h
//
// TITLE:  DSP2833x Device McBSP Register Definitions.
//
//###########################################################################
// $TI Release: DSP2833x/DSP2823x C/C++ Header Files V1.31 $
// $Release Date: August 4, 2009 $
//###########################################################################

#ifndef DSP2833x_MCBSP_H
#define DSP2833x_MCBSP_H

#ifdef __cplusplus
extern "C" {
#endif

//---------------------------------------------------------------------------
// McBSP Individual Register Bit Definitions:
//
// McBSP DRR2 register bit definitions:
struct  DRR2_BITS {       // bit   description
   uint16     HWLB:8;     // 16:23 High word low byte
   uint16     HWHB:8;     // 24:31 High word high byte
};

union DRR2_REG {
   uint16            all;
   struct DRR2_BITS  bit;
};

// McBSP DRR1 register bit definitions:
struct  DRR1_BITS {       // bit   description
   uint16     LWLB:8;     // 16:23 Low word low byte
   uint16     LWHB:8;     // 24:31 low word high byte
};

union DRR1_REG {
   uint16            all;
   struct DRR1_BITS  bit;
};

// McBSP DXR2 register bit definitions:
struct  DXR2_BITS {       // bit   description
   uint16     HWLB:8;     // 16:23 High word low byte
   uint16     HWHB:8;     // 24:31 High word high byte
};

union DXR2_REG {
   uint16            all;
   struct DXR2_BITS  bit;
};

// McBSP DXR1 register bit definitions:
struct  DXR1_BITS {       // bit   description
   uint16     LWLB:8;     // 16:23 Low word low byte
   uint16     LWHB:8;     // 24:31 low word high byte
};

union DXR1_REG {
   uint16              all;
   struct DXR1_BITS  bit;
};

// SPCR2 control register bit definitions:
struct  SPCR2_BITS {       // bit   description
   uint16     XRST:1;      // 0     transmit reset
   uint16     XRDY:1;      // 1     transmit ready
   uint16     XEMPTY:1;    // 2     Transmit empty
   uint16     XSYNCERR:1;  // 3     Transmit syn errorINT flag
   uint16     XINTM:2;     // 5:4   Transmit interrupt types
   uint16     GRST:1;      // 6     CLKG reset
   uint16     FRST:1;      // 7     Frame sync reset
   uint16     SOFT:1;      // 8     SOFT bit
   uint16     FREE:1;      // 9     FREE bit
   uint16     rsvd:6;      // 15:10 reserved
};

union SPCR2_REG {
   uint16               all;
   struct SPCR2_BITS  bit;
};

// SPCR1 control register bit definitions:
struct  SPCR1_BITS {       // bit   description
   uint16     RRST:1;      // 0     Receive reset
   uint16     RRDY:1;      // 1     Receive  ready
   uint16     RFULL:1;     // 2     Receive  full
   uint16     RSYNCERR:1;  // 7     Receive  syn error
   uint16     RINTM:2;     // 5:4   Receive  interrupt types
   uint16     ABIS:1;      // 6     ABIS mode select
   uint16     DXENA:1;     // 7     DX hi-z enable
   uint16     rsvd:3;      // 10:8  reserved
   uint16     CLKSTP:2;    // 12:11 CLKSTOP mode bit
   uint16     RJUST:2;     // 13:14 Right justified
   uint16     DLB:1;       // 15    Digital loop back
};

union SPCR1_REG {
   uint16              all;
   struct SPCR1_BITS bit;
};

// RCR2 control register bit definitions:
struct  RCR2_BITS {         // bit    description
   uint16     RDATDLY:2;    // 1:0    Receive data delay
   uint16     RFIG:1;       // 2      Receive  frame sync ignore
   uint16     RCOMPAND:2;   // 4:3    Receive  Companding Mode selects
   uint16     RWDLEN2:3;    // 7:5    Receive  word length
   uint16     RFRLEN2:7;    // 14:8   Receive  Frame sync
   uint16     RPHASE:1;     // 15     Receive Phase
};

union RCR2_REG {
   uint16           all;
   struct RCR2_BITS bit;
};

// RCR1 control register bit definitions:
struct  RCR1_BITS {         // bit   description
   uint16     rsvd1:5;      // 4:0   reserved
   uint16     RWDLEN1:3;    // 7:5   Receive word length
   uint16     RFRLEN1:7;    // 14:8  Receive frame length
   uint16     rsvd2:1;      // 15    reserved
};

union RCR1_REG {
   uint16           all;
   struct RCR1_BITS bit;
};

// XCR2 control register bit definitions:

struct  XCR2_BITS {         // bit    description
   uint16     XDATDLY:2;    // 1:0    Transmit data delay
   uint16     XFIG:1;       // 2      Transmit frame sync ignore
   uint16     XCOMPAND:2;   // 4:3    Transmit Companding Mode selects
   uint16     XWDLEN2:3;    // 7:5    Transmit  word length
   uint16     XFRLEN2:7;    // 14:8   Transmit  Frame sync
   uint16     XPHASE:1;     // 15     Transmit Phase
};

union XCR2_REG {
   uint16           all;
   struct XCR2_BITS bit;
};

// XCR1 control register bit definitions:
struct  XCR1_BITS {         // bit   description
   uint16     rsvd1:5;      // 4:0   reserved
   uint16     XWDLEN1:3;    // 7:5   Transmit word length
   uint16     XFRLEN1:7;    // 14:8  Transmit frame length
   uint16     rsvd2:1;      // 15    reserved
};

union XCR1_REG {
   uint16             all;
   struct XCR1_BITS bit;
};

// SRGR2 Sample rate generator control register bit definitions:
struct  SRGR2_BITS {        // bit  description
   uint16     FPER:12;      // 11:0 Frame period
   uint16     FSGM:1;       // 12   Frame sync generator mode
   uint16     CLKSM:1;      // 13   Sample rate generator mode
   uint16     rsvd:1;       // 14   reserved
   uint16     GSYNC:1;      // 15   CLKG sync
};

union  SRGR2_REG {
   uint16              all;
   struct  SRGR2_BITS  bit;
};

// SRGR1 control register bit definitions:
struct  SRGR1_BITS {        // bit   description
   uint16     CLKGDV:8;     // 7:0   CLKG divider
   uint16     FWID:8;       // 15:8  Frame width
};

union  SRGR1_REG {
   uint16              all;
   struct  SRGR1_BITS  bit;
};

// MCR2 Multichannel control register bit definitions:
struct  MCR2_BITS {         // bit   description
   uint16     XMCM:2;       // 1:0   Transmit multichannel mode
   uint16     XCBLK:3;      // 2:4   Transmit current block
   uint16     XPABLK:2;     // 5:6   Transmit partition A Block
   uint16     XPBBLK:2;     // 7:8   Transmit partition B Block
   uint16     XMCME:1;      // 9     Transmit multi-channel enhance mode
   uint16     rsvd:6;       // 15:10 reserved
};

union  MCR2_REG {
   uint16             all;
   struct  MCR2_BITS  bit;
};

// MCR1 Multichannel control register bit definitions:
struct  MCR1_BITS {         // bit   description
   uint16     RMCM:1;       // 0     Receive multichannel mode
   uint16     rsvd:1;       // 1     reserved
   uint16     RCBLK:3;      // 4:2   Receive current block
   uint16     RPABLK:2;     // 6:5   Receive partition A Block
   uint16     RPBBLK:2;     // 7:8   Receive partition B Block
   uint16     RMCME:1;      // 9     Receive multi-channel enhance mode
   uint16     rsvd1:6;      // 15:10 reserved
};

union  MCR1_REG {
   uint16             all;
   struct  MCR1_BITS  bit;
};

// RCERA control register bit definitions:
struct  RCERA_BITS {         // bit description
   uint16     RCEA0:1;       // 0   Receive Channel enable bit
   uint16     RCEA1:1;       // 1   Receive Channel enable bit
   uint16     RCEA2:1;       // 2   Receive Channel enable bit
   uint16     RCEA3:1;       // 3   Receive Channel enable bit
   uint16     RCEA4:1;       // 4   Receive Channel enable bit
   uint16     RCEA5:1;       // 5   Receive Channel enable bit
   uint16     RCEA6:1;       // 6   Receive Channel enable bit
   uint16     RCEA7:1;       // 7   Receive Channel enable bit
   uint16     RCEA8:1;       // 8   Receive Channel enable bit
   uint16     RCEA9:1;       // 9   Receive Channel enable bit
   uint16     RCEA10:1;      // 10  Receive Channel enable bit
   uint16     RCEA11:1;      // 11  Receive Channel enable bit
   uint16     RCEA12:1;      // 12  Receive Channel enable bit
   uint16     RCEA13:1;      // 13  Receive Channel enable bit
   uint16     RCEA14:1;      // 14  Receive Channel enable bit
   uint16     RCEA15:1;      // 15  Receive Channel enable bit
};

union RCERA_REG {
   uint16              all;
   struct  RCERA_BITS  bit;
};

// RCERB control register bit definitions:
struct  RCERB_BITS {         // bit description
   uint16     RCEB0:1;       // 0   Receive Channel enable bit
   uint16     RCEB1:1;       // 1   Receive Channel enable bit
   uint16     RCEB2:1;       // 2   Receive Channel enable bit
   uint16     RCEB3:1;       // 3   Receive Channel enable bit
   uint16     RCEB4:1;       // 4   Receive Channel enable bit
   uint16     RCEB5:1;       // 5   Receive Channel enable bit
   uint16     RCEB6:1;       // 6   Receive Channel enable bit
   uint16     RCEB7:1;       // 7   Receive Channel enable bit
   uint16     RCEB8:1;       // 8   Receive Channel enable bit
   uint16     RCEB9:1;       // 9   Receive Channel enable bit
   uint16     RCEB10:1;      // 10  Receive Channel enable bit
   uint16     RCEB11:1;      // 11  Receive Channel enable bit
   uint16     RCEB12:1;      // 12  Receive Channel enable bit
   uint16     RCEB13:1;      // 13  Receive Channel enable bit
   uint16     RCEB14:1;      // 14  Receive Channel enable bit
   uint16     RCEB15:1;      // 15  Receive Channel enable bit
};

union RCERB_REG {
   uint16              all;
   struct  RCERB_BITS  bit;
};

// XCERA control register bit definitions:
struct  XCERA_BITS {         // bit description
   uint16     XCERA0:1;       // 0   Receive Channel enable bit
   uint16     XCERA1:1;       // 1   Receive Channel enable bit
   uint16     XCERA2:1;       // 2   Receive Channel enable bit
   uint16     XCERA3:1;       // 3   Receive Channel enable bit
   uint16     XCERA4:1;       // 4   Receive Channel enable bit
   uint16     XCERA5:1;       // 5   Receive Channel enable bit
   uint16     XCERA6:1;       // 6   Receive Channel enable bit
   uint16     XCERA7:1;       // 7   Receive Channel enable bit
   uint16     XCERA8:1;       // 8   Receive Channel enable bit
   uint16     XCERA9:1;       // 9   Receive Channel enable bit
   uint16     XCERA10:1;      // 10  Receive Channel enable bit
   uint16     XCERA11:1;      // 11  Receive Channel enable bit
   uint16     XCERA12:1;      // 12  Receive Channel enable bit
   uint16     XCERA13:1;      // 13  Receive Channel enable bit
   uint16     XCERA14:1;      // 14  Receive Channel enable bit
   uint16     XCERA15:1;      // 15  Receive Channel enable bit
};

union XCERA_REG {
   uint16              all;
   struct  XCERA_BITS  bit;
};

// XCERB control register bit definitions:
struct  XCERB_BITS {         // bit description
   uint16     XCERB0:1;       // 0   Receive Channel enable bit
   uint16     XCERB1:1;       // 1   Receive Channel enable bit
   uint16     XCERB2:1;       // 2   Receive Channel enable bit
   uint16     XCERB3:1;       // 3   Receive Channel enable bit
   uint16     XCERB4:1;       // 4   Receive Channel enable bit
   uint16     XCERB5:1;       // 5   Receive Channel enable bit
   uint16     XCERB6:1;       // 6   Receive Channel enable bit
   uint16     XCERB7:1;       // 7   Receive Channel enable bit
   uint16     XCERB8:1;       // 8   Receive Channel enable bit
   uint16     XCERB9:1;       // 9   Receive Channel enable bit
   uint16     XCERB10:1;      // 10  Receive Channel enable bit
   uint16     XCERB11:1;      // 11  Receive Channel enable bit
   uint16     XCERB12:1;      // 12  Receive Channel enable bit
   uint16     XCERB13:1;      // 13  Receive Channel enable bit
   uint16     XCERB14:1;      // 14  Receive Channel enable bit
   uint16     XCERB15:1;      // 15  Receive Channel enable bit
};

union XCERB_REG {
   uint16              all;
   struct  XCERB_BITS  bit;
};

// PCR control register bit definitions:
struct  PCR_BITS {          // bit description
   uint16     CLKRP:1;       // 0   Receive Clock polarity
   uint16     CLKXP:1;       // 1   Transmit clock polarity
   uint16     FSRP:1;        // 2   Receive Frame synchronization polarity
   uint16     FSXP:1;        // 3   Transmit Frame synchronization polarity
   uint16     DR_STAT:1;     // 4   DR pin status - reserved for this McBSP
   uint16     DX_STAT:1;     // 5   DX pin status - reserved for this McBSP
   uint16     CLKS_STAT:1;   // 6   CLKS pin status - reserved for 28x -McBSP
   uint16     SCLKME:1;      // 7   Enhanced sample clock mode selection bit.
   uint16     CLKRM:1;       // 8   Receiver Clock Mode
   uint16     CLKXM:1;       // 9   Transmitter Clock Mode.
   uint16     FSRM:1;        // 10  Receive Frame Synchronization Mode
   uint16     FSXM:1;        // 11  Transmit Frame Synchronization Mode
   uint16     RIOEN:1;       // 12  General Purpose I/O Mode - reserved in this 28x-McBSP
   uint16     XIOEN:1;       // 13  General Purpose I/O Mode - reserved in this 28x-McBSP
   uint16     IDEL_EN:1;     // 14  reserved in this 28x-McBSP
   uint16     rsvd:1  ;      // 15  reserved
};

union PCR_REG {
   uint16            all;
   struct  PCR_BITS  bit;
};

// RCERC control register bit definitions:
struct  RCERC_BITS {         // bit description
   uint16     RCEC0:1;       // 0   Receive Channel enable bit
   uint16     RCEC1:1;       // 1   Receive Channel enable bit
   uint16     RCEC2:1;       // 2   Receive Channel enable bit
   uint16     RCEC3:1;       // 3   Receive Channel enable bit
   uint16     RCEC4:1;       // 4   Receive Channel enable bit
   uint16     RCEC5:1;       // 5   Receive Channel enable bit
   uint16     RCEC6:1;       // 6   Receive Channel enable bit
   uint16     RCEC7:1;       // 7   Receive Channel enable bit
   uint16     RCEC8:1;       // 8   Receive Channel enable bit
   uint16     RCEC9:1;       // 9   Receive Channel enable bit
   uint16     RCEC10:1;      // 10  Receive Channel enable bit
   uint16     RCEC11:1;      // 11  Receive Channel enable bit
   uint16     RCEC12:1;      // 12  Receive Channel enable bit
   uint16     RCEC13:1;      // 13  Receive Channel enable bit
   uint16     RCEC14:1;      // 14  Receive Channel enable bit
   uint16     RCEC15:1;      // 15  Receive Channel enable bit
};

union RCERC_REG {
   uint16              all;
   struct  RCERC_BITS  bit;
};

// RCERD control register bit definitions:
struct  RCERD_BITS {         // bit description
   uint16     RCED0:1;       // 0   Receive Channel enable bit
   uint16     RCED1:1;       // 1   Receive Channel enable bit
   uint16     RCED2:1;       // 2   Receive Channel enable bit
   uint16     RCED3:1;       // 3   Receive Channel enable bit
   uint16     RCED4:1;       // 4   Receive Channel enable bit
   uint16     RCED5:1;       // 5   Receive Channel enable bit
   uint16     RCED6:1;       // 6   Receive Channel enable bit
   uint16     RCED7:1;       // 7   Receive Channel enable bit
   uint16     RCED8:1;       // 8   Receive Channel enable bit
   uint16     RCED9:1;       // 9   Receive Channel enable bit
   uint16     RCED10:1;      // 10  Receive Channel enable bit
   uint16     RCED11:1;      // 11  Receive Channel enable bit
   uint16     RCED12:1;      // 12  Receive Channel enable bit
   uint16     RCED13:1;      // 13  Receive Channel enable bit
   uint16     RCED14:1;      // 14  Receive Channel enable bit
   uint16     RCED15:1;      // 15  Receive Channel enable bit
};

union RCERD_REG {
   uint16              all;
   struct  RCERD_BITS  bit;
};

// XCERC control register bit definitions:
struct  XCERC_BITS {         // bit description
   uint16     XCERC0:1;       // 0   Receive Channel enable bit
   uint16     XCERC1:1;       // 1   Receive Channel enable bit
   uint16     XCERC2:1;       // 2   Receive Channel enable bit
   uint16     XCERC3:1;       // 3   Receive Channel enable bit
   uint16     XCERC4:1;       // 4   Receive Channel enable bit
   uint16     XCERC5:1;       // 5   Receive Channel enable bit
   uint16     XCERC6:1;       // 6   Receive Channel enable bit
   uint16     XCERC7:1;       // 7   Receive Channel enable bit
   uint16     XCERC8:1;       // 8   Receive Channel enable bit
   uint16     XCERC9:1;       // 9   Receive Channel enable bit
   uint16     XCERC10:1;      // 10  Receive Channel enable bit
   uint16     XCERC11:1;      // 11  Receive Channel enable bit
   uint16     XCERC12:1;      // 12  Receive Channel enable bit
   uint16     XCERC13:1;      // 13  Receive Channel enable bit
   uint16     XCERC14:1;      // 14  Receive Channel enable bit
   uint16     XCERC15:1;      // 15  Receive Channel enable bit
};

union XCERC_REG {
   uint16              all;
   struct  XCERC_BITS  bit;
};

// XCERD control register bit definitions:
struct  XCERD_BITS {         // bit description
   uint16     XCERD0:1;       // 0   Receive Channel enable bit
   uint16     XCERD1:1;       // 1   Receive Channel enable bit
   uint16     XCERD2:1;       // 2   Receive Channel enable bit
   uint16     XCERD3:1;       // 3   Receive Channel enable bit
   uint16     XCERD4:1;       // 4   Receive Channel enable bit
   uint16     XCERD5:1;       // 5   Receive Channel enable bit
   uint16     XCERD6:1;       // 6   Receive Channel enable bit
   uint16     XCERD7:1;       // 7   Receive Channel enable bit
   uint16     XCERD8:1;       // 8   Receive Channel enable bit
   uint16     XCERD9:1;       // 9   Receive Channel enable bit
   uint16     XCERD10:1;      // 10  Receive Channel enable bit
   uint16     XCERD11:1;      // 11  Receive Channel enable bit
   uint16     XCERD12:1;      // 12  Receive Channel enable bit
   uint16     XCERD13:1;      // 13  Receive Channel enable bit
   uint16     XCERD14:1;      // 14  Receive Channel enable bit
   uint16     XCERD15:1;      // 15  Receive Channel enable bit
};

union XCERD_REG {
   uint16              all;
   struct  XCERD_BITS  bit;
};

// RCERE control register bit definitions:
struct  RCERE_BITS {         // bit description
   uint16     RCEE0:1;       // 0   Receive Channel enable bit
   uint16     RCEE1:1;       // 1   Receive Channel enable bit
   uint16     RCEE2:1;       // 2   Receive Channel enable bit
   uint16     RCEE3:1;       // 3   Receive Channel enable bit
   uint16     RCEE4:1;       // 4   Receive Channel enable bit
   uint16     RCEE5:1;       // 5   Receive Channel enable bit
   uint16     RCEE6:1;       // 6   Receive Channel enable bit
   uint16     RCEE7:1;       // 7   Receive Channel enable bit
   uint16     RCEE8:1;       // 8   Receive Channel enable bit
   uint16     RCEE9:1;       // 9   Receive Channel enable bit
   uint16     RCEE10:1;      // 10  Receive Channel enable bit
   uint16     RCEE11:1;      // 11  Receive Channel enable bit
   uint16     RCEE12:1;      // 12  Receive Channel enable bit
   uint16     RCEE13:1;      // 13  Receive Channel enable bit
   uint16     RCEE14:1;      // 14  Receive Channel enable bit
   uint16     RCEE15:1;      // 15  Receive Channel enable bit
};

union RCERE_REG {
   uint16              all;
   struct  RCERE_BITS  bit;
};

// RCERF control register bit definitions:
struct  RCERF_BITS {         // bit   description
   uint16     RCEF0:1;       // 0   Receive Channel enable bit
   uint16     RCEF1:1;       // 1   Receive Channel enable bit
   uint16     RCEF2:1;       // 2   Receive Channel enable bit
   uint16     RCEF3:1;       // 3   Receive Channel enable bit
   uint16     RCEF4:1;       // 4   Receive Channel enable bit
   uint16     RCEF5:1;       // 5   Receive Channel enable bit
   uint16     RCEF6:1;       // 6   Receive Channel enable bit
   uint16     RCEF7:1;       // 7   Receive Channel enable bit
   uint16     RCEF8:1;       // 8   Receive Channel enable bit
   uint16     RCEF9:1;       // 9   Receive Channel enable bit
   uint16     RCEF10:1;      // 10  Receive Channel enable bit
   uint16     RCEF11:1;      // 11  Receive Channel enable bit
   uint16     RCEF12:1;      // 12  Receive Channel enable bit
   uint16     RCEF13:1;      // 13  Receive Channel enable bit
   uint16     RCEF14:1;      // 14  Receive Channel enable bit
   uint16     RCEF15:1;      // 15  Receive Channel enable bit
};

union RCERF_REG {
   uint16              all;
   struct  RCERF_BITS  bit;
};

// XCERE control register bit definitions:
struct  XCERE_BITS {         // bit description
   uint16     XCERE0:1;       // 0   Receive Channel enable bit
   uint16     XCERE1:1;       // 1   Receive Channel enable bit
   uint16     XCERE2:1;       // 2   Receive Channel enable bit
   uint16     XCERE3:1;       // 3   Receive Channel enable bit
   uint16     XCERE4:1;       // 4   Receive Channel enable bit
   uint16     XCERE5:1;       // 5   Receive Channel enable bit
   uint16     XCERE6:1;       // 6   Receive Channel enable bit
   uint16     XCERE7:1;       // 7   Receive Channel enable bit
   uint16     XCERE8:1;       // 8   Receive Channel enable bit
   uint16     XCERE9:1;       // 9   Receive Channel enable bit
   uint16     XCERE10:1;      // 10  Receive Channel enable bit
   uint16     XCERE11:1;      // 11  Receive Channel enable bit
   uint16     XCERE12:1;      // 12  Receive Channel enable bit
   uint16     XCERE13:1;      // 13  Receive Channel enable bit
   uint16     XCERE14:1;      // 14  Receive Channel enable bit
   uint16     XCERE15:1;      // 15  Receive Channel enable bit
};

union XCERE_REG {
   uint16              all;
   struct  XCERE_BITS  bit;
};

// XCERF control register bit definitions:
struct  XCERF_BITS {         // bit description
   uint16     XCERF0:1;       // 0   Receive Channel enable bit
   uint16     XCERF1:1;       // 1   Receive Channel enable bit
   uint16     XCERF2:1;       // 2   Receive Channel enable bit
   uint16     XCERF3:1;       // 3   Receive Channel enable bit
   uint16     XCERF4:1;       // 4   Receive Channel enable bit
   uint16     XCERF5:1;       // 5   Receive Channel enable bit
   uint16     XCERF6:1;       // 6   Receive Channel enable bit
   uint16     XCERF7:1;       // 7   Receive Channel enable bit
   uint16     XCERF8:1;       // 8   Receive Channel enable bit
   uint16     XCERF9:1;       // 9   Receive Channel enable bit
   uint16     XCERF10:1;      // 10  Receive Channel enable bit
   uint16     XCERF11:1;      // 11  Receive Channel enable bit
   uint16     XCERF12:1;      // 12  Receive Channel enable bit
   uint16     XCERF13:1;      // 13  Receive Channel enable bit
   uint16     XCERF14:1;      // 14  Receive Channel enable bit
   uint16     XCERF15:1;      // 15  Receive Channel enable bit
};

union XCERF_REG {
   uint16              all;
   struct  XCERF_BITS  bit;
};

// RCERG control register bit definitions:
struct  RCERG_BITS {         // bit description
   uint16     RCEG0:1;       // 0   Receive Channel enable bit
   uint16     RCEG1:1;       // 1   Receive Channel enable bit
   uint16     RCEG2:1;       // 2   Receive Channel enable bit
   uint16     RCEG3:1;       // 3   Receive Channel enable bit
   uint16     RCEG4:1;       // 4   Receive Channel enable bit
   uint16     RCEG5:1;       // 5   Receive Channel enable bit
   uint16     RCEG6:1;       // 6   Receive Channel enable bit
   uint16     RCEG7:1;       // 7   Receive Channel enable bit
   uint16     RCEG8:1;       // 8   Receive Channel enable bit
   uint16     RCEG9:1;       // 9   Receive Channel enable bit
   uint16     RCEG10:1;      // 10  Receive Channel enable bit
   uint16     RCEG11:1;      // 11  Receive Channel enable bit
   uint16     RCEG12:1;      // 12  Receive Channel enable bit
   uint16     RCEG13:1;      // 13  Receive Channel enable bit
   uint16     RCEG14:1;      // 14  Receive Channel enable bit
   uint16     RCEG15:1;      // 15  Receive Channel enable bit
};

union RCERG_REG {
   uint16              all;
   struct  RCERG_BITS  bit;
};

// RCERH control register bit definitions:
struct  RCERH_BITS {         // bit description
   uint16     RCEH0:1;       // 0   Receive Channel enable bit
   uint16     RCEH1:1;       // 1   Receive Channel enable bit
   uint16     RCEH2:1;       // 2   Receive Channel enable bit
   uint16     RCEH3:1;       // 3   Receive Channel enable bit
   uint16     RCEH4:1;       // 4   Receive Channel enable bit
   uint16     RCEH5:1;       // 5   Receive Channel enable bit
   uint16     RCEH6:1;       // 6   Receive Channel enable bit
   uint16     RCEH7:1;       // 7   Receive Channel enable bit
   uint16     RCEH8:1;       // 8   Receive Channel enable bit
   uint16     RCEH9:1;       // 9   Receive Channel enable bit
   uint16     RCEH10:1;      // 10  Receive Channel enable bit
   uint16     RCEH11:1;      // 11  Receive Channel enable bit
   uint16     RCEH12:1;      // 12  Receive Channel enable bit
   uint16     RCEH13:1;      // 13  Receive Channel enable bit
   uint16     RCEH14:1;      // 14  Receive Channel enable bit
   uint16     RCEH15:1;      // 15  Receive Channel enable bit
};

union RCERH_REG {
   uint16              all;
   struct  RCERH_BITS  bit;
};

// XCERG control register bit definitions:
struct  XCERG_BITS {         // bit description
   uint16     XCERG0:1;       // 0   Receive Channel enable bit
   uint16     XCERG1:1;       // 1   Receive Channel enable bit
   uint16     XCERG2:1;       // 2   Receive Channel enable bit
   uint16     XCERG3:1;       // 3   Receive Channel enable bit
   uint16     XCERG4:1;       // 4   Receive Channel enable bit
   uint16     XCERG5:1;       // 5   Receive Channel enable bit
   uint16     XCERG6:1;       // 6   Receive Channel enable bit
   uint16     XCERG7:1;       // 7   Receive Channel enable bit
   uint16     XCERG8:1;       // 8   Receive Channel enable bit
   uint16     XCERG9:1;       // 9   Receive Channel enable bit
   uint16     XCERG10:1;      // 10  Receive Channel enable bit
   uint16     XCERG11:1;      // 11  Receive Channel enable bit
   uint16     XCERG12:1;      // 12  Receive Channel enable bit
   uint16     XCERG13:1;      // 13  Receive Channel enable bit
   uint16     XCERG14:1;      // 14  Receive Channel enable bit
   uint16     XCERG15:1;      // 15  Receive Channel enable bit
};

union XCERG_REG {
   uint16              all;
   struct  XCERG_BITS  bit;
};

// XCERH control register bit definitions:
struct  XCERH_BITS {         // bit description
   uint16     XCEH0:1;       // 0   Receive Channel enable bit
   uint16     XCEH1:1;       // 1   Receive Channel enable bit
   uint16     XCEH2:1;       // 2   Receive Channel enable bit
   uint16     XCEH3:1;       // 3   Receive Channel enable bit
   uint16     XCEH4:1;       // 4   Receive Channel enable bit
   uint16     XCEH5:1;       // 5   Receive Channel enable bit
   uint16     XCEH6:1;       // 6   Receive Channel enable bit
   uint16     XCEH7:1;       // 7   Receive Channel enable bit
   uint16     XCEH8:1;       // 8   Receive Channel enable bit
   uint16     XCEH9:1;       // 9   Receive Channel enable bit
   uint16     XCEH10:1;      // 10  Receive Channel enable bit
   uint16     XCEH11:1;      // 11  Receive Channel enable bit
   uint16     XCEH12:1;      // 12  Receive Channel enable bit
   uint16     XCEH13:1;      // 13  Receive Channel enable bit
   uint16     XCEH14:1;      // 14  Receive Channel enable bit
   uint16     XCEH15:1;      // 15  Receive Channel enable bit
};

union XCERH_REG {
   uint16              all;
   struct  XCERH_BITS  bit;
};

// McBSP Interrupt enable register for RINT/XINT
struct  MFFINT_BITS {       // bits description
    uint16     XINT:1;      // 0    XINT  interrupt enable
    uint16     rsvd1:1;     // 1    reserved
    uint16     RINT:1;      // 2    RINT  interrupt enable
    uint16     rsvd2:13;    // 15:3 reserved
};

union MFFINT_REG {
   uint16              all;
   struct MFFINT_BITS  bit;
};

//---------------------------------------------------------------------------
// McBSP Register File:
//
struct  MCBSP_REGS {
   union DRR2_REG    DRR2;       // MCBSP Data receive register bits 31-16
   union DRR1_REG    DRR1;       // MCBSP Data receive register bits 15-0
   union DXR2_REG    DXR2;       // MCBSP Data transmit register bits 31-16
   union DXR1_REG    DXR1;       // MCBSP Data transmit register bits 15-0
   union SPCR2_REG   SPCR2;      // MCBSP control register bits 31-16
   union SPCR1_REG   SPCR1;      // MCBSP control register bits 15-0
   union RCR2_REG    RCR2;       // MCBSP receive control register bits 31-16
   union RCR1_REG    RCR1;       // MCBSP receive control register bits 15-0
   union XCR2_REG    XCR2;       // MCBSP transmit control register bits 31-16
   union XCR1_REG    XCR1;       // MCBSP transmit control register bits 15-0
   union SRGR2_REG   SRGR2;      // MCBSP sample rate gen register bits 31-16
   union SRGR1_REG   SRGR1;      // MCBSP sample rate gen register bits 15-0
   union MCR2_REG    MCR2;       // MCBSP multichannel register bits 31-16
   union MCR1_REG    MCR1;       // MCBSP multichannel register bits 15-0
   union RCERA_REG   RCERA;      // MCBSP Receive channel enable partition A
   union RCERB_REG   RCERB;      // MCBSP Receive channel enable partition B
   union XCERA_REG   XCERA;      // MCBSP Transmit channel enable partition A
   union XCERB_REG   XCERB;      // MCBSP Transmit channel enable partition B
   union PCR_REG     PCR;        // MCBSP Pin control register bits 15-0
   union RCERC_REG   RCERC;      // MCBSP Receive channel enable partition C
   union RCERD_REG   RCERD;      // MCBSP Receive channel enable partition D
   union XCERC_REG   XCERC;      // MCBSP Transmit channel enable partition C
   union XCERD_REG   XCERD;      // MCBSP Transmit channel enable partition D
   union RCERE_REG   RCERE;      // MCBSP Receive channel enable partition E
   union RCERF_REG   RCERF;      // MCBSP Receive channel enable partition F
   union XCERE_REG   XCERE;      // MCBSP Transmit channel enable partition E
   union XCERF_REG   XCERF;      // MCBSP Transmit channel enable partition F
   union RCERG_REG   RCERG;      // MCBSP Receive channel enable partition G
   union RCERH_REG   RCERH;      // MCBSP Receive channel enable partition H
   union XCERG_REG   XCERG;      // MCBSP Transmit channel enable partition G
   union XCERH_REG   XCERH;      // MCBSP Transmit channel enable partition H
   uint16            rsvd1[4];   // reserved
   union MFFINT_REG  MFFINT;     // MCBSP Interrupt enable register for RINT/XINT
   uint16            rsvd2;      // reserved
};

//---------------------------------------------------------------------------
// McBSP External References & Function Declarations:
//
extern volatile struct MCBSP_REGS McbspaRegs;
extern volatile struct MCBSP_REGS McbspbRegs;

#ifdef __cplusplus
}
#endif /* extern "C" */

#endif  // end of DSP2833x_MCBSP_H definition

//===========================================================================
// No more.
//===========================================================================


text:
using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using log4net;

namespace PRTracker.Web.Components
{
    /// <summary>
    /// Authorization filter to check that the GitHub provided signature is valid for the specified content.
    /// </summary>
    /// <remarks>
    /// GitHub webhooks will pass a signature in the X-Hub-Signature header which is a SHA1 digest of the body contents.
    /// </remarks>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class GitHubAuthorizationFilter : AuthorizationFilterAttribute
    {

        public bool Active { get; private set; }
        public string Secret { get; private set; }

        public GitHubAuthorizationFilter() : this(ConfigurationManager.AppSettings["webhook-secret"], true)
        { }

        /// <summary>
        /// The GitHub Authorization filter requires a key used for signing the body of the webhook post.
        /// </summary>
        /// <param name="secret"></param>
        public GitHubAuthorizationFilter(string secret) : this(secret, true)
        { }

        /// <summary>
        /// Overriden constructor to allow explicit disabling of this
        /// filter's behavior. Pass false to disable (same as no filter
        /// but declarative)
        /// </summary>
        /// <param name="secret"></param>
        /// <param name="active"></param>
        public GitHubAuthorizationFilter(string secret, bool active)
        {
            Secret = secret;
            Active = !string.IsNullOrEmpty(secret) && active;
        }

        /// <summary>
        /// Adds a filter to verify that a valid X-Hub-Signature exists in the request header
        /// </summary>
        /// <param name="actionContext"></param>
        public override async void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);

            if (Active)
            {
                if (actionContext.Request.Headers.Contains("X-Hub-Signature"))
                {
                    var signature = actionContext.Request.Headers.GetValues("X-Hub-Signature").FirstOrDefault().Replace("sha1=", "");
                    var body = await actionContext.Request.Content.ReadAsByteArrayAsync();

                    if (VerifySignature(body, EncodingUtilities.FromHex(Secret)))
                    {
                        return;
                    }
                }

                // We did not have a valid signature
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }

        private bool VerifySignature(byte[] message, byte[] secret)
        {
            byte[] token;
            using (var hasher = new HMACSHA1(secret))
            {
                token = hasher.ComputeHash(message);
            }

            var log = LogManager.GetLogger("PRTracker");
            log.InfoFormat("Signature: {0}, Token: {1}", secret, token);

            return (secret == token);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "Logger.hh"

namespace Core
{
/****************
 * Old Logger implementation
 */

Logger::Logger(const std::string & LogPrefix,int indentlvl, int indentwidth)
        : _indentlvl(indentlvl), _indentwidth(indentwidth),_logprefix(LogPrefix)
{
    _consoleLog = true;
    _fileLog = false;

#ifdef DEBUG

    std::clog << std::endl << "Logger created : " << _logprefix << std::endl;
#endif

}

//TO TEST
bool Logger::setLogfile( const std::string & filename)
{
    bool res=true;
    _ofstr.open(filename.c_str(),std::ofstream::out);
    if (!_ofstr )
    {
        *this << "Logger ERROR : Failed to open " << filename ;
        res=false;
    }
    return res;
}

Logger& nl (Logger& log) // adds a new line with the prefix
{
    std::string s(log._indentlvl * log._indentwidth, ' ');
    s +=log._logprefix + " : ";

    log << "\n" << s;
    return log;
}

Logger & Logger::flush(void)
{

    if (_consoleLog)
        std::clog.flush();
    if (_fileLog)
        _ofstr.flush();
    return *this;
}

//to enable ostream manipulators on Logger
Logger& Logger::operator << (std::ostream& (*manip)(std::ostream&))
{
    if (_consoleLog)
        (*manip)(std::clog);
    if (_fileLog)
        (*manip)(_ofstr);
    return *this;
}

//to enable ios manipulators on Logger
Logger& Logger::operator << (std::ios_base& (*manip)(std::ios_base&))
{
    if (_consoleLog)
        (*manip)(std::clog);
    if (_fileLog)
        (*manip)(_ofstr);
    return *this;
}

//to enable ostream manipulators on Logger
Logger& Logger::operator << (Logger& (*manip)(Logger&))
{
    (*manip)(*this);
    return *this;
}

Logger::~Logger()
{
    flush();
#ifdef DEBUG

    std::clog << std::endl << "Logger terminated : " << _logprefix << std::endl;
#endif

}

} // Core


text:
from google.cloud import functions_v1

def sample_generate_download_url():
    # Create a client
    client = functions_v1.CloudFunctionsServiceClient()

    # Initialize request argument(s)
    request = functions_v1.GenerateDownloadUrlRequest(
    )

    # Make the request
    response = client.generate_download_url(request=request)

    # Handle the response
    print(response)

# [END cloudfunctions_v1_generated_CloudFunctionsService_GenerateDownloadUrl_sync]


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Interview.BinarySearch;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Interview.BinarySearch.Tests
{
    [TestClass]
    public class BinarySearchTests
    {
        private enum SearchType
        {
            SimpleApproach
        }

        private static class SearchFactory
        {
            public static IBinarySearch CreateSearch(SearchType type, IEnumerable<int> values)
            {
                switch (type)
                {
                    case SearchType.SimpleApproach:
                        return new SimpleApproach(values);
                    default:
                        return null;
                }
            }
        }

        private const SearchType _typeToTest = SearchType.SimpleApproach;

        [TestMethod]
        public void BinarySearch_SearchForExistingElementOddLength()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1, 3, 5, 7, 9, 11, 13 });

            int result = c.BinarySearch(5);

            Assert.AreEqual<int>(2, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForExistingElementEvenLength()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1, 3, 5, 7, 9, 11 });

            int result = c.BinarySearch(9);

            Assert.AreEqual<int>(4, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForExistingElementInTwoElementsArray()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1, 3 });

            int result = c.BinarySearch(3);

            Assert.AreEqual<int>(1, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForNonExistingElementInTwoElementsArray()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 7, 9 });

            int result = c.BinarySearch(8);

            Assert.AreEqual<int>(-1, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForMaxElement()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1, 3, 5, 7, 9, 11, 13 });

            int result = c.BinarySearch(13);

            Assert.AreEqual<int>(6, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForMinElement()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1, 3, 5, 7, 9, 11, 13 });

            int result = c.BinarySearch(1);

            Assert.AreEqual<int>(0, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForExistingElementArrayWithEqualElements()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1, 1, 1, 1, 1, 1 });

            int result = c.BinarySearch(1);

            Assert.AreEqual<int>(3, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForNonexistingValueBiggerThanMax()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1, 3, 5, 7, 9, 11, 13 });

            int result = c.BinarySearch(15);

            Assert.AreEqual<int>(-1, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForNonexistingValueSmallerThanMin()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1, 3, 5, 7, 9, 11, 13 });

            int result = c.BinarySearch(0);

            Assert.AreEqual<int>(-1, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForExistingElementInOneElementArray()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1 });

            int result = c.BinarySearch(1);

            Assert.AreEqual<int>(0, result);
        }

        [TestMethod]
        public void BinarySearch_SearchForNonExistingElementInOneElementArray()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { 1 });

            int result = c.BinarySearch(2);

            Assert.AreEqual<int>(-1, result);
        }

        [TestMethod]
        public void BinarySearch_SearchInEmptyArray()
        {
            IBinarySearch c = SearchFactory.CreateSearch(_typeToTest, new int[] { });

            int result = c.BinarySearch(2);

            Assert.AreEqual<int>(-1, result);
        }
    }
}


text:
NSString *OFMD5HexStringFromNSString(NSString *inStr)
{
    const char *data = [inStr UTF8String];
    CC_LONG length = (CC_LONG) strlen(data);

    unsigned char *md5buf = (unsigned char*)calloc(1, CC_MD5_DIGEST_LENGTH);

    CC_MD5_CTX md5ctx;
    CC_MD5_Init(&md5ctx);
    CC_MD5_Update(&md5ctx, data, length);
    CC_MD5_Final(md5buf, &md5ctx);

    NSMutableString *md5hex = [NSMutableString string];
	size_t i;
    for (i = 0 ; i < CC_MD5_DIGEST_LENGTH ; i++) {
        [md5hex appendFormat:@"%02x", md5buf[i]];
    }
    free(md5buf);
    return md5hex;
}

NSString *OFEscapedURLStringFromNSString(NSString *inStr)
{
	return OFEscapedURLStringFromNSStringWithExtraEscapedChars(inStr, @"&");
}

NSString *OFEscapedURLStringFromNSStringWithExtraEscapedChars(NSString *inStr, NSString *inEscChars)
{
	CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)inStr, NULL, (CFStringRef)inEscChars, kCFStringEncodingUTF8);

#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
	return (NSString *)[(NSString*)escaped autorelease];
#else
	return (NSString *)[NSMakeCollectable(escaped) autorelease];
#endif
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-prototypes"
NSString *OFGenerateUUIDString()
{
#pragma clang diagnostic pop
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
    CFRelease(uuid);

#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
	return (NSString *)[(NSString*)uuidStr autorelease];
#else
	return (NSString *)[NSMakeCollectable(uuidStr) autorelease];
#endif
}

static NSData *OFSha1(NSData *inData)
{
    NSMutableData *result = [NSMutableData dataWithLength:CC_SHA1_DIGEST_LENGTH];
    CC_SHA1_CTX context;
    CC_SHA1_Init(&context);
    CC_SHA1_Update(&context, [inData bytes], (CC_LONG)[inData length]);
    CC_SHA1_Final([result mutableBytes], &context);
    return result;
}

static char *NewBase64Encode(const void *buffer, size_t length, bool separateLines, size_t *outputLength);

// http://en.wikipedia.org/wiki/HMAC
NSString *OFHMACSha1Base64(NSString *inKey, NSString *inMessage)
{
    NSData *keyData = [inKey dataUsingEncoding:NSUTF8StringEncoding];

    if ([keyData length] > CC_SHA1_BLOCK_BYTES) {
        keyData = OFSha1(keyData);
    }

    if ([keyData length] < CC_SHA1_BLOCK_BYTES) {
        NSUInteger padSize = CC_SHA1_BLOCK_BYTES - [keyData length];

        NSMutableData *paddedData = [NSMutableData dataWithData:keyData];
        [paddedData appendData:[NSMutableData dataWithLength:padSize]];
        keyData  = paddedData;
    }

    NSMutableData *oKeyPad = [NSMutableData dataWithLength:CC_SHA1_BLOCK_BYTES];
    NSMutableData *iKeyPad = [NSMutableData dataWithLength:CC_SHA1_BLOCK_BYTES];

    const uint8_t *kdPtr = [keyData bytes];
    uint8_t *okpPtr = [oKeyPad mutableBytes];
    uint8_t *ikpPtr = [iKeyPad mutableBytes];

    memset(okpPtr, 0x5c, CC_SHA1_BLOCK_BYTES);
    memset(ikpPtr, 0x36, CC_SHA1_BLOCK_BYTES);

    NSUInteger i;
    for (i = 0; i < CC_SHA1_BLOCK_BYTES; i++) {
        okpPtr[i] = okpPtr[i] ^ kdPtr[i];
        ikpPtr[i] = ikpPtr[i] ^ kdPtr[i];
    }

    NSData *msgData = [inMessage dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableData *innerData = [NSMutableData dataWithData:iKeyPad];
    [innerData appendData:msgData];
    NSData *innerDataHashed = OFSha1(innerData);

    NSMutableData *outerData = [NSMutableData dataWithData:oKeyPad];
    [outerData appendData:innerDataHashed];

    NSData *outerHashedData = OFSha1(outerData);

	size_t outputLength;
	char *outputBuffer = NewBase64Encode([outerHashedData bytes], [outerHashedData length], true, &outputLength);

	NSString *result = [[[NSString alloc] initWithBytes:outputBuffer length:outputLength encoding:NSASCIIStringEncoding] autorelease];
	free(outputBuffer);
	return result;
}

NSDictionary *OFExtractURLQueryParameter(NSString *inQuery)
{
    if (![inQuery length]) {
        return nil;
    }

    NSArray *params = [inQuery componentsSeparatedByString:@"&"];

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    for (NSString *p in params) {
        NSArray *kv = [p componentsSeparatedByString:@"="];
        if ([kv count] != 2) {
            return nil;
        }

        [dict setObject:[kv objectAtIndex:1] forKey:[kv objectAtIndex:0]];
    }
    return dict;
}

BOOL OFExtractOAuthCallback(NSURL *inReceivedURL, NSURL *inBaseURL, NSString **outRequestToken, NSString **outVerifier)
{
    assert(outRequestToken && "outRequestToken cannot be nil");
    assert(outVerifier && "outVerifier cannot be nil");

    NSString *ruStr = [inReceivedURL absoluteString];
    NSString *buStr = [[inBaseURL absoluteString] stringByAppendingString:@"?"];

    if (![ruStr hasPrefix:buStr]) {
        return NO;
    }

    NSString *query = [ruStr substringFromIndex:[buStr length]];
    if (![query length]) {
        return NO;
    }

    NSDictionary *dict = OFExtractURLQueryParameter(query);
    if (!dict) {
        return NO;
    }

    NSString *t = [dict objectForKey:@"oauth_token"];
    NSString *v = [dict objectForKey:@"oauth_verifier"];

    if (!t || !v) {
        return NO;
    }

    *outRequestToken = [[t copy] autorelease];
    *outVerifier = [[v copy] autorelease];
    return YES;
}

// From http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html
//
// License header:
//
//  Created by Matt Gallagher on 2009/06/03.
//  Copyright 2009 Matt Gallagher. All rights reserved.
//
//  This software is provided 'as-is', without any express or implied
//  warranty. In no event will the authors be held liable for any damages
//  arising from the use of this software. Permission is granted to anyone to
//  use this software for any purpose, including commercial applications, and to
//  alter it and redistribute it freely, subject to the following restrictions:
//
//  1. The origin of this software must not be misrepresented; you must not
//     claim that you wrote the original software. If you use this software
//     in a product, an acknowledgment in the product documentation would be
//     appreciated but is not required.
//  2. Altered source versions must be plainly marked as such, and must not be
//     misrepresented as being the original software.
//  3. This notice may not be removed or altered from any source
//     distribution.
//

//
// Mapping from 6 bit pattern to ASCII character.
//
static unsigned char base64EncodeLookup[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

//
// Fundamental sizes of the binary and base64 encode/decode units in bytes
//
#define BINARY_UNIT_SIZE 3
#define BASE64_UNIT_SIZE 4

//
// NewBase64Encode
//
// Encodes the arbitrary data in the inputBuffer as base64 into a newly malloced
// output buffer.
//
//  inputBuffer - the source data for the encode
//	length - the length of the input in bytes
//  separateLines - if zero, no CR/LF characters will be added. Otherwise
//		a CR/LF pair will be added every 64 encoded chars.
//	outputLength - if not-NULL, on output will contain the encoded length
//		(not including terminating 0 char)
//
// returns the encoded buffer. Must be free'd by caller. Length is given by
//	outputLength.
//
static char *NewBase64Encode(
                      const void *buffer,
                      size_t length,
                      bool separateLines,
                      size_t *outputLength)
{
	const unsigned char *inputBuffer = (const unsigned char *)buffer;

#define MAX_NUM_PADDING_CHARS 2
#define OUTPUT_LINE_LENGTH 64
#define INPUT_LINE_LENGTH ((OUTPUT_LINE_LENGTH / BASE64_UNIT_SIZE) * BINARY_UNIT_SIZE)
#define CR_LF_SIZE 2

	//
	// Byte accurate calculation of final buffer size
	//
	size_t outputBufferSize =
    ((length / BINARY_UNIT_SIZE)
     + ((length % BINARY_UNIT_SIZE) ? 1 : 0))
    * BASE64_UNIT_SIZE;
	if (separateLines)
	{
		outputBufferSize +=
        (outputBufferSize / OUTPUT_LINE_LENGTH) * CR_LF_SIZE;
	}

	//
	// Include space for a terminating zero
	//
	outputBufferSize += 1;

	//
	// Allocate the output buffer
	//
	char *outputBuffer = (char *)malloc(outputBufferSize);
	if (!outputBuffer)
	{
		return NULL;
	}

	size_t i = 0;
	size_t j = 0;
	const size_t lineLength = separateLines ? INPUT_LINE_LENGTH : length;
	size_t lineEnd = lineLength;

	while (true)
	{
		if (lineEnd > length)
		{
			lineEnd = length;
		}

		for (; i + BINARY_UNIT_SIZE - 1 < lineEnd; i += BINARY_UNIT_SIZE)
		{
			//
			// Inner loop: turn 48 bytes into 64 base64 characters
			//
			outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2];
			outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i] & 0x03) << 4)
                                                   | ((inputBuffer[i + 1] & 0xF0) >> 4)];
			outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i + 1] & 0x0F) << 2)
                                                   | ((inputBuffer[i + 2] & 0xC0) >> 6)];
			outputBuffer[j++] = base64EncodeLookup[inputBuffer[i + 2] & 0x3F];
		}

		if (lineEnd == length)
		{
			break;
		}

		//
		// Add the newline
		//
		outputBuffer[j++] = '\r';
		outputBuffer[j++] = '\n';
		lineEnd += lineLength;
	}

	if (i + 1 < length)
	{
		//
		// Handle the single '=' case
		//
		outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2];
		outputBuffer[j++] = base64EncodeLookup[((inputBuffer[i] & 0x03) << 4)
                                               | ((inputBuffer[i + 1] & 0xF0) >> 4)];
		outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i + 1] & 0x0F) << 2];
		outputBuffer[j++] =	'=';
	}
	else if (i < length)
	{
		//
		// Handle the double '=' case
		//
		outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0xFC) >> 2];
		outputBuffer[j++] = base64EncodeLookup[(inputBuffer[i] & 0x03) << 4];
		outputBuffer[j++] = '=';
		outputBuffer[j++] = '=';
	}
	outputBuffer[j] = 0;

	//
	// Set the output length and return the buffer
	//
	if (outputLength)
	{
		*outputLength = j;
	}
	return outputBuffer;
}


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_MeshFilter : LuaObject {
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int constructor(IntPtr l) {
		try {
			UnityEngine.MeshFilter o;
			o=new UnityEngine.MeshFilter();
			pushValue(l,true);
			pushValue(l,o);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int get_mesh(IntPtr l) {
		try {
			UnityEngine.MeshFilter self=(UnityEngine.MeshFilter)checkSelf(l);
			pushValue(l,true);
			pushValue(l,self.mesh);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int set_mesh(IntPtr l) {
		try {
			UnityEngine.MeshFilter self=(UnityEngine.MeshFilter)checkSelf(l);
			UnityEngine.Mesh v;
			checkType(l,2,out v);
			self.mesh=v;
			pushValue(l,true);
			return 1;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int get_sharedMesh(IntPtr l) {
		try {
			UnityEngine.MeshFilter self=(UnityEngine.MeshFilter)checkSelf(l);
			pushValue(l,true);
			pushValue(l,self.sharedMesh);
			return 2;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int set_sharedMesh(IntPtr l) {
		try {
			UnityEngine.MeshFilter self=(UnityEngine.MeshFilter)checkSelf(l);
			UnityEngine.Mesh v;
			checkType(l,2,out v);
			self.sharedMesh=v;
			pushValue(l,true);
			return 1;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	static public void reg(IntPtr l) {
		getTypeTable(l,"UnityEngine.MeshFilter");
		addMember(l,"mesh",get_mesh,set_mesh,true);
		addMember(l,"sharedMesh",get_sharedMesh,set_sharedMesh,true);
		createTypeMetatable(l,constructor, typeof(UnityEngine.MeshFilter),typeof(UnityEngine.Component));
	}
}


text:
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy import orm
from sqlalchemy.sql import functions as sql_func

from airflow import configuration

class Connection:

    def __init__(self, db_url=None):
        if db_url is None:
            db_url = configuration.get('data-factory', 'DATA_CATALOG_SQL_ALCHEMY_CONN')

        self.Base = automap_base()
        self.engine = create_engine(db_url)
        self.Base.prepare(self.engine, reflect=True)

        self.ParticipantMapping = self.Base.classes.participant_mapping
        self.Participant = self.Base.classes.participant
        self.Visit = self.Base.classes.visit
        self.VisitMapping = self.Base.classes.visit_mapping
        self.DataFile = self.Base.classes.data_file
        self.Session = self.Base.classes.session
        self.SequenceType = self.Base.classes.sequence_type
        self.Sequence = self.Base.classes.sequence
        self.Repetition = self.Base.classes.repetition
        self.ProcessingStep = self.Base.classes.processing_step
        self.Provenance = self.Base.classes.provenance

        self.db_session = orm.Session(self.engine)

    def close(self):
        self.db_session.close()

    def get_dataset(self, step_id):
        provenance_id = self.db_session.query(self.ProcessingStep).filter_by(id=step_id).first().provenance_id
        return self.db_session.query(self.Provenance).filter_by(id=provenance_id).first().dataset

    def new_participant_id(self):
        try:
            return self.db_session.query(
                sql_func.max(self.ParticipantMapping.participant_id).label('max')).one().max + 1
        except TypeError:
            return 1

    def get_participant_id(self, participant_name, dataset):
        participant_name = str(participant_name)
        participant = self.db_session.query(self.ParticipantMapping).filter_by(
            dataset=dataset, name=participant_name).one_or_none()
        if not participant:
            participant = self.ParticipantMapping(dataset=dataset, name=participant_name,
                                                  participant_id=self.new_participant_id())
            self.db_session.merge(participant)
            self.db_session.commit()
        return participant.participant_id

    def new_visit_id(self):
        try:
            return self.db_session.query(
                sql_func.max(self.VisitMapping.visit_id).label('max')).one().max + 1
        except TypeError:
            return 1

    def get_visit_id(self, visit_name, dataset):
        import logging
        logging.basicConfig(level=logging.INFO)
        logging.debug("VISIT : v_name=%s, ds=%s" % (str(visit_name), dataset))
        visit_name = str(visit_name)
        visit = self.db_session.query(self.VisitMapping).filter_by(
            dataset=dataset, name=visit_name).one_or_none()
        if not visit:
            logging.debug("VISIT : visit was not found in db")
            visit = self.VisitMapping(dataset=dataset, name=visit_name, visit_id=self.new_visit_id())
            self.db_session.merge(visit)
            self.db_session.commit()
        logging.debug("returning visit_id "+str(visit.visit_id))
        return visit.visit_id

    def get_session_id(self, session_name, visit_id):
        session_name = str(session_name)
        session = self.db_session.query(self.Session).filter_by(
            name=session_name, visit_id=visit_id).one_or_none()
        if not session:
            session = self.Session(name=session_name, visit_id=visit_id)
            self.db_session.merge(session)
            self.db_session.commit()
        return session.id

    def get_sequence_id(self, sequence_name, session_id):
        sequence_name = str(sequence_name)
        sequence = self.db_session.query(self.Sequence).filter_by(
            name=sequence_name, session_id=session_id).one_or_none()
        if not sequence:
            sequence = self.Sequence(name=sequence_name, session_id=session_id)
            self.db_session.merge(sequence)
            self.db_session.commit()
        return sequence.id

    def get_repetition_id(self, repetition_name, sequence_id):
        repetition_name = str(repetition_name)
        repetition = self.db_session.query(self.Repetition).filter_by(
            name=repetition_name, sequence_id=sequence_id).one_or_none()
        if not repetition:
            repetition = self.Repetition(name=repetition_name, sequence_id=sequence_id)
            self.db_session.merge(repetition)
            self.db_session.commit()
        return repetition.id

    def get_patient_map(self, patient_id):
        patient_map = self.db_session.query(self.ParticipantMapping).filter_by(participant_id=patient_id).one_or_none()
        return patient_map.name, patient_map.dataset

    def get_visit_map(self, visit_id):
        visit_map = self.db_session.query(self.VisitMapping).filter_by(visit_id=visit_id).one_or_none()
        return visit_map.name, visit_map.dataset


text:
package com.github.fakemongo.impl.aggregation;

import com.github.fakemongo.impl.ExpressionParser;
import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Created by rkolliva
 * 1/28/17.
 */

public class ReplaceRoot extends PipelineKeyword {

  private static final Logger LOGGER = LoggerFactory.getLogger(ReplaceRoot.class);

  public static ReplaceRoot INSTANCE = new ReplaceRoot();

  @Override
  public DBCollection apply(DB originalDB, DBCollection parentColl, DBObject replaceRootQuery) {
    LOGGER.trace(">>>> applying $replaceRoot pipeline operation");

    DBObject newRoot = ExpressionParser.toDbObject(replaceRootQuery.get(getKeyword()));
    LOGGER.trace("<<<< applying $replaceRoot pipeline operation");
    List<DBObject> dbObjects = replaceRootFromDocument(parentColl, newRoot);
    return dropAndInsert(parentColl, dbObjects);
  }

  private List<DBObject> replaceRootFromDocument(DBCollection parentColl, DBObject replaceRootExpr) {
    Object replaceRootExprValue = replaceRootExpr.get("newRoot");
    validateNull(replaceRootExprValue, "newRoot expression cannot be null");
    List<DBObject> retval = new ArrayList<DBObject>();
    if(replaceRootExprValue instanceof String) {
      String newRootValue = (String)replaceRootExprValue;
      int index = 0;
      validateTrue(newRootValue.charAt(0) == '$', "Field path expression for newRoot must start with $");
      newRootValue = newRootValue.substring(1);
      DBCursor cursor = parentColl.find();
      while(cursor.hasNext()) {
        DBObject object = cursor.next();
        Object embeddedDoc = object.get(newRootValue);
        validateNull(embeddedDoc, newRootValue + " is missing in collection at index " + index);
        validateTrue(DBObject.class.isAssignableFrom(embeddedDoc.getClass()),
                     "Embedded value must evaluate to document at " + index);
        index++;
        retval.add((DBObject) embeddedDoc);
      }
      return retval;
    }
    else {
      DBObject newRootExpr = ExpressionParser.toDbObject(replaceRootExprValue);
      String projectionExpr = "{$project :".concat(newRootExpr.toString()).concat("}");
      DBObject projection = ExpressionParser.toDbObject(BasicDBObject.parse(projectionExpr));
      AggregationOutput aggregationOutput = parentColl.aggregate(Arrays.asList(projection));
      Iterable<DBObject> results = aggregationOutput.results();
      validateNull(results, "Expression for new root resulted in a null object");
      for (DBObject result : results) {
        retval.add(result);
      }
    }

    return retval;
  }

  @Override
  public String getKeyword() {
    return "$replaceRoot";
  }
}


text:
require 'vagrant'

module VagrantPlugins
  module OVirtProvider

    # This is the base class for a provider for the V2 API. A provider
    # is responsible for creating compute resources to match the
    # needs of a Vagrant-configured system.
    class Provider < Vagrant.plugin('2', :provider)
      def initialize(machine)
        @machine = machine
      end

      # This should return an action callable for the given name.
      def action(name)
        # Attempt to get the action method from the Action class if it
        # exists, otherwise return nil to show that we don't support the
        # given action.
        action_method = "action_#{name}"
        return Action.send(action_method) if Action.respond_to?(action_method)
        nil
      end

      # This method is called if the underying machine ID changes. Providers
      # can use this method to load in new data for the actual backing
      # machine or to realize that the machine is now gone (the ID can
      # become `nil`).
      def machine_id_changed
      end

      # This should return a hash of information that explains how to
      # SSH into the machine. If the machine is not at a point where
      # SSH is even possible, then `nil` should be returned.
      def ssh_info
        # Run a custom action called "read_ssh_info" which does what it says
        # and puts the resulting SSH info into the `:machine_ssh_info` key in
        # the environment.
        #
        # Ssh info has following format..
        #
        #{
        #  :host => "1.2.3.4",
        #  :port => "22",
        #  :username => "mitchellh",
        #  :private_key_path => "/path/to/my/key"
        #}
        env = @machine.action("read_ssh_info")
        env[:machine_ssh_info]
      end

      # This should return the state of the machine within this provider.
      # The state must be an instance of {MachineState}.
      def state
        # Run a custom action we define called "read_state" which does
        # what it says. It puts the state in the `:machine_state_id`
        # key in the environment.
        env = @machine.action("read_state")

        state_id = env[:machine_state_id]

        # Get the short and long description
        short = I18n.t("vagrant_ovirt3.states.short_#{state_id}")
        long  = I18n.t("vagrant_ovirt3.states.long_#{state_id}")

        # Return the MachineState object
        Vagrant::MachineState.new(state_id, short, long)
      end

      def to_s
        id = @machine.id.nil? ? "new" : @machine.id
        "oVirt (#{id})"
      end
    end
  end
end


text:
var Db = require('./db').Db
  , Server = require('./connection/server').Server
  , Mongos = require('./connection/mongos').Mongos
  , ReplSet = require('./connection/repl_set/repl_set').ReplSet
  , ReadPreference = require('./connection/read_preference').ReadPreference
  , inherits = require('util').inherits
  , EventEmitter = require('events').EventEmitter
  , parse = require('./connection/url_parser').parse;

/**
 * Create a new MongoClient instance.
 *
 * Options
 *  - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
 *  - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
 *  - **fsync**, (Boolean, default:false) write waits for fsync before returning
 *  - **journal**, (Boolean, default:false) write waits for journal sync before returning
 *  - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
 *  - **native_parser** {Boolean, default:false}, use c++ bson parser.
 *  - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client.
 *  - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
 *  - **serializeFunctions** {Boolean, default:false}, serialize functions.
 *  - **raw** {Boolean, default:false}, peform operations using raw bson buffers.
 *  - **recordQueryStats** {Boolean, default:false}, record query statistics during execution.
 *  - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries.
 *  - **numberOfRetries** {Number, default:5}, number of retries off connection.
 *
 * Deprecated Options
 *  - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
 *
 * @class Represents a MongoClient
 * @param {Object} serverConfig server config object.
 * @param {Object} [options] additional options for the collection.
 */
function MongoClient(serverConfig, options) {
  if(serverConfig != null) {
    options = options == null ? {} : options;
    // If no write concern is set set the default to w:1
    if(options != null && !options.journal && !options.w && !options.fsync) {
      options.w = 1;
    }

    // The internal db instance we are wrapping
    this._db = new Db('test', serverConfig, options);
  }
}

/**
 * @ignore
 */
inherits(MongoClient, EventEmitter);

/**
 * Connect to MongoDB using a url as documented at
 *
 *  docs.mongodb.org/manual/reference/connection-string/
 *
 * Options
 *  - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication
 *  - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor**
 *  - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor**
 *  - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor**
 *  - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor**
 *
 * @param {String} url connection url for MongoDB.
 * @param {Object} [options] optional options for insert command
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.
 * @return {null}
 * @api public
 */
MongoClient.prototype.connect = function(url, options, callback) {
  var self = this;

  if(typeof options == 'function') {
    callback = options;
    options = {};
  }

  MongoClient.connect(url, options, function(err, db) {
    if(err) return callback(err, db);
    // Store internal db instance reference
    self._db = db;
    // Emit open and perform callback
    self.emit("open", err, db);
    callback(err, db);
  });
}

/**
 * Initialize the database connection.
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the connected mongoclient or null if an error occured.
 * @return {null}
 * @api public
 */
MongoClient.prototype.open = function(callback) {
  // Self reference
  var self = this;
  // Open the db
  this._db.open(function(err, db) {
    if(err) return callback(err, null);
    // Emit open event
    self.emit("open", err, db);
    // Callback
    callback(null, self);
  })
}

/**
 * Close the current db connection, including all the child db instances. Emits close event if no callback is provided.
 *
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the close method or null if an error occured.
 * @return {null}
 * @api public
 */
MongoClient.prototype.close = function(callback) {
  this._db.close(callback);
}

/**
 * Create a new Db instance sharing the current socket connections.
 *
 * @param {String} dbName the name of the database we want to use.
 * @return {Db} a db instance using the new database.
 * @api public
 */
MongoClient.prototype.db = function(dbName) {
  return this._db.db(dbName);
}

/**
 * Connect to MongoDB using a url as documented at
 *
 *  docs.mongodb.org/manual/reference/connection-string/
 *
 * Options
 *  - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication
 *  - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor**
 *  - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor**
 *  - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor**
 *  - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor**
 *
 * @param {String} url connection url for MongoDB.
 * @param {Object} [options] optional options for insert command
 * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.
 * @return {null}
 * @api public
 */
MongoClient.connect = function(url, options, callback) {
  var args = Array.prototype.slice.call(arguments, 1);
  callback = typeof args[args.length - 1] == 'function' ? args.pop() : null;
  options = args.length ? args.shift() : null;
  options = options || {};

  // Set default empty server options
  var serverOptions = options.server || {};
  var mongosOptions = options.mongos || {};
  var replSetServersOptions = options.replSet || options.replSetServers || {};
  var dbOptions = options.db || {};

  // If callback is null throw an exception
  if(callback == null)
    throw new Error("no callback function provided");

  // Parse the string
  var object = parse(url, options);
  // Merge in any options for db in options object
  if(dbOptions) {
    for(var name in dbOptions) object.db_options[name] = dbOptions[name];
  }

  // Added the url to the options
  object.db_options.url = url;

  // Merge in any options for server in options object
  if(serverOptions) {
    for(var name in serverOptions) object.server_options[name] = serverOptions[name];
  }

  // Merge in any replicaset server options
  if(replSetServersOptions) {
    for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name];
  }

  // Merge in any replicaset server options
  if(mongosOptions) {
    for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name];
  }

  // We need to ensure that the list of servers are only either direct members or mongos
  // they cannot be a mix of monogs and mongod's
  var totalNumberOfServers = object.servers.length;
  var totalNumberOfMongosServers = 0;
  var totalNumberOfMongodServers = 0;
  var serverConfig = null;
  var errorServers = {};

  // Failure modes
  if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host");

  // If we have no db setting for the native parser try to set the c++ one first
  object.db_options.native_parser = _setNativeParser(object.db_options);
  // If no auto_reconnect is set, set it to true as default for single servers
  if(typeof object.server_options.auto_reconnect != 'boolean') {
    object.server_options.auto_reconnect = true;
  }

  // If we have more than a server, it could be replicaset or mongos list
  // need to verify that it's one or the other and fail if it's a mix
  // Connect to all servers and run ismaster
  for(var i = 0; i < object.servers.length; i++) {
    // Set up socket options
    var _server_options = {poolSize:1, socketOptions:{connectTimeoutMS:1000}, auto_reconnect:false};

    // Ensure we have ssl setup for the servers
    if(object.rs_options.ssl) {
      _server_options.ssl = object.rs_options.ssl;
      _server_options.sslValidate = object.rs_options.sslValidate;
      _server_options.sslCA = object.rs_options.sslCA;
      _server_options.sslCert = object.rs_options.sslCert;
      _server_options.sslKey = object.rs_options.sslKey;
      _server_options.sslPass = object.rs_options.sslPass;
    } else if(object.server_options.ssl) {
      _server_options.ssl = object.server_options.ssl;
      _server_options.sslValidate = object.server_options.sslValidate;
      _server_options.sslCA = object.server_options.sslCA;
      _server_options.sslCert = object.server_options.sslCert;
      _server_options.sslKey = object.server_options.sslKey;
      _server_options.sslPass = object.server_options.sslPass;
    }

    // Set up the Server object
    var _server = object.servers[i].domain_socket
	? new Server(object.servers[i].domain_socket, _server_options)
	: new Server(object.servers[i].host, object.servers[i].port, _server_options);

    var connectFunction = function(__server) {
      // Attempt connect
      new Db(object.dbName, __server, {safe:false, native_parser:false}).open(function(err, db) {
	// Update number of servers
	totalNumberOfServers = totalNumberOfServers - 1;
	// If no error do the correct checks
	if(!err) {
	  // Close the connection
	  db.close(true);
	  var isMasterDoc = db.serverConfig.isMasterDoc;
	  // Check what type of server we have
	  if(isMasterDoc.setName) totalNumberOfMongodServers++;
	  if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++;
	} else {
	  errorServers[__server.host + ":" + __server.port] = __server;
	}

	if(totalNumberOfServers == 0) {
	  // If we have a mix of mongod and mongos, throw an error
	  if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) {
	    return process.nextTick(function() {
	      try {
		callback(new Error("cannot combine a list of replicaset seeds and mongos seeds"));
	      } catch (err) {
		if(db) db.close();
		throw err
	      }
	    })
	  }

	  if(totalNumberOfMongodServers == 0 && object.servers.length == 1) {
	    var obj = object.servers[0];
	    serverConfig = obj.domain_socket ?
		new Server(obj.domain_socket, object.server_options)
	      : new Server(obj.host, obj.port, object.server_options);
	  } else if(totalNumberOfMongodServers > 0 || totalNumberOfMongosServers > 0) {
	    var finalServers = object.servers
	      .filter(function(serverObj) {
		return errorServers[serverObj.host + ":" + serverObj.port] == null;
	      })
	      .map(function(serverObj) {
		  return new Server(serverObj.host, serverObj.port, object.server_options);
	      });
	    // Clean out any error servers
	    errorServers = {};
	    // Set up the final configuration
	    if(totalNumberOfMongodServers > 0) {
	      serverConfig = new ReplSet(finalServers, object.rs_options);
	    } else {
	      serverConfig = new Mongos(finalServers, object.mongos_options);
	    }
	  }

	  if(serverConfig == null) {
	    return process.nextTick(function() {
	      try {
		callback(new Error("Could not locate any valid servers in initial seed list"));
	      } catch (err) {
		if(db) db.close();
		throw err
	      }
	    });
	  }
	  // Ensure no firing off open event before we are ready
	  serverConfig.emitOpen = false;
	  // Set up all options etc and connect to the database
	  _finishConnecting(serverConfig, object, options, callback)
	}
      });
    }

    // Wrap the context of the call
    connectFunction(_server);
  }
}

var _setNativeParser = function(db_options) {
  if(typeof db_options.native_parser == 'boolean') return db_options.native_parser;

  try {
    require('bson').BSONNative.BSON;
    return true;
  } catch(err) {
    return false;
  }
}

var _finishConnecting = function(serverConfig, object, options, callback) {
  // Safe settings
  var safe = {};
  // Build the safe parameter if needed
  if(object.db_options.journal) safe.j = object.db_options.journal;
  if(object.db_options.w) safe.w = object.db_options.w;
  if(object.db_options.fsync) safe.fsync = object.db_options.fsync;
  if(object.db_options.wtimeoutMS) safe.wtimeout = object.db_options.wtimeoutMS;

  // If we have a read Preference set
  if(object.db_options.read_preference) {
    var readPreference = new ReadPreference(object.db_options.read_preference);
    // If we have the tags set up
    if(object.db_options.read_preference_tags)
      readPreference = new ReadPreference(object.db_options.read_preference, object.db_options.read_preference_tags);
    // Add the read preference
    object.db_options.readPreference = readPreference;
  }

  // No safe mode if no keys
  if(Object.keys(safe).length == 0) safe = false;

  // Add the safe object
  object.db_options.safe = safe;

  // Set up the db options
  var db = new Db(object.dbName, serverConfig, object.db_options);
  // Open the db
  db.open(function(err, db){
    if(err) {
      return process.nextTick(function() {
	try {
	  callback(err, null);
	} catch (err) {
	  if(db) db.close();
	  throw err
	}
      });
    }

    if(db.options !== null && !db.options.safe && !db.options.journal
      && !db.options.w && !db.options.fsync && typeof db.options.w != 'number'
      && (db.options.safe == false && object.db_options.url.indexOf("safe=") == -1)) {
	db.options.w = 1;
    }

    if(err == null && object.auth){
      // What db to authenticate against
      var authentication_db = db;
      if(object.db_options && object.db_options.authSource) {
	authentication_db = db.db(object.db_options.authSource);
      }

      // Build options object
      var options = {};
      if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism;
      if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName;

      // Authenticate
      authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){
	if(success){
	  process.nextTick(function() {
	    try {
	      callback(null, db);
	    } catch (err) {
	      if(db) db.close();
	      throw err
	    }
	  });
	} else {
	  if(db) db.close();
	  process.nextTick(function() {
	    try {
	      callback(err ? err : new Error('Could not authenticate user ' + auth[0]), null);
	    } catch (err) {
	      if(db) db.close();
	      throw err
	    }
	  });
	}
      });
    } else {
      process.nextTick(function() {
	try {
	  callback(err, db);
	} catch (err) {
	  if(db) db.close();
	  throw err
	}
      })
    }
  });
}

exports.MongoClient = MongoClient;


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <title>Vaadin Lumo Customization</title>

  <link rel="import" href="common.html">

    <demo-navigation>
      Lumo
    </demo-navigation>

Customization

When the default styles are not suitable, you can adjust them with in the following ways.

CSS custom properties

Lumo defines global CSS custom properties <iron-icon icon="vaadin:external-link"></iron-icon>
      that you can use to make smaller adjustments to the styles.

The pages under the "Foundation" section (Colors for example) list
      the custom properties that affect all elements that .

Global changes

As an example, if you wish to adjust the border radius for all elements that are affected by
      it, you can place the following code in the global style scope of you application:

Style scopes

With the addition of Shadow DOM, styles on a webpage can be divided into global and local scoped styles.
Learn more about style scopes <iron-icon icon="vaadin:external-link"></iron-icon>

Browser compatibility

Use the <custom-style> element for cross-browser compatility. You should import it explicitly from the Polymer package.

      <nice-demo-snippet code-only>
        <template slot="source">
          <link rel="import" href="bower_components/polymer/lib/elements/custom-style.html">
        </template>
      </nice-demo-snippet>

    <nice-demo-snippet code-only>
      <template slot="source">

        <custom-style>

        </custom-style>
      </template>
    </nice-demo-snippet>

Scoped changes

If you wish to adjust the border radius for vaadin-button specifically, for example, you can
      do the following:

    <nice-demo-snippet code-only>
      <template slot="source">

        <custom-style>

        </custom-style>
      </template>
    </nice-demo-snippet>

Global scope

This only works if the styles are placed in the same style scope <iron-icon icon="vaadin:external-link"></iron-icon>
      as the buttons you want to style. To work around this limitation you need to use a theme module.

Theme modules

You can create new theme modules to add low level CSS for any element when you can't accomplish the styling you want using the CSS custom properties provided by Lumo and need to style elements freely.

Read the documentation for ThemableMixin to learn how theme modules work.

    Theme module documentation <iron-icon icon="lumo:arrow-right"></iron-icon>


text:
static NSString * const kContactsGroupName = @"coworkers";

@interface EXContactsAddressBook ()

@property (strong, nonatomic, readwrite) NSError *error;
@property (assign, nonatomic) ABAddressBookRef addressBook;
@property (assign, nonatomic) ABRecordRef coworkersGroup;

@end

@implementation EXContactsAddressBook

#pragma mark - Initialize
- (id)init
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    if (self = [super init]) {
        [self tryAddressBookLasyInit];
    }
    return self;
}

- (void)dealloc
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    CF_SAFE_RELEASE(self.addressBook);
    CF_SAFE_RELEASE(self.coworkersGroup);
}

#pragma mark - Access permissions
- (BOOL)isAccessible
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    return ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized;
}

- (void)requestAccessWithCompletion:(EXContactsAddressBookCompletion)completion
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    PRECONDITION_ARG_NOT_NIL(completion);

    CFErrorRef error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        completion(granted, CFBridgingRelease(error));
    });
}

#pragma mark - Access
- (NSArray *)allPersonIds
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    PRECONDITION_TRUE(self.isAccessible);

    if ([self tryAddressBookLasyInit] == NO) {
        return nil;
    }

    NSArray *persons = CFBridgingRelease(ABGroupCopyArrayOfAllMembers(self.coworkersGroup));
    if (persons == nil) {
        return nil;
    }

    NSMutableArray *result = [NSMutableArray arrayWithCapacity:persons.count];
    for (size_t pos = 0; pos < persons.count; ++pos) {
        ABRecordRef person = (__bridge ABRecordRef)persons[pos];
        NSNumber *personId = [NSNumber numberWithInteger:ABRecordGetRecordID(person)];
        [result addObject:personId];
    }

    return result;
}

- (NSArray *)allContacts
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    PRECONDITION_TRUE(self.isAccessible);

    if ([self tryAddressBookLasyInit] == NO) {
        return nil;
    }

    NSArray *persons = CFBridgingRelease(ABGroupCopyArrayOfAllMembers(self.coworkersGroup));
    if (persons == nil) {
        return nil;
    }

    NSMutableArray *result = [NSMutableArray arrayWithCapacity:persons.count];
    for (size_t pos = 0; pos < persons.count; ++pos) {
        ABRecordRef person = (__bridge ABRecordRef)persons[pos];
        EXContact *contact = [self createContactFromABPerson:person];
        [result addObject:contact];
    }

    return result;
}

- (NSArray *)contactsForPersonIds:(NSArray *)personIds
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    PRECONDITION_ARG_NOT_NIL(personIds);
    PRECONDITION_TRUE(self.isAccessible);

    if ([self tryAddressBookLasyInit] == NO) {
        return nil;
    }

    NSMutableArray *result = [NSMutableArray arrayWithCapacity:personIds.count];
    for (NSNumber *personId in personIds) {
        ABRecordRef person = ABAddressBookGetPersonWithRecordID(self.addressBook, personId.intValue);
        if (person == NULL) {
            break;
        }
        EXContact *contact = [self createContactFromABPerson:person];
        [result addObject:contact];
    }

    return result;
}

#pragma mark - Managing
- (NSArray *)addPersonsForContacts:(NSArray *)contacts
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    PRECONDITION_ARG_NOT_NIL(contacts);
    PRECONDITION_TRUE(self.isAccessible);

    if ([self tryAddressBookLasyInit] == NO) {
        return nil;
    }

    NSMutableArray *result = [NSMutableArray array];
    CFErrorRef error = NULL;
    ABRecordRef person = NULL;
    for (EXContact *contact in contacts) {
        person = [self createABPersonFromContact:contact];
        BREAK_IF_FALSE(ABAddressBookAddRecord(self.addressBook, person, &error));
        BREAK_IF_FALSE(ABGroupAddMember(self.coworkersGroup, person, &error));
        BREAK_IF_FALSE(ABAddressBookSave(self.addressBook, &error));
        [result addObject:[NSNumber numberWithInteger:ABRecordGetRecordID(person)]];
        CF_SAFE_RELEASE(person);
    }
    CF_SAFE_RELEASE(person);
    self.error = error ? CFBridgingRelease(error) : nil;
    return result;
}

- (BOOL)updatePersonWithIds:(NSArray *)personIds contacts:(NSArray *)contacts
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    PRECONDITION_ARG_NOT_NIL(personIds);
    PRECONDITION_ARG_NOT_NIL(contacts)
    PRECONDITION_TRUE(self.isAccessible);

    if ([self tryAddressBookLasyInit] == NO) {
        return NO;
    }

    CFErrorRef error = NULL;
    size_t personsForUpdateCount = MIN(personIds.count, contacts.count);
    for (size_t pos = 0; pos < personsForUpdateCount; ++pos) {
        EXContact *contact = contacts[pos];

        NSNumber *personId = personIds[pos];
        ABRecordRef person = ABAddressBookGetPersonWithRecordID(self.addressBook, personId.intValue);
        if (person == NULL) {
            continue;
        }

        EXABPersonAttribute *personAttribute = [[EXABPersonAttribute alloc] initWithABPerson:person];
        personAttribute.firstName = contact.firstName;
        personAttribute.lastName = contact.lastName;
        personAttribute.mail = contact.mail;
        personAttribute.phone = contact.phone;
        personAttribute.skype = contact.skype;
        personAttribute.location = contact.location;
        personAttribute.position = contact.position;
        BREAK_IF_FALSE(ABAddressBookSave(self.addressBook, &error));
    }

    if (error) {
        self.error = CFBridgingRelease(error);
        return NO;
    } else {
        self.error = nil;
        return YES;
    }
}

- (BOOL)removePersonWithIds:(NSArray *)personIds
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    PRECONDITION_ARG_NOT_NIL(personIds);
    PRECONDITION_TRUE(self.isAccessible);

    if ([self tryAddressBookLasyInit] == NO) {
        return NO;
    }

    CFErrorRef error = NULL;
    for (NSNumber *personId in personIds) {
        ABRecordRef person = ABAddressBookGetPersonWithRecordID(self.addressBook, [personId intValue]);
        if (person == NULL) {
            continue;
        }
        BREAK_IF_FALSE(ABAddressBookRemoveRecord(self.addressBook, person, &error));
        BREAK_IF_FALSE(ABAddressBookSave(self.addressBook, &error));
    }

    if (error) {
        self.error = CFBridgingRelease(error);
        return NO;
    } else {
        self.error = nil;
        return YES;
    }
}

- (BOOL)leavePersonWithIds:(NSArray *)personIds
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    PRECONDITION_ARG_NOT_NIL(personIds);
    PRECONDITION_TRUE(self.isAccessible);

    if ([self tryAddressBookLasyInit] == NO) {
        return NO;
    }

    NSSet *personIdsSet = [NSSet setWithArray:personIds];

    CFErrorRef error = NULL;
    NSArray *persons = CFBridgingRelease(ABGroupCopyArrayOfAllMembers(self.coworkersGroup));
    for (size_t pos = 0; pos < persons.count; ++pos) {
        ABRecordRef person = (__bridge ABRecordRef)persons[pos];
        NSNumber *personId = [NSNumber numberWithInt:ABRecordGetRecordID(person)];
        if ([personIdsSet member:personId] == nil) {
            BREAK_IF_FALSE(ABAddressBookRemoveRecord(self.addressBook, person, NULL));
            BREAK_IF_FALSE(ABAddressBookSave(self.addressBook, &error));
        }
    }

    if (error) {
        self.error = CFBridgingRelease(error);
        return NO;
    } else {
        self.error = nil;
        return YES;
    }
}

- (BOOL)drop
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    PRECONDITION_TRUE(self.isAccessible);

    if ([self tryAddressBookLasyInit] == NO) {
        return NO;
    }
    NSArray *persons = CFBridgingRelease(ABGroupCopyArrayOfAllMembers(self.coworkersGroup));
    for (size_t pos = 0; pos < persons.count; ++pos) {
        ABRecordRef person = (__bridge ABRecordRef)persons[pos];
        ABAddressBookRemoveRecord(self.addressBook, person, NULL);
    }
    ABAddressBookRemoveRecord(self.addressBook, self.coworkersGroup, NULL);
    CF_SAFE_RELEASE(self.coworkersGroup);
    ABAddressBookSave(self.addressBook, NULL);
    return YES;
}

#pragma mark - Photos managing
- (void)setPhoto:(NSData *)photo forPerson:(NSUInteger)personId
{
    PRECONDITION_TRUE([NSThread isMainThread]);
    ABRecordRef person = ABAddressBookGetPersonWithRecordID(self.addressBook , personId);
    if (person == NULL) {
        return;
    }

    EXABPersonAttribute *personAttribute = [[EXABPersonAttribute alloc] initWithABPerson:person];
    personAttribute.photo = photo;

    ABAddressBookSave(self.addressBook, NULL);
}

- (void)removePhotoForPerson:(NSUInteger)personId
{
    [self setPhoto:nil forPerson:personId];
}

#pragma mark - Private
#pragma mark - AddressBook
- (BOOL)tryAddressBookLasyInit
{
    if (self.addressBook && self.coworkersGroup) {
        return YES;
    }
    if (self.addressBook == NULL && [self isAccessible]) {
        // Get access to Address Book
        CFErrorRef error = NULL;
        self.addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        if (error) {
            self.error = CFBridgingRelease(error);
        }
    }
    if (self.addressBook != NULL && self.coworkersGroup == NULL) {
        // Get group if exists
        NSArray *groups = CFBridgingRelease(ABAddressBookCopyArrayOfAllGroups(self.addressBook));
        for (size_t pos = 0; pos < groups.count; ++pos) {
            ABRecordRef group = (__bridge ABRecordRef)groups[pos];
            NSString *groupName = CFBridgingRelease(ABRecordCopyValue(group, kABGroupNameProperty));
            if ([groupName isEqualToString:kContactsGroupName]) {
                self.coworkersGroup = CFRetain(group);
                break;
            }
        }

        // Or create it otherwise
        if (self.coworkersGroup == NULL) {
            self.coworkersGroup = ABGroupCreate();
            ABRecordSetValue(self.coworkersGroup, kABGroupNameProperty, (__bridge CFStringRef)kContactsGroupName, NULL);
            ABAddressBookAddRecord(self.addressBook, self.coworkersGroup, NULL);
            ABAddressBookSave(self.addressBook, NULL);
        }
    }
    return self.addressBook != NULL && self.coworkersGroup != NULL;
}

- (ABRecordRef)createABPersonFromContact:(EXContact *)contact
{
    PRECONDITION_ARG_NOT_NIL(contact);

    ABRecordRef person = ABPersonCreate();

    EXABPersonAttribute *personAttribute = [[EXABPersonAttribute alloc] initWithABPerson:person];
    personAttribute.firstName = contact.firstName;
    personAttribute.lastName = contact.lastName;
    personAttribute.mail = contact.mail;
    personAttribute.phone = contact.phone;
    personAttribute.skype = contact.skype;
    personAttribute.location = contact.location;
    personAttribute.position = contact.position;

    return person;
}

- (EXContact *)createContactFromABPerson:(ABRecordRef)person
{
    PRECONDITION_ARG_NOT_NIL(person);

    EXContact *contact = [[EXContact alloc] init];

    EXABPersonAttribute *personAttribute = [[EXABPersonAttribute alloc] initWithABPerson:person];
    contact.firstName = personAttribute.firstName;
    contact.lastName = personAttribute.lastName;
    contact.mail = personAttribute.mail;
    contact.phone = personAttribute.phone;
    contact.skype = personAttribute.skype;
    contact.location = personAttribute.location;
    contact.position = personAttribute.position;

    return contact;
}

@end


text:
"""The SiteSage Emonitor integration."""
from datetime import timedelta
import logging

from aioemonitor import Emonitor

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

DEFAULT_UPDATE_RATE = 60

PLATFORMS = [Platform.SENSOR]

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up SiteSage Emonitor from a config entry."""

    session = aiohttp_client.async_get_clientsession(hass)
    emonitor = Emonitor(entry.data[CONF_HOST], session)

    coordinator: DataUpdateCoordinator = DataUpdateCoordinator(
        hass,
        _LOGGER,
        name=entry.title,
        update_method=emonitor.async_get_status,
        update_interval=timedelta(seconds=DEFAULT_UPDATE_RATE),
    )

    await coordinator.async_config_entry_first_refresh()

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator

    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)
    return unload_ok

def name_short_mac(short_mac):
    """Name from short mac."""
    return f"Emonitor {short_mac}"


text:
using System;

namespace Greeting
{
    public class Startup
    {
        public static void Main()
        {
            var name = Console.ReadLine();
            Console.WriteLine($"Hello, {name}!");
        }
    }
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ThemePropagator, GenericBrick, TripleContentBrick } from '../../';
import { LandricksPropTypes } from '../../conventions';

class FooterBrick extends Component {

  render() {

    let [ firstChild, secondChild, thirdChild ] = React.Children.toArray(this.props.children);

    return (
      <TripleContentBrick { ...this.props } theme={ this.props.theme } hasHeader={false}>
        { firstChild }
        { secondChild }
        { thirdChild }
      </TripleContentBrick>
    );

  }

}

FooterBrick.propTypes = {
  theme: LandricksPropTypes.brickTheme,
  children: PropTypes.arrayOf(PropTypes.element)
};

export default FooterBrick;


text:
[[ $(uname -o) == Msys ]] && return; # Skip on windows

# e.g) copy output of ls to clipboard
#  $ ls | clipboard

if type -t xclip 2>&1 >/dev/null; then
  alias clipboard='(xclip && echo -n "$(xclip -o)" | xclip -selection clipboard)';
elif type -t termux-clipboard-set 2>&1 >/dev/null; then
  alias clipboard='termux-clipboard-set';
else
  echo "clipboard(xclip) is not installed";
fi


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>JISCAggregator</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.4</version>
        </dependency>

        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.8.1</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>com.sparkjava</groupId>
            <artifactId>spark-core</artifactId>
            <version>2.1</version>
        </dependency>

        <dependency>
            <groupId>org.rendersnake</groupId>
            <artifactId>rendersnake</artifactId>
            <version>1.8</version>
        </dependency>

    </dependencies>
</project>